From 85e417d115c9e1b84e3d0e776d8d91fe1a9bcf3f Mon Sep 17 00:00:00 2001 From: Davin Date: Sun, 4 Sep 2022 21:16:36 +1000 Subject: [PATCH 01/20] A few changes to WinForms stuff Removed WindowsAPICodePack, updated strings to work correctly with the UI without much change, renamed APIs to their respective WinForms counterpart, turned ObjectListView into a .NET 6 project, instead of remaining as a legacy .NET Framework nuget dependency --- .../CellEditing/CellEditKeyEngine.cs | 520 + ObjectListView/CellEditing/CellEditors.cs | 325 + ObjectListView/CellEditing/EditorRegistry.cs | 213 + ObjectListView/CustomDictionary.xml | 46 + ObjectListView/DataListView.cs | 240 + ObjectListView/DataTreeListView.cs | 240 + ObjectListView/DragDrop/DragSource.cs | 219 + ObjectListView/DragDrop/DropSink.cs | 1562 +++ ObjectListView/DragDrop/OLVDataObject.cs | 185 + ObjectListView/FastDataListView.cs | 169 + ObjectListView/FastObjectListView.cs | 422 + ObjectListView/Filtering/Cluster.cs | 125 + .../Filtering/ClusteringStrategy.cs | 189 + .../Filtering/ClustersFromGroupsStrategy.cs | 70 + .../Filtering/DateTimeClusteringStrategy.cs | 187 + ObjectListView/Filtering/FilterMenuBuilder.cs | 369 + ObjectListView/Filtering/Filters.cs | 489 + .../Filtering/FlagClusteringStrategy.cs | 160 + ObjectListView/Filtering/ICluster.cs | 56 + .../Filtering/IClusteringStrategy.cs | 80 + ObjectListView/Filtering/TextMatchFilter.cs | 642 + ObjectListView/FullClassDiagram.cd | 1261 ++ ObjectListView/Implementation/Attributes.cs | 335 + ObjectListView/Implementation/Comparers.cs | 330 + .../Implementation/DataSourceAdapter.cs | 628 + ObjectListView/Implementation/Delegates.cs | 168 + ObjectListView/Implementation/DragSource.cs | 407 + ObjectListView/Implementation/DropSink.cs | 1402 ++ ObjectListView/Implementation/Enums.cs | 104 + ObjectListView/Implementation/Events.cs | 2514 ++++ .../Implementation/GroupingParameters.cs | 204 + ObjectListView/Implementation/Groups.cs | 761 ++ ObjectListView/Implementation/Munger.cs | 568 + .../Implementation/NativeMethods.cs | 1223 ++ .../Implementation/NullableDictionary.cs | 87 + ObjectListView/Implementation/OLVListItem.cs | 325 + .../Implementation/OLVListSubItem.cs | 173 + .../Implementation/OlvListViewHitTestInfo.cs | 388 + .../Implementation/TreeDataSourceAdapter.cs | 262 + .../Implementation/VirtualGroups.cs | 341 + .../Implementation/VirtualListDataSource.cs | 349 + ObjectListView/OLVColumn.cs | 1909 +++ ObjectListView/ObjectListView.DesignTime.cs | 550 + ObjectListView/ObjectListView.FxCop | 3521 +++++ ObjectListView/ObjectListView.cs | 10924 ++++++++++++++++ ObjectListView/ObjectListView.shfb | 47 + ObjectListView/ObjectListView2019.csproj | 54 + ObjectListView/ObjectListView2019.nuspec | 22 + ObjectListView/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 113 + ObjectListView/Properties/Resources.resx | 137 + ObjectListView/Rendering/Adornments.cs | 743 ++ ObjectListView/Rendering/Decorations.cs | 973 ++ ObjectListView/Rendering/Overlays.cs | 302 + ObjectListView/Rendering/Renderers.cs | 3887 ++++++ ObjectListView/Rendering/Styles.cs | 400 + ObjectListView/Rendering/TreeRenderer.cs | 309 + ObjectListView/Resources/clear-filter.png | Bin 0 -> 1381 bytes ObjectListView/Resources/coffee.jpg | Bin 0 -> 73464 bytes ObjectListView/Resources/filter-icons3.png | Bin 0 -> 1305 bytes ObjectListView/Resources/filter.png | Bin 0 -> 1331 bytes ObjectListView/Resources/sort-ascending.png | Bin 0 -> 1364 bytes ObjectListView/Resources/sort-descending.png | Bin 0 -> 1371 bytes ObjectListView/SubControls/GlassPanelForm.cs | 459 + ObjectListView/SubControls/HeaderControl.cs | 1230 ++ .../SubControls/ToolStripCheckedListBox.cs | 189 + ObjectListView/SubControls/ToolTipControl.cs | 699 + ObjectListView/TreeListView.cs | 2269 ++++ .../Utilities/ColumnSelectionForm.Designer.cs | 190 + .../Utilities/ColumnSelectionForm.cs | 263 + .../Utilities/ColumnSelectionForm.resx | 120 + ObjectListView/Utilities/Generator.cs | 563 + ObjectListView/Utilities/OLVExporter.cs | 277 + .../Utilities/TypedObjectListView.cs | 561 + ObjectListView/VirtualObjectListView.cs | 1255 ++ ObjectListView/olv-keyfile.snk | Bin 0 -> 596 bytes .../Properties/Strings.resx | 12 +- .../VG Music Studio - Core.csproj | 2 - VG Music Studio - WinForms/MainForm.cs | 152 +- .../VG Music Studio - WinForms.csproj | 4 +- VG Music Studio.sln | 6 + 81 files changed, 50398 insertions(+), 118 deletions(-) create mode 100644 ObjectListView/CellEditing/CellEditKeyEngine.cs create mode 100644 ObjectListView/CellEditing/CellEditors.cs create mode 100644 ObjectListView/CellEditing/EditorRegistry.cs create mode 100644 ObjectListView/CustomDictionary.xml create mode 100644 ObjectListView/DataListView.cs create mode 100644 ObjectListView/DataTreeListView.cs create mode 100644 ObjectListView/DragDrop/DragSource.cs create mode 100644 ObjectListView/DragDrop/DropSink.cs create mode 100644 ObjectListView/DragDrop/OLVDataObject.cs create mode 100644 ObjectListView/FastDataListView.cs create mode 100644 ObjectListView/FastObjectListView.cs create mode 100644 ObjectListView/Filtering/Cluster.cs create mode 100644 ObjectListView/Filtering/ClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ClustersFromGroupsStrategy.cs create mode 100644 ObjectListView/Filtering/DateTimeClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/FilterMenuBuilder.cs create mode 100644 ObjectListView/Filtering/Filters.cs create mode 100644 ObjectListView/Filtering/FlagClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ICluster.cs create mode 100644 ObjectListView/Filtering/IClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/TextMatchFilter.cs create mode 100644 ObjectListView/FullClassDiagram.cd create mode 100644 ObjectListView/Implementation/Attributes.cs create mode 100644 ObjectListView/Implementation/Comparers.cs create mode 100644 ObjectListView/Implementation/DataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/Delegates.cs create mode 100644 ObjectListView/Implementation/DragSource.cs create mode 100644 ObjectListView/Implementation/DropSink.cs create mode 100644 ObjectListView/Implementation/Enums.cs create mode 100644 ObjectListView/Implementation/Events.cs create mode 100644 ObjectListView/Implementation/GroupingParameters.cs create mode 100644 ObjectListView/Implementation/Groups.cs create mode 100644 ObjectListView/Implementation/Munger.cs create mode 100644 ObjectListView/Implementation/NativeMethods.cs create mode 100644 ObjectListView/Implementation/NullableDictionary.cs create mode 100644 ObjectListView/Implementation/OLVListItem.cs create mode 100644 ObjectListView/Implementation/OLVListSubItem.cs create mode 100644 ObjectListView/Implementation/OlvListViewHitTestInfo.cs create mode 100644 ObjectListView/Implementation/TreeDataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/VirtualGroups.cs create mode 100644 ObjectListView/Implementation/VirtualListDataSource.cs create mode 100644 ObjectListView/OLVColumn.cs create mode 100644 ObjectListView/ObjectListView.DesignTime.cs create mode 100644 ObjectListView/ObjectListView.FxCop create mode 100644 ObjectListView/ObjectListView.cs create mode 100644 ObjectListView/ObjectListView.shfb create mode 100644 ObjectListView/ObjectListView2019.csproj create mode 100644 ObjectListView/ObjectListView2019.nuspec create mode 100644 ObjectListView/Properties/AssemblyInfo.cs create mode 100644 ObjectListView/Properties/Resources.Designer.cs create mode 100644 ObjectListView/Properties/Resources.resx create mode 100644 ObjectListView/Rendering/Adornments.cs create mode 100644 ObjectListView/Rendering/Decorations.cs create mode 100644 ObjectListView/Rendering/Overlays.cs create mode 100644 ObjectListView/Rendering/Renderers.cs create mode 100644 ObjectListView/Rendering/Styles.cs create mode 100644 ObjectListView/Rendering/TreeRenderer.cs create mode 100644 ObjectListView/Resources/clear-filter.png create mode 100644 ObjectListView/Resources/coffee.jpg create mode 100644 ObjectListView/Resources/filter-icons3.png create mode 100644 ObjectListView/Resources/filter.png create mode 100644 ObjectListView/Resources/sort-ascending.png create mode 100644 ObjectListView/Resources/sort-descending.png create mode 100644 ObjectListView/SubControls/GlassPanelForm.cs create mode 100644 ObjectListView/SubControls/HeaderControl.cs create mode 100644 ObjectListView/SubControls/ToolStripCheckedListBox.cs create mode 100644 ObjectListView/SubControls/ToolTipControl.cs create mode 100644 ObjectListView/TreeListView.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.Designer.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.resx create mode 100644 ObjectListView/Utilities/Generator.cs create mode 100644 ObjectListView/Utilities/OLVExporter.cs create mode 100644 ObjectListView/Utilities/TypedObjectListView.cs create mode 100644 ObjectListView/VirtualObjectListView.cs create mode 100644 ObjectListView/olv-keyfile.snk diff --git a/ObjectListView/CellEditing/CellEditKeyEngine.cs b/ObjectListView/CellEditing/CellEditKeyEngine.cs new file mode 100644 index 0000000..a0d67b6 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditKeyEngine.cs @@ -0,0 +1,520 @@ +/* + * CellEditKeyEngine - A engine that allows the behaviour of arbitrary keys to be configured + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * v2.8 + * 2014-05-30 JPP - When a row is disabled, skip over it when looking for another cell to edit + * v2.5 + * 2012-04-14 JPP - Fixed bug where, on a OLV with only a single editable column, tabbing + * to change rows would edit the cell above rather than the cell below + * the cell being edited. + * 2.5 + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using BrightIdeasSoftware; + +namespace BrightIdeasSoftware { + /// + /// Indicates the behavior of a key when a cell "on the edge" is being edited. + /// and the normal behavior of that key would exceed the edge. For example, + /// for a key that normally moves one column to the left, the "edge" would be + /// the left most column, since the normal action of the key cannot be taken + /// (since there are no more columns to the left). + /// + public enum CellEditAtEdgeBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will result in the cell editing wrapping to the + /// cell on the opposite edge. + /// + Wrap, + + /// + /// The key press will wrap, but the column will be changed to the + /// appropriate adjacent column. This only makes sense for keys where + /// the normal action is ChangeRow. + /// + ChangeColumn, + + /// + /// The key press will wrap, but the row will be changed to the + /// appropriate adjacent row. This only makes sense for keys where + /// the normal action is ChangeColumn. + /// + ChangeRow, + + /// + /// The key will result in the current edit operation being ended. + /// + EndEdit + }; + + /// + /// Indicates the normal behaviour of a key when used during a cell edit + /// operation. + /// + public enum CellEditCharacterBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the left. + /// + ChangeColumnLeft, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the right. + /// + ChangeColumnRight, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row above. + /// + ChangeRowUp, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row below + /// + ChangeRowDown, + + /// + /// The key press will cancel the current edit + /// + CancelEdit, + + /// + /// The key press will finish the current edit operation + /// + EndEdit, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb1, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb2, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb3, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb4, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb5, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb6, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb7, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb8, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb9, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb10, + }; + + /// + /// Instances of this class handle key presses during a cell edit operation. + /// + public class CellEditKeyEngine { + + #region Public interface + + /// + /// Sets the behaviour of a given key + /// + /// + /// + /// + public virtual void SetKeyBehaviour(Keys key, CellEditCharacterBehaviour normalBehaviour, CellEditAtEdgeBehaviour atEdgeBehaviour) { + this.CellEditKeyMap[key] = normalBehaviour; + this.CellEditKeyAtEdgeBehaviourMap[key] = atEdgeBehaviour; + } + + /// + /// Handle a key press + /// + /// + /// + /// True if the key was completely handled. + public virtual bool HandleKey(ObjectListView olv, Keys keyData) { + if (olv == null) throw new ArgumentNullException("olv"); + + CellEditCharacterBehaviour behaviour; + if (!CellEditKeyMap.TryGetValue(keyData, out behaviour)) + return false; + + this.ListView = olv; + + switch (behaviour) { + case CellEditCharacterBehaviour.Ignore: + break; + case CellEditCharacterBehaviour.CancelEdit: + this.HandleCancelEdit(); + break; + case CellEditCharacterBehaviour.EndEdit: + this.HandleEndEdit(); + break; + case CellEditCharacterBehaviour.ChangeColumnLeft: + case CellEditCharacterBehaviour.ChangeColumnRight: + this.HandleColumnChange(keyData, behaviour); + break; + case CellEditCharacterBehaviour.ChangeRowDown: + case CellEditCharacterBehaviour.ChangeRowUp: + this.HandleRowChange(keyData, behaviour); + break; + default: + return this.HandleCustomVerb(keyData, behaviour); + }; + + return true; + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the ObjectListView on which the current key is being handled. + /// This cannot be null. + /// + protected ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the row of the cell that is currently being edited + /// + protected OLVListItem ItemBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? null : this.ListView.CellEditEventArgs.ListViewItem; + } + } + + /// + /// Gets the index of the column of the cell that is being edited + /// + protected int SubItemIndexBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? -1 : this.ListView.CellEditEventArgs.SubItemIndex; + } + } + + /// + /// Gets or sets the map that remembers the normal behaviour of keys + /// + protected IDictionary CellEditKeyMap { + get { + if (cellEditKeyMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyMap; + } + set { + cellEditKeyMap = value; + } + } + private IDictionary cellEditKeyMap; + + /// + /// Gets or sets the map that remembers the desired behaviour of keys + /// on edge cases. + /// + protected IDictionary CellEditKeyAtEdgeBehaviourMap { + get { + if (cellEditKeyAtEdgeBehaviourMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyAtEdgeBehaviourMap; + } + set { + cellEditKeyAtEdgeBehaviourMap = value; + } + } + private IDictionary cellEditKeyAtEdgeBehaviourMap; + + #endregion + + #region Initialization + + /// + /// Setup the default key mapping + /// + protected virtual void InitializeCellEditKeyMaps() { + this.cellEditKeyMap = new Dictionary(); + this.cellEditKeyMap[Keys.Escape] = CellEditCharacterBehaviour.CancelEdit; + this.cellEditKeyMap[Keys.Return] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Enter] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Tab] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Tab | Keys.Shift] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Left | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Right | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Up | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowUp; + this.cellEditKeyMap[Keys.Down | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowDown; + + this.cellEditKeyAtEdgeBehaviourMap = new Dictionary(); + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab | Keys.Shift] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Left | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Right | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Up | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Down | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + } + + #endregion + + #region Command handling + + /// + /// Handle the end edit command + /// + protected virtual void HandleEndEdit() { + this.ListView.PossibleFinishCellEditing(); + } + + /// + /// Handle the cancel edit command + /// + protected virtual void HandleCancelEdit() { + this.ListView.CancelCellEdit(); + } + + /// + /// Placeholder that subclasses can override to handle any custom verbs + /// + /// + /// + /// + protected virtual bool HandleCustomVerb(Keys keyData, CellEditCharacterBehaviour behaviour) { + return false; + } + + /// + /// Handle a change row command + /// + /// + /// + protected virtual void HandleRowChange(Keys keyData, CellEditCharacterBehaviour behaviour) { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + OLVListItem olvi = this.ItemBeingEdited; + int subItemIndex = this.SubItemIndexBeingEdited; + bool isGoingUp = behaviour == CellEditCharacterBehaviour.ChangeRowUp; + + // Try to find a row above (or below) the currently edited cell + // If we find one, start editing it and we're done. + OLVListItem adjacentOlvi = this.GetAdjacentItemOrNull(olvi, isGoingUp); + if (adjacentOlvi != null) { + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + return; + } + + // There is no adjacent row in the direction we want, so we must be on an edge. + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) { + case CellEditAtEdgeBehaviour.Ignore: + break; + case CellEditAtEdgeBehaviour.EndEdit: + this.ListView.PossibleFinishCellEditing(); + break; + case CellEditAtEdgeBehaviour.Wrap: + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + case CellEditAtEdgeBehaviour.ChangeColumn: + // Figure out the next editable column + List editableColumnsInDisplayOrder = this.EditableColumnsInDisplayOrder; + int displayIndex = Math.Max(0, editableColumnsInDisplayOrder.IndexOf(this.ListView.GetColumn(subItemIndex))); + if (isGoingUp) + displayIndex = (editableColumnsInDisplayOrder.Count + displayIndex - 1) % editableColumnsInDisplayOrder.Count; + else + displayIndex = (displayIndex + 1) % editableColumnsInDisplayOrder.Count; + subItemIndex = editableColumnsInDisplayOrder[displayIndex].Index; + + // Wrap to the next row and start the cell edit + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + } + } + + /// + /// Handle a change column command + /// + /// + /// + protected virtual void HandleColumnChange(Keys keyData, CellEditCharacterBehaviour behaviour) + { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + // Changing columns only works in details mode + if (this.ListView.View != View.Details) + return; + + List editableColumns = this.EditableColumnsInDisplayOrder; + OLVListItem olvi = this.ItemBeingEdited; + int displayIndex = Math.Max(0, + editableColumns.IndexOf(this.ListView.GetColumn(this.SubItemIndexBeingEdited))); + bool isGoingLeft = behaviour == CellEditCharacterBehaviour.ChangeColumnLeft; + + // Are we trying to continue past one of the edges? + if ((isGoingLeft && displayIndex == 0) || + (!isGoingLeft && displayIndex == editableColumns.Count - 1)) + { + // Yes, so figure out our at edge behaviour + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) + { + case CellEditAtEdgeBehaviour.Ignore: + return; + case CellEditAtEdgeBehaviour.EndEdit: + this.HandleEndEdit(); + return; + case CellEditAtEdgeBehaviour.ChangeRow: + case CellEditAtEdgeBehaviour.Wrap: + if (atEdgeBehaviour == CellEditAtEdgeBehaviour.ChangeRow) + olvi = GetAdjacentItem(olvi, isGoingLeft && displayIndex == 0); + if (isGoingLeft) + displayIndex = editableColumns.Count - 1; + else + displayIndex = 0; + break; + } + } + else + { + if (isGoingLeft) + displayIndex -= 1; + else + displayIndex += 1; + } + + int subItemIndex = editableColumns[displayIndex].Index; + this.StartCellEditIfDifferent(olvi, subItemIndex); + } + + #endregion + + #region Utilities + + /// + /// Start editing the indicated cell if that cell is not already being edited + /// + /// The row to edit + /// The cell within that row to edit + protected void StartCellEditIfDifferent(OLVListItem olvi, int subItemIndex) { + if (this.ItemBeingEdited == olvi && this.SubItemIndexBeingEdited == subItemIndex) + return; + + this.ListView.EnsureVisible(olvi.Index); + this.ListView.StartCellEdit(olvi, subItemIndex); + } + + /// + /// Gets the adjacent item to the given item in the given direction. + /// If that item is disabled, continue in that direction until an enabled item is found. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more enabled items in that direction. + protected OLVListItem GetAdjacentItemOrNull(OLVListItem olvi, bool up) { + OLVListItem item = up ? this.ListView.GetPreviousItem(olvi) : this.ListView.GetNextItem(olvi); + while (item != null && !item.Enabled) + item = up ? this.ListView.GetPreviousItem(item) : this.ListView.GetNextItem(item); + return item; + } + + /// + /// Gets the adjacent item to the given item in the given direction, wrapping if needed. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more items in that direction. + protected OLVListItem GetAdjacentItem(OLVListItem olvi, bool up) { + return this.GetAdjacentItemOrNull(olvi, up) ?? this.GetAdjacentItemOrNull(null, up); + } + + /// + /// Gets a collection of columns that are editable in the order they are shown to the user + /// + protected List EditableColumnsInDisplayOrder { + get { + List editableColumnsInDisplayOrder = new List(); + foreach (OLVColumn x in this.ListView.ColumnsInDisplayOrder) + if (x.IsEditable) + editableColumnsInDisplayOrder.Add(x); + return editableColumnsInDisplayOrder; + } + } + + #endregion + } +} diff --git a/ObjectListView/CellEditing/CellEditors.cs b/ObjectListView/CellEditing/CellEditors.cs new file mode 100644 index 0000000..4314021 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditors.cs @@ -0,0 +1,325 @@ +/* + * CellEditors - Several slightly modified controls that are used as cell editors within ObjectListView. + * + * Author: Phillip Piper + * Date: 20/10/2008 5:15 PM + * + * Change log: + * 2018-05-05 JPP - Added ControlUtilities.AutoResizeDropDown() + * v2.6 + * 2012-08-02 JPP - Make most editors public so they can be reused/subclassed + * v2.3 + * 2009-08-13 JPP - Standardized code formatting + * v2.2.1 + * 2008-01-18 JPP - Added special handling for enums + * 2008-01-16 JPP - Added EditorRegistry + * v2.0.1 + * 2008-10-20 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An interface that allows cell editors to specifically handle getting and setting + /// values from ObjectListView + /// + public interface IOlvEditor { + object Value { get; set; } + } + + public static class ControlUtilities { + + /// + /// Configure the given ComboBox so that the dropped down menu is auto-sized to + /// be wide enough to show the widest item. + /// + /// + public static void AutoResizeDropDown(ComboBox dropDown) { + if (dropDown == null) + throw new ArgumentNullException("dropDown"); + + dropDown.DropDown += delegate(object sender, EventArgs args) { + + // Calculate the maximum width of the drop down items + int newWidth = 0; + foreach (object item in dropDown.Items) { + newWidth = Math.Max(newWidth, TextRenderer.MeasureText(item.ToString(), dropDown.Font).Width); + } + + int vertScrollBarWidth = dropDown.Items.Count > dropDown.MaxDropDownItems ? SystemInformation.VerticalScrollBarWidth : 0; + dropDown.DropDownWidth = newWidth + vertScrollBarWidth; + }; + } + } + + /// + /// These items allow combo boxes to remember a value and its description. + /// + public class ComboBoxItem + { + /// + /// + /// + /// + /// + public ComboBoxItem(Object key, String description) { + this.key = key; + this.description = description; + } + private readonly String description; + + /// + /// + /// + public Object Key { + get { return key; } + } + private readonly Object key; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return this.description; + } + } + + //----------------------------------------------------------------------- + // Cell editors + // These classes are simple cell editors that make it easier to get and set + // the value that the control is showing. + // In many cases, you can intercept the CellEditStarting event to + // change the characteristics of the editor. For example, changing + // the acceptable range for a numeric editor or changing the strings + // that represent true and false values for a boolean editor. + + /// + /// This editor shows and auto completes values from the given listview column. + /// + [ToolboxItem(false)] + public class AutoCompleteCellEditor : ComboBox + { + /// + /// Create an AutoCompleteCellEditor + /// + /// + /// + public AutoCompleteCellEditor(ObjectListView lv, OLVColumn column) { + this.DropDownStyle = ComboBoxStyle.DropDown; + + Dictionary alreadySeen = new Dictionary(); + for (int i = 0; i < Math.Min(lv.GetItemCount(), 1000); i++) { + String str = column.GetStringValue(lv.GetModelObject(i)); + if (!alreadySeen.ContainsKey(str)) { + this.Items.Add(str); + alreadySeen[str] = true; + } + } + + this.Sorted = true; + this.AutoCompleteSource = AutoCompleteSource.ListItems; + this.AutoCompleteMode = AutoCompleteMode.Append; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This combo box is specialized to allow editing of an enum. + /// + [ToolboxItem(false)] + public class EnumCellEditor : ComboBox + { + /// + /// + /// + /// + public EnumCellEditor(Type type) { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + foreach (object value in Enum.GetValues(type)) + values.Add(new ComboBoxItem(value, Enum.GetName(type, value))); + + this.DataSource = values; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This editor simply shows and edits integer values. + /// + [ToolboxItem(false)] + public class IntUpDown : NumericUpDown + { + /// + /// + /// + public IntUpDown() { + this.DecimalPlaces = 0; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new int Value { + get { return Decimal.ToInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits unsigned integer values. + /// + /// This class can't be made public because unsigned int is not a + /// CLS-compliant type. If you want to use, just copy the code to this class + /// into your project and use it from there. + [ToolboxItem(false)] + internal class UintUpDown : NumericUpDown + { + public UintUpDown() { + this.DecimalPlaces = 0; + this.Minimum = 0; + this.Maximum = 9999999; + } + + public new uint Value { + get { return Decimal.ToUInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits boolean values. + /// + [ToolboxItem(false)] + public class BooleanCellEditor : ComboBox + { + /// + /// + /// + public BooleanCellEditor() { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + values.Add(new ComboBoxItem(false, "False")); + values.Add(new ComboBoxItem(true, "True")); + + this.DataSource = values; + } + } + + /// + /// This editor simply shows and edits boolean values using a checkbox + /// + [ToolboxItem(false)] + public class BooleanCellEditor2 : CheckBox + { + /// + /// Gets or sets the value shown by this editor + /// + public bool? Value { + get { + switch (this.CheckState) { + case CheckState.Checked: return true; + case CheckState.Indeterminate: return null; + case CheckState.Unchecked: + default: return false; + } + } + set { + if (value.HasValue) + this.CheckState = value.Value ? CheckState.Checked : CheckState.Unchecked; + else + this.CheckState = CheckState.Indeterminate; + } + } + + /// + /// Gets or sets how the checkbox will be aligned + /// + public new HorizontalAlignment TextAlign { + get { + switch (this.CheckAlign) { + case ContentAlignment.MiddleRight: return HorizontalAlignment.Right; + case ContentAlignment.MiddleCenter: return HorizontalAlignment.Center; + case ContentAlignment.MiddleLeft: + default: return HorizontalAlignment.Left; + } + } + set { + switch (value) { + case HorizontalAlignment.Left: + this.CheckAlign = ContentAlignment.MiddleLeft; + break; + case HorizontalAlignment.Center: + this.CheckAlign = ContentAlignment.MiddleCenter; + break; + case HorizontalAlignment.Right: + this.CheckAlign = ContentAlignment.MiddleRight; + break; + } + } + } + } + + /// + /// This editor simply shows and edits floating point values. + /// + /// You can intercept the CellEditStarting event if you want + /// to change the characteristics of the editor. For example, by increasing + /// the number of decimal places. + [ToolboxItem(false)] + public class FloatCellEditor : NumericUpDown + { + /// + /// + /// + public FloatCellEditor() { + this.DecimalPlaces = 2; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new double Value { + get { return Convert.ToDouble(base.Value); } + set { base.Value = Convert.ToDecimal(value); } + } + } +} diff --git a/ObjectListView/CellEditing/EditorRegistry.cs b/ObjectListView/CellEditing/EditorRegistry.cs new file mode 100644 index 0000000..f92854f --- /dev/null +++ b/ObjectListView/CellEditing/EditorRegistry.cs @@ -0,0 +1,213 @@ +/* + * EditorRegistry - A registry mapping types to cell editors. + * + * Author: Phillip Piper + * Date: 6-March-2011 7:53 am + * + * Change log: + * 2011-03-31 JPP - Use OLVColumn.DataType if the value to be edited is null + * 2011-03-06 JPP - Separated from CellEditors.cs + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; + +namespace BrightIdeasSoftware { + + /// + /// A delegate that creates an editor for the given value + /// + /// The model from which that value came + /// The column for which the editor is being created + /// A representative value of the type to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A control which can edit the given value + public delegate Control EditorCreatorDelegate(Object model, OLVColumn column, Object value); + + /// + /// An editor registry gives a way to decide what cell editor should be used to edit + /// the value of a cell. Programmers can register non-standard types and the control that + /// should be used to edit instances of that type. + /// + /// + /// All ObjectListViews share the same editor registry. + /// + public class EditorRegistry { + #region Initializing + + /// + /// Create an EditorRegistry + /// + public EditorRegistry() { + this.InitializeStandardTypes(); + } + + private void InitializeStandardTypes() { + this.Register(typeof(Boolean), typeof(BooleanCellEditor)); + this.Register(typeof(Int16), typeof(IntUpDown)); + this.Register(typeof(Int32), typeof(IntUpDown)); + this.Register(typeof(Int64), typeof(IntUpDown)); + this.Register(typeof(UInt16), typeof(UintUpDown)); + this.Register(typeof(UInt32), typeof(UintUpDown)); + this.Register(typeof(UInt64), typeof(UintUpDown)); + this.Register(typeof(Single), typeof(FloatCellEditor)); + this.Register(typeof(Double), typeof(FloatCellEditor)); + this.Register(typeof(DateTime), delegate(Object model, OLVColumn column, Object value) { + DateTimePicker c = new DateTimePicker(); + c.Format = DateTimePickerFormat.Short; + return c; + }); + this.Register(typeof(Boolean), delegate(Object model, OLVColumn column, Object value) { + CheckBox c = new BooleanCellEditor2(); + c.ThreeState = column.TriStateCheckBoxes; + return c; + }); + } + + #endregion + + #region Registering + + /// + /// Register that values of 'type' should be edited by instances of 'controlType'. + /// + /// The type of value to be edited + /// The type of the Control that will edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), typeof(MySpecialColorEditor)); + /// + public void Register(Type type, Type controlType) { + this.Register(type, delegate(Object model, OLVColumn column, Object value) { + return controlType.InvokeMember("", BindingFlags.CreateInstance, null, null, null) as Control; + }); + } + + /// + /// Register the given delegate so that it is called to create editors + /// for values of the given type + /// + /// The type of value to be edited + /// The delegate that will create a control that can edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), CreateColorEditor); + /// ... + /// public Control CreateColorEditor(Object model, OLVColumn column, Object value) + /// { + /// return new MySpecialColorEditor(); + /// } + /// + public void Register(Type type, EditorCreatorDelegate creator) { + this.creatorMap[type] = creator; + } + + /// + /// Register a delegate that will be called to create an editor for values + /// that have not been handled. + /// + /// The delegate that will create a editor for all other types + public void RegisterDefault(EditorCreatorDelegate creator) { + this.defaultCreator = creator; + } + + /// + /// Register a delegate that will be given a chance to create a control + /// before any other option is considered. + /// + /// The delegate that will create a control + public void RegisterFirstChance(EditorCreatorDelegate creator) { + this.firstChanceCreator = creator; + } + + /// + /// Remove the registered handler for the given type + /// + /// Does nothing if the given type doesn't exist + /// The type whose registration is to be removed + public void Unregister(Type type) { + if (this.creatorMap.ContainsKey(type)) + this.creatorMap.Remove(type); + } + + #endregion + + #region Accessing + + /// + /// Create and return an editor that is appropriate for the given value. + /// Return null if no appropriate editor can be found. + /// + /// The model involved + /// The column to be edited + /// The value to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A Control that can edit the given type of values + public Control GetEditor(Object model, OLVColumn column, Object value) { + Control editor; + + // Give the first chance delegate a chance to decide + if (this.firstChanceCreator != null) { + editor = this.firstChanceCreator(model, column, value); + if (editor != null) + return editor; + } + + // Try to find a creator based on the type of the value (or the column) + Type type = value == null ? column.DataType : value.GetType(); + if (type != null && this.creatorMap.ContainsKey(type)) { + editor = this.creatorMap[type](model, column, value); + if (editor != null) + return editor; + } + + // Enums without other processing get a special editor + if (value != null && value.GetType().IsEnum) + return this.CreateEnumEditor(value.GetType()); + + // Give any default creator a final chance + if (this.defaultCreator != null) + return this.defaultCreator(model, column, value); + + return null; + } + + /// + /// Create and return an editor that will edit values of the given type + /// + /// A enum type + protected Control CreateEnumEditor(Type type) { + return new EnumCellEditor(type); + } + + #endregion + + #region Private variables + + private EditorCreatorDelegate firstChanceCreator; + private EditorCreatorDelegate defaultCreator; + private Dictionary creatorMap = new Dictionary(); + + #endregion + } +} diff --git a/ObjectListView/CustomDictionary.xml b/ObjectListView/CustomDictionary.xml new file mode 100644 index 0000000..f2cf5b9 --- /dev/null +++ b/ObjectListView/CustomDictionary.xml @@ -0,0 +1,46 @@ + + + + + br + Canceled + Center + Color + Colors + f + fmt + g + gdi + hti + i + lightbox + lv + lvi + lvsi + m + multi + Munger + n + olv + olvi + p + parms + r + Renderer + s + SubItem + Unapply + Unpause + x + y + + + ComPlus + + + + + OLV + + + diff --git a/ObjectListView/DataListView.cs b/ObjectListView/DataListView.cs new file mode 100644 index 0000000..2961d04 --- /dev/null +++ b/ObjectListView/DataListView.cs @@ -0,0 +1,240 @@ +/* + * DataListView - A data-bindable listview + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2011-02-27 JPP - Moved most of the logic to DataSourceAdapter (where it + * can be used by FastDataListView too) + * v2.3 + * 2009-01-18 JPP - Boolean columns are now handled as checkboxes + * - Auto-generated columns would fail if the data source was + * reseated, even to the same data source + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-10-03 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + + /// + /// A DataListView is a ListView that can be bound to a datasource (which would normally be a DataTable or DataView). + /// + /// + /// This listview keeps itself in sync with its source datatable by listening for change events. + /// The DataListView will automatically create columns to show all of the data source's columns/properties, if there is not already + /// a column showing that property. This allows you to define one or two columns in the designer and then have the others generated automatically. + /// If you don't want any column to be auto generated, set to false. + /// These generated columns will be only the simplest view of the world, and would look more interesting with a few delegates installed. + /// This listview will also automatically generate missing aspect getters to fetch the values from the data view. + /// Changing data sources is possible, but error prone. Before changing data sources, the programmer is responsible for modifying/resetting + /// the column collection to be valid for the new data source. + /// Internally, a CurrencyManager controls keeping the data source in-sync with other users of the data source (as per normal .NET + /// behavior). This means that the model objects in the DataListView are DataRowView objects. If you write your own AspectGetters/Setters, + /// they will be given DataRowView objects. + /// + public class DataListView : ObjectListView + { + #region Life and death + + /// + /// Make a DataListView + /// + public DataListView() + { + this.Adapter = new DataSourceAdapter(this); + } + + /// + /// + /// + /// + protected override void Dispose(bool disposing) { + this.Adapter.Dispose(); + base.Dispose(disposing); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// When a DataSource is set, the control will create OLVColumns to show any + /// data source columns that are not already shown. + /// If the DataSource is changed, you will have to remove any previously + /// created columns, since they will be configured for the previous DataSource. + /// . + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource + { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember + { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + /// + /// Adaptors cannot be shared between controls. Each DataListView needs its own adapter. + /// + protected DataSourceAdapter Adapter { + get { + Debug.Assert(adapter != null, "Data adapter should not be null"); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Object manipulations + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void AddObjects(ICollection modelObjects) + { + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// Remove the given collection of model objects from this control. + /// + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void RemoveObjects(ICollection modelObjects) + { + } + + #endregion + + #region Event Handlers + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + /// + /// Handles parent binding context changes + /// + /// Unused EventArgs. + protected override void OnParentBindingContextChanged(EventArgs e) + { + base.OnParentBindingContextChanged(e); + + // BindingContext is an ambient property - by default it simply picks + // up the parent control's context (unless something has explicitly + // given us our own). So we must respond to changes in our parent's + // binding context in the same way we would changes to our own + // binding context. + + // THINK: Do we need to forward this to the adapter? + } + + #endregion + } +} diff --git a/ObjectListView/DataTreeListView.cs b/ObjectListView/DataTreeListView.cs new file mode 100644 index 0000000..65179a9 --- /dev/null +++ b/ObjectListView/DataTreeListView.cs @@ -0,0 +1,240 @@ +/* + * DataTreeListView - A data bindable TreeListView + * + * Author: Phillip Piper + * Date: 05/05/2012 3:26 PM + * + * Change log: + + * 2012-05-05 JPP Initial version + * + * TO DO: + + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A DataTreeListView is a TreeListView that calculates its hierarchy based on + /// information in the data source. + /// + /// + /// Like a , a DataTreeListView sources all its information + /// from a combination of and . + /// can be a DataTable, DataSet, + /// or anything that implements . + /// + /// + /// To function properly, the DataTreeListView requires: + /// + /// the table to have a column which holds a unique for the row. The name of this column must be set in . + /// the table to have a column which holds id of the hierarchical parent of the row. The name of this column must be set in . + /// a value which identifies which rows are the roots of the tree (). + /// + /// The hierarchy structure is determined finding all the rows where the parent key is equal to . These rows + /// become the root objects of the hierarchy. + /// + /// Like a TreeListView, the hierarchy must not contain cycles. Bad things will happen if the data is cyclic. + /// + public partial class DataTreeListView : TreeListView + { + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of a row"), + DefaultValue(null)] + public virtual string KeyAspectName { + get { return this.Adapter.KeyAspectName; } + set { this.Adapter.KeyAspectName = value; } + } + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of the parent of a row"), + DefaultValue(null)] + public virtual string ParentKeyAspectName { + get { return this.Adapter.ParentKeyAspectName; } + set { this.Adapter.ParentKeyAspectName = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. Actually, it can be any value that can + /// be compared for equality against a basic type. + /// If this is set to the wrong value (i.e. to a value that no row + /// has in the parent id column), the list will be empty. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual object RootKeyValue { + get { return this.Adapter.RootKeyValue; } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// . The RootKeyValue can be of any type, + /// but the IDE cannot sensibly represent a value of any type, + /// so this is a typed wrapper around that property. + /// + /// + /// If you want the root value to be something other than a string, + /// you will have set it yourself. + /// + [Category("Data"), + Description("The parent id value that identifies a row as a root object"), + DefaultValue(null)] + public virtual string RootKeyValueString { + get { return Convert.ToString(this.Adapter.RootKeyValue); } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + [Category("Data"), + Description("Should the keys columns (id and parent id) be shown to the user?"), + DefaultValue(true)] + public virtual bool ShowKeyColumns { + get { return this.Adapter.ShowKeyColumns; } + set { this.Adapter.ShowKeyColumns = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected TreeDataSourceAdapter Adapter { + get { + if (this.adapter == null) + this.adapter = new TreeDataSourceAdapter(this); + return adapter; + } + set { adapter = value; } + } + private TreeDataSourceAdapter adapter; + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DragSource.cs b/ObjectListView/DragDrop/DragSource.cs new file mode 100644 index 0000000..1abf13b --- /dev/null +++ b/ObjectListView/DragDrop/DragSource.cs @@ -0,0 +1,219 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2011-03-29 JPP - Separate OLVDataObject.cs + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. The data + /// object will normally include all the selected objects. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All operations are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshes the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + return new OLVDataObject(olv); + } + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DropSink.cs b/ObjectListView/DragDrop/DropSink.cs new file mode 100644 index 0000000..c82bd67 --- /dev/null +++ b/ObjectListView/DragDrop/DropSink.cs @@ -0,0 +1,1562 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2018-04-26 JPP - Implemented LeftOfItem and RightOfItem target locations + * - Added support for rearranging on non-Detail views. + * v2.9 + * 2015-07-08 JPP - Added SimpleDropSink.EnableFeedback to allow all the pretty and helpful + * user feedback during drags to be turned off + * v2.7 + * 2011-04-20 JPP - Rewrote how ModelDropEventArgs.RefreshObjects() works on TreeListViews + * v2.4.1 + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it should be called CleverDropSink -- it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists. Defaults to true. + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. Defaults to true. + /// + /// AutoScroll does not scroll horizontally. + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Gets or sets whether the drop sink should draw feedback onto the given list + /// during the drag operation. Defaults to true. + /// + /// If this is false, you will have to give the user feedback in some + /// other fashion, like cursor changes + public bool EnableFeedback { + get { return enableFeedback; } + set { enableFeedback = value; } + } + private bool enableFeedback = true; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + /// + /// Gets or sets whether the drop sink will automatically use cursors + /// based on the drop effect. By default, this is true. If this is + /// set to false, you must set the Cursor yourself. + /// + public bool UseDefaultCursors { + get { return useDefaultCursors; } + set { useDefaultCursors = value; } + } + private bool useDefaultCursors = true; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + if (this.EnableFeedback) { + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + case DropTargetLocation.LeftOfItem: + this.DrawFeedbackLeftOfItemTarget(g, bounds); + break; + case DropTargetLocation.RightOfItem: + this.DrawFeedbackRightOfItemTarget(g, bounds); + break; + } + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.dropEventArgs.DragEventArgs = args; + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DragEventArgs = args; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + public override void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = this.UseDefaultCursors; + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.dropEventArgs.DragEventArgs = args; + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continue while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined). + // If the view is Details or List, then "between" is considered vertically. + // If the view is SmallIcon, LargeIcon or Tile, then "between" is considered horizontally. + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + switch (this.ListView.View) { + case View.LargeIcon: + case View.Tile: + case View.SmallIcon: + // If the mouse is over an item, check to see if it is near the left or right edge. + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : info.Item.Bounds.Width / 2; + if (pt.X <= info.Item.Bounds.Left + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else if (pt.X >= info.Item.Bounds.Right - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } else { + // Is there an item a little to the *right* of the mouse? + // If so, we say the drop point is *left* that item + int probeWidth = SMALL_VALUE * 2; + info = this.ListView.OlvHitTest(pt.X + probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else { + // Is there an item a little to the left of the mouse? + info = this.ListView.OlvHitTest(pt.X - probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } + } + break; + case View.Details: + case View.List: + // If the mouse is over an item, check to see if it is near the top or bottom + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : this.ListView.RowHeightEffective / 2; + + if (pt.Y <= info.Item.Bounds.Top + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else if (pt.Y >= info.Item.Bounds.Bottom - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the left of target + /// + /// + /// + protected virtual void DrawFeedbackLeftOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Left, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the right of target + /// + /// + /// + protected virtual void DrawFeedbackRightOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Right, r.Top, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * item.IndentCount; + r.X += indentWidth; + r.Width -= indentWidth; + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + if (y1 == y2) { + // Put right and left arrow on a horizontal line + DrawClosedFigure(g, b, RightPointingArrow(x1, y1)); + DrawClosedFigure(g, b, LeftPointingArrow(x2, y2)); + } else { + // Put up and down arrows on a vertical line + DrawClosedFigure(g, b, DownPointingArrow(x1, y1)); + DrawClosedFigure(g, b, UpPointingArrow(x2, y2)); + } + } + + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + private const int ARROW_SIZE = 6; + + private static void DrawClosedFigure(Graphics g, Brush b, Point[] pts) { + using (GraphicsPath gp = new GraphicsPath()) { + gp.StartFigure(); + gp.AddLines(pts); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + + private static Point[] RightPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x + ARROW_SIZE, y) + }; + } + + private static Point[] LeftPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x - ARROW_SIZE, y) + }; + } + + private static Point[] DownPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y + ARROW_SIZE) + }; + } + + private static Point[] UpPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y - ARROW_SIZE) + }; + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amongst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging the same list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + case DropTargetLocation.LeftOfItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + case DropTargetLocation.RightOfItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + + // Some views have to be "encouraged" to show the changes + switch (this.ListView.View) { + case View.LargeIcon: + case View.SmallIcon: + case View.Tile: + this.ListView.BuildList(); + break; + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occurred, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the original drag-drop event args + /// + public DragEventArgs DragEventArgs + { + get { return this.dragEventArgs; } + internal set { this.dragEventArgs = value; } + } + private DragEventArgs dragEventArgs; + + /// + /// Get the data object that is being dragged + /// + public object DataObject + { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + + toBeRefreshed.AddRange(this.SourceModels); + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv == null) + this.SourceListView.RefreshObjects(toBeRefreshed); + else + tlv.RebuildAll(true); + + TreeListView tlv2 = this.ListView as TreeListView; + if (tlv2 == null) + this.ListView.RefreshObject(this.TargetModel); + else + tlv2.RebuildAll(true); + } + } +} diff --git a/ObjectListView/DragDrop/OLVDataObject.cs b/ObjectListView/DragDrop/OLVDataObject.cs new file mode 100644 index 0000000..116861b --- /dev/null +++ b/ObjectListView/DragDrop/OLVDataObject.cs @@ -0,0 +1,185 @@ +/* + * OLVDataObject.cs - An OLE DataObject that knows how to convert rows of an OLV to text and HTML + * + * Author: Phillip Piper + * Date: 2011-03-29 3:34PM + * + * Change log: + * v2.8 + * 2014-05-02 JPP - When the listview is completely empty, don't try to set CSV text in the clipboard. + * v2.6 + * 2012-08-08 JPP - Changed to use OLVExporter. + * - Added CSV to formats exported to Clipboard + * v2.4 + * 2011-03-29 JPP - Initial version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) + : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + this.CreateTextFormats(); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private readonly bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + } + private readonly bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private readonly ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private readonly IList modelObjects; + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + + OLVExporter exporter = this.CreateExporter(); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(exporter.ExportTo(OLVExporter.ExportFormat.TabSeparated)); + string exportTo = exporter.ExportTo(OLVExporter.ExportFormat.CSV); + if (!String.IsNullOrEmpty(exportTo)) + this.SetText(exportTo, TextDataFormat.CommaSeparatedValue); + this.SetText(ConvertToHtmlFragment(exporter.ExportTo(OLVExporter.ExportFormat.HTML)), TextDataFormat.Html); + } + + /// + /// Create an exporter for the data contained in this object + /// + /// + protected OLVExporter CreateExporter() { + OLVExporter exporter = new OLVExporter(this.ListView); + exporter.IncludeColumnHeaders = this.IncludeColumnHeaders; + exporter.IncludeHiddenColumns = this.IncludeHiddenColumns; + exporter.ModelObjects = this.ModelObjects; + return exporter; + } + + /// + /// Make a HTML representation of our model objects + /// + [Obsolete("Use OLVExporter directly instead", false)] + public string CreateHtml() { + OLVExporter exporter = this.CreateExporter(); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognised as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + const string SOURCE = "http://www.codeproject.com/Articles/16009/A-Much-Easier-to-Use-ListView"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, SOURCE, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment, StringComparison.Ordinal); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, SOURCE, html); + } + } +} diff --git a/ObjectListView/FastDataListView.cs b/ObjectListView/FastDataListView.cs new file mode 100644 index 0000000..8b30d2b --- /dev/null +++ b/ObjectListView/FastDataListView.cs @@ -0,0 +1,169 @@ +/* + * FastDataListView - A data bindable listview that has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 22/09/2010 8:11 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2010-09-22 JPP - Initial version + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing.Design; + +namespace BrightIdeasSoftware +{ + /// + /// A FastDataListView virtualizes the display of data from a DataSource. It operates on + /// DataSets and DataTables in the same way as a DataListView, but does so much more efficiently. + /// + /// + /// + /// A FastDataListView still has to load all its data from the DataSource. If you have SQL statement + /// that returns 1 million rows, all 1 million rows will still need to read from the database. + /// However, once the rows are loaded, the FastDataListView will only build rows as they are displayed. + /// + /// + public class FastDataListView : FastObjectListView + { + /// + /// + /// + /// + protected override void Dispose(bool disposing) + { + if (this.adapter != null) { + this.adapter.Dispose(); + this.adapter = null; + } + + base.Dispose(disposing); + } + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the VirtualListDataSource that will be displayed in this list view. + /// + /// The VirtualListDataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// VirtualListDataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected DataSourceAdapter Adapter { + get { + if (adapter == null) + adapter = this.CreateDataSourceAdapter(); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Implementation + + /// + /// Create the DataSourceAdapter that this control will use. + /// + /// A DataSourceAdapter configured for this list + /// Subclasses should override this to create their + /// own specialized adapters + protected virtual DataSourceAdapter CreateDataSourceAdapter() { + return new DataSourceAdapter(this); + } + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() + { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + #endregion + } +} diff --git a/ObjectListView/FastObjectListView.cs b/ObjectListView/FastObjectListView.cs new file mode 100644 index 0000000..0c5fe30 --- /dev/null +++ b/ObjectListView/FastObjectListView.cs @@ -0,0 +1,422 @@ +/* + * FastObjectListView - A listview that behaves like an ObjectListView but has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2014-10-15 JPP - Fire Filter event when applying filters + * v2.8 + * 2012-06-11 JPP - Added more efficient version of FilteredObjects + * v2.5.1 + * 2011-04-25 JPP - Fixed problem with removing objects from filtered or sorted list + * v2.4 + * 2010-04-05 JPP - Added filtering + * v2.3 + * 2009-08-27 JPP - Added GroupingStrategy + * - Added optimized Objects property + * v2.2.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A FastObjectListView trades function for speed. + /// + /// + /// On my mid-range laptop, this view builds a list of 10,000 objects in 0.1 seconds, + /// as opposed to a normal ObjectListView which takes 10-15 seconds. Lists of up to 50,000 items should be + /// able to be handled with sub-second response times even on low end machines. + /// + /// A FastObjectListView is implemented as a virtual list with many of the virtual modes limits (e.g. no sorting) + /// fixed through coding. There are some functions that simply cannot be provided. Specifically, a FastObjectListView cannot: + /// + /// use Tile view + /// show groups on XP + /// + /// + /// + public class FastObjectListView : VirtualObjectListView + { + /// + /// Make a FastObjectListView + /// + public FastObjectListView() { + this.VirtualListDataSource = new FastObjectListDataSource(this); + this.GroupingStrategy = new FastListGroupingStrategy(); + } + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).FilteredObjectList; + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).ObjectList; + } + set { base.Objects = value; } + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public override void MoveObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.MoveObjects(index, modelObjects); }); + return; + } + + // If any object that is going to be moved is before the point where the insertion + // will occur, then we have to reduce the location of our insertion point + int displacedObjectCount = 0; + foreach (object modelObject in modelObjects) { + int i = this.IndexOf(modelObject); + if (i >= 0 && i <= index) + displacedObjectCount++; + } + index -= displacedObjectCount; + + this.BeginUpdate(); + try { + this.RemoveObjects(modelObjects); + this.InsertObjects(index, modelObjects); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + /// To be really honest, Unsort() doesn't work on FastObjectListViews since + /// the original ordering of model objects is lost when Sort() is called. So this method + /// effectively just turns off sorting. + public override void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.SetObjects(this.Objects); + } + } + + /// + /// Provide a data source for a FastObjectListView + /// + /// + /// This class isn't intended to be used directly, but it is left as a public + /// class just in case someone wants to subclass it. + /// + public class FastObjectListDataSource : AbstractVirtualListDataSource + { + /// + /// Create a FastObjectListDataSource + /// + /// + public FastObjectListDataSource(FastObjectListView listView) + : base(listView) { + } + + #region IVirtualListDataSource Members + + /// + /// Get n'th object + /// + /// + /// + public override object GetNthObject(int n) { + if (n >= 0 && n < this.filteredObjectList.Count) + return this.filteredObjectList[n]; + + return null; + } + + /// + /// How many items are in the data source + /// + /// + public override int GetObjectCount() { + return this.filteredObjectList.Count; + } + + /// + /// Get the index of the given model + /// + /// + /// + public override int GetObjectIndex(object model) { + int index; + + if (model != null && this.objectsToIndexMap.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// + /// + /// + /// + public override void Sort(OLVColumn column, SortOrder sortOrder) { + if (sortOrder != SortOrder.None) { + ModelObjectComparer comparer = new ModelObjectComparer(column, sortOrder, this.listView.SecondarySortColumn, this.listView.SecondarySortOrder); + this.fullObjectList.Sort(comparer); + this.filteredObjectList.Sort(comparer); + } + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void AddObjects(ICollection modelObjects) { + foreach (object modelObject in modelObjects) { + if (modelObject != null) + this.fullObjectList.Add(modelObject); + } + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + /// + public override void InsertObjects(int index, ICollection modelObjects) { + this.fullObjectList.InsertRange(index, modelObjects); + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Remove the given collection of models from this source. + /// + /// + public override void RemoveObjects(ICollection modelObjects) { + + // We have to unselect any object that is about to be deleted + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + int i = this.GetObjectIndex(modelObject); + if (i >= 0) + indicesToRemove.Add(i); + } + + // Sort the indices from highest to lowest so that we + // remove latter ones before earlier ones. In this way, the + // indices of the rows doesn't change after the deletes. + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + + foreach (int i in indicesToRemove) + this.listView.SelectedIndices.Remove(i); + + // Remove the objects from the unfiltered list + foreach (object modelObject in modelObjects) + this.fullObjectList.Remove(modelObject); + + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void SetObjects(IEnumerable collection) { + ArrayList newObjects = ObjectListView.EnumerableToArray(collection, true); + + this.fullObjectList = newObjects; + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public override void UpdateObject(int index, object modelObject) { + if (index < 0 || index >= this.filteredObjectList.Count) + return; + + int i = this.fullObjectList.IndexOf(this.filteredObjectList[index]); + if (i < 0) + return; + + if (ReferenceEquals(this.fullObjectList[i], modelObject)) + return; + + this.fullObjectList[i] = modelObject; + this.filteredObjectList[index] = modelObject; + this.objectsToIndexMap[modelObject] = index; + } + + private ArrayList fullObjectList = new ArrayList(); + private ArrayList filteredObjectList = new ArrayList(); + private IModelFilter modelFilter; + private IListFilter listFilter; + + #endregion + + #region IFilterableDataSource Members + + /// + /// Apply the given filters to this data source. One or both may be null. + /// + /// + /// + public override void ApplyFilters(IModelFilter iModelFilter, IListFilter iListFilter) { + this.modelFilter = iModelFilter; + this.listFilter = iListFilter; + this.SetObjects(this.fullObjectList); + } + + #endregion + + #region Implementation + + /// + /// Gets the full list of objects being used for this fast list. + /// This list is unfiltered. + /// + public ArrayList ObjectList { + get { return fullObjectList; } + } + + /// + /// Gets the list of objects from ObjectList which survive any installed filters. + /// + public ArrayList FilteredObjectList { + get { return filteredObjectList; } + } + + /// + /// Rebuild the map that remembers which model object is displayed at which line + /// + protected void RebuildIndexMap() { + this.objectsToIndexMap.Clear(); + for (int i = 0; i < this.filteredObjectList.Count; i++) + this.objectsToIndexMap[this.filteredObjectList[i]] = i; + } + readonly Dictionary objectsToIndexMap = new Dictionary(); + + /// + /// Build our filtered list from our full list. + /// + protected void FilterObjects() { + + // If this list isn't filtered, we don't need to do anything else + if (!this.listView.UseFiltering) { + this.filteredObjectList = new ArrayList(this.fullObjectList); + return; + } + + // Tell the world to filter the objects. If they do so, don't do anything else + // ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(this.fullObjectList); + this.listView.OnFilter(args); + if (args.FilteredObjects != null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(args.FilteredObjects, false); + return; + } + + IEnumerable objects = (this.listFilter == null) ? + this.fullObjectList : this.listFilter.Filter(this.fullObjectList); + + // Apply the object filter if there is one + if (this.modelFilter == null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(objects, false); + } else { + this.filteredObjectList = new ArrayList(); + foreach (object model in objects) { + if (this.modelFilter.Filter(model)) + this.filteredObjectList.Add(model); + } + } + } + + #endregion + } + +} diff --git a/ObjectListView/Filtering/Cluster.cs b/ObjectListView/Filtering/Cluster.cs new file mode 100644 index 0000000..f90a84d --- /dev/null +++ b/ObjectListView/Filtering/Cluster.cs @@ -0,0 +1,125 @@ +/* + * Cluster - Implements a simple cluster + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// Concrete implementation of the ICluster interface. + /// + public class Cluster : ICluster { + + #region Life and death + + /// + /// Create a cluster + /// + /// The key for the cluster + public Cluster(object key) { + this.Count = 1; + this.ClusterKey = key; + } + + #endregion + + #region Public overrides + + /// + /// Return a string representation of this cluster + /// + /// + public override string ToString() { + return this.DisplayLabel ?? "[empty]"; + } + + #endregion + + #region Implementation of ICluster + + /// + /// Gets or sets how many items belong to this cluster + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + public string DisplayLabel { + get { return displayLabel; } + set { displayLabel = value; } + } + private string displayLabel; + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + public object ClusterKey { + get { return clusterKey; } + set { clusterKey = value; } + } + private object clusterKey; + + #endregion + + #region Implementation of IComparable + + /// + /// Return an indication of the ordering between this object and the given one + /// + /// + /// + public int CompareTo(object other) { + if (other == null || other == System.DBNull.Value) + return 1; + + ICluster otherCluster = other as ICluster; + if (otherCluster == null) + return 1; + + string keyAsString = this.ClusterKey as string; + if (keyAsString != null) + return String.Compare(keyAsString, otherCluster.ClusterKey as string, StringComparison.CurrentCultureIgnoreCase); + + IComparable keyAsComparable = this.ClusterKey as IComparable; + if (keyAsComparable != null) + return keyAsComparable.CompareTo(otherCluster.ClusterKey); + + return -1; + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClusteringStrategy.cs b/ObjectListView/Filtering/ClusteringStrategy.cs new file mode 100644 index 0000000..b2380f0 --- /dev/null +++ b/ObjectListView/Filtering/ClusteringStrategy.cs @@ -0,0 +1,189 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class provides a useful base implementation of a clustering + /// strategy where the clusters are grouped around the value of a given column. + /// + public class ClusteringStrategy : IClusteringStrategy { + + #region Static properties + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is null. It is exposed so it can be localized. + /// + static public string NULL_LABEL = "[null]"; + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is empty (i.e. a string of zero length). It is exposed so it can be localized. + /// + static public string EMPTY_LABEL = "[empty]"; + + /// + /// Gets or sets the format that will be used by default for clusters that only + /// contain 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + static public string DefaultDisplayLabelFormatSingular { + get { return defaultDisplayLabelFormatSingular; } + set { defaultDisplayLabelFormatSingular = value; } + } + static private string defaultDisplayLabelFormatSingular = "{0} ({1} item)"; + + /// + /// Gets or sets the format that will be used by default for clusters that + /// contain 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + static public string DefaultDisplayLabelFormatPlural { + get { return defaultDisplayLabelFormatPural; } + set { defaultDisplayLabelFormatPural = value; } + } + static private string defaultDisplayLabelFormatPural = "{0} ({1} items)"; + + #endregion + + #region Life and death + + /// + /// Create a clustering strategy + /// + public ClusteringStrategy() { + this.DisplayLabelFormatSingular = DefaultDisplayLabelFormatSingular; + this.DisplayLabelFormatPlural = DefaultDisplayLabelFormatPlural; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets the column upon which this strategy is operating + /// + public OLVColumn Column { + get { return column; } + set { column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains only 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatSingular will be used + public string DisplayLabelFormatSingular { + get { return displayLabelFormatSingular; } + set { displayLabelFormatSingular = value; } + } + private string displayLabelFormatSingular; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatPlural will be used + public string DisplayLabelFormatPlural { + get { return displayLabelFormatPural; } + set { displayLabelFormatPural = value; } + } + private string displayLabelFormatPural; + + #endregion + + #region ICluster implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + virtual public object GetClusterKey(object model) { + return this.Column.GetValue(model); + } + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + virtual public ICluster CreateCluster(object clusterKey) { + return new Cluster(clusterKey); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + virtual public string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ValueToString(cluster.ClusterKey) ?? NULL_LABEL; + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + virtual public IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new OneOfFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + /// + /// Create a label that combines the string representation of the cluster + /// key with a format string that holds an "X [N items in cluster]" type layout. + /// + /// + /// + /// + virtual protected string ApplyDisplayFormat(ICluster cluster, string s) { + string format = (cluster.Count == 1) ? this.DisplayLabelFormatSingular : this.DisplayLabelFormatPlural; + return String.IsNullOrEmpty(format) ? s : String.Format(format, s, cluster.Count); + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs new file mode 100644 index 0000000..ca95ecf --- /dev/null +++ b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs @@ -0,0 +1,70 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 1-April-2011 8:12am + * + * Change log: + * 2011-04-01 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class calculates clusters from the groups that the column uses. + /// + /// + /// + /// This is the default strategy for all non-date, filterable columns. + /// + /// + /// This class does not strictly mimic the groups created by the given column. + /// In particular, if the programmer changes the default grouping technique + /// by listening for grouping events, this class will not mimic that behaviour. + /// + /// + public class ClustersFromGroupsStrategy : ClusteringStrategy { + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + return this.Column.GetGroupKey(model); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ConvertGroupKeyToTitle(cluster.ClusterKey); + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + } +} diff --git a/ObjectListView/Filtering/DateTimeClusteringStrategy.cs b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs new file mode 100644 index 0000000..e0a864b --- /dev/null +++ b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs @@ -0,0 +1,187 @@ +/* + * DateTimeClusteringStrategy - A strategy to cluster objects by a date time + * + * Author: Phillip Piper + * Date: 30-March-2011 9:40am + * + * Change log: + * 2011-03-30 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// This enum is used to indicate various portions of a datetime + /// + [Flags] + public enum DateTimePortion { + /// + /// Year + /// + Year = 0x01, + + /// + /// Month + /// + Month = 0x02, + + /// + /// Day of the month + /// + Day = 0x04, + + /// + /// Hour + /// + Hour = 0x08, + + /// + /// Minute + /// + Minute = 0x10, + + /// + /// Second + /// + Second = 0x20 + } + + /// + /// This class implements a strategy where the model objects are clustered + /// according to some portion of the datetime value in the configured column. + /// + /// To create a strategy that grouped people who were born in + /// the same month, you would create a strategy that extracted just + /// the month, and formatted it to show just the month's name. Like this: + /// + /// + /// someColumn.ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Month, "MMMM"); + /// + public class DateTimeClusteringStrategy : ClusteringStrategy { + #region Life and death + + /// + /// Create a strategy that clusters by month/year + /// + public DateTimeClusteringStrategy() + : this(DateTimePortion.Year | DateTimePortion.Month, "MMMM yyyy") { + } + + /// + /// Create a strategy that clusters around the given parts + /// + /// + /// + public DateTimeClusteringStrategy(DateTimePortion portions, string format) { + this.Portions = portions; + this.Format = format; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the format string that will be used to create a user-presentable + /// version of the cluster key. + /// + /// The format should use the date/time format strings, as documented + /// in the Windows SDK. Both standard formats and custom format will work. + /// "D" - long date pattern + /// "MMMM, yyyy" - "January, 1999" + public string Format { + get { return format; } + set { format = value; } + } + private string format; + + /// + /// Gets or sets the parts of the DateTime that will be extracted when + /// determining the clustering key for an object. + /// + public DateTimePortion Portions { + get { return portions; } + set { portions = value; } + } + private DateTimePortion portions = DateTimePortion.Year | DateTimePortion.Month; + + #endregion + + #region IClusterStrategy implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + // Get the data attribute we want from the given model + // Make sure the returned value is a DateTime + DateTime? dateTime = this.Column.GetValue(model) as DateTime?; + if (!dateTime.HasValue) + return null; + + // Extract the parts of the datetime that we are interested in. + // Even if we aren't interested in a particular portion, we still have to give it a reasonable default + // otherwise we won't be able to build a DateTime object for it + int year = ((this.Portions & DateTimePortion.Year) == DateTimePortion.Year) ? dateTime.Value.Year : 1; + int month = ((this.Portions & DateTimePortion.Month) == DateTimePortion.Month) ? dateTime.Value.Month : 1; + int day = ((this.Portions & DateTimePortion.Day) == DateTimePortion.Day) ? dateTime.Value.Day : 1; + int hour = ((this.Portions & DateTimePortion.Hour) == DateTimePortion.Hour) ? dateTime.Value.Hour : 0; + int minute = ((this.Portions & DateTimePortion.Minute) == DateTimePortion.Minute) ? dateTime.Value.Minute : 0; + int second = ((this.Portions & DateTimePortion.Second) == DateTimePortion.Second) ? dateTime.Value.Second : 0; + + return new DateTime(year, month, day, hour, minute, second); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + DateTime? dateTime = cluster.ClusterKey as DateTime?; + + return this.ApplyDisplayFormat(cluster, dateTime.HasValue ? this.DateToString(dateTime.Value) : NULL_LABEL); + } + + /// + /// Convert the given date into a user presentable string + /// + /// + /// + protected virtual string DateToString(DateTime dateTime) { + if (String.IsNullOrEmpty(this.Format)) + return dateTime.ToString(CultureInfo.CurrentUICulture); + + try { + return dateTime.ToString(this.Format); + } + catch (FormatException) { + return String.Format("Bad format string '{0}' for value '{1}'", this.Format, dateTime); + } + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/FilterMenuBuilder.cs b/ObjectListView/Filtering/FilterMenuBuilder.cs new file mode 100644 index 0000000..e91614a --- /dev/null +++ b/ObjectListView/Filtering/FilterMenuBuilder.cs @@ -0,0 +1,369 @@ +/* + * FilterMenuBuilder - Responsible for creating a Filter menu + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-20 JPP - Allow the same model object to be in multiple clusters + * Useful for xor'ed flag fields, and multi-value strings + * (e.g. hobbies that are stored as comma separated values). + * v2.5.1 + * 2012-04-14 JPP - Fixed rare bug with clustering an empty list (SF #3445118) + * v2.5 + * 2011-04-12 JPP - Added some images to menu + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Collections; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class know how to build a Filter menu. + /// It is responsible for clustering the values in the target column, + /// build a menu that shows those clusters, and then constructing + /// a filter that will enact the users choices. + /// + /// + /// Almost all of the methods in this class are declared as "virtual protected" + /// so that subclasses can provide alternative behaviours. + /// + public class FilterMenuBuilder { + + #region Static properties + + /// + /// Gets or sets the string that labels the Apply button. + /// Exposed so it can be localized. + /// + static public string APPLY_LABEL = "Apply"; + + /// + /// Gets or sets the string that labels the Clear All menu item. + /// Exposed so it can be localized. + /// + static public string CLEAR_ALL_FILTERS_LABEL = "Clear All Filters"; + + /// + /// Gets or sets the string that labels the Filtering menu as a whole.. + /// Exposed so it can be localized. + /// + static public string FILTERING_LABEL = "Filtering"; + + /// + /// Gets or sets the string that represents Select All values. + /// If this is set to null or empty, no Select All option will be included. + /// Exposed so it can be localized. + /// + static public string SELECT_ALL_LABEL = "Select All"; + + /// + /// Gets or sets the image that will be placed next to the Clear Filtering menu item + /// + static public Bitmap ClearFilteringImage = BrightIdeasSoftware.Properties.Resources.ClearFiltering; + + /// + /// Gets or sets the image that will be placed next to all "Apply" menu items on the filtering menu + /// + static public Bitmap FilteringImage = BrightIdeasSoftware.Properties.Resources.Filtering; + + #endregion + + #region Public properties + + /// + /// Gets or sets whether null should be considered as a valid data value. + /// If this is true (the default), then a cluster will null as a key will be allow. + /// If this is false, object that return a cluster key of null will ignored. + /// + public bool TreatNullAsDataValue { + get { return treatNullAsDataValue; } + set { treatNullAsDataValue = value; } + } + private bool treatNullAsDataValue = true; + + /// + /// Gets or sets the maximum number of objects that the clustering strategy + /// will consider. This should be large enough to collect all unique clusters, + /// but small enough to finish in a reasonable time. + /// + /// The default value is 10,000. This should be perfectly + /// acceptable for almost all lists. + public int MaxObjectsToConsider { + get { return maxObjectsToConsider; } + set { maxObjectsToConsider = value; } + } + private int maxObjectsToConsider = 10000; + + #endregion + + /// + /// Create a Filter menu on the given tool tip for the given column in the given ObjectListView. + /// + /// This is the main entry point into this class. + /// + /// + /// + /// The strip that should be shown to the user + virtual public ToolStripDropDown MakeFilterMenu(ToolStripDropDown strip, ObjectListView listView, OLVColumn column) { + if (strip == null) throw new ArgumentNullException("strip"); + if (listView == null) throw new ArgumentNullException("listView"); + if (column == null) throw new ArgumentNullException("column"); + + if (!column.UseFiltering || column.ClusteringStrategy == null || listView.Objects == null) + return strip; + + List clusters = this.Cluster(column.ClusteringStrategy, listView, column); + if (clusters.Count > 0) { + this.SortClusters(column.ClusteringStrategy, clusters); + strip.Items.Add(this.CreateFilteringMenuItem(column, clusters)); + } + + return strip; + } + + /// + /// Create a collection of clusters that should be presented to the user + /// + /// + /// + /// + /// + virtual protected List Cluster(IClusteringStrategy strategy, ObjectListView listView, OLVColumn column) { + // Build a map that correlates cluster key to clusters + NullableDictionary map = new NullableDictionary(); + int count = 0; + foreach (object model in listView.ObjectsForClustering) { + this.ClusterOneModel(strategy, map, model); + + if (count++ > this.MaxObjectsToConsider) + break; + } + + // Now that we know exactly how many items are in each cluster, create a label for it + foreach (ICluster cluster in map.Values) + cluster.DisplayLabel = strategy.GetClusterDisplayLabel(cluster); + + return new List(map.Values); + } + + private void ClusterOneModel(IClusteringStrategy strategy, NullableDictionary map, object model) { + object clusterKey = strategy.GetClusterKey(model); + + // If the returned value is an IEnumerable, that means the given model can belong to more than one cluster + IEnumerable keyEnumerable = clusterKey as IEnumerable; + if (clusterKey is string || keyEnumerable == null) + keyEnumerable = new object[] {clusterKey}; + + // Deal with nulls and DBNulls + ArrayList nullCorrected = new ArrayList(); + foreach (object key in keyEnumerable) { + if (key == null || key == System.DBNull.Value) { + if (this.TreatNullAsDataValue) + nullCorrected.Add(null); + } else nullCorrected.Add(key); + } + + // Group by key + foreach (object key in nullCorrected) { + if (map.ContainsKey(key)) + map[key].Count += 1; + else + map[key] = strategy.CreateCluster(key); + } + } + + /// + /// Order the given list of clusters in the manner in which they should be presented to the user. + /// + /// + /// + virtual protected void SortClusters(IClusteringStrategy strategy, List clusters) { + clusters.Sort(); + } + + /// + /// Do the work of making a menu that shows the clusters to the users + /// + /// + /// + /// + virtual protected ToolStripMenuItem CreateFilteringMenuItem(OLVColumn column, List clusters) { + ToolStripCheckedListBox checkedList = new ToolStripCheckedListBox(); + checkedList.Tag = column; + foreach (ICluster cluster in clusters) + checkedList.AddItem(cluster, column.ValuesChosenForFiltering.Contains(cluster.ClusterKey)); + if (!String.IsNullOrEmpty(SELECT_ALL_LABEL)) { + int checkedCount = checkedList.CheckedItems.Count; + if (checkedCount == 0) + checkedList.AddItem(SELECT_ALL_LABEL, CheckState.Unchecked); + else + checkedList.AddItem(SELECT_ALL_LABEL, checkedCount == clusters.Count ? CheckState.Checked : CheckState.Indeterminate); + } + checkedList.ItemCheck += new ItemCheckEventHandler(HandleItemCheckedWrapped); + + ToolStripMenuItem clearAll = new ToolStripMenuItem(CLEAR_ALL_FILTERS_LABEL, ClearFilteringImage, delegate(object sender, EventArgs args) { + this.ClearAllFilters(column); + }); + ToolStripMenuItem apply = new ToolStripMenuItem(APPLY_LABEL, FilteringImage, delegate(object sender, EventArgs args) { + this.EnactFilter(checkedList, column); + }); + ToolStripMenuItem subMenu = new ToolStripMenuItem(FILTERING_LABEL, null, new ToolStripItem[] { + clearAll, new ToolStripSeparator(), checkedList, apply }); + return subMenu; + } + + /// + /// Wrap a protected section around the real HandleItemChecked method, so that if + /// that method tries to change a "checkedness" of an item, we don't get a recursive + /// stack error. Effectively, this ensure that HandleItemChecked is only called + /// in response to a user action. + /// + /// + /// + private void HandleItemCheckedWrapped(object sender, ItemCheckEventArgs e) { + if (alreadyInHandleItemChecked) + return; + + try { + alreadyInHandleItemChecked = true; + this.HandleItemChecked(sender, e); + } + finally { + alreadyInHandleItemChecked = false; + } + } + bool alreadyInHandleItemChecked = false; + + /// + /// Handle a user-generated ItemCheck event + /// + /// + /// + virtual protected void HandleItemChecked(object sender, ItemCheckEventArgs e) { + + ToolStripCheckedListBox checkedList = sender as ToolStripCheckedListBox; + if (checkedList == null) return; + OLVColumn column = checkedList.Tag as OLVColumn; + if (column == null) return; + ObjectListView listView = column.ListView as ObjectListView; + if (listView == null) return; + + // Deal with the "Select All" item if there is one + int selectAllIndex = checkedList.Items.IndexOf(SELECT_ALL_LABEL); + if (selectAllIndex >= 0) + HandleSelectAllItem(e, checkedList, selectAllIndex); + } + + /// + /// Handle any checking/unchecking of the Select All option, and keep + /// its checkedness in sync with everything else that is checked. + /// + /// + /// + /// + virtual protected void HandleSelectAllItem(ItemCheckEventArgs e, ToolStripCheckedListBox checkedList, int selectAllIndex) { + // Did they check/uncheck the "Select All"? + if (e.Index == selectAllIndex) { + if (e.NewValue == CheckState.Checked) + checkedList.CheckAll(); + if (e.NewValue == CheckState.Unchecked) + checkedList.UncheckAll(); + return; + } + + // OK. The user didn't check/uncheck SelectAll. Now we have to update it's + // checkedness to reflect the state of everything else + // If all clusters are checked, we check the Select All. + // If no clusters are checked, the uncheck the Select All. + // For everything else, Select All is set to indeterminate. + + // How many items are currently checked? + int count = checkedList.CheckedItems.Count; + + // First complication. + // The value of the Select All itself doesn't count + if (checkedList.GetItemCheckState(selectAllIndex) != CheckState.Unchecked) + count -= 1; + + // Another complication. + // CheckedItems does not yet know about the item the user has just + // clicked, so we have to adjust the count of checked items to what + // it is going to be + if (e.NewValue != e.CurrentValue) { + if (e.NewValue == CheckState.Checked) + count += 1; + else + count -= 1; + } + + // Update the state of the Select All item + if (count == 0) + checkedList.SetItemState(selectAllIndex, CheckState.Unchecked); + else if (count == checkedList.Items.Count - 1) + checkedList.SetItemState(selectAllIndex, CheckState.Checked); + else + checkedList.SetItemState(selectAllIndex, CheckState.Indeterminate); + } + + /// + /// Clear all the filters that are applied to the given column + /// + /// The column from which filters are to be removed + virtual protected void ClearAllFilters(OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + olv.ResetColumnFiltering(); + } + + /// + /// Apply the selected values from the given list as a filter on the given column + /// + /// A list in which the checked items should be used as filters + /// The column for which a filter should be generated + virtual protected void EnactFilter(ToolStripCheckedListBox checkedList, OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + // Collect all the checked values + ArrayList chosenValues = new ArrayList(); + foreach (object x in checkedList.CheckedItems) { + ICluster cluster = x as ICluster; + if (cluster != null) { + chosenValues.Add(cluster.ClusterKey); + } + } + column.ValuesChosenForFiltering = chosenValues; + + olv.UpdateColumnFiltering(); + } + } +} diff --git a/ObjectListView/Filtering/Filters.cs b/ObjectListView/Filtering/Filters.cs new file mode 100644 index 0000000..db69a62 --- /dev/null +++ b/ObjectListView/Filtering/Filters.cs @@ -0,0 +1,489 @@ +/* + * Filters - Filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 03/03/2010 17:00 + * + * Change log: + * 2011-03-01 JPP Added CompositeAllFilter, CompositeAnyFilter and OneOfFilter + * v2.4.1 + * 2010-06-23 JPP Extended TextMatchFilter to handle regular expressions and string prefix matching. + * v2.4 + * 2010-03-03 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Drawing; + +namespace BrightIdeasSoftware +{ + /// + /// Interface for model-by-model filtering + /// + public interface IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + bool Filter(object modelObject); + } + + /// + /// Interface for whole list filtering + /// + public interface IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + IEnumerable Filter(IEnumerable modelObjects); + } + + /// + /// Base class for model-by-model filters + /// + public class AbstractModelFilter : IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + virtual public bool Filter(object modelObject) { + return true; + } + } + + /// + /// This filter calls a given Predicate to decide if a model object should be included + /// + public class ModelFilter : IModelFilter + { + /// + /// Create a filter based on the given predicate + /// + /// The function that will filter objects + public ModelFilter(Predicate predicate) { + this.Predicate = predicate; + } + + /// + /// Gets or sets the predicate used to filter model objects + /// + protected Predicate Predicate { + get { return predicate; } + set { predicate = value; } + } + private Predicate predicate; + + /// + /// Should the given model object be included? + /// + /// + /// + virtual public bool Filter(object modelObject) { + return this.Predicate == null ? true : this.Predicate(modelObject); + } + } + + /// + /// A CompositeFilter joins several other filters together. + /// If there are no filters, all model objects are included + /// + abstract public class CompositeFilter : IModelFilter { + + /// + /// Create an empty filter + /// + public CompositeFilter() { + } + + /// + /// Create a composite filter from the given list of filters + /// + /// A list of filters + public CompositeFilter(IEnumerable filters) { + foreach (IModelFilter filter in filters) { + if (filter != null) + Filters.Add(filter); + } + } + + /// + /// Gets or sets the filters used by this composite + /// + public IList Filters { + get { return filters; } + set { filters = value; } + } + private IList filters = new List(); + + /// + /// Get the sub filters that are text match filters + /// + public IEnumerable TextFilters { + get { + foreach (IModelFilter filter in this.Filters) { + TextMatchFilter textFilter = filter as TextMatchFilter; + if (textFilter != null) + yield return textFilter; + } + } + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// + /// True if the object is included by the filter + virtual public bool Filter(object modelObject) { + if (this.Filters == null || this.Filters.Count == 0) + return true; + + return this.FilterObject(modelObject); + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + abstract public bool FilterObject(object modelObject); + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must satisfy all filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAllFilter : CompositeFilter { + + /// + /// Create a filter + /// + /// + public CompositeAllFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (!filter.Filter(modelObject)) + return false; + + return true; + } + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must only satisfy one of the filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAnyFilter : CompositeFilter { + + /// + /// Create a filter from the given filters + /// + /// + public CompositeAnyFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (filter.Filter(modelObject)) + return true; + + return false; + } + } + + /// + /// Instances of this class extract a value from the model object + /// and compare that value to a list of fixed values. The model + /// object is included if the extracted value is in the list + /// + /// If there is no delegate installed or there are + /// no values to match, no model objects will be matched + public class OneOfFilter : IModelFilter { + + /// + /// Create a filter that will use the given delegate to extract values + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter) : + this(valueGetter, new ArrayList()) { + } + + /// + /// Create a filter that will extract values using the given delegate + /// and compare them to the values in the given list. + /// + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) { + this.ValueGetter = valueGetter; + this.PossibleValues = new ArrayList(possibleValues); + } + + /// + /// Gets or sets the delegate that will be used to extract values + /// from model objects + /// + virtual public AspectGetterDelegate ValueGetter { + get { return valueGetter; } + set { valueGetter = value; } + } + private AspectGetterDelegate valueGetter; + + /// + /// Gets or sets the list of values that the value extracted from + /// the model object must match in order to be included. + /// + virtual public IList PossibleValues { + get { return possibleValues; } + set { possibleValues = value; } + } + private IList possibleValues; + + /// + /// Should the given model object be included? + /// + /// + /// + public virtual bool Filter(object modelObject) { + if (this.ValueGetter == null || this.PossibleValues == null || this.PossibleValues.Count == 0) + return false; + + object result = this.ValueGetter(modelObject); + IEnumerable enumerable = result as IEnumerable; + if (result is string || enumerable == null) + return this.DoesValueMatch(result); + + foreach (object x in enumerable) { + if (this.DoesValueMatch(x)) + return true; + } + return false; + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected virtual bool DoesValueMatch(object result) { + return this.PossibleValues.Contains(result); + } + } + + /// + /// Instances of this class match a property of a model objects against + /// a list of bit flags. The property should be an xor-ed collection + /// of bits flags. + /// + /// Both the property compared and the list of possible values + /// must be convertible to ulongs. + public class FlagBitSetFilter : OneOfFilter { + + /// + /// Create an instance + /// + /// + /// + public FlagBitSetFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) : base(valueGetter, possibleValues) { + this.ConvertPossibleValues(); + } + + /// + /// Gets or sets the collection of values that will be matched. + /// These must be ulongs (or convertible to ulongs). + /// + public override IList PossibleValues { + get { return base.PossibleValues; } + set { + base.PossibleValues = value; + this.ConvertPossibleValues(); + } + } + + private void ConvertPossibleValues() { + this.possibleValuesAsUlongs = new List(); + foreach (object x in this.PossibleValues) + this.possibleValuesAsUlongs.Add(Convert.ToUInt64(x)); + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected override bool DoesValueMatch(object result) { + try { + UInt64 value = Convert.ToUInt64(result); + foreach (ulong flag in this.possibleValuesAsUlongs) { + if ((value & flag) == flag) + return true; + } + return false; + } + catch (InvalidCastException) { + return false; + } + catch (FormatException) { + return false; + } + } + + private List possibleValuesAsUlongs = new List(); + } + + /// + /// Base class for whole list filters + /// + public class AbstractListFilter : IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + virtual public IEnumerable Filter(IEnumerable modelObjects) { + return modelObjects; + } + } + + /// + /// Instance of this class implement delegate based whole list filtering + /// + public class ListFilter : AbstractListFilter + { + /// + /// A delegate that filters on a whole list + /// + /// + /// + public delegate IEnumerable ListFilterDelegate(IEnumerable rowObjects); + + /// + /// Create a ListFilter + /// + /// + public ListFilter(ListFilterDelegate function) { + this.Function = function; + } + + /// + /// Gets or sets the delegate that will filter the list + /// + public ListFilterDelegate Function { + get { return function; } + set { function = value; } + } + private ListFilterDelegate function; + + /// + /// Do the actual work of filtering + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Function == null) + return modelObjects; + + return this.Function(modelObjects); + } + } + + /// + /// Filter the list so only the last N entries are displayed + /// + public class TailFilter : AbstractListFilter + { + /// + /// Create a no-op tail filter + /// + public TailFilter() { + } + + /// + /// Create a filter that includes on the last N model objects + /// + /// + public TailFilter(int numberOfObjects) { + this.Count = numberOfObjects; + } + + /// + /// Gets or sets the number of model objects that will be + /// returned from the tail of the list + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Return the last N subset of the model objects + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Count <= 0) + return modelObjects; + + ArrayList list = ObjectListView.EnumerableToArray(modelObjects, false); + + if (this.Count > list.Count) + return list; + + object[] tail = new object[this.Count]; + list.CopyTo(list.Count - this.Count, tail, 0, this.Count); + return new ArrayList(tail); + } + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/FlagClusteringStrategy.cs b/ObjectListView/Filtering/FlagClusteringStrategy.cs new file mode 100644 index 0000000..519ce89 --- /dev/null +++ b/ObjectListView/Filtering/FlagClusteringStrategy.cs @@ -0,0 +1,160 @@ +/* + * FlagClusteringStrategy - Implements a clustering strategy for a field which is a single integer + * containing an XOR'ed collection of bit flags + * + * Author: Phillip Piper + * Date: 23-March-2012 8:33 am + * + * Change log: + * 2012-03-23 JPP - First version + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class cluster model objects on the basis of a + /// property that holds an xor-ed collection of bit flags. + /// + public class FlagClusteringStrategy : ClusteringStrategy + { + #region Life and death + + /// + /// Create a clustering strategy that operates on the flags of the given enum + /// + /// + public FlagClusteringStrategy(Type enumType) { + if (enumType == null) throw new ArgumentNullException("enumType"); + if (!enumType.IsEnum) throw new ArgumentException("Type must be enum", "enumType"); + if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false) == null) throw new ArgumentException("Type must have [Flags] attribute", "enumType"); + + List flags = new List(); + foreach (object x in Enum.GetValues(enumType)) + flags.Add(Convert.ToInt64(x)); + + List flagLabels = new List(); + foreach (string x in Enum.GetNames(enumType)) + flagLabels.Add(x); + + this.SetValues(flags.ToArray(), flagLabels.ToArray()); + } + + /// + /// Create a clustering strategy around the given collections of flags and their display labels. + /// There must be the same number of elements in both collections. + /// + /// The list of flags. + /// + public FlagClusteringStrategy(long[] values, string[] labels) { + this.SetValues(values, labels); + } + + #endregion + + #region Implementation + + /// + /// Gets the value that will be xor-ed to test for the presence of a particular value. + /// + public long[] Values { + get { return this.values; } + private set { this.values = value; } + } + private long[] values; + + /// + /// Gets the labels that will be used when the corresponding Value is XOR present in the data. + /// + public string[] Labels { + get { return this.labels; } + private set { this.labels = value; } + } + private string[] labels; + + private void SetValues(long[] flags, string[] flagLabels) { + if (flags == null || flags.Length == 0) throw new ArgumentNullException("flags"); + if (flagLabels == null || flagLabels.Length == 0) throw new ArgumentNullException("flagLabels"); + if (flags.Length != flagLabels.Length) throw new ArgumentException("values and labels must have the same number of entries", "flags"); + + this.Values = flags; + this.Labels = flagLabels; + } + + #endregion + + #region Implementation of IClusteringStrategy + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + List flags = new List(); + try { + long modelValue = Convert.ToInt64(this.Column.GetValue(model)); + foreach (long x in this.Values) { + if ((x & modelValue) == x) + flags.Add(x); + } + return flags; + } + catch (InvalidCastException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + catch (FormatException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + long clusterKeyAsUlong = Convert.ToInt64(cluster.ClusterKey); + for (int i = 0; i < this.Values.Length; i++ ) { + if (clusterKeyAsUlong == this.Values[i]) + return this.ApplyDisplayFormat(cluster, this.Labels[i]); + } + return this.ApplyDisplayFormat(cluster, clusterKeyAsUlong.ToString(CultureInfo.CurrentUICulture)); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + public override IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new FlagBitSetFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/ICluster.cs b/ObjectListView/Filtering/ICluster.cs new file mode 100644 index 0000000..3196595 --- /dev/null +++ b/ObjectListView/Filtering/ICluster.cs @@ -0,0 +1,56 @@ +/* + * ICluster - A cluster is a group of objects that can be included or excluded as a whole + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// A cluster is a like collection of objects that can be usefully filtered + /// as whole using the filtering UI provided by the ObjectListView. + /// + public interface ICluster : IComparable { + /// + /// Gets or sets how many items belong to this cluster + /// + int Count { get; set; } + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + string DisplayLabel { get; set; } + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + object ClusterKey { get; set; } + } +} diff --git a/ObjectListView/Filtering/IClusteringStrategy.cs b/ObjectListView/Filtering/IClusteringStrategy.cs new file mode 100644 index 0000000..fb6a4e2 --- /dev/null +++ b/ObjectListView/Filtering/IClusteringStrategy.cs @@ -0,0 +1,80 @@ +/* + * IClusterStrategy - Encapsulates the ability to create a list of clusters from an ObjectListView + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-23 JPP - Added CreateFilter() method to interface to allow the strategy + * to control the actual model filter that is created. + * v2.5 + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware{ + + /// + /// Implementation of this interface control the selecting of cluster keys + /// and how those clusters will be presented to the user + /// + public interface IClusteringStrategy { + + /// + /// Gets or sets the column upon which this strategy will operate + /// + OLVColumn Column { get; set; } + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// If the returned value is an IEnumerable, the given model is considered + /// to belong to multiple clusters + /// + /// + object GetClusterKey(object model); + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + ICluster CreateCluster(object clusterKey); + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + string GetClusterDisplayLabel(ICluster cluster); + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + IModelFilter CreateFilter(IList valuesChosenForFiltering); + } +} diff --git a/ObjectListView/Filtering/TextMatchFilter.cs b/ObjectListView/Filtering/TextMatchFilter.cs new file mode 100644 index 0000000..8df3719 --- /dev/null +++ b/ObjectListView/Filtering/TextMatchFilter.cs @@ -0,0 +1,642 @@ +/* + * TextMatchFilter - Text based filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 31/05/2011 7:45am + * + * Change log: + * 2018-05-01 JPP - Added ITextMatchFilter to allow for alternate implementations + * - Made several classes public so they can be subclassed + * v2.6 + * 2012-10-13 JPP Allow filtering to consider additional columns + * v2.5.1 + * 2011-06-22 JPP Handle searching for empty strings + * v2.5.0 + * 2011-05-31 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using System.Drawing; + +namespace BrightIdeasSoftware { + + public interface ITextMatchFilter: IModelFilter { + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + IEnumerable FindAllMatchedRanges(string cellText); + } + + /// + /// Instances of this class include only those rows of the listview + /// that match one or more given strings. + /// + /// This class can match strings by prefix, regex, or simple containment. + /// There are factory methods for each of these matching strategies. + public class TextMatchFilter : AbstractModelFilter, ITextMatchFilter { + + #region Life and death + + /// + /// Create a text filter that will include rows where any cell matches + /// any of the given regex expressions. + /// + /// + /// + /// + /// Any string that is not a valid regex expression will be ignored. + public static TextMatchFilter Regex(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.RegexStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell begins with one of the given strings + /// + /// + /// + /// + public static TextMatchFilter Prefix(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.PrefixStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell contains any of the given strings. + /// + /// + /// + /// + public static TextMatchFilter Contains(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.ContainsStrings = texts; + return filter; + } + + /// + /// Create a TextFilter + /// + /// + public TextMatchFilter(ObjectListView olv) { + this.ListView = olv; + } + + /// + /// Create a TextFilter that finds the given string + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + } + + /// + /// Create a TextFilter that finds the given string using the given comparison + /// + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text, StringComparison comparison) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + this.StringComparison = comparison; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets which columns will be used for the comparisons? If this is null, all columns will be used + /// + public OLVColumn[] Columns { + get { return columns; } + set { columns = value; } + } + private OLVColumn[] columns; + + /// + /// Gets or sets additional columns which will be used in the comparison. These will be used + /// in addition to either the Columns property or to all columns taken from the control. + /// + public OLVColumn[] AdditionalColumns { + get { return additionalColumns; } + set { additionalColumns = value; } + } + private OLVColumn[] additionalColumns; + + /// + /// Gets or sets the collection of strings that will be used for + /// contains matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable ContainsStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextContainsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets whether or not this filter has any search criteria + /// + public bool HasComponents { + get { + return this.MatchingStrategies.Count > 0; + } + } + + /// + /// Gets or set the ObjectListView upon which this filter will work + /// + /// + /// You cannot really rebase a filter after it is created, so do not change this value. + /// It is included so that it can be set in an object initialiser. + /// + public ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the collection of strings that will be used for + /// prefix matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable PrefixStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextBeginsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + /// + /// This is only used when doing Regex matching (obviously). + /// If this is not set specifically, the appropriate options are chosen to match the + /// StringComparison setting (culture invariant, case sensitive). + /// + public RegexOptions RegexOptions { + get { + if (!regexOptions.HasValue) { + switch (this.StringComparison) { + case StringComparison.CurrentCulture: + regexOptions = RegexOptions.None; + break; + case StringComparison.CurrentCultureIgnoreCase: + regexOptions = RegexOptions.IgnoreCase; + break; + case StringComparison.Ordinal: + case StringComparison.InvariantCulture: + regexOptions = RegexOptions.CultureInvariant; + break; + case StringComparison.OrdinalIgnoreCase: + case StringComparison.InvariantCultureIgnoreCase: + regexOptions = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + break; + default: + regexOptions = RegexOptions.None; + break; + } + } + return regexOptions.Value; + } + set { + regexOptions = value; + } + } + private RegexOptions? regexOptions; + + /// + /// Gets or sets the collection of strings that will be used for + /// regex pattern matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable RegexStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextRegexMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.stringComparison; } + set { this.stringComparison = value; } + } + private StringComparison stringComparison = StringComparison.InvariantCultureIgnoreCase; + + #endregion + + #region Implementation + + /// + /// Loop over the columns that are being considering by the filter + /// + /// + protected virtual IEnumerable IterateColumns() { + if (this.Columns == null) { + foreach (OLVColumn column in this.ListView.Columns) + yield return column; + } else { + foreach (OLVColumn column in this.Columns) + yield return column; + } + if (this.AdditionalColumns != null) { + foreach (OLVColumn column in this.AdditionalColumns) + yield return column; + } + } + + #endregion + + #region Public interface + + /// + /// Do the actual work of filtering + /// + /// + /// + public override bool Filter(object modelObject) { + if (this.ListView == null || !this.HasComponents) + return true; + + foreach (OLVColumn column in this.IterateColumns()) { + if (column.IsVisible && column.Searchable) { + string[] cellTexts = column.GetSearchValues(modelObject); + if (cellTexts != null && cellTexts.Length > 0) { + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (String.IsNullOrEmpty(filter.Text)) + return true; + foreach (string cellText in cellTexts) { + if (filter.MatchesText(cellText)) + return true; + } + } + } + } + } + + return false; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + public IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (!String.IsNullOrEmpty(filter.Text)) + ranges.AddRange(filter.FindAllMatchedRanges(cellText)); + } + + return ranges; + } + + /// + /// Is the given column one of the columns being used by this filter? + /// + /// + /// + public bool IsIncluded(OLVColumn column) { + if (this.Columns == null) { + return column.ListView == this.ListView; + } + + foreach (OLVColumn x in this.Columns) { + if (x == column) + return true; + } + + return false; + } + + #endregion + + #region Implementation members + + protected List MatchingStrategies = new List(); + + #endregion + + #region Components + + /// + /// Base class for the various types of string matching that TextMatchFilter provides + /// + public abstract class TextMatchingStrategy { + + /// + /// Gets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.TextFilter.StringComparison; } + } + + /// + /// Gets the text filter to which this component belongs + /// + public TextMatchFilter TextFilter { + get { return textFilter; } + set { textFilter = value; } + } + private TextMatchFilter textFilter; + + /// + /// Gets or sets the text that will be matched + /// + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public abstract IEnumerable FindAllMatchedRanges(string cellText); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public abstract bool MatchesText(string cellText); + } + + /// + /// This component provides text contains matching strategy. + /// + public class TextContainsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text contains strategy + /// + /// + /// + public TextContainsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.IndexOf(this.Text, this.StringComparison) != -1; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + int matchIndex = cellText.IndexOf(this.Text, this.StringComparison); + while (matchIndex != -1) { + ranges.Add(new CharacterRange(matchIndex, this.Text.Length)); + matchIndex = cellText.IndexOf(this.Text, matchIndex + this.Text.Length, this.StringComparison); + } + + return ranges; + } + } + + /// + /// This component provides text begins with matching strategy. + /// + public class TextBeginsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text begins strategy + /// + /// + /// + public TextBeginsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.StartsWith(this.Text, this.StringComparison); + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (cellText.StartsWith(this.Text, this.StringComparison)) + ranges.Add(new CharacterRange(0, this.Text.Length)); + + return ranges; + } + + } + + /// + /// This component provides regex matching strategy. + /// + public class TextRegexMatchingStrategy : TextMatchingStrategy { + + /// + /// Creates a regex strategy + /// + /// + /// + public TextRegexMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + public RegexOptions RegexOptions { + get { + return this.TextFilter.RegexOptions; + } + } + + /// + /// Gets or sets a compiled regular expression, based on our current Text and RegexOptions. + /// + /// + /// If Text fails to compile as a regular expression, this will return a Regex object + /// that will match all strings. + /// + protected Regex Regex { + get { + if (this.regex == null) { + try { + this.regex = new Regex(this.Text, this.RegexOptions); + } + catch (ArgumentException) { + this.regex = TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + return this.regex; + } + set { + this.regex = value; + } + } + private Regex regex; + + /// + /// Gets whether or not our current regular expression is a valid regex + /// + protected bool IsRegexInvalid { + get { + return this.Regex == TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + private static Regex InvalidRegexMarker = new Regex(".*"); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + if (this.IsRegexInvalid) + return true; + return this.Regex.Match(cellText).Success; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (!this.IsRegexInvalid) { + foreach (Match match in this.Regex.Matches(cellText)) { + if (match.Length > 0) + ranges.Add(new CharacterRange(match.Index, match.Length)); + } + } + + return ranges; + } + } + + #endregion + } +} diff --git a/ObjectListView/FullClassDiagram.cd b/ObjectListView/FullClassDiagram.cd new file mode 100644 index 0000000..3126de2 --- /dev/null +++ b/ObjectListView/FullClassDiagram.cd @@ -0,0 +1,1261 @@ + + + + + + AQCABIAAAIAhAACgAAAAAIAMAAAECAAggAIAIIAAAEA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAAAAAAAAAAQEIAAEAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAQIAAABAQAAQAAgAAAAAAABAIAAAAQAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + ABgAAAAAAAAAAgIhAAACAAAEAAAAAAAAAAAAAAAAAAA= + DataListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + BAAAAAAAAAAAAAAAAQAAAAAQAAAQEAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAMAAAAA= + DragDrop\DropSink.cs + + + + + + + ZS0gAiQEBAoQDA8YQBMAMCAFgwQHBALcAEBEiEAAAQA= + DragDrop\DropSink.cs + + + + + + BYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + IACgGiAAIBoAAAAAAAAAAAAAAALAAAAKgAQECIAEgAA= + DragDrop\DropSink.cs + + + + + + BAEAAAAAAAAAAAAAAAEQAAAAAAAAAAIAAAAAgAQAAEA= + DragDrop\DropSink.cs + + + + + + AQAAEAEABAAAAAAAEAAAAAAAAAIAAgACgAAAAAAAQBA= + DragDrop\OLVDataObject.cs + + + + + + AAAAAAAAAAAAAgIAAAACAAAEQAAAAAAAAAAAAAAAAAA= + FastDataListView.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEQAAAAAAAAAAA= + FastObjectListView.cs + + + + + + ABAAAAgAQAQAABAgAAASQ4AQAAIEAAAAAAAAAEIAgAA= + FastObjectListView.cs + + + + + + AAAAAAAQAAAAEAQEBAAAAAQAgAAAAIAAAAAAAAAAAAA= + Filtering\Cluster.cs + + + + + + + AAAAAAAEAAAAAAAAAhBABAgAQAAIKAQBAQAAAAAAoIA= + Filtering\ClusteringStrategy.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQBAAAAAAAAAAA= + Filtering\ClustersFromGroupsStrategy.cs + + + + + + AAAAAAIAAAACAAAAAAAACAAAAQgAAAQBAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + SAEAADAQgEEAAQAIAAgQIAAAAFQAAAAAAAAAoAAAAAE= + Filtering\FilterMenuBuilder.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAEAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAIAAAACAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAAAAAAAAgAAAAIAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAABAAAAAQAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAgAAACAAAABAAABAAgAQACABABAAAAyEIAAIgSgAA= + Filtering\TextMatchFilter.cs + + + + + + EgAAQTAAZAEgWGAASFwIIEYECGBGAQKAQEEGAQJAAEE= + Implementation\Attributes.cs + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AZggAAAwAGAAAgACQAYCBCAEICACACUEhAEAQKBAgQg= + Implementation\DataSourceAdapter.cs + + + + + + + 5/7+//3///fX/+//+///f/3//f/37N////+//7+///8= + Implementation\Enums.cs + + + + + + + ASgQyXBAABICBAAAAIAAACCEMAKBQAOAABDAgAUpAQA= + Implementation\Events.cs + + + + + + ABEAEAAFQAAAABAABABQEAQAQAAAECAAAAAgAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAABAAAIAAAAAAAAAEAAAQAAAAABAAAAAAAABAAIAA= + Implementation\Events.cs + + + + + + AAQABAAAAAQQAAAAAAEAAAQAAAAABAAAAAAgABQAIAE= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAEAAAAAAAAAAAAEAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAEAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAQAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAgAAAAIAAAAAAAAAAAAgAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAQAAAIAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAEA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAQAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAMABAAAAQgAZAFAAGUARAAAAAgAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + CAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAQAAAAAAAEGAAAAAAAAAAAgAACAIAAAACAAHAAA= + Implementation\Events.cs + + + + + + AAAgAAAAMAAAAAAAgARABAAEUAQIAAAAiAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAABAAAAAQAAAAAAIiAgACIAIAAA= + Implementation\Events.cs + + + + + + AEAAAAAAAAAAAAAAgAQAAAAEAAAAAQAAgAkEAIAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAEAAAAAAAAABABAAAUAQAAAAAAAgAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAIgAAAGJACRCAAEEABEAAAAJACBAAAAAAgIAAAAAAA= + Implementation\Events.cs + + + + + + QAAAEAAAAAAAABAABABQEAQAQAAAEAAAAAAAAEAAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAgAAAAIAAAAAAAAAAAIAAAACAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + QAAAgEAACggAgAAIAAAAAEAAAIAAAAAAAAAAAAAAAII= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAIMAAAACBEAEAoQAAAKAACAAUhAAgRIQAIAE= + Implementation\GroupingParameters.cs + + + + + + bEYChOwmAAQgiCQEQBgEAMwAEAAMAEQMgEFAFODAGhM= + Implementation\Groups.cs + + + + + + AAAAgAAAJAAAAAQEABCAAAAAhAAAAACAAAAAAAIAAAE= + Implementation\Munger.cs + + + + + + AAAIACAAJAAAgAAEACAAAAAABAAAIAAAAAEAAAAAEAA= + Implementation\Munger.cs + + + + + + AAEAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAABAAA= + Implementation\Munger.cs + + + + + + cChxFKmMjlNGI/LfZWKToPLMK45gioYxDANnzL7yfN4= + Implementation\NativeMethods.cs + + + + + + AAEAAAAAAAAEAAAACAAAAAAAQAAAAAAAAAAAAAAAAAA= + Implementation\NullableDictionary.cs + + + + + + ABAAAAAAAABEAACAAAAAAAAQABAAEgAQAAIAASAAAgE= + Implementation\OLVListItem.cs + + + + + + AAAAAAAAAAAEAAAAAAAAAAAAABAIAAAQCAgACSAAAAk= + Implementation\OLVListSubItem.cs + + + + + + AAAAgEAAEAgAAABEAAZABAAGAAQAEAAAgAAAAAAIAAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + + AAAAABAAAAAAAACAAAAAAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEACAAA= + Implementation\VirtualGroups.cs + + + + + + + ABAAAAAAgAAAAAAgAAASQgAQAAAEAAAAAAAAAIAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + + AABAAAAAAAAAAAAAAABCAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + MgARTxAAJEcEWCbkoNwJbE6WTnSOEnOKQhSWGDJgsFk= + OLVColumn.cs + + + + + + AACgAIAABAAAAIABACCiAIAgAACAAgAAABAIAAAAgAE= + Rendering\Adornments.cs + + + + + + ABAAAAAAAIAAAAAAAEAAAAAAEAAAABAAAEABAAAAAAA= + Rendering\Adornments.cs + + + + + + QAIggAAEIAAgBIAIAAIASEACIABAACIIAAMACCADAsA= + Rendering\Adornments.cs + + + + + + AAEAAAAAAAABAgAAAQAABAAAAAQBAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AgAAAAAAEAAAAgAAAAAAAAAAAAAAAAAAAAAQAAIAAAA= + Rendering\Decorations.cs + + + + + + YAgAgCABAAAgA4AAAAIAgAAAAAAAAAAAAAIAACBIgAA= + Rendering\Decorations.cs + + + + + + AAAAgAAgAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAAIA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA= + Rendering\Decorations.cs + + + + + + QAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAEAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAAIAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAIAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAIAAAACAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + + AAABAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AxLAQSEQZQhhAmA5IRBAASSQUhQgkFAAgJDGAAMDE8I= + Rendering\Renderers.cs + + + + + + QAggCAEAAEAAAIAwAAKAEAIQABAAEAAAAAAAAAAKAAA= + Rendering\Renderers.cs + + + + + + AAIAEBAAAQAAAAgAABAAEAAAAAAAAAAAABAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAAQBIAAAAAAAAAAAAAAAAAAAAAAACBAAAAIAAAA= + Rendering\Renderers.cs + + + + + + AAAgAAAAAAAAAAAAAIAAAAAgIAAAAABBABAAAAAEIAA= + Rendering\Renderers.cs + + + + + + AAIAAQAAAAEAAgAAEAIAABAAAAAAAAAAIAEAACADAAA= + Rendering\Styles.cs + + + + + + + AAIAAQAAAAEAAgAAAAIAAAAAAAAAAAAAAAEAAAADAAA= + Rendering\Styles.cs + + + + + + + AAAAAAAAQAiAAAAAgAIAAAAAAAAIBAAgAAAAAAAAAAA= + Rendering\Styles.cs + + + + + + AAIAAQAAAAEAAAAAAAAAAAACACAAAgAgAAEAAAADAAA= + Rendering\Styles.cs + + + + + + AAAAAAAQAAgAAAAAAAAAAICAAIAIAAAABAAAAQAEAAA= + Rendering\Styles.cs + + + + + + BgCkgAAARAoAAEAyEAAAAAIAAAAIAhCAAQIERAgAASA= + SubControls\GlassPanelForm.cs + + + + + + MAAIOQAUABAAAACQiBQCKRgAACECAAoAwAAQxJAACaE= + SubControls\HeaderControl.cs + + + + + + AkAACAgAACCACAAAAAAAAIAAwAAIAAQCAAAAAAAAAAA= + SubControls\ToolStripCheckedListBox.cs + + + + + + CkoAByAwQQAggEvSAAIQiIWIBELAYOIpiAKQUIQDqEA= + SubControls\ToolTipControl.cs + + + + + + AAAAAEAAFDAAQTAUAACIBAoWEAAAAAAoAAAAAIEAAgA= + Utilities\ColumnSelectionForm.cs + + + + + + AAABAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAACAAAAAA= + Utilities\Generator.cs + + + + + + AAAAwABEAAAAAACIAIAQEAABEAAAAAEEggAAAAACQAA= + Utilities\TypedObjectListView.cs + + + + + + AAAACAAAAEAEAABAAEAQCAAAQAAEAEAAAAgAAAAAAAA= + Utilities\TypedObjectListView.cs + + + + + + AVkQQAAAAGIEAQAkKkHAEAgRH4gBgAGOCCEigAAgIAQ= + VirtualObjectListView.cs + + + + + + AAEAAAABACAEAQAEAAAAAAAgAQCAAAAAAAMIQAABEAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAABAAAABAAAAAAAAQAAAAAAAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAIAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAIAAAABEAAAgQAAAAAAAAAAQAIAAIg= + + + + + + AAAAAAAAAAAAAgIAAAACAAEGAAAAAEAAAAAAABAAQAA= + DataTreeListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAQAAAAAAAAAAAAAAQAgAAAAAAAAAAAAAAAAAA= + Filtering\ICluster.cs + + + + + + AAAAAAAAAAAAAAAAABBAAAAAAAAAAAQBAQAAAAAAAAA= + Filtering\IClusteringStrategy.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEAAAAA= + Implementation\VirtualGroups.cs + + + + + + ABAAAAAAAAAAAAAgAAASAgAQAAAEAAAAAAAAAAAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAQAAAAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAA= + Rendering\Styles.cs + + + + + + AAAgAAAACAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAAA= + CellEditing\CellEditKeyEngine.cs + + + + + + gAEAAAAQCAIAAAAAAIAAAAAAAUAQIABAAEAgAAAgACA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAQAAAAABAAAAAAAAAAAEAAQBBAAAAAIgAAEAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAJAAAAAAAAAAAAAIAAAAAACIEAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + AEAAAAAAAAAAABAAEAQAARAAIQAAAAQAAAAAAEAAAAA= + Implementation\Groups.cs + + + + + + AgAAgAAAwABAAAAAAAUAAAIAgQAAAAAEACAgAAAFAAA= + Implementation\Groups.cs + + + + + + AAAAAAQAAAAAAAAAAAAAAQAAAAAAEAAAAIAAAAAAAAA= + Implementation\Groups.cs + + + + + + ASAAEEAAAAAAAAQAEAAAAAAAAAAAABAAAAAACAAAEAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAEAAAAAAAAAAAAAAAAAAAQAAAABAAAAAAAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAQAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAgAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAQABgAAAAACAQAAAAAAAAAAAAAAAAAAAAAAgAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAACAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAABAAAAAAgACAAAAACAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAABAAAAAAAAAA= + Implementation\Events.cs + + + + \ No newline at end of file diff --git a/ObjectListView/Implementation/Attributes.cs b/ObjectListView/Implementation/Attributes.cs new file mode 100644 index 0000000..fd8df36 --- /dev/null +++ b/ObjectListView/Implementation/Attributes.cs @@ -0,0 +1,335 @@ +/* + * Attributes - Attributes that can be attached to properties of models to allow columns to be + * built from them directly + * + * Author: Phillip Piper + * Date: 15/08/2009 22:01 + * + * Change log: + * v2.6 + * 2012-08-16 JPP - Added [OLVChildren] and [OLVIgnore] + * - OLV attributes can now only be set on properties + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This attribute is used to mark a property of a model + /// class that should be noticed by Generator class. + /// + /// + /// All the attributes of this class match their equivalent properties on OLVColumn. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVColumnAttribute : Attribute + { + #region Constructor + + // There are several property where we actually want nullable value (bool?, int?), + // but it seems attribute properties can't be nullable types. + // So we explicitly track if those properties have been set. + + /// + /// Create a new OLVColumnAttribute + /// + public OLVColumnAttribute() { + } + + /// + /// Create a new OLVColumnAttribute with the given title + /// + /// The title of the column + public OLVColumnAttribute(string title) { + this.Title = title; + } + + #endregion + + #region Public properties + + /// + /// + /// + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// + /// + public bool CheckBoxes { + get { return checkBoxes; } + set { + checkBoxes = value; + this.IsCheckBoxesSet = true; + } + } + private bool checkBoxes; + internal bool IsCheckBoxesSet = false; + + /// + /// + /// + public int DisplayIndex { + get { return displayIndex; } + set { displayIndex = value; } + } + private int displayIndex = -1; + + /// + /// + /// + public bool FillsFreeSpace { + get { return fillsFreeSpace; } + set { fillsFreeSpace = value; } + } + private bool fillsFreeSpace; + + /// + /// + /// + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { + freeSpaceProportion = value; + IsFreeSpaceProportionSet = true; + } + } + private int freeSpaceProportion; + internal bool IsFreeSpaceProportionSet = false; + + /// + /// An array of IComparables that mark the cutoff points for values when + /// grouping on this column. + /// + public object[] GroupCutoffs { + get { return groupCutoffs; } + set { groupCutoffs = value; } + } + private object[] groupCutoffs; + + /// + /// + /// + public string[] GroupDescriptions { + get { return groupDescriptions; } + set { groupDescriptions = value; } + } + private string[] groupDescriptions; + + /// + /// + /// + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// + /// + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// + /// + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// + /// + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// + /// + public bool IsEditable { + get { return isEditable; } + set { + isEditable = value; + this.IsEditableSet = true; + } + } + private bool isEditable = true; + internal bool IsEditableSet = false; + + /// + /// + /// + public bool IsVisible { + get { return isVisible; } + set { isVisible = value; } + } + private bool isVisible = true; + + /// + /// + /// + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// + /// + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + private int maximumWidth = -1; + + /// + /// + /// + public int MinimumWidth { + get { return minimumWidth; } + set { minimumWidth = value; } + } + private int minimumWidth = -1; + + /// + /// + /// + public String Name { + get { return name; } + set { name = value; } + } + private String name; + + /// + /// + /// + public HorizontalAlignment TextAlign { + get { return this.textAlign; } + set { + this.textAlign = value; + IsTextAlignSet = true; + } + } + private HorizontalAlignment textAlign = HorizontalAlignment.Left; + internal bool IsTextAlignSet = false; + + /// + /// + /// + public String Tag { + get { return tag; } + set { tag = value; } + } + private String tag; + + /// + /// + /// + public String Title { + get { return title; } + set { title = value; } + } + private String title; + + /// + /// + /// + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// + /// + public bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + this.IsTriStateCheckBoxesSet = true; + } + } + private bool triStateCheckBoxes; + internal bool IsTriStateCheckBoxesSet = false; + + /// + /// + /// + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// + /// + public int Width { + get { return width; } + set { width = value; } + } + private int width = 150; + + #endregion + } + + /// + /// Properties marked with [OLVChildren] will be used as the children source in a TreeListView. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVChildrenAttribute : Attribute + { + + } + + /// + /// Properties marked with [OLVIgnore] will not have columns generated for them. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVIgnoreAttribute : Attribute + { + + } +} diff --git a/ObjectListView/Implementation/Comparers.cs b/ObjectListView/Implementation/Comparers.cs new file mode 100644 index 0000000..1ec33d0 --- /dev/null +++ b/ObjectListView/Implementation/Comparers.cs @@ -0,0 +1,330 @@ +/* + * Comparers - Various Comparer classes used within ObjectListView + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * v2.8.1 + * 2014-12-03 JPP - Added StringComparer + * v2.3 + * 2009-08-24 JPP - Added OLVGroupComparer + * 2009-06-01 JPP - ModelObjectComparer would crash if secondary sort column was null. + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-11-25 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// ColumnComparer is the workhorse for all comparison between two values of a particular column. + /// If the column has a specific comparer, use that to compare the values. Otherwise, do + /// a case insensitive string compare of the string representations of the values. + /// + /// This class inherits from both IComparer and its generic counterpart + /// so that it can be used on untyped and typed collections. + /// This is used by normal (non-virtual) ObjectListViews. Virtual lists use + /// ModelObjectComparer + /// + public class ColumnComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column + /// + /// The column whose values will be compared + /// The ordering for column values + public ColumnComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column, and by a secondary column if the primary + /// column is equal. + /// + /// The column whose values will be compared + /// The ordering for column values + /// The column whose values will be compared for secondary sorting + /// The ordering for secondary column values + public ColumnComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2) + this.secondComparer = new ColumnComparer(col2, order2); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(object x, object y) + { + return this.Compare((OLVListItem)x, (OLVListItem)y); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVListItem x, OLVListItem y) + { + if (this.sortOrder == SortOrder.None) + return 0; + + int result = 0; + object x1 = this.column.GetValue(x.RowObject); + object y1 = this.column.GetValue(y.RowObject); + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values to be used for sorting + /// + /// The aspect extracted from the first row + /// The aspect extracted from the second row + /// An ordering indication: -1, 0, 1 + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xAsString = x as String; + if (xAsString != null) + return CompareStrings(xAsString, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ColumnComparer secondComparer; + } + + + /// + /// This comparer sort list view groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + public class OLVGroupComparer : IComparer + { + /// + /// Create a group comparer + /// + /// The ordering for column values + public OLVGroupComparer(SortOrder order) { + this.sortOrder = order; + } + + /// + /// Compare the two groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + /// group1 + /// group2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVGroup x, OLVGroup y) { + // If we can compare the sort values, do that. + // Otherwise do a case insensitive compare on the group header. + int result; + if (x.SortValue != null && y.SortValue != null) + result = x.SortValue.CompareTo(y.SortValue); + else + result = String.Compare(x.Header, y.Header, StringComparison.CurrentCultureIgnoreCase); + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + return result; + } + + private SortOrder sortOrder; + } + + /// + /// This comparer can be used to sort a collection of model objects by a given column + /// + /// + /// This is used by virtual ObjectListViews. Non-virtual lists use + /// ColumnComparer + /// + public class ModelObjectComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a model object comparer + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a model object comparer with a secondary sorting column + /// + /// + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2 && col2 != null && order2 != SortOrder.None) + this.secondComparer = new ModelObjectComparer(col2, order2); + } + + /// + /// Compare the two model objects + /// + /// + /// + /// + public int Compare(object x, object y) + { + int result = 0; + object x1 = this.column.GetValue(x); + object y1 = this.column.GetValue(y); + + if (this.sortOrder == SortOrder.None) + return 0; + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values + /// + /// + /// + /// + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xStr = x as String; + if (xStr != null) + return CompareStrings(xStr, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ModelObjectComparer secondComparer; + + #region IComparer Members + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/Implementation/DataSourceAdapter.cs b/ObjectListView/Implementation/DataSourceAdapter.cs new file mode 100644 index 0000000..80f6da3 --- /dev/null +++ b/ObjectListView/Implementation/DataSourceAdapter.cs @@ -0,0 +1,628 @@ +/* + * DataSourceAdapter - A helper class that translates DataSource events for an ObjectListView + * + * Author: Phillip Piper + * Date: 20/09/2010 7:42 AM + * + * Change log: + * 2018-04-30 JPP - Sanity check upper limit against CurrencyManager rather than ListView just in + * case the CurrencyManager has gotten ahead of the ListView's contents. + * v2.9 + * 2015-10-31 JPP - Put back sanity check on upper limit of source items + * 2015-02-02 JPP - Made CreateColumnsFromSource() only rebuild columns when new ones were added + * v2.8.1 + * 2014-11-23 JPP - Honour initial CurrencyManager.Position when setting DataSource. + * 2014-10-27 JPP - Fix issue where SelectedObject was not sync'ed with CurrencyManager.Position (SF #129) + * v2.6 + * 2012-08-16 JPP - Unify common column creation functionality with Generator when possible + * + * 2010-09-20 JPP - Initial version + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Data; +using System.Windows.Forms; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A helper class that translates DataSource events for an ObjectListView + /// + public class DataSourceAdapter : IDisposable + { + #region Life and death + + /// + /// Make a DataSourceAdapter + /// + public DataSourceAdapter(ObjectListView olv) { + if (olv == null) throw new ArgumentNullException("olv"); + + this.ListView = olv; + // ReSharper disable once DoNotCallOverridableMethodsInConstructor + this.BindListView(this.ListView); + } + + /// + /// Finalize this object + /// + ~DataSourceAdapter() { + this.Dispose(false); + } + + /// + /// Release all the resources used by this instance + /// + public void Dispose() { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Release all the resources used by this instance + /// + public virtual void Dispose(bool fromUser) { + this.UnbindListView(this.ListView); + this.UnbindDataSource(); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + public bool AutoGenerateColumns { + get { return this.autoGenerateColumns; } + set { this.autoGenerateColumns = value; } + } + private bool autoGenerateColumns = true; + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + public virtual Object DataSource { + get { return dataSource; } + set { + dataSource = value; + this.RebindDataSource(true); + } + } + private Object dataSource; + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + public virtual string DataMember { + get { return dataMember; } + set { + if (dataMember != value) { + dataMember = value; + RebindDataSource(); + } + } + } + private string dataMember = ""; + + /// + /// Gets the ObjectListView upon which this adaptor will operate + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the currency manager which is handling our binding context + /// + protected CurrencyManager CurrencyManager { + get { return currencyManager; } + set { currencyManager = value; } + } + private CurrencyManager currencyManager; + + #endregion + + #region Binding and unbinding + + /// + /// + /// + /// + protected virtual void BindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing += new EventHandler(HandleListViewFreezing); + olv.SelectionChanged += new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged += new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + /// + protected virtual void UnbindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing -= new EventHandler(HandleListViewFreezing); + olv.SelectionChanged -= new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged -= new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + protected virtual void BindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged += new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged += new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged += new ListChangedEventHandler(CurrencyManagerListChanged); + } + + /// + /// + /// + protected virtual void UnbindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged -= new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged -= new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged -= new ListChangedEventHandler(CurrencyManagerListChanged); + } + + #endregion + + #region Initialization + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource() { + RebindDataSource(false); + } + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource(bool forceDataInitialization) { + + CurrencyManager tempCurrencyManager = null; + if (this.ListView != null && this.ListView.BindingContext != null && this.DataSource != null) { + tempCurrencyManager = this.ListView.BindingContext[this.DataSource, this.DataMember] as CurrencyManager; + } + + // Has our currency manager changed? + if (this.CurrencyManager != tempCurrencyManager) { + this.UnbindDataSource(); + this.CurrencyManager = tempCurrencyManager; + this.BindDataSource(); + + // Our currency manager has changed so we have to initialize a new data source + forceDataInitialization = true; + } + + if (forceDataInitialization) + InitializeDataSource(); + } + + /// + /// The data source for this control has changed. Reconfigure the control for the new source + /// + protected virtual void InitializeDataSource() { + if (this.ListView.Frozen || this.CurrencyManager == null) + return; + + this.CreateColumnsFromSource(); + this.CreateMissingAspectGettersAndPutters(); + this.SetListContents(); + this.ListView.AutoSizeColumns(); + + // Fake a position change event so that the control matches any initial Position + this.HandleCurrencyManagerPositionChanged(null, null); + } + + /// + /// Take the contents of the currently bound list and put them into the control + /// + protected virtual void SetListContents() { + this.ListView.Objects = this.CurrencyManager.List; + } + + /// + /// Create columns for the listview based on what properties are available in the data source + /// + /// + /// This method will create columns if there is not already a column displaying that property. + /// + protected virtual void CreateColumnsFromSource() { + if (this.CurrencyManager == null) + return; + + // Don't generate any columns in design mode. If we do, the user will see them, + // but the Designer won't know about them and won't persist them, which is very confusing + if (this.ListView.IsDesignMode) + return; + + // Don't create columns if we've been told not to + if (!this.AutoGenerateColumns) + return; + + // Use a Generator to create columns + Generator generator = Generator.Instance as Generator ?? new Generator(); + + PropertyDescriptorCollection properties = this.CurrencyManager.GetItemProperties(); + if (properties.Count == 0) + return; + + bool wereColumnsAdded = false; + foreach (PropertyDescriptor property in properties) { + + if (!this.ShouldCreateColumn(property)) + continue; + + // Create a column + OLVColumn column = generator.MakeColumnFromPropertyDescriptor(property); + this.ConfigureColumn(column, property); + + // Add it to our list + this.ListView.AllColumns.Add(column); + wereColumnsAdded = true; + } + + if (wereColumnsAdded) + generator.PostCreateColumns(this.ListView); + } + + /// + /// Decide if a new column should be added to the control to display + /// the given property + /// + /// + /// + protected virtual bool ShouldCreateColumn(PropertyDescriptor property) { + + // Is there a column that already shows this property? If so, we don't show it again + if (this.ListView.AllColumns.Exists(delegate(OLVColumn x) { return x.AspectName == property.Name; })) + return false; + + // Relationships to other tables turn up as IBindibleLists. Don't make columns to show them. + // CHECK: Is this always true? What other things could be here? Constraints? Triggers? + if (property.PropertyType == typeof(IBindingList)) + return false; + + // Ignore anything marked with [OLVIgnore] + return property.Attributes[typeof(OLVIgnoreAttribute)] == null; + } + + /// + /// Configure the given column to show the given property. + /// The title and aspect name of the column are already filled in. + /// + /// + /// + protected virtual void ConfigureColumn(OLVColumn column, PropertyDescriptor property) { + + column.LastDisplayIndex = this.ListView.AllColumns.Count; + + // If our column is a BLOB, it could be an image, so assign a renderer to draw it. + // CONSIDER: Is this a common enough case to warrant this code? + if (property.PropertyType == typeof(System.Byte[])) + column.Renderer = new ImageRenderer(); + } + + /// + /// Generate aspect getters and putters for any columns that are missing them (and for which we have + /// enough information to actually generate a getter) + /// + protected virtual void CreateMissingAspectGettersAndPutters() { + foreach (OLVColumn x in this.ListView.AllColumns) { + OLVColumn column = x; // stack based variable accessible from closures + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectGetter = delegate(object row) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + return column.GetAspectByName(row); + return (drv.Row.RowState == DataRowState.Detached) ? null : drv[column.AspectName]; + }; + } + if (column.IsEditable && column.AspectPutter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectPutter = delegate(object row, object newValue) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + column.PutAspectByName(row, newValue); + else { + if (drv.Row.RowState != DataRowState.Detached) + drv[column.AspectName] = newValue; + } + }; + } + } + } + + #endregion + + #region Event Handlers + + /// + /// CurrencyManager ListChanged event handler. + /// Deals with fine-grained changes to list items. + /// + /// + /// It's actually difficult to deal with these changes in a fine-grained manner. + /// If our listview is grouped, then any change may make a new group appear or + /// an old group disappear. It is rarely enough to simply update the affected row. + /// + /// + /// + protected virtual void CurrencyManagerListChanged(object sender, ListChangedEventArgs e) { + Debug.Assert(sender == this.CurrencyManager); + + // Ignore changes make while frozen, since we will do a complete rebuild when we unfreeze + if (this.ListView.Frozen) + return; + + //System.Diagnostics.Debug.WriteLine(e.ListChangedType); + Stopwatch sw = Stopwatch.StartNew(); + switch (e.ListChangedType) { + + case ListChangedType.Reset: + this.HandleListChangedReset(e); + break; + + case ListChangedType.ItemChanged: + this.HandleListChangedItemChanged(e); + break; + + case ListChangedType.ItemAdded: + this.HandleListChangedItemAdded(e); + break; + + // An item has gone away. + case ListChangedType.ItemDeleted: + this.HandleListChangedItemDeleted(e); + break; + + // An item has changed its index. + case ListChangedType.ItemMoved: + this.HandleListChangedItemMoved(e); + break; + + // Something has changed in the metadata. + // CHECK: When are these events actually fired? + case ListChangedType.PropertyDescriptorAdded: + case ListChangedType.PropertyDescriptorChanged: + case ListChangedType.PropertyDescriptorDeleted: + this.HandleListChangedMetadataChanged(e); + break; + } + sw.Stop(); + System.Diagnostics.Debug.WriteLine(String.Format("PERF - Processing {0} event on {1} rows took {2}ms", e.ListChangedType, this.ListView.GetItemCount(), sw.ElapsedMilliseconds)); + + } + + /// + /// Handle PropertyDescriptor* events + /// + /// + protected virtual void HandleListChangedMetadataChanged(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle ItemMoved event + /// + /// + protected virtual void HandleListChangedItemMoved(ListChangedEventArgs e) { + // When is this actually triggered? + this.InitializeDataSource(); + } + + /// + /// Handle the ItemDeleted event + /// + /// + protected virtual void HandleListChangedItemDeleted(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle an ItemAdded event. + /// + /// + protected virtual void HandleListChangedItemAdded(ListChangedEventArgs e) { + // We get this event twice if certain grid controls are used to add a new row to a + // datatable: once when the editing of a new row begins, and once again when that + // editing commits. (If the user cancels the creation of the new row, we never see + // the second creation.) We detect this by seeing if this is a view on a row in a + // DataTable, and if it is, testing to see if it's a new row under creation. + + Object newRow = this.CurrencyManager.List[e.NewIndex]; + DataRowView drv = newRow as DataRowView; + if (drv == null || !drv.IsNew) { + // Either we're not dealing with a view on a data table, or this is the commit + // notification. Either way, this is the final notification, so we want to + // handle the new row now! + this.InitializeDataSource(); + } + } + + /// + /// Handle the Reset event + /// + /// + protected virtual void HandleListChangedReset(ListChangedEventArgs e) { + // The whole list has changed utterly, so reload it. + this.InitializeDataSource(); + } + + /// + /// Handle ItemChanged event. This is triggered when a single item + /// has changed, so just refresh that one item. + /// + /// + /// Even in this simple case, we should probably rebuild the list. + /// For example, the change could put the item into its own new group. + protected virtual void HandleListChangedItemChanged(ListChangedEventArgs e) { + // A single item has changed, so just refresh that. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleListChangedItemChanged: {0}, {1}", e.NewIndex, e.PropertyDescriptor.Name)); + + Object changedRow = this.CurrencyManager.List[e.NewIndex]; + this.ListView.RefreshObject(changedRow); + } + + /// + /// The CurrencyManager calls this if the data source looks + /// different. We just reload everything. + /// + /// + /// + /// + /// CHECK: Do we need this if we are handle ListChanged metadata events? + /// + protected virtual void HandleCurrencyManagerMetaDataChanged(object sender, EventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Called by the CurrencyManager when the currently selected item + /// changes. We update the ListView selection so that we stay in sync + /// with any other controls bound to the same source. + /// + /// + /// + protected virtual void HandleCurrencyManagerPositionChanged(object sender, EventArgs e) { + int index = this.CurrencyManager.Position; + + // Make sure the index is sane (-1 pops up from time to time) + if (index < 0 || index >= this.CurrencyManager.Count) + return; + + // Avoid recursion. If we are currently changing the index, don't + // start the process again. + if (this.isChangingIndex) + return; + + try { + this.isChangingIndex = true; + this.ChangePosition(index); + } + finally { + this.isChangingIndex = false; + } + } + private bool isChangingIndex = false; + + /// + /// Change the control's position (which is it's currently selected row) + /// to the nth row in the dataset + /// + /// The index of the row to be selected + protected virtual void ChangePosition(int index) { + // We can't use the index directly, since our listview may be sorted + this.ListView.SelectedObject = this.CurrencyManager.List[index]; + + // THINK: Do we always want to bring it into view? + if (this.ListView.SelectedIndices.Count > 0) + this.ListView.EnsureVisible(this.ListView.SelectedIndices[0]); + } + + #endregion + + #region ObjectListView event handlers + + /// + /// Handle the selection changing in our ListView. + /// We need to tell our currency manager about the new position. + /// + /// + /// + protected virtual void HandleListViewSelectionChanged(object sender, EventArgs e) { + // Prevent recursion + if (this.isChangingIndex) + return; + + // Sanity + if (this.CurrencyManager == null) + return; + + // If only one item is selected, tell the currency manager which item is selected. + // CurrencyManager can't handle multiple selection so there's nothing we can do + // if more than one row is selected. + if (this.ListView.SelectedIndices.Count != 1) + return; + + try { + this.isChangingIndex = true; + + // We can't use the selectedIndex directly, since our listview may be sorted and/or filtered + // So we have to find the index of the selected object within the original list. + this.CurrencyManager.Position = this.CurrencyManager.List.IndexOf(this.ListView.SelectedObject); + } finally { + this.isChangingIndex = false; + } + } + + /// + /// Handle the frozenness of our ListView changing. + /// + /// + /// + protected virtual void HandleListViewFreezing(object sender, FreezeEventArgs e) { + if (!alreadyFreezing && e.FreezeLevel == 0) { + try { + alreadyFreezing = true; + this.RebindDataSource(true); + } finally { + alreadyFreezing = false; + } + } + } + private bool alreadyFreezing = false; + + /// + /// Handle a change to the BindingContext of our ListView. + /// + /// + /// + protected virtual void HandleListViewBindingContextChanged(object sender, EventArgs e) { + this.RebindDataSource(false); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/Delegates.cs b/ObjectListView/Implementation/Delegates.cs new file mode 100644 index 0000000..52da366 --- /dev/null +++ b/ObjectListView/Implementation/Delegates.cs @@ -0,0 +1,168 @@ +/* + * Delegates - All delegate definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * v2.10 + * 2015-12-30 JPP - Added CellRendererGetterDelegate + * v2.? + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + #region Delegate declarations + + /// + /// These delegates are used to extract an aspect from a row object + /// + public delegate Object AspectGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed value back into a model object + /// + public delegate void AspectPutterDelegate(Object rowObject, Object newValue); + + /// + /// These delegates can be used to convert an aspect value to a display string, + /// instead of using the default ToString() + /// + public delegate string AspectToStringConverterDelegate(Object value); + + /// + /// These delegates are used to get the tooltip for a cell + /// + public delegate String CellToolTipGetterDelegate(OLVColumn column, Object modelObject); + + /// + /// These delegates are used to the state of the checkbox for a row object. + /// + /// + /// For reasons known only to someone in Microsoft, we can only set + /// a boolean on the ListViewItem to indicate it's "checked-ness", but when + /// we receive update events, we have to use a tristate CheckState. So we can + /// be told about an indeterminate state, but we can't set it ourselves. + /// + /// As of version 2.0, we can now return indeterminate state. + /// + public delegate CheckState CheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to get the state of the checkbox for a row object. + /// + /// + /// + public delegate bool BooleanCheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + public delegate CheckState CheckStatePutterDelegate(Object rowObject, CheckState newValue); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + /// + /// + /// + public delegate bool BooleanCheckStatePutterDelegate(Object rowObject, bool newValue); + + /// + /// These delegates are used to get the renderer for a particular cell + /// + public delegate IRenderer CellRendererGetterDelegate(Object rowObject, OLVColumn column); + + /// + /// The callbacks for RightColumnClick events + /// + public delegate void ColumnRightClickEventHandler(object sender, ColumnClickEventArgs e); + + /// + /// This delegate will be used to own draw header column. + /// + public delegate bool HeaderDrawingDelegate(Graphics g, Rectangle r, int columnIndex, OLVColumn column, bool isPressed, HeaderStateStyle stateStyle); + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + public delegate void GroupFormatterDelegate(OLVGroup group, GroupingParameters parms); + + /// + /// These delegates are used to retrieve the object that is the key of the group to which the given row belongs. + /// + public delegate Object GroupKeyGetterDelegate(Object rowObject); + + /// + /// These delegates are used to convert a group key into a title for the group + /// + public delegate string GroupKeyToTitleConverterDelegate(Object groupKey); + + /// + /// These delegates are used to get the tooltip for a column header + /// + public delegate String HeaderToolTipGetterDelegate(OLVColumn column); + + /// + /// These delegates are used to fetch the image selector that should be used + /// to choose an image for this column. + /// + public delegate Object ImageGetterDelegate(Object rowObject); + + /// + /// These delegates are used to draw a cell + /// + public delegate bool RenderDelegate(EventArgs e, Graphics g, Rectangle r, Object rowObject); + + /// + /// These delegates are used to fetch a row object for virtual lists + /// + public delegate Object RowGetterDelegate(int rowIndex); + + /// + /// These delegates are used to format a listviewitem before it is added to the control. + /// + public delegate void RowFormatterDelegate(OLVListItem olvItem); + + /// + /// These delegates can be used to return the array of texts that should be searched for text filtering + /// + public delegate string[] SearchValueGetterDelegate(Object value); + + /// + /// These delegates are used to sort the listview in some custom fashion + /// + public delegate void SortDelegate(OLVColumn column, SortOrder sortOrder); + + /// + /// These delegates are used to order two strings. + /// x cannot be null. y can be null. + /// + public delegate int StringCompareDelegate(string x, string y); + + #endregion +} diff --git a/ObjectListView/Implementation/DragSource.cs b/ObjectListView/Implementation/DragSource.cs new file mode 100644 index 0000000..f0f4783 --- /dev/null +++ b/ObjectListView/Implementation/DragSource.cs @@ -0,0 +1,407 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * UNFINISHED + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All opertions are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshe the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + OLVDataObject data = new OLVDataObject(olv); + data.CreateTextFormats(); + return data; + } + + #endregion + } + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject + { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders + { + get { return includeColumnHeaders; } + } + private bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + // Build text and html versions of the selection + StringBuilder sbText = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (includeColumnHeaders) + { + sbHtml.Append(""); + } + + foreach (object modelObject in this.ModelObjects) + { + sbHtml.Append(""); + } + sbHtml.AppendLine("
"); + foreach (OLVColumn col in columns) + { + if (col != columns[0]) + { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.Text; + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
"); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
"); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(sbText.ToString()); + this.SetText(ConvertToHtmlFragment(sbHtml.ToString()), TextDataFormat.Html); + } + + /// + /// Make a HTML representation of our model objects + /// + public string CreateHtml() { + IList columns = this.ListView.ColumnsInDisplayOrder; + + // Build html version of the selection + StringBuilder sbHtml = new StringBuilder(""); + + foreach (object modelObject in this.ModelObjects) { + sbHtml.Append(""); + } + sbHtml.AppendLine("
"); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbHtml.AppendLine("
"); + + return sbHtml.ToString(); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognized as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + string source = "http://www.codeproject.com/KB/list/ObjectListView.aspx"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, source, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, source, html); + } + } +} diff --git a/ObjectListView/Implementation/DropSink.cs b/ObjectListView/Implementation/DropSink.cs new file mode 100644 index 0000000..03818d8 --- /dev/null +++ b/ObjectListView/Implementation/DropSink.cs @@ -0,0 +1,1402 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2010 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target (not currently used) + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target (not currently used) + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. + /// + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continune while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + //ListViewHitTestInfo info = this.ListView.HitTest(pt.X, pt.Y); + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined) + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + // If the mouse is over an item, check to see if it is near the top or bottom + if (location == DropTargetLocation.Item) { + if (pt.Y - SMALL_VALUE <= info.Item.Bounds.Top) + location = DropTargetLocation.AboveItem; + if (pt.Y + SMALL_VALUE >= info.Item.Bounds.Bottom) + location = DropTargetLocation.BelowItem; + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width; + r.X += (indentWidth * item.IndentCount); + r.Width -= (indentWidth * item.IndentCount); + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + int x = x1; + int y = y1; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 5, + x, y - 5); + gp.AddBezier( + x, y - 6, + x + 3, y - 2, + x + 6, y - 1, + x + 11, y); + gp.AddBezier( + x + 11, y, + x + 6, y + 1, + x + 3, y + 2, + x, y + 6); + gp.CloseFigure(); + g.FillPath(b, gp); + } + x = x2; + y = y2; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 6, + x, y - 6); + gp.AddBezier( + x, y - 7, + x - 3, y - 2, + x - 6, y - 1, + x - 11, y); + gp.AddBezier( + x - 11, y, + x - 6, y + 1, + x - 3, y + 2, + x, y + 7); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amonst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging a list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occured, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the data object that is being dragged + /// + public object DataObject { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + toBeRefreshed.AddRange(this.SourceModels); + if (this.ListView == this.SourceListView) { + toBeRefreshed.Add(this.TargetModel); + this.ListView.RefreshObjects(toBeRefreshed); + } else { + this.SourceListView.RefreshObjects(toBeRefreshed); + this.ListView.RefreshObject(this.TargetModel); + } + } + } +} diff --git a/ObjectListView/Implementation/Enums.cs b/ObjectListView/Implementation/Enums.cs new file mode 100644 index 0000000..572b4b4 --- /dev/null +++ b/ObjectListView/Implementation/Enums.cs @@ -0,0 +1,104 @@ +/* + * Enums - All enum definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + public partial class ObjectListView { + /// + /// How does a user indicate that they want to edit cells? + /// + public enum CellEditActivateMode { + /// + /// This list cannot be edited. F2 does nothing. + /// + None = 0, + + /// + /// A single click on a subitem will edit the value. Single clicking the primary column, + /// selects the row just like normal. The user must press F2 to edit the primary column. + /// + SingleClick = 1, + + /// + /// Double clicking a subitem or the primary column will edit that cell. + /// F2 will edit the primary column. + /// + DoubleClick = 2, + + /// + /// Pressing F2 is the only way to edit the cells. Once the primary column is being edited, + /// the other cells in the row can be edited by pressing Tab. + /// + F2Only = 3, + + /// + /// A single click on a any cell will edit the value, even the primary column. + /// + SingleClickAlways = 4, + } + + /// + /// These values specify how column selection will be presented to the user + /// + public enum ColumnSelectBehaviour { + /// + /// No column selection will be presented + /// + None, + + /// + /// The columns will be show in the main menu + /// + InlineMenu, + + /// + /// The columns will be shown in a submenu + /// + Submenu, + + /// + /// A model dialog will be presented to allow the user to choose columns + /// + ModelDialog, + + /* + * NonModelDialog is just a little bit tricky since the OLV can change views while the dialog is showing + * So, just comment this out for the time being. + + /// + /// A non-model dialog will be presented to allow the user to choose columns + /// + NonModelDialog + * + */ + } + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/Events.cs b/ObjectListView/Implementation/Events.cs new file mode 100644 index 0000000..7a1c466 --- /dev/null +++ b/ObjectListView/Implementation/Events.cs @@ -0,0 +1,2514 @@ +/* + * Events - All the events that can be triggered within an ObjectListView. + * + * Author: Phillip Piper + * Date: 17/10/2008 9:15 PM + * + * Change log: + * v2.8.0 + * 2014-05-20 JPP - Added IsHyperlinkEventArgs.IsHyperlink + * v2.6 + * 2012-04-17 JPP - Added group state change and group expansion events + * v2.5 + * 2010-08-08 JPP - CellEdit validation and finish events now have NewValue property. + * v2.4 + * 2010-03-04 JPP - Added filtering events + * v2.3 + * 2009-08-16 JPP - Added group events + * 2009-08-08 JPP - Added HotItem event + * 2009-07-24 JPP - Added Hyperlink events + * - Added Formatting events + * v2.2.1 + * 2009-06-13 JPP - Added Cell events + * - Moved all event parameter blocks to this file. + * - Added Handled property to AfterSearchEventArgs + * v2.2 + * 2009-06-01 JPP - Added ColumnToGroupBy and GroupByOrder to sorting events + - Gave all event descriptions + * 2009-04-23 JPP - Added drag drop events + * v2.1 + * 2009-01-18 JPP - Moved SelectionChanged event to this file + * v2.0 + * 2008-12-06 JPP - Added searching events + * 2008-12-01 JPP - Added secondary sort information to Before/AfterSorting events + * 2008-10-17 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + /// + /// The callbacks for CellEditing events + /// + /// this + /// We could replace this with EventHandler<CellEditEventArgs> but that would break all + /// cell editing event code from v1.x. + /// + public delegate void CellEditEventHandler(object sender, CellEditEventArgs e); + + public partial class ObjectListView { + //----------------------------------------------------------------------------------- + + #region Events + + /// + /// Triggered after a ObjectListView has been searched by the user typing into the list + /// + [Category("ObjectListView"), + Description("This event is triggered after the control has done a search-by-typing action.")] + public event EventHandler AfterSearching; + + /// + /// Triggered after a ObjectListView has been sorted + /// + [Category("ObjectListView"), + Description("This event is triggered after the items in the list have been sorted.")] + public event EventHandler AfterSorting; + + /// + /// Triggered before a ObjectListView is searched by the user typing into the list + /// + /// + /// Set Cancelled to true to prevent the searching from taking place. + /// Changing StringToFind or StartSearchFrom will change the subsequent search. + /// + [Category("ObjectListView"), + Description("This event is triggered before the control does a search-by-typing action.")] + public event EventHandler BeforeSearching; + + /// + /// Triggered before a ObjectListView is sorted + /// + /// + /// Set Cancelled to true to prevent the sort from taking place. + /// Changing ColumnToSort or SortOrder will change the subsequent sort. + /// + [Category("ObjectListView"), + Description("This event is triggered before the items in the list are sorted.")] + public event EventHandler BeforeSorting; + + /// + /// Triggered after a ObjectListView has created groups + /// + [Category("ObjectListView"), + Description("This event is triggered after the groups are created.")] + public event EventHandler AfterCreatingGroups; + + /// + /// Triggered before a ObjectListView begins to create groups + /// + /// + /// Set Groups to prevent the default group creation process + /// + [Category("ObjectListView"), + Description("This event is triggered before the groups are created.")] + public event EventHandler BeforeCreatingGroups; + + /// + /// Triggered just before a ObjectListView creates groups + /// + /// + /// You can make changes to the groups, which have been created, before those + /// groups are created within the listview. + /// + [Category("ObjectListView"), + Description("This event is triggered when the groups are just about to be created.")] + public event EventHandler AboutToCreateGroups; + + /// + /// Triggered when a button in a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a button.")] + public event EventHandler ButtonClick; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the user drop the currently dragged items at the current mouse location?")] + public event EventHandler CanDrop; + + /// + /// Triggered when a cell has finished being edited. + /// + [Category("ObjectListView"), + Description("This event is triggered cell edit operation has completely finished")] + public event CellEditEventHandler CellEditFinished; + + /// + /// Triggered when a cell is about to finish being edited. + /// + /// If Cancel is already true, the user is cancelling the edit operation. + /// Set Cancel to true to prevent the value from the cell being written into the model. + /// You cannot prevent the editing from finishing within this event -- you need + /// the CellEditValidating event for that. + [Category("ObjectListView"), + Description("This event is triggered cell edit operation is finishing.")] + public event CellEditEventHandler CellEditFinishing; + + /// + /// Triggered when a cell is about to be edited. + /// + /// Set Cancel to true to prevent the cell being edited. + /// You can change the Control to be something completely different. + [Category("ObjectListView"), + Description("This event is triggered when cell edit is about to begin.")] + public event CellEditEventHandler CellEditStarting; + + /// + /// Triggered when a cell editor needs to be validated + /// + /// + /// If this event is cancelled, focus will remain on the cell editor. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell editor is about to lose focus and its new contents need to be validated.")] + public event CellEditEventHandler CellEditValidating; + + /// + /// Triggered when a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a cell.")] + public event EventHandler CellClick; + + /// + /// Triggered when the mouse is above a cell. + /// + [Category("ObjectListView"), + Description("This event is triggered when the mouse is over a cell.")] + public event EventHandler CellOver; + + /// + /// Triggered when a cell is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a cell.")] + public event EventHandler CellRightClick; + + /// + /// This event is triggered when a cell needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs a tool tip.")] + public event EventHandler CellToolTipShowing; + + /// + /// This event is triggered when a checkbox is checked/unchecked on a subitem + /// + [Category("ObjectListView"), + Description("This event is triggered when a checkbox is checked/unchecked on a subitem.")] + public event EventHandler SubItemChecking; + + /// + /// Triggered when a column header is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a column header.")] + public event ColumnRightClickEventHandler ColumnRightClick; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user dropped items onto the control.")] + public event EventHandler Dropped; + + /// + /// This event is triggered when the control needs to filter its collection of objects. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to filter its collection of objects.")] + public event EventHandler Filter; + + /// + /// This event is triggered when a cell needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs to be formatted.")] + public event EventHandler FormatCell; + + /// + /// This event is triggered when the frozenness of the control changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when frozenness of the control changes.")] + public event EventHandler Freezing; + + /// + /// This event is triggered when a row needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a row needs to be formatted.")] + public event EventHandler FormatRow; + + /// + /// This event is triggered when a group is about to collapse or expand. + /// This can be cancelled to prevent the expansion. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group is about to collapse or expand.")] + public event EventHandler GroupExpandingCollapsing; + + /// + /// This event is triggered when a group changes state. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group changes state.")] + public event EventHandler GroupStateChanged; + + /// + /// This event is triggered when a header checkbox is changing value + /// + [Category("ObjectListView"), + Description("This event is triggered when a header checkbox changes value.")] + public event EventHandler HeaderCheckBoxChanging; + + /// + /// This event is triggered when a header needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a header needs a tool tip.")] + public event EventHandler HeaderToolTipShowing; + + /// + /// Triggered when the "hot" item changes + /// + [Category("ObjectListView"), + Description("This event is triggered when the hot item changed.")] + public event EventHandler HotItemChanged; + + /// + /// Triggered when a hyperlink cell is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when a hyperlink cell is clicked.")] + public event EventHandler HyperlinkClicked; + + /// + /// Triggered when the task text of a group is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the task text of a group is clicked.")] + public event EventHandler GroupTaskClicked; + + /// + /// Is the value in the given cell a hyperlink. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to know if a given cell contains a hyperlink.")] + public event EventHandler IsHyperlink; + + /// + /// Some new objects are about to be added to an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are about to be added to the control")] + public event EventHandler ItemsAdding; + + /// + /// The contents of the ObjectListView has changed. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control have changed.")] + public event EventHandler ItemsChanged; + + /// + /// The contents of the ObjectListView is about to change via a SetObjects call + /// + /// + /// Set Cancelled to true to prevent the contents of the list changing. This does not work with virtual lists. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control changes.")] + public event EventHandler ItemsChanging; + + /// + /// Some objects are about to be removed from an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are removed from the control.")] + public event EventHandler ItemsRemoving; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler, and when the source control + /// for the drag was an ObjectListView. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the dragged collection of model objects be dropped at the current mouse location")] + public event EventHandler ModelCanDrop; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler and when the source control + /// for the drag was an ObjectListView. + /// + [Category("ObjectListView"), + Description("A collection of model objects from a ObjectListView has been dropped on this control")] + public event EventHandler ModelDropped; + + /// + /// This event is triggered once per user action that changes the selection state + /// of one or more rows. + /// + [Category("ObjectListView"), + Description("This event is triggered once per user action that changes the selection state of one or more rows.")] + public event EventHandler SelectionChanged; + + /// + /// This event is triggered when the contents of the ObjectListView has scrolled. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the ObjectListView has scrolled.")] + public event EventHandler Scroll; + + #endregion + + //----------------------------------------------------------------------------------- + + #region OnEvents + + /// + /// + /// + /// + protected virtual void OnAboutToCreateGroups(CreateGroupsEventArgs e) { + if (this.AboutToCreateGroups != null) + this.AboutToCreateGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeCreatingGroups(CreateGroupsEventArgs e) { + if (this.BeforeCreatingGroups != null) + this.BeforeCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterCreatingGroups(CreateGroupsEventArgs e) { + if (this.AfterCreatingGroups != null) + this.AfterCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSearching(AfterSearchingEventArgs e) { + if (this.AfterSearching != null) + this.AfterSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSorting(AfterSortingEventArgs e) { + if (this.AfterSorting != null) + this.AfterSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSearching(BeforeSearchingEventArgs e) { + if (this.BeforeSearching != null) + this.BeforeSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSorting(BeforeSortingEventArgs e) { + if (this.BeforeSorting != null) + this.BeforeSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnButtonClick(CellClickEventArgs args) { + if (this.ButtonClick != null) + this.ButtonClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellClick(CellClickEventArgs args) { + if (this.CellClick != null) + this.CellClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellOver(CellOverEventArgs args) { + if (this.CellOver != null) + this.CellOver(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellRightClick(CellRightClickEventArgs args) { + if (this.CellRightClick != null) + this.CellRightClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellToolTip(ToolTipShowingEventArgs args) { + if (this.CellToolTipShowing != null) + this.CellToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSubItemChecking(SubItemCheckingEventArgs args) { + if (this.SubItemChecking != null) + this.SubItemChecking(this, args); + } + + /// + /// + /// + /// + protected virtual void OnColumnRightClick(ColumnRightClickEventArgs e) { + if (this.ColumnRightClick != null) + this.ColumnRightClick(this, e); + } + + /// + /// + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// + /// + /// + internal protected virtual void OnFilter(FilterEventArgs e) { + if (this.Filter != null) + this.Filter(this, e); + } + + /// + /// + /// + /// + protected virtual void OnFormatCell(FormatCellEventArgs args) { + if (this.FormatCell != null) + this.FormatCell(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFormatRow(FormatRowEventArgs args) { + if (this.FormatRow != null) + this.FormatRow(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFreezing(FreezeEventArgs args) { + if (this.Freezing != null) + this.Freezing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupExpandingCollapsing(GroupExpandingCollapsingEventArgs args) { + if (this.GroupExpandingCollapsing != null) + this.GroupExpandingCollapsing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupStateChanged(GroupStateChangedEventArgs args) { + if (this.GroupStateChanged != null) + this.GroupStateChanged(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderCheckBoxChanging(HeaderCheckBoxChangingEventArgs args) { + if (this.HeaderCheckBoxChanging != null) + this.HeaderCheckBoxChanging(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderToolTip(ToolTipShowingEventArgs args) { + if (this.HeaderToolTipShowing != null) + this.HeaderToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHotItemChanged(HotItemChangedEventArgs e) { + if (this.HotItemChanged != null) + this.HotItemChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnHyperlinkClicked(HyperlinkClickedEventArgs e) { + if (this.HyperlinkClicked != null) + this.HyperlinkClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnGroupTaskClicked(GroupTaskClickedEventArgs e) { + if (this.GroupTaskClicked != null) + this.GroupTaskClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnIsHyperlink(IsHyperlinkEventArgs e) { + if (this.IsHyperlink != null) + this.IsHyperlink(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsAdding(ItemsAddingEventArgs e) { + if (this.ItemsAdding != null) + this.ItemsAdding(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanged(ItemsChangedEventArgs e) { + if (this.ItemsChanged != null) + this.ItemsChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanging(ItemsChangingEventArgs e) { + if (this.ItemsChanging != null) + this.ItemsChanging(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsRemoving(ItemsRemovingEventArgs e) { + if (this.ItemsRemoving != null) + this.ItemsRemoving(this, e); + } + + /// + /// + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSelectionChanged(EventArgs e) { + if (this.SelectionChanged != null) + this.SelectionChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnScroll(ScrollEventArgs e) { + if (this.Scroll != null) + this.Scroll(this, e); + } + + + /// + /// Tell the world when a cell is about to be edited. + /// + protected virtual void OnCellEditStarting(CellEditEventArgs e) { + if (this.CellEditStarting != null) + this.CellEditStarting(this, e); + } + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditorValidating(CellEditEventArgs e) { + // Hack. ListView is an imperfect control container. It does not manage validation + // perfectly. If the ListView is part of a TabControl, and the cell editor loses + // focus by the user clicking on another tab, the TabControl processes the click + // and switches tabs, even if this Validating event cancels. This results in the + // strange situation where the cell editor is active, but isn't visible. When the + // user switches back to the tab with the ListView, composite controls like spin + // controls, DateTimePicker and ComboBoxes do not work properly. Specifically, + // keyboard input still works fine, but the controls do not respond to mouse + // input. SO, if the validation fails, we have to specifically give focus back to + // the cell editor. (this is the Select() call in the code below). + // But (there is always a 'but'), doing that changes the focus so the cell editor + // triggers another Validating event -- which fails again. From the user's point + // of view, they click away from the cell editor, and the validating code + // complains twice. So we only trigger a Validating event if more than 0.1 seconds + // has elapsed since the last validate event. + // I know it's a hack. I'm very open to hear a neater solution. + + // Also, this timed response stops us from sending a series of validation events + // if the user clicks and holds on the OLV scroll bar. + //System.Diagnostics.Debug.WriteLine(Environment.TickCount - lastValidatingEvent); + if ((Environment.TickCount - lastValidatingEvent) < 100) { + e.Cancel = true; + } else { + lastValidatingEvent = Environment.TickCount; + if (this.CellEditValidating != null) + this.CellEditValidating(this, e); + } + + lastValidatingEvent = Environment.TickCount; + } + + private int lastValidatingEvent = 0; + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditFinishing(CellEditEventArgs e) { + if (this.CellEditFinishing != null) + this.CellEditFinishing(this, e); + } + + /// + /// Tell the world when a cell has finished being edited. + /// + protected virtual void OnCellEditFinished(CellEditEventArgs e) { + if (this.CellEditFinished != null) + this.CellEditFinished(this, e); + } + + #endregion + } + + public partial class TreeListView { + + #region Events + + /// + /// This event is triggered when user input requests the expansion of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to expand.")] + public event EventHandler Expanding; + + /// + /// This event is triggered when user input requests the collapse of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to collapsed.")] + public event EventHandler Collapsing; + + /// + /// This event is triggered after the expansion of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been expanded.")] + public event EventHandler Expanded; + + /// + /// This event is triggered after the collapse of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been collapsed.")] + public event EventHandler Collapsed; + + #endregion + + #region OnEvents + + /// + /// Trigger the expanding event + /// + /// + protected virtual void OnExpanding(TreeBranchExpandingEventArgs e) { + if (this.Expanding != null) + this.Expanding(this, e); + } + + /// + /// Trigger the collapsing event + /// + /// + protected virtual void OnCollapsing(TreeBranchCollapsingEventArgs e) { + if (this.Collapsing != null) + this.Collapsing(this, e); + } + + /// + /// Trigger the expanded event + /// + /// + protected virtual void OnExpanded(TreeBranchExpandedEventArgs e) { + if (this.Expanded != null) + this.Expanded(this, e); + } + + /// + /// Trigger the collapsed event + /// + /// + protected virtual void OnCollapsed(TreeBranchCollapsedEventArgs e) { + if (this.Collapsed != null) + this.Collapsed(this, e); + } + + #endregion + } + + //----------------------------------------------------------------------------------- + + #region Event Parameter Blocks + + /// + /// Let the world know that a cell edit operation is beginning or ending + /// + public class CellEditEventArgs : EventArgs { + /// + /// Create an event args + /// + /// + /// + /// + /// + /// + public CellEditEventArgs(OLVColumn column, Control control, Rectangle cellBounds, OLVListItem item, int subItemIndex) { + this.Control = control; + this.column = column; + this.cellBounds = cellBounds; + this.listViewItem = item; + this.rowObject = item.RowObject; + this.subItemIndex = subItemIndex; + this.value = column.GetValue(item.RowObject); + } + + /// + /// Change this to true to cancel the cell editing operation. + /// + /// + /// During the CellEditStarting event, setting this to true will prevent the cell from being edited. + /// During the CellEditFinishing event, if this value is already true, this indicates that the user has + /// cancelled the edit operation and that the handler should perform cleanup only. Setting this to true, + /// will prevent the ObjectListView from trying to write the new value into the model object. + /// + public bool Cancel; + + /// + /// During the CellEditStarting event, this can be modified to be the control that you want + /// to edit the value. You must fully configure the control before returning from the event, + /// including its bounds and the value it is showing. + /// During the CellEditFinishing event, you can use this to get the value that the user + /// entered and commit that value to the model. Changing the control during the finishing + /// event has no effect. + /// + public Control Control; + + /// + /// The column of the cell that is going to be or has been edited. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is going to be or has been edited. + /// + public Object RowObject { + get { return this.rowObject; } + } + + private Object rowObject; + + /// + /// The listview item of the cell that is going to be or has been edited. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The data value of the cell as it stands in the control. + /// + /// Only validate during Validating and Finishing events. + public Object NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private Object newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + + /// + /// The data value of the cell before the edit operation began. + /// + public Object Value { + get { return this.value; } + } + + private Object value; + + /// + /// The bounds of the cell that is going to be or has been edited. + /// + public Rectangle CellBounds { + get { return this.cellBounds; } + } + + private Rectangle cellBounds; + + /// + /// Gets or sets whether the control used for editing should be auto matically disposed + /// when the cell edit operation finishes. Defaults to true + /// + /// If the control is expensive to create, you might want to cache it and reuse for + /// for various cells. If so, you don't want ObjectListView to dispose of the control automatically + public bool AutoDispose { + get { return autoDispose; } + set { autoDispose = value; } + } + + private bool autoDispose = true; + } + + /// + /// Event blocks for events that can be cancelled + /// + public class CancellableEventArgs : EventArgs { + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled; + } + + /// + /// BeforeSorting + /// + public class BeforeSortingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = column; + this.GroupByOrder = order; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = groupColumn; + this.GroupByOrder = groupOrder; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Did the event handler already do the sorting for us? + /// + public bool Handled; + + /// + /// What column will be used for grouping + /// + public OLVColumn ColumnToGroupBy; + + /// + /// How will groups be ordered + /// + public SortOrder GroupByOrder; + + /// + /// What column will be used for sorting + /// + public OLVColumn ColumnToSort; + + /// + /// What order will be used for sorting. None means no sorting. + /// + public SortOrder SortOrder; + + /// + /// What column will be used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort; + + /// + /// What order will be used for secondary sorting? + /// + public SortOrder SecondarySortOrder; + } + + /// + /// Sorting has just occurred. + /// + public class AfterSortingEventArgs : EventArgs { + /// + /// Create a AfterSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public AfterSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.columnToGroupBy = groupColumn; + this.groupByOrder = groupOrder; + this.columnToSort = column; + this.sortOrder = order; + this.secondaryColumnToSort = column2; + this.secondarySortOrder = order2; + } + + /// + /// Create a AfterSortingEventArgs + /// + /// + public AfterSortingEventArgs(BeforeSortingEventArgs args) { + this.columnToGroupBy = args.ColumnToGroupBy; + this.groupByOrder = args.GroupByOrder; + this.columnToSort = args.ColumnToSort; + this.sortOrder = args.SortOrder; + this.secondaryColumnToSort = args.SecondaryColumnToSort; + this.secondarySortOrder = args.SecondarySortOrder; + } + + /// + /// What column was used for grouping? + /// + public OLVColumn ColumnToGroupBy { + get { return columnToGroupBy; } + } + + private OLVColumn columnToGroupBy; + + /// + /// What ordering was used for grouping? + /// + public SortOrder GroupByOrder { + get { return groupByOrder; } + } + + private SortOrder groupByOrder; + + /// + /// What column was used for sorting? + /// + public OLVColumn ColumnToSort { + get { return columnToSort; } + } + + private OLVColumn columnToSort; + + /// + /// What ordering was used for sorting? + /// + public SortOrder SortOrder { + get { return sortOrder; } + } + + private SortOrder sortOrder; + + /// + /// What column was used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort { + get { return secondaryColumnToSort; } + } + + private OLVColumn secondaryColumnToSort; + + /// + /// What order was used for secondary sorting? + /// + public SortOrder SecondarySortOrder { + get { return secondarySortOrder; } + } + + private SortOrder secondarySortOrder; + } + + /// + /// This event is triggered when the contents of a list have changed + /// and we want the world to have a chance to filter the list. + /// + public class FilterEventArgs : EventArgs { + /// + /// Create a FilterEventArgs + /// + /// + public FilterEventArgs(IEnumerable objects) { + this.Objects = objects; + } + + /// + /// Gets or sets what objects are being filtered + /// + public IEnumerable Objects; + + /// + /// Gets or sets what objects survived the filtering + /// + public IEnumerable FilteredObjects; + } + + /// + /// This event is triggered after the items in the list have been changed, + /// either through SetObjects, AddObjects or RemoveObjects. + /// + public class ItemsChangedEventArgs : EventArgs { + /// + /// Create a ItemsChangedEventArgs + /// + public ItemsChangedEventArgs() { } + + /// + /// Constructor for this event when used by a virtual list + /// + /// + /// + public ItemsChangedEventArgs(int oldObjectCount, int newObjectCount) { + this.oldObjectCount = oldObjectCount; + this.newObjectCount = newObjectCount; + } + + /// + /// Gets how many items were in the list before it changed + /// + public int OldObjectCount { + get { return oldObjectCount; } + } + + private int oldObjectCount; + + /// + /// Gets how many objects are in the list after the change. + /// + public int NewObjectCount { + get { return newObjectCount; } + } + + private int newObjectCount; + } + + /// + /// This event is triggered by AddObjects before any change has been made to the list. + /// + public class ItemsAddingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsAddingEventArgs + /// + /// + public ItemsAddingEventArgs(ICollection objectsToAdd) { + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Create an ItemsAddingEventArgs + /// + /// + /// + public ItemsAddingEventArgs(int index, ICollection objectsToAdd) { + this.Index = index; + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Gets or sets where the collection is going to be inserted. + /// + public int Index; + + /// + /// Gets or sets the objects to be added to the list + /// + public ICollection ObjectsToAdd; + } + + /// + /// This event is triggered by SetObjects before any change has been made to the list. + /// + /// + /// When used with a virtual list, OldObjects will always be null. + /// + public class ItemsChangingEventArgs : CancellableEventArgs { + /// + /// Create ItemsChangingEventArgs + /// + /// + /// + public ItemsChangingEventArgs(IEnumerable oldObjects, IEnumerable newObjects) { + this.oldObjects = oldObjects; + this.NewObjects = newObjects; + } + + /// + /// Gets the objects that were in the list before it change. + /// For virtual lists, this will always be null. + /// + public IEnumerable OldObjects { + get { return oldObjects; } + } + + private IEnumerable oldObjects; + + /// + /// Gets or sets the objects that will be in the list after it changes. + /// + public IEnumerable NewObjects; + } + + /// + /// This event is triggered by RemoveObjects before any change has been made to the list. + /// + public class ItemsRemovingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsRemovingEventArgs + /// + /// + public ItemsRemovingEventArgs(ICollection objectsToRemove) { + this.ObjectsToRemove = objectsToRemove; + } + + /// + /// Gets or sets the objects that will be removed + /// + public ICollection ObjectsToRemove; + } + + /// + /// Triggered after the user types into a list + /// + public class AfterSearchingEventArgs : EventArgs { + /// + /// Create an AfterSearchingEventArgs + /// + /// + /// + public AfterSearchingEventArgs(string stringToFind, int indexSelected) { + this.stringToFind = stringToFind; + this.indexSelected = indexSelected; + } + + /// + /// Gets the string that was actually searched for + /// + public string StringToFind { + get { return this.stringToFind; } + } + + private string stringToFind; + + /// + /// Gets or sets whether an the event handler already handled this event + /// + public bool Handled; + + /// + /// Gets the index of the row that was selected by the search. + /// -1 means that no row was matched + /// + public int IndexSelected { + get { return this.indexSelected; } + } + + private int indexSelected; + } + + /// + /// Triggered when the user types into a list + /// + public class BeforeSearchingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSearchingEventArgs + /// + /// + /// + public BeforeSearchingEventArgs(string stringToFind, int startSearchFrom) { + this.StringToFind = stringToFind; + this.StartSearchFrom = startSearchFrom; + } + + /// + /// Gets or sets the string that will be found by the search routine + /// + /// Modifying this value does not modify the memory of what the user has typed. + /// When the user next presses a character, the search string will revert to what + /// the user has actually typed. + public string StringToFind; + + /// + /// Gets or sets the index of the first row that will be considered to matching. + /// + public int StartSearchFrom; + } + + /// + /// The parameter block when telling the world about a cell based event + /// + public class CellEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + /// This is null for events triggered by the header. + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + /// This is -1 for events triggered by the header. + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location { + get { return this.location; } + internal set { this.location = value; } + } + + private Point location; + + /// + /// Gets the state of the modifier keys at the time of the event + /// + public Keys ModifierKeys { + get { return this.modifierKeys; } + internal set { this.modifierKeys = value; } + } + + private Keys modifierKeys; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view and + /// for event triggered by the header + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the HitTest object that determined which cell was hit + /// + public OlvListViewHitTestInfo HitTest { + get { return hitTest; } + internal set { hitTest = value; } + } + + private OlvListViewHitTestInfo hitTest; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled; + } + + /// + /// Tells the world that a cell was clicked + /// + public class CellClickEventArgs : CellEventArgs { + /// + /// Gets or sets the number of clicks associated with this event + /// + public int ClickCount { + get { return this.clickCount; } + set { this.clickCount = value; } + } + + private int clickCount; + } + + /// + /// Tells the world that a cell was right clicked + /// + public class CellRightClickEventArgs : CellEventArgs { + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ContextMenuStrip MenuStrip; + } + + /// + /// Tell the world that the mouse is over a given cell + /// + public class CellOverEventArgs : CellEventArgs { } + + /// + /// Tells the world that the frozen-ness of the ObjectListView has changed. + /// + public class FreezeEventArgs : EventArgs { + /// + /// Make a FreezeEventArgs + /// + /// + public FreezeEventArgs(int freeze) { + this.FreezeLevel = freeze; + } + + /// + /// How frozen is the control? 0 means that the control is unfrozen, + /// more than 0 indicates froze. + /// + public int FreezeLevel { + get { return this.freezeLevel; } + set { this.freezeLevel = value; } + } + + private int freezeLevel; + } + + /// + /// The parameter block when telling the world that a tool tip is about to be shown. + /// + public class ToolTipShowingEventArgs : CellEventArgs { + /// + /// Gets the tooltip control that is triggering the tooltip event + /// + public ToolTipControl ToolTipControl { + get { return this.toolTipControl; } + internal set { this.toolTipControl = value; } + } + + private ToolTipControl toolTipControl; + + /// + /// Gets or sets the text should be shown on the tooltip for this event + /// + /// Setting this to empty or null prevents any tooltip from showing + public string Text; + + /// + /// In what direction should the text for this tooltip be drawn? + /// + public RightToLeft RightToLeft; + + /// + /// Should the tooltip for this event been shown in bubble style? + /// + /// This doesn't work reliable under Vista + public bool? IsBalloon; + + /// + /// What color should be used for the background of the tooltip + /// + /// Setting this does nothing under Vista + public Color? BackColor; + + /// + /// What color should be used for the foreground of the tooltip + /// + /// Setting this does nothing under Vista + public Color? ForeColor; + + /// + /// What string should be used as the title for the tooltip for this event? + /// + public string Title; + + /// + /// Which standard icon should be used for the tooltip for this event + /// + public ToolTipControl.StandardIcons? StandardIcon; + + /// + /// How many milliseconds should the tooltip remain before it automatically + /// disappears. + /// + public int? AutoPopDelay; + + /// + /// What font should be used to draw the text of the tooltip? + /// + public Font Font; + } + + /// + /// Common information to all hyperlink events + /// + public class HyperlinkEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the ObjectListView that is the source of the event + /// + public string Url { + get { return this.url; } + internal set { this.url = value; } + } + + private string url; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + } + + /// + /// + /// + public class IsHyperlinkEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the text of the cell + /// + public string Text { + get { return this.text; } + internal set { this.text = value; } + } + + private string text; + + /// + /// Gets or sets whether or not this cell is a hyperlink. + /// Defaults to true for enabled rows and false for disabled rows. + /// + public bool IsHyperlink { + get { return this.isHyperlink; } + set { this.isHyperlink = value; } + } + + private bool isHyperlink; + + /// + /// Gets or sets the url that should be invoked when this cell is clicked. + /// + /// Setting this to None or String.Empty means that this cell is not a hyperlink + public string Url; + } + + /// + /// + public class FormatRowEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.Item.RowObject; } + } + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the display index of the row + /// + public int DisplayIndex { + get { return this.displayIndex; } + internal set { this.displayIndex = value; } + } + + private int displayIndex = -1; + + /// + /// Should events be triggered for each cell in this row? + /// + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + + private bool useCellFormatEvents; + } + + /// + /// Parameter block for FormatCellEvent + /// + public class FormatCellEventArgs : FormatRowEventArgs { + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the model value that is being displayed by the cell. + /// + /// This is null when the view is not in details view + public object CellValue { + get { return this.SubItem == null ? null : this.SubItem.ModelValue; } + } + } + + /// + /// The event args when a hyperlink is clicked + /// + public class HyperlinkClickedEventArgs : CellEventArgs { + /// + /// Gets the url that was associated with this cell. + /// + public string Url { + get { return url; } + set { url = value; } + } + + private string url; + + } + + /// + /// The event args when the check box in a column header is changing + /// + public class HeaderCheckBoxChangingEventArgs : CancelEventArgs { + + /// + /// Get the column whose checkbox is changing + /// + public OLVColumn Column { + get { return column; } + internal set { column = value; } + } + + private OLVColumn column; + + /// + /// Get or set the new state that should be used by the column + /// + public CheckState NewCheckState { + get { return newCheckState; } + set { newCheckState = value; } + } + + private CheckState newCheckState; + } + + /// + /// The event args when the hot item changed + /// + public class HotItemChangedEventArgs : EventArgs { + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + /// + /// Gets the part of the cell that the mouse is over + /// + public HitTestLocation HotCellHitLocation { + get { return newHotCellHitLocation; } + internal set { newHotCellHitLocation = value; } + } + + private HitTestLocation newHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + public virtual HitTestLocationEx HotCellHitLocationEx { + get { return this.hotCellHitLocationEx; } + internal set { this.hotCellHitLocationEx = value; } + } + + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse is over + /// + /// In non-details view, this will always be 0. + public int HotColumnIndex { + get { return newHotColumnIndex; } + internal set { newHotColumnIndex = value; } + } + + private int newHotColumnIndex; + + /// + /// Gets the index of the row that the mouse is over + /// + public int HotRowIndex { + get { return newHotRowIndex; } + internal set { newHotRowIndex = value; } + } + + private int newHotRowIndex; + + /// + /// Gets the group that the mouse is over + /// + public OLVGroup HotGroup { + get { return hotGroup; } + internal set { hotGroup = value; } + } + + private OLVGroup hotGroup; + + /// + /// Gets the part of the cell that the mouse used to be over + /// + public HitTestLocation OldHotCellHitLocation { + get { return oldHotCellHitLocation; } + internal set { oldHotCellHitLocation = value; } + } + + private HitTestLocation oldHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse used to be over + /// + public virtual HitTestLocationEx OldHotCellHitLocationEx { + get { return this.oldHotCellHitLocationEx; } + internal set { this.oldHotCellHitLocationEx = value; } + } + + private HitTestLocationEx oldHotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse used to be over + /// + public int OldHotColumnIndex { + get { return oldHotColumnIndex; } + internal set { oldHotColumnIndex = value; } + } + + private int oldHotColumnIndex; + + /// + /// Gets the index of the row that the mouse used to be over + /// + public int OldHotRowIndex { + get { return oldHotRowIndex; } + internal set { oldHotRowIndex = value; } + } + + private int oldHotRowIndex; + + /// + /// Gets the group that the mouse used to be over + /// + public OLVGroup OldHotGroup { + get { return oldHotGroup; } + internal set { oldHotGroup = value; } + } + + private OLVGroup oldHotGroup; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return string.Format("NewHotCellHitLocation: {0}, HotCellHitLocationEx: {1}, NewHotColumnIndex: {2}, NewHotRowIndex: {3}, HotGroup: {4}", this.newHotCellHitLocation, this.hotCellHitLocationEx, this.newHotColumnIndex, this.newHotRowIndex, this.hotGroup); + } + } + + /// + /// Let the world know that a checkbox on a subitem is changing + /// + public class SubItemCheckingEventArgs : CancellableEventArgs { + /// + /// Create a new event block + /// + /// + /// + /// + /// + /// + public SubItemCheckingEventArgs(OLVColumn column, OLVListItem item, int subItemIndex, CheckState currentValue, CheckState newValue) { + this.column = column; + this.listViewItem = item; + this.subItemIndex = subItemIndex; + this.currentValue = currentValue; + this.newValue = newValue; + } + + /// + /// The column of the cell that is having its checkbox changed. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is having its checkbox changed. + /// + public Object RowObject { + get { return this.listViewItem.RowObject; } + } + + /// + /// The listview item of the cell that is having its checkbox changed. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The current check state of the cell. + /// + public CheckState CurrentValue { + get { return this.currentValue; } + } + + private CheckState currentValue; + + /// + /// The proposed new check state of the cell. + /// + public CheckState NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private CheckState newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + } + + /// + /// This event argument block is used when groups are created for a list. + /// + public class CreateGroupsEventArgs : EventArgs { + /// + /// Create a CreateGroupsEventArgs + /// + /// + public CreateGroupsEventArgs(GroupingParameters parms) { + this.parameters = parms; + } + + /// + /// Gets the settings that control the creation of groups + /// + public GroupingParameters Parameters { + get { return this.parameters; } + } + + private GroupingParameters parameters; + + /// + /// Gets or sets the groups that should be used + /// + public IList Groups { + get { return this.groups; } + set { this.groups = value; } + } + + private IList groups; + + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled { + get { return canceled; } + set { canceled = value; } + } + + private bool canceled; + + } + + /// + /// This event argument block is used when the text of a group task is clicked + /// + public class GroupTaskClickedEventArgs : EventArgs { + /// + /// Create a GroupTaskClickedEventArgs + /// + /// + public GroupTaskClickedEventArgs(OLVGroup group) { + this.group = group; + } + + /// + /// Gets which group was clicked + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + } + + /// + /// This event argument block is used when a group is about to expand or collapse + /// + public class GroupExpandingCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a GroupExpandingCollapsingEventArgs + /// + /// + public GroupExpandingCollapsingEventArgs(OLVGroup group) { + if (group == null) throw new ArgumentNullException("group"); + this.olvGroup = group; + } + + /// + /// Gets which group is expanding/collapsing + /// + public OLVGroup Group { + get { return this.olvGroup; } + } + + private readonly OLVGroup olvGroup; + + /// + /// Gets whether this event is going to expand the group. + /// If this is false, the group must be collapsing. + /// + public bool IsExpanding { + get { return this.Group.Collapsed; } + } + } + + /// + /// This event argument block is used when the state of group has changed (collapsed, selected) + /// + public class GroupStateChangedEventArgs : EventArgs { + /// + /// Create a GroupStateChangedEventArgs + /// + /// + /// + /// + public GroupStateChangedEventArgs(OLVGroup group, GroupState oldState, GroupState newState) { + this.group = group; + this.oldState = oldState; + this.newState = newState; + } + + /// + /// Gets whether the group was collapsed by this event + /// + public bool Collapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was focused by this event + /// + public bool Focused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was selected by this event + /// + public bool Selected { + get { + return ((oldState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets whether the group was uncollapsed by this event + /// + public bool Uncollapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was unfocused by this event + /// + public bool Unfocused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was unselected by this event + /// + public bool Unselected { + get { + return ((oldState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets which group had its state changed + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + + /// + /// Gets the previous state of the group + /// + public GroupState OldState { + get { return this.oldState; } + } + + private readonly GroupState oldState; + + + /// + /// Gets the new state of the group + /// + public GroupState NewState { + get { return this.newState; } + } + + private readonly GroupState newState; + } + + /// + /// This event argument block is used when a branch of a tree is about to be expanded + /// + public class TreeBranchExpandingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to expand. If null, all branches are going to be expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree has just been expanded + /// + public class TreeBranchExpandedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was expanded. If null, all branches were expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree is about to be collapsed + /// + public class TreeBranchCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to collapse. If this is null, all models are going to collapse. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be collapsed. Can be null + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + } + + + /// + /// This event argument block is used when a branch of a tree has just been collapsed + /// + public class TreeBranchCollapsedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was collapsed. If null, all branches were collapsed + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was collapsed + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// Tells the world that a column header was right clicked + /// + public class ColumnRightClickEventArgs : ColumnClickEventArgs { + public ColumnRightClickEventArgs(int columnIndex, ToolStripDropDown menu, Point location) : base(columnIndex) { + MenuStrip = menu; + Location = location; + } + + /// + /// Set this to true to cancel the right click operation. + /// + public bool Cancel; + + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ToolStripDropDown MenuStrip; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location; + } + + #endregion +} diff --git a/ObjectListView/Implementation/GroupingParameters.cs b/ObjectListView/Implementation/GroupingParameters.cs new file mode 100644 index 0000000..a87f217 --- /dev/null +++ b/ObjectListView/Implementation/GroupingParameters.cs @@ -0,0 +1,204 @@ +/* + * GroupingParameters - All the data that is used to create groups in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// This class contains all the settings used when groups are created + /// + public class GroupingParameters { + /// + /// Create a GroupingParameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public GroupingParameters(ObjectListView olv, OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder, + string titleFormat, string titleSingularFormat, bool sortItemsByPrimaryColumn) { + this.ListView = olv; + this.GroupByColumn = groupByColumn; + this.GroupByOrder = groupByOrder; + this.PrimarySort = column; + this.PrimarySortOrder = order; + this.SecondarySort = secondaryColumn; + this.SecondarySortOrder = secondaryOrder; + this.SortItemsByPrimaryColumn = sortItemsByPrimaryColumn; + this.TitleFormat = titleFormat; + this.TitleSingularFormat = titleSingularFormat; + } + + /// + /// Gets or sets the ObjectListView being grouped + /// + public ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the column used to create groups + /// + public OLVColumn GroupByColumn { + get { return this.groupByColumn; } + set { this.groupByColumn = value; } + } + private OLVColumn groupByColumn; + + /// + /// In what order will the groups themselves be sorted? + /// + public SortOrder GroupByOrder { + get { return this.groupByOrder; } + set { this.groupByOrder = value; } + } + private SortOrder groupByOrder; + + /// + /// If this is set, this comparer will be used to order the groups + /// + public IComparer GroupComparer { + get { return this.groupComparer; } + set { this.groupComparer = value; } + } + private IComparer groupComparer; + + /// + /// If this is set, this comparer will be used to order items within each group + /// + public IComparer ItemComparer { + get { return this.itemComparer; } + set { this.itemComparer = value; } + } + private IComparer itemComparer; + + /// + /// Gets or sets the column that will be the primary sort + /// + public OLVColumn PrimarySort { + get { return this.primarySort; } + set { this.primarySort = value; } + } + private OLVColumn primarySort; + + /// + /// Gets or sets the ordering for the primary sort + /// + public SortOrder PrimarySortOrder { + get { return this.primarySortOrder; } + set { this.primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets the column used for secondary sorting + /// + public OLVColumn SecondarySort { + get { return this.secondarySort; } + set { this.secondarySort = value; } + } + private OLVColumn secondarySort; + + /// + /// Gets or sets the ordering for the secondary sort + /// + public SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder; + + /// + /// Gets or sets the title format used for groups with zero or more than one element + /// + public string TitleFormat { + get { return this.titleFormat; } + set { this.titleFormat = value; } + } + private string titleFormat; + + /// + /// Gets or sets the title format used for groups with only one element + /// + public string TitleSingularFormat { + get { return this.titleSingularFormat; } + set { this.titleSingularFormat = value; } + } + private string titleSingularFormat; + + /// + /// Gets or sets whether the items should be sorted by the primary column + /// + public bool SortItemsByPrimaryColumn { + get { return this.sortItemsByPrimaryColumn; } + set { this.sortItemsByPrimaryColumn = value; } + } + private bool sortItemsByPrimaryColumn; + + /// + /// Create an OLVGroup for the given information + /// + /// + /// + /// + /// + public OLVGroup CreateGroup(object key, int count, bool hasCollapsibleGroups) { + string title = GroupByColumn.ConvertGroupKeyToTitle(key); + if (!String.IsNullOrEmpty(TitleFormat)) + { + string format = (count == 1 ? TitleSingularFormat : TitleFormat); + try + { + title = String.Format(format, title, count); + } + catch (FormatException) + { + title = "Invalid group format: " + format; + } + } + OLVGroup lvg = new OLVGroup(title); + lvg.Column = GroupByColumn; + lvg.Collapsible = hasCollapsibleGroups; + lvg.Key = key; + lvg.SortValue = key as IComparable; + return lvg; + } + } +} diff --git a/ObjectListView/Implementation/Groups.cs b/ObjectListView/Implementation/Groups.cs new file mode 100644 index 0000000..33a7cb2 --- /dev/null +++ b/ObjectListView/Implementation/Groups.cs @@ -0,0 +1,761 @@ +/* + * Groups - Enhancements to the normal ListViewGroup + * + * Author: Phillip Piper + * Date: 22/08/2009 6:03PM + * + * Change log: + * v2.3 + * 2009-09-09 JPP - Added Collapsed and Collapsible properties + * 2009-09-01 JPP - Cleaned up code, added more docs + * - Works under VS2005 again + * 2009-08-22 JPP - Initial version + * + * To do: + * - Implement subseting + * - Implement footer items + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// These values indicate what is the state of the group. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupState + { + /// + /// Normal + /// + LVGS_NORMAL = 0x0, + + /// + /// Collapsed + /// + LVGS_COLLAPSED = 0x1, + + /// + /// Hidden + /// + LVGS_HIDDEN = 0x2, + + /// + /// NoHeader + /// + LVGS_NOHEADER = 0x4, + + /// + /// Can be collapsed + /// + LVGS_COLLAPSIBLE = 0x8, + + /// + /// Has focus + /// + LVGS_FOCUSED = 0x10, + + /// + /// Is Selected + /// + LVGS_SELECTED = 0x20, + + /// + /// Is subsetted + /// + LVGS_SUBSETED = 0x40, + + /// + /// Subset link has focus + /// + LVGS_SUBSETLINKFOCUSED = 0x80, + + /// + /// All styles + /// + LVGS_ALL = 0xFFFF + } + + /// + /// This mask indicates which members of a LVGROUP have valid data. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupMask + { + /// + /// No mask + /// + LVGF_NONE = 0, + + /// + /// Group has header + /// + LVGF_HEADER = 1, + + /// + /// Group has footer + /// + LVGF_FOOTER = 2, + + /// + /// Group has state + /// + LVGF_STATE = 4, + + /// + /// + /// + LVGF_ALIGN = 8, + + /// + /// + /// + LVGF_GROUPID = 0x10, + + /// + /// pszSubtitle is valid + /// + LVGF_SUBTITLE = 0x00100, + + /// + /// pszTask is valid + /// + LVGF_TASK = 0x00200, + + /// + /// pszDescriptionTop is valid + /// + LVGF_DESCRIPTIONTOP = 0x00400, + + /// + /// pszDescriptionBottom is valid + /// + LVGF_DESCRIPTIONBOTTOM = 0x00800, + + /// + /// iTitleImage is valid + /// + LVGF_TITLEIMAGE = 0x01000, + + /// + /// iExtendedImage is valid + /// + LVGF_EXTENDEDIMAGE = 0x02000, + + /// + /// iFirstItem and cItems are valid + /// + LVGF_ITEMS = 0x04000, + + /// + /// pszSubsetTitle is valid + /// + LVGF_SUBSET = 0x08000, + + /// + /// readonly, cItems holds count of items in visible subset, iFirstItem is valid + /// + LVGF_SUBSETITEMS = 0x10000 + } + + /// + /// This mask indicates which members of a GROUPMETRICS structure are valid + /// + [Flags] + public enum GroupMetricsMask + { + /// + /// + /// + LVGMF_NONE = 0, + + /// + /// + /// + LVGMF_BORDERSIZE = 1, + + /// + /// + /// + LVGMF_BORDERCOLOR = 2, + + /// + /// + /// + LVGMF_TEXTCOLOR = 4 + } + + /// + /// Instances of this class enhance the capabilities of a normal ListViewGroup, + /// enabling the functionality that was released in v6 of the common controls. + /// + /// + /// + /// In this implementation (2009-09), these objects are essentially passive. + /// Setting properties does not automatically change the associated group in + /// the listview. Collapsed and Collapsible are two exceptions to this and + /// give immediate results. + /// + /// + /// This really should be a subclass of ListViewGroup, but that class is + /// sealed (why is that?). So this class provides the same interface as a + /// ListViewGroup, plus many other new properties. + /// + /// + public class OLVGroup + { + #region Creation + + /// + /// Create an OLVGroup + /// + public OLVGroup() : this("Default group header") { + } + + /// + /// Create a group with the given title + /// + /// Title of the group + public OLVGroup(string header) { + this.Header = header; + this.Id = OLVGroup.nextId++; + this.TitleImage = -1; + this.ExtendedImage = -1; + } + private static int nextId; + + #endregion + + #region Public properties + + /// + /// Gets or sets the bottom description of the group + /// + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + /// + /// THIS PROPERTY IS CURRENTLY NOT USED. + /// + /// + public string BottomDescription { + get { return this.bottomDescription; } + set { this.bottomDescription = value; } + } + private string bottomDescription; + + /// + /// Gets or sets whether or not this group is collapsed + /// + public bool Collapsed { + get { return this.GetOneState(GroupState.LVGS_COLLAPSED); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSED); } + } + + /// + /// Gets or sets whether or not this group can be collapsed + /// + public bool Collapsible { + get { return this.GetOneState(GroupState.LVGS_COLLAPSIBLE); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSIBLE); } + } + + /// + /// Gets or sets the column that was used to construct this group. + /// + public OLVColumn Column { + get { return this.column; } + set { this.column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets some representation of the contents of this group + /// + /// This is user defined (like Tag) + public IList Contents { + get { return this.contents; } + set { this.contents = value; } + } + private IList contents; + + /// + /// Gets whether this group has been created. + /// + public bool Created { + get { return this.ListView != null; } + } + + /// + /// Gets or sets the int or string that will select the extended image to be shown against the title + /// + public object ExtendedImage { + get { return this.extendedImage; } + set { this.extendedImage = value; } + } + private object extendedImage; + + /// + /// Gets or sets the footer of the group + /// + public string Footer { + get { return this.footer; } + set { this.footer = value; } + } + private string footer; + + /// + /// Gets the internal id of our associated ListViewGroup. + /// + public int GroupId { + get { + if (this.ListViewGroup == null) + return this.Id; + + // Use reflection to get around the access control on the ID property + if (OLVGroup.groupIdPropInfo == null) { + OLVGroup.groupIdPropInfo = typeof(ListViewGroup).GetProperty("ID", + BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(OLVGroup.groupIdPropInfo != null); + } + + int? groupId = OLVGroup.groupIdPropInfo.GetValue(this.ListViewGroup, null) as int?; + return groupId.HasValue ? groupId.Value : -1; + } + } + private static PropertyInfo groupIdPropInfo; + + /// + /// Gets or sets the header of the group + /// + public string Header { + get { return this.header; } + set { this.header = value; } + } + private string header; + + /// + /// Gets or sets the horizontal alignment of the group header + /// + public HorizontalAlignment HeaderAlignment { + get { return this.headerAlignment; } + set { this.headerAlignment = value; } + } + private HorizontalAlignment headerAlignment; + + /// + /// Gets or sets the internally created id of the group + /// + public int Id { + get { return this.id; } + set { this.id = value; } + } + private int id; + + /// + /// Gets or sets ListViewItems that are members of this group + /// + /// Listener of the BeforeCreatingGroups event can populate this collection. + /// It is only used on non-virtual lists. + public IList Items { + get { return this.items; } + set { this.items = value; } + } + private IList items = new List(); + + /// + /// Gets or sets the key that was used to partition objects into this group + /// + /// This is user defined (like Tag) + public object Key { + get { return this.key; } + set { this.key = value; } + } + private object key; + + /// + /// Gets the ObjectListView that this group belongs to + /// + /// If this is null, the group has not yet been created. + public ObjectListView ListView { + get { return this.listView; } + protected set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the name of the group + /// + /// As of 2009-09-01, this property is not used. + public string Name { + get { return this.name; } + set { this.name = value; } + } + private string name; + + /// + /// Gets or sets whether this group is focused + /// + public bool Focused + { + get { return this.GetOneState(GroupState.LVGS_FOCUSED); } + set { this.SetOneState(value, GroupState.LVGS_FOCUSED); } + } + + /// + /// Gets or sets whether this group is selected + /// + public bool Selected + { + get { return this.GetOneState(GroupState.LVGS_SELECTED); } + set { this.SetOneState(value, GroupState.LVGS_SELECTED); } + } + + /// + /// Gets or sets the text that will show that this group is subsetted + /// + /// + /// As of WinSDK v7.0, subsetting of group is officially unimplemented. + /// We can get around this using undocumented interfaces and may do so. + /// + public string SubsetTitle { + get { return this.subsetTitle; } + set { this.subsetTitle = value; } + } + private string subsetTitle; + + /// + /// Gets or set the subtitleof the task + /// + public string Subtitle { + get { return this.subtitle; } + set { this.subtitle = value; } + } + private string subtitle; + + /// + /// Gets or sets the value by which this group will be sorted. + /// + public IComparable SortValue { + get { return this.sortValue; } + set { this.sortValue = value; } + } + private IComparable sortValue; + + /// + /// Gets or sets the state of the group + /// + public GroupState State { + get { return this.state; } + set { this.state = value; } + } + private GroupState state; + + /// + /// Gets or sets which bits of State are valid + /// + public GroupState StateMask { + get { return this.stateMask; } + set { this.stateMask = value; } + } + private GroupState stateMask; + + /// + /// Gets or sets whether this group is showing only a subset of its elements + /// + /// + /// As of WinSDK v7.0, this property officially does nothing. + /// + public bool Subseted { + get { return this.GetOneState(GroupState.LVGS_SUBSETED); } + set { this.SetOneState(value, GroupState.LVGS_SUBSETED); } + } + + /// + /// Gets or sets the user-defined data attached to this group + /// + public object Tag { + get { return this.tag; } + set { this.tag = value; } + } + private object tag; + + /// + /// Gets or sets the task of this group + /// + /// This task is the clickable text that appears on the right margin + /// of the group header. + public string Task { + get { return this.task; } + set { this.task = value; } + } + private string task; + + /// + /// Gets or sets the int or string that will select the image to be shown against the title + /// + public object TitleImage { + get { return this.titleImage; } + set { this.titleImage = value; } + } + private object titleImage; + + /// + /// Gets or sets the top description of the group + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + public string TopDescription { + get { return this.topDescription; } + set { this.topDescription = value; } + } + private string topDescription; + + /// + /// Gets or sets the number of items that are within this group. + /// + /// This should only be used for virtual groups. + public int VirtualItemCount { + get { return this.virtualItemCount; } + set { this.virtualItemCount = value; } + } + private int virtualItemCount; + + #endregion + + #region Protected properties + + /// + /// Gets or sets the ListViewGroup that is shadowed by this group. + /// + /// For virtual groups, this will always be null. + protected ListViewGroup ListViewGroup { + get { return this.listViewGroup; } + set { this.listViewGroup = value; } + } + private ListViewGroup listViewGroup; + #endregion + + #region Calculations/Conversions + + /// + /// Calculate the index into the group image list of the given image selector + /// + /// + /// + public int GetImageIndex(object imageSelector) { + if (imageSelector == null || this.ListView == null || this.ListView.GroupImageList == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null) + return this.ListView.GroupImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Convert this object to a string representation + /// + /// + public override string ToString() { + return this.Header; + } + + #endregion + + #region Commands + + /// + /// Insert a native group into the underlying Windows control, + /// *without* using a ListViewGroup + /// + /// + /// This is used when creating virtual groups + public void InsertGroupNewStyle(ObjectListView olv) { + this.ListView = olv; + NativeMethods.InsertGroup(olv, this.AsNativeGroup(true)); + } + + /// + /// Insert a native group into the underlying control via a ListViewGroup + /// + /// + public void InsertGroupOldStyle(ObjectListView olv) { + this.ListView = olv; + + // Create/update the associated ListViewGroup + if (this.ListViewGroup == null) + this.ListViewGroup = new ListViewGroup(); + this.ListViewGroup.Header = this.Header; + this.ListViewGroup.HeaderAlignment = this.HeaderAlignment; + this.ListViewGroup.Name = this.Name; + + // Remember which OLVGroup created the ListViewGroup + this.ListViewGroup.Tag = this; + + // Add the group to the control + olv.Groups.Add(this.ListViewGroup); + + // Add any extra information + NativeMethods.SetGroupInfo(olv, this.GroupId, this.AsNativeGroup(false)); + } + + /// + /// Change the members of the group to match the current contents of Items, + /// using a ListViewGroup + /// + public void SetItemsOldStyle() { + List list = this.Items as List; + if (list == null) { + foreach (OLVListItem item in this.Items) { + this.ListViewGroup.Items.Add(item); + } + } else { + this.ListViewGroup.Items.AddRange(list.ToArray()); + } + } + + #endregion + + #region Implementation + + /// + /// Create a native LVGROUP structure that matches this group + /// + internal NativeMethods.LVGROUP2 AsNativeGroup(bool withId) { + + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2)); + group.mask = (uint)(GroupMask.LVGF_HEADER ^ GroupMask.LVGF_ALIGN ^ GroupMask.LVGF_STATE); + group.pszHeader = this.Header; + group.uAlign = (uint)this.HeaderAlignment; + group.stateMask = (uint)this.StateMask; + group.state = (uint)this.State; + + if (withId) { + group.iGroupId = this.GroupId; + group.mask ^= (uint)GroupMask.LVGF_GROUPID; + } + + if (!String.IsNullOrEmpty(this.Footer)) { + group.pszFooter = this.Footer; + group.mask ^= (uint)GroupMask.LVGF_FOOTER; + } + + if (!String.IsNullOrEmpty(this.Subtitle)) { + group.pszSubtitle = this.Subtitle; + group.mask ^= (uint)GroupMask.LVGF_SUBTITLE; + } + + if (!String.IsNullOrEmpty(this.Task)) { + group.pszTask = this.Task; + group.mask ^= (uint)GroupMask.LVGF_TASK; + } + + if (!String.IsNullOrEmpty(this.TopDescription)) { + group.pszDescriptionTop = this.TopDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONTOP; + } + + if (!String.IsNullOrEmpty(this.BottomDescription)) { + group.pszDescriptionBottom = this.BottomDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONBOTTOM; + } + + int imageIndex = this.GetImageIndex(this.TitleImage); + if (imageIndex >= 0) { + group.iTitleImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_TITLEIMAGE; + } + + imageIndex = this.GetImageIndex(this.ExtendedImage); + if (imageIndex >= 0) { + group.iExtendedImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_EXTENDEDIMAGE; + } + + if (!String.IsNullOrEmpty(this.SubsetTitle)) { + group.pszSubsetTitle = this.SubsetTitle; + group.mask ^= (uint)GroupMask.LVGF_SUBSET; + } + + if (this.VirtualItemCount > 0) { + group.cItems = this.VirtualItemCount; + group.mask ^= (uint)GroupMask.LVGF_ITEMS; + } + + return group; + } + + private bool GetOneState(GroupState mask) { + if (this.Created) + this.State = this.GetState(); + return (this.State & mask) == mask; + } + + /// + /// Get the current state of this group from the underlying control + /// + protected GroupState GetState() { + return NativeMethods.GetGroupState(this.ListView, this.GroupId, GroupState.LVGS_ALL); + } + + /// + /// Get the current state of this group from the underlying control + /// + protected int SetState(GroupState newState, GroupState mask) { + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2))); + group.mask = (uint)GroupMask.LVGF_STATE; + group.state = (uint)newState; + group.stateMask = (uint)mask; + return NativeMethods.SetGroupInfo(this.ListView, this.GroupId, group); + } + + private void SetOneState(bool value, GroupState mask) + { + this.StateMask ^= mask; + if (value) + this.State ^= mask; + else + this.State &= ~mask; + + if (this.Created) + this.SetState(this.State, mask); + } + + #endregion + + } +} diff --git a/ObjectListView/Implementation/Munger.cs b/ObjectListView/Implementation/Munger.cs new file mode 100644 index 0000000..8b81aec --- /dev/null +++ b/ObjectListView/Implementation/Munger.cs @@ -0,0 +1,568 @@ +/* + * Munger - An Interface pattern on getting and setting values from object through Reflection + * + * Author: Phillip Piper + * Date: 28/11/2008 17:15 + * + * Change log: + * v2.5.1 + * 2012-05-01 JPP - Added IgnoreMissingAspects property + * v2.5 + * 2011-05-20 JPP - Accessing through an indexer when the target had both a integer and + * a string indexer didn't work reliably. + * v2.4.1 + * 2010-08-10 JPP - Refactored into Munger/SimpleMunger. 3x faster! + * v2.3 + * 2009-02-15 JPP - Made Munger a public class + * 2009-01-20 JPP - Made the Munger capable of handling indexed access. + * Incidentally, this removed the ugliness that the last change introduced. + * 2009-01-18 JPP - Handle target objects from a DataListView (normally DataRowViews) + * v2.0 + * 2008-11-28 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace BrightIdeasSoftware +{ + /// + /// An instance of Munger gets a value from or puts a value into a target object. The property + /// to be peeked (or poked) is determined from a string. The peeking or poking is done using reflection. + /// + /// + /// Name of the aspect to be peeked can be a field, property or parameterless method. The name of an + /// aspect to poke can be a field, writable property or single parameter method. + /// + /// Aspect names can be dotted to chain a series of references. + /// + /// Order.Customer.HomeAddress.State + /// + public class Munger + { + #region Life and death + + /// + /// Create a do nothing Munger + /// + public Munger() + { + } + + /// + /// Create a Munger that works on the given aspect name + /// + /// The name of the + public Munger(String aspectName) + { + this.AspectName = aspectName; + } + + #endregion + + #region Static utility methods + + /// + /// A helper method to put the given value into the given aspect of the given object. + /// + /// This method catches and silently ignores any errors that occur + /// while modifying the target object + /// The object to be modified + /// The name of the property/field to be modified + /// The value to be assigned + /// Did the modification work? + public static bool PutProperty(object target, string propertyName, object value) { + try { + Munger munger = new Munger(propertyName); + return munger.PutValue(target, value); + } + catch (MungerException) { + // Not a lot we can do about this. Something went wrong in the bowels + // of the property. Let's take the ostrich approach and just ignore it :-) + + // Normally, we would never just silently ignore an exception. + // However, in this case, this is a utility method that explicitly + // contracts to catch and ignore errors. If this is not acceptable, + // the programmer should not use this method. + } + + return false; + } + + /// + /// Gets or sets whether Mungers will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if a Munger is asked to fetch a field/property/method + /// that does not exist from a model, it returns an error message, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error, and the munger should simply keep quiet. + /// + /// By default this is true during release builds. + /// + public static bool IgnoreMissingAspects { + get { return ignoreMissingAspects; } + set { ignoreMissingAspects = value; } + } + private static bool ignoreMissingAspects +#if !DEBUG + = true +#endif + ; + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or parameter-less method. + /// + /// + /// The name can be dotted, which chains references. If any link in the chain returns + /// null, the entire chain is considered to return null. + /// + /// + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + public string AspectName + { + get { return aspectName; } + set { + aspectName = value; + + // Clear any cache + aspectParts = null; + } + } + private string aspectName; + + #endregion + + + #region Public interface + + /// + /// Extract the value indicated by our AspectName from the given target. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValue(Object target) { + if (this.Parts.Count == 0) + return null; + + try { + return this.EvaluateParts(target, this.Parts); + } catch (MungerException ex) { + if (Munger.IgnoreMissingAspects) + return null; + + return String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", + ex.Munger.AspectName, ex.Target.GetType()); + } + } + + /// + /// Extract the value indicated by our AspectName from the given target, raising exceptions + /// if the munger fails. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValueEx(Object target) { + if (this.Parts.Count == 0) + return null; + + return this.EvaluateParts(target, this.Parts); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// + /// + /// If the AspectName is a dotted path, all the selectors bar the last + /// are used to find the object that should be updated, and the last + /// selector is used as the property to update on that object. + /// + /// + /// So, if 'target' is a Person and the AspectName is "HomeAddress.Postcode", + /// this method will first fetch "HomeAddress" property, and then try to set the + /// "Postcode" property on the home address object. + /// + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating whether the put worked + public bool PutValue(Object target, Object value) + { + if (this.Parts.Count == 0) + return false; + + SimpleMunger lastPart = this.Parts[this.Parts.Count - 1]; + + if (this.Parts.Count > 1) { + List parts = new List(this.Parts); + parts.RemoveAt(parts.Count - 1); + try { + target = this.EvaluateParts(target, parts); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + return false; + } + } + + if (target != null) { + try { + return lastPart.PutValue(target, value); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + } + } + + return false; + } + + #endregion + + #region Implementation + + /// + /// Gets the list of SimpleMungers that match our AspectName + /// + private IList Parts { + get { + if (aspectParts == null) + aspectParts = BuildParts(this.AspectName); + return aspectParts; + } + } + private IList aspectParts; + + /// + /// Convert a possibly dotted AspectName into a list of SimpleMungers + /// + /// + /// + private IList BuildParts(string aspect) { + List parts = new List(); + if (!String.IsNullOrEmpty(aspect)) { + foreach (string part in aspect.Split('.')) { + parts.Add(new SimpleMunger(part.Trim())); + } + } + return parts; + } + + /// + /// Evaluate the given chain of SimpleMungers against an initial target. + /// + /// + /// + /// + private object EvaluateParts(object target, IList parts) { + foreach (SimpleMunger part in parts) { + if (target == null) + break; + target = part.GetValue(target); + } + return target; + } + + private void ReportPutValueException(MungerException ex) { + //TODO: How should we report this error? + System.Diagnostics.Debug.WriteLine("PutValue failed"); + System.Diagnostics.Debug.WriteLine(String.Format("- Culprit aspect: {0}", ex.Munger.AspectName)); + System.Diagnostics.Debug.WriteLine(String.Format("- Target: {0} of type {1}", ex.Target, ex.Target.GetType())); + System.Diagnostics.Debug.WriteLine(String.Format("- Inner exception: {0}", ex.InnerException)); + } + + #endregion + } + + /// + /// A SimpleMunger deals with a single property/field/method on its target. + /// + /// + /// Munger uses a chain of these resolve a dotted aspect name. + /// + public class SimpleMunger + { + #region Life and death + + /// + /// Create a SimpleMunger + /// + /// + public SimpleMunger(String aspectName) + { + this.aspectName = aspectName; + } + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or method. + /// When using a method to get a value, the method must be parameter-less. + /// When using a method to set a value, the method must accept 1 parameter. + /// + /// + /// It cannot be a dotted name. + /// + /// + public string AspectName { + get { return aspectName; } + } + private readonly string aspectName; + + #endregion + + #region Public interface + + /// + /// Get a value from the given target + /// + /// + /// + public Object GetValue(Object target) { + if (target == null) + return null; + + this.ResolveName(target, this.AspectName, 0); + + try { + if (this.resolvedPropertyInfo != null) + return this.resolvedPropertyInfo.GetValue(target, null); + + if (this.resolvedMethodInfo != null) + return this.resolvedMethodInfo.Invoke(target, null); + + if (this.resolvedFieldInfo != null) + return this.resolvedFieldInfo.GetValue(target); + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) + return this.indexerPropertyInfo.GetValue(target, new object[] { this.AspectName }); + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + // If we get to here, we couldn't find a match for the aspect + throw new MungerException(this, target, new MissingMethodException()); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating if the put worked + public bool PutValue(object target, object value) { + if (target == null) + return false; + + this.ResolveName(target, this.AspectName, 1); + + try { + if (this.resolvedPropertyInfo != null) { + this.resolvedPropertyInfo.SetValue(target, value, null); + return true; + } + + if (this.resolvedMethodInfo != null) { + this.resolvedMethodInfo.Invoke(target, new object[] { value }); + return true; + } + + if (this.resolvedFieldInfo != null) { + this.resolvedFieldInfo.SetValue(target, value); + return true; + } + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) { + this.indexerPropertyInfo.SetValue(target, value, new object[] { this.AspectName }); + return true; + } + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + return false; + } + + #endregion + + #region Implementation + + private void ResolveName(object target, string name, int numberMethodParameters) { + + if (cachedTargetType == target.GetType() && cachedName == name && cachedNumberParameters == numberMethodParameters) + return; + + cachedTargetType = target.GetType(); + cachedName = name; + cachedNumberParameters = numberMethodParameters; + + resolvedFieldInfo = null; + resolvedPropertyInfo = null; + resolvedMethodInfo = null; + indexerPropertyInfo = null; + + const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.NonPublic*/; + + foreach (PropertyInfo pinfo in target.GetType().GetProperties(flags)) { + if (pinfo.Name == name) { + resolvedPropertyInfo = pinfo; + return; + } + + // See if we can find an string indexer property while we are here. + // We also need to allow for old style keyed collections. + if (indexerPropertyInfo == null && pinfo.Name == "Item") { + ParameterInfo[] par = pinfo.GetGetMethod().GetParameters(); + if (par.Length > 0) { + Type parameterType = par[0].ParameterType; + if (parameterType == typeof(string) || parameterType == typeof(object)) + indexerPropertyInfo = pinfo; + } + } + } + + foreach (FieldInfo info in target.GetType().GetFields(flags)) { + if (info.Name == name) { + resolvedFieldInfo = info; + return; + } + } + + foreach (MethodInfo info in target.GetType().GetMethods(flags)) { + if (info.Name == name && info.GetParameters().Length == numberMethodParameters) { + resolvedMethodInfo = info; + return; + } + } + } + + private Type cachedTargetType; + private string cachedName; + private int cachedNumberParameters; + + private FieldInfo resolvedFieldInfo; + private PropertyInfo resolvedPropertyInfo; + private MethodInfo resolvedMethodInfo; + private PropertyInfo indexerPropertyInfo; + + #endregion + } + + /// + /// These exceptions are raised when a munger finds something it cannot process + /// + public class MungerException : ApplicationException + { + /// + /// Create a MungerException + /// + /// + /// + /// + public MungerException(SimpleMunger munger, object target, Exception ex) + : base("Munger failed", ex) { + this.munger = munger; + this.target = target; + } + + /// + /// Get the munger that raised the exception + /// + public SimpleMunger Munger { + get { return munger; } + } + private readonly SimpleMunger munger; + + /// + /// Gets the target that threw the exception + /// + public object Target { + get { return target; } + } + private readonly object target; + } + + /* + * We don't currently need this + * 2010-08-06 + * + + internal class SimpleBinder : Binder + { + public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, System.Globalization.CultureInfo culture) { + //return Type.DefaultBinder.BindToField( + throw new NotImplementedException(); + } + + public override object ChangeType(object value, Type type, System.Globalization.CultureInfo culture) { + throw new NotImplementedException(); + } + + public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] names, out object state) { + throw new NotImplementedException(); + } + + public override void ReorderArgumentArray(ref object[] args, object state) { + throw new NotImplementedException(); + } + + public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { + throw new NotImplementedException(); + } + + public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { + if (match == null) + throw new ArgumentNullException("match"); + + if (match.Length == 0) + return null; + + return match[0]; + } + } + */ + +} diff --git a/ObjectListView/Implementation/NativeMethods.cs b/ObjectListView/Implementation/NativeMethods.cs new file mode 100644 index 0000000..d48588f --- /dev/null +++ b/ObjectListView/Implementation/NativeMethods.cs @@ -0,0 +1,1223 @@ +/* + * NativeMethods - All the Windows SDK structures and imports + * + * Author: Phillip Piper + * Date: 10/10/2006 + * + * Change log: + * v2.8.0 + * 2014-05-21 JPP - Added DeselectOneItem + * - Added new imagelist drawing + * v2.3 + * 2006-10-10 JPP - Initial version + * + * To do: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Wrapper for all native method calls on ListView controls + /// + internal static class NativeMethods + { + #region Constants + + private const int LVM_FIRST = 0x1000; + private const int LVM_GETCOLUMN = LVM_FIRST + 95; + private const int LVM_GETCOUNTPERPAGE = LVM_FIRST + 40; + private const int LVM_GETGROUPINFO = LVM_FIRST + 149; + private const int LVM_GETGROUPSTATE = LVM_FIRST + 92; + private const int LVM_GETHEADER = LVM_FIRST + 31; + private const int LVM_GETTOOLTIPS = LVM_FIRST + 78; + private const int LVM_GETTOPINDEX = LVM_FIRST + 39; + private const int LVM_HITTEST = LVM_FIRST + 18; + private const int LVM_INSERTGROUP = LVM_FIRST + 145; + private const int LVM_REMOVEALLGROUPS = LVM_FIRST + 160; + private const int LVM_SCROLL = LVM_FIRST + 20; + private const int LVM_SETBKIMAGE = LVM_FIRST + 0x8A; + private const int LVM_SETCOLUMN = LVM_FIRST + 96; + private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54; + private const int LVM_SETGROUPINFO = LVM_FIRST + 147; + private const int LVM_SETGROUPMETRICS = LVM_FIRST + 155; + private const int LVM_SETIMAGELIST = LVM_FIRST + 3; + private const int LVM_SETITEM = LVM_FIRST + 76; + private const int LVM_SETITEMCOUNT = LVM_FIRST + 47; + private const int LVM_SETITEMSTATE = LVM_FIRST + 43; + private const int LVM_SETSELECTEDCOLUMN = LVM_FIRST + 140; + private const int LVM_SETTOOLTIPS = LVM_FIRST + 74; + private const int LVM_SUBITEMHITTEST = LVM_FIRST + 57; + private const int LVS_EX_SUBITEMIMAGES = 0x0002; + + private const int LVIF_TEXT = 0x0001; + private const int LVIF_IMAGE = 0x0002; + private const int LVIF_PARAM = 0x0004; + private const int LVIF_STATE = 0x0008; + private const int LVIF_INDENT = 0x0010; + private const int LVIF_NORECOMPUTE = 0x0800; + + private const int LVIS_SELECTED = 2; + + private const int LVCF_FMT = 0x0001; + private const int LVCF_WIDTH = 0x0002; + private const int LVCF_TEXT = 0x0004; + private const int LVCF_SUBITEM = 0x0008; + private const int LVCF_IMAGE = 0x0010; + private const int LVCF_ORDER = 0x0020; + private const int LVCFMT_LEFT = 0x0000; + private const int LVCFMT_RIGHT = 0x0001; + private const int LVCFMT_CENTER = 0x0002; + private const int LVCFMT_JUSTIFYMASK = 0x0003; + + private const int LVCFMT_IMAGE = 0x0800; + private const int LVCFMT_BITMAP_ON_RIGHT = 0x1000; + private const int LVCFMT_COL_HAS_IMAGES = 0x8000; + + private const int LVBKIF_SOURCE_NONE = 0x0; + private const int LVBKIF_SOURCE_HBITMAP = 0x1; + private const int LVBKIF_SOURCE_URL = 0x2; + private const int LVBKIF_SOURCE_MASK = 0x3; + private const int LVBKIF_STYLE_NORMAL = 0x0; + private const int LVBKIF_STYLE_TILE = 0x10; + private const int LVBKIF_STYLE_MASK = 0x10; + private const int LVBKIF_FLAG_TILEOFFSET = 0x100; + private const int LVBKIF_TYPE_WATERMARK = 0x10000000; + private const int LVBKIF_FLAG_ALPHABLEND = 0x20000000; + + private const int LVSICF_NOINVALIDATEALL = 1; + private const int LVSICF_NOSCROLL = 2; + + private const int HDM_FIRST = 0x1200; + private const int HDM_HITTEST = HDM_FIRST + 6; + private const int HDM_GETITEMRECT = HDM_FIRST + 7; + private const int HDM_GETITEM = HDM_FIRST + 11; + private const int HDM_SETITEM = HDM_FIRST + 12; + + private const int HDI_WIDTH = 0x0001; + private const int HDI_TEXT = 0x0002; + private const int HDI_FORMAT = 0x0004; + private const int HDI_BITMAP = 0x0010; + private const int HDI_IMAGE = 0x0020; + + private const int HDF_LEFT = 0x0000; + private const int HDF_RIGHT = 0x0001; + private const int HDF_CENTER = 0x0002; + private const int HDF_JUSTIFYMASK = 0x0003; + private const int HDF_RTLREADING = 0x0004; + private const int HDF_STRING = 0x4000; + private const int HDF_BITMAP = 0x2000; + private const int HDF_BITMAP_ON_RIGHT = 0x1000; + private const int HDF_IMAGE = 0x0800; + private const int HDF_SORTUP = 0x0400; + private const int HDF_SORTDOWN = 0x0200; + + private const int SB_HORZ = 0; + private const int SB_VERT = 1; + private const int SB_CTL = 2; + private const int SB_BOTH = 3; + + private const int SIF_RANGE = 0x0001; + private const int SIF_PAGE = 0x0002; + private const int SIF_POS = 0x0004; + private const int SIF_DISABLENOSCROLL = 0x0008; + private const int SIF_TRACKPOS = 0x0010; + private const int SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS); + + private const int ILD_NORMAL = 0x0; + private const int ILD_TRANSPARENT = 0x1; + private const int ILD_MASK = 0x10; + private const int ILD_IMAGE = 0x20; + private const int ILD_BLEND25 = 0x2; + private const int ILD_BLEND50 = 0x4; + + const int SWP_NOSIZE = 1; + const int SWP_NOMOVE = 2; + const int SWP_NOZORDER = 4; + const int SWP_NOREDRAW = 8; + const int SWP_NOACTIVATE = 16; + public const int SWP_FRAMECHANGED = 32; + + const int SWP_ZORDERONLY = SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOACTIVATE; + const int SWP_SIZEONLY = SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER | SWP_NOACTIVATE; + const int SWP_UPDATE_FRAME = SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED; + + #endregion + + #region Structures + + [StructLayout(LayoutKind.Sequential)] + public struct HDITEM + { + public int mask; + public int cxy; + public IntPtr pszText; + public IntPtr hbm; + public int cchTextMax; + public int fmt; + public IntPtr lParam; + public int iImage; + public int iOrder; + //if (_WIN32_IE >= 0x0500) + public int type; + public IntPtr pvFilter; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDLAYOUT + { + public IntPtr prc; + public IntPtr pwpos; + } + + [StructLayout(LayoutKind.Sequential)] + public struct IMAGELISTDRAWPARAMS + { + public int cbSize; + public IntPtr himl; + public int i; + public IntPtr hdcDst; + public int x; + public int y; + public int cx; + public int cy; + public int xBitmap; + public int yBitmap; + public uint rgbBk; + public uint rgbFg; + public uint fStyle; + public uint dwRop; + public uint fState; + public uint Frame; + public uint crEffect; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVBKIMAGE + { + public int ulFlags; + public IntPtr hBmp; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszImage; + public int cchImageMax; + public int xOffset; + public int yOffset; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVCOLUMN + { + public int mask; + public int fmt; + public int cx; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iSubItem; + // These are available in Common Controls >= 0x0300 + public int iImage; + public int iOrder; + }; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVFINDINFO + { + public int flags; + public string psz; + public IntPtr lParam; + public int ptX; + public int ptY; + public int vkDirection; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public int cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP2 + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public uint cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubtitle; + public uint cchSubtitle; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszTask; + public uint cchTask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionTop; + public uint cchDescriptionTop; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionBottom; + public uint cchDescriptionBottom; + public int iTitleImage; + public int iExtendedImage; + public int iFirstItem; // Read only + public int cItems; // Read only + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubsetTitle; // NULL if group is not subset + public uint cchSubsetTitle; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUPMETRICS + { + public uint cbSize; + public uint mask; + public uint Left; + public uint Top; + public uint Right; + public uint Bottom; + public int crLeft; + public int crTop; + public int crRight; + public int crBottom; + public int crHeader; + public int crFooter; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + public int iSubItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVITEM + { + public int mask; + public int iItem; + public int iSubItem; + public int state; + public int stateMask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iImage; + public IntPtr lParam; + // These are available in Common Controls >= 0x0300 + public int iIndent; + // These are available in Common Controls >= 0x056 + public int iGroupId; + public int cColumns; + public IntPtr puColumns; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct NMHDR + { + public IntPtr hwndFrom; + public IntPtr idFrom; + public int code; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMCUSTOMDRAW + { + public NativeMethods.NMHDR nmcd; + public int dwDrawStage; + public IntPtr hdc; + public NativeMethods.RECT rc; + public IntPtr dwItemSpec; + public int uItemState; + public IntPtr lItemlParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMHEADER + { + public NMHDR nhdr; + public int iItem; + public int iButton; + public IntPtr pHDITEM; + } + + const int MAX_LINKID_TEXT = 48; + const int L_MAX_URL_LENGTH = 2048 + 32 + 4; + //#define L_MAX_URL_LENGTH (2048 + 32 + sizeof("://")) + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct LITEM + { + public uint mask; + public int iLink; + public uint state; + public uint stateMask; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_LINKID_TEXT)] + public string szID; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = L_MAX_URL_LENGTH)] + public string szUrl; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLISTVIEW + { + public NativeMethods.NMHDR hdr; + public int iItem; + public int iSubItem; + public int uNewState; + public int uOldState; + public int uChanged; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVCUSTOMDRAW + { + public NativeMethods.NMCUSTOMDRAW nmcd; + public int clrText; + public int clrTextBk; + public int iSubItem; + public int dwItemType; + public int clrFace; + public int iIconEffect; + public int iIconPhase; + public int iPartId; + public int iStateId; + public NativeMethods.RECT rcText; + public uint uAlign; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVFINDITEM + { + public NativeMethods.NMHDR hdr; + public int iStart; + public NativeMethods.LVFINDINFO lvfi; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGETINFOTIP + { + public NativeMethods.NMHDR hdr; + public int dwFlags; + public string pszText; + public int cchTextMax; + public int iItem; + public int iSubItem; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGROUP + { + public NMHDR hdr; + public int iGroupId; // which group is changing + public uint uNewState; // LVGS_xxx flags + public uint uOldState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVLINK + { + public NMHDR hdr; + public LITEM link; + public int iItem; + public int iSubItem; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVSCROLL + { + public NativeMethods.NMHDR hdr; + public int dx; + public int dy; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct NMTTDISPINFO + { + public NativeMethods.NMHDR hdr; + [MarshalAs(UnmanagedType.LPTStr)] + public string lpszText; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] + public string szText; + public IntPtr hinst; + public int uFlags; + public IntPtr lParam; + //public int hbmp; This is documented but doesn't work + } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + } + + [StructLayout(LayoutKind.Sequential)] + public class SCROLLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO)); + public int fMask; + public int nMin; + public int nMax; + public int nPage; + public int nPos; + public int nTrackPos; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class TOOLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.TOOLINFO)); + public int uFlags; + public IntPtr hwnd; + public IntPtr uId; + public NativeMethods.RECT rect; + public IntPtr hinst = IntPtr.Zero; + public IntPtr lpszText; + public IntPtr lParam = IntPtr.Zero; + } + + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPOS + { + public IntPtr hwnd; + public IntPtr hwndInsertAfter; + public int x; + public int y; + public int cx; + public int cy; + public int flags; + } + + #endregion + + #region Entry points + + // Various flavours of SendMessage: plain vanilla, and passing references to various structures + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVHITTESTINFO ht); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageRECT(IntPtr hWnd, int msg, int wParam, ref RECT r); + //[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + //private static extern IntPtr SendMessageLVColumn(IntPtr hWnd, int m, int wParam, ref LVCOLUMN lvc); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + private static extern IntPtr SendMessageHDItem(IntPtr hWnd, int msg, int wParam, ref HDITEM hdi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageHDHITTESTINFO(IntPtr hWnd, int Msg, IntPtr wParam, [In, Out] HDHITTESTINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageTOOLINFO(IntPtr hWnd, int Msg, int wParam, NativeMethods.TOOLINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVBKIMAGE(IntPtr hWnd, int Msg, int wParam, ref NativeMethods.LVBKIMAGE lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageString(IntPtr hWnd, int Msg, int wParam, string lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageIUnknown(IntPtr hWnd, int msg, [MarshalAs(UnmanagedType.IUnknown)] object wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP2 lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUPMETRICS lParam); + + [DllImport("gdi32.dll")] + public static extern bool DeleteObject(IntPtr objectHandle); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetClientRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo); + + [DllImport("user32.dll", EntryPoint = "GetUpdateRect", CharSet = CharSet.Auto)] + private static extern bool GetUpdateRectInternal(IntPtr hWnd, ref Rectangle r, bool eraseBackground); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_Draw(IntPtr himl, int i, IntPtr hdcDst, int x, int y, int fStyle); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_DrawIndirect(ref IMAGELISTDRAWPARAMS parms); + + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll", EntryPoint = "ValidateRect", CharSet = CharSet.Auto)] + private static extern IntPtr ValidatedRectInternal(IntPtr hWnd, ref Rectangle r); + + #endregion + + //[DllImport("user32.dll", EntryPoint = "LockWindowUpdate", CharSet = CharSet.Auto)] + //private static extern int LockWindowUpdateInternal(IntPtr hWnd); + + //public static void LockWindowUpdate(IWin32Window window) { + // if (window == null) + // NativeMethods.LockWindowUpdateInternal(IntPtr.Zero); + // else + // NativeMethods.LockWindowUpdateInternal(window.Handle); + //} + + /// + /// Put an image under the ListView. + /// + /// + /// + /// The ListView must have its handle created before calling this. + /// + /// + /// This doesn't work very well. Specifically, it doesn't play well with owner drawn, + /// and grid lines are drawn over it. + /// + /// + /// + /// The image to be used as the background. If this is null, any existing background image will be cleared. + /// If this is true, the image is pinned to the bottom right and does not scroll. The other parameters are ignored + /// If this is true, the image will be tiled to fill the whole control background. The offset parameters will be ignored. + /// If both watermark and tiled are false, this indicates the horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// If both watermark and tiled are false, this indicates the vertical percentage where the image will be placed. + /// + public static bool SetBackgroundImage(ListView lv, Image image, bool isWatermark, bool isTiled, int xOffset, int yOffset) { + + LVBKIMAGE lvbkimage = new LVBKIMAGE(); + + // We have to clear any pre-existing background image, otherwise the attempt to set the image will fail. + // We don't know which type may already have been set, so we just clear both the watermark and the image. + lvbkimage.ulFlags = LVBKIF_TYPE_WATERMARK; + IntPtr result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + lvbkimage.ulFlags = LVBKIF_SOURCE_HBITMAP; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + + Bitmap bm = image as Bitmap; + if (bm != null) { + lvbkimage.hBmp = bm.GetHbitmap(); + lvbkimage.ulFlags = isWatermark ? LVBKIF_TYPE_WATERMARK : (isTiled ? LVBKIF_SOURCE_HBITMAP | LVBKIF_STYLE_TILE : LVBKIF_SOURCE_HBITMAP); + lvbkimage.xOffset = xOffset; + lvbkimage.yOffset = yOffset; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + } + + return (result != IntPtr.Zero); + } + + public static bool DrawImageList(Graphics g, ImageList il, int index, int x, int y, bool isSelected, bool isDisabled) { + ImageListDrawItemConstants flags = (isSelected ? ImageListDrawItemConstants.ILD_SELECTED : ImageListDrawItemConstants.ILD_NORMAL) | ImageListDrawItemConstants.ILD_TRANSPARENT; + ImageListDrawStateConstants state = isDisabled ? ImageListDrawStateConstants.ILS_SATURATE : ImageListDrawStateConstants.ILS_NORMAL; + try { + IntPtr hdc = g.GetHdc(); + return DrawImage(il, hdc, index, x, y, flags, 0, 0, state); + } + finally { + g.ReleaseHdc(); + } + } + + /// + /// Flags controlling how the Image List item is + /// drawn + /// + [Flags] + public enum ImageListDrawItemConstants + { + /// + /// Draw item normally. + /// + ILD_NORMAL = 0x0, + /// + /// Draw item transparently. + /// + ILD_TRANSPARENT = 0x1, + /// + /// Draw item blended with 25% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_BLEND25 = 0x2, + /// + /// Draw item blended with 50% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_SELECTED = 0x4, + /// + /// Draw the icon's mask + /// + ILD_MASK = 0x10, + /// + /// Draw the icon image without using the mask + /// + ILD_IMAGE = 0x20, + /// + /// Draw the icon using the ROP specified. + /// + ILD_ROP = 0x40, + /// + /// Preserves the alpha channel in dest. XP only. + /// + ILD_PRESERVEALPHA = 0x1000, + /// + /// Scale the image to cx, cy instead of clipping it. XP only. + /// + ILD_SCALE = 0x2000, + /// + /// Scale the image to the current DPI of the display. XP only. + /// + ILD_DPISCALE = 0x4000 + } + + /// + /// Enumeration containing XP ImageList Draw State options + /// + [Flags] + public enum ImageListDrawStateConstants + { + /// + /// The image state is not modified. + /// + ILS_NORMAL = (0x00000000), + /// + /// Adds a glow effect to the icon, which causes the icon to appear to glow + /// with a given color around the edges. (Note: does not appear to be implemented) + /// + ILS_GLOW = (0x00000001), //The color for the glow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Adds a drop shadow effect to the icon. (Note: does not appear to be implemented) + /// + ILS_SHADOW = (0x00000002), //The color for the drop shadow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Saturates the icon by increasing each color component + /// of the RGB triplet for each pixel in the icon. (Note: only ever appears to result in a completely unsaturated icon) + /// + ILS_SATURATE = (0x00000004), // The amount to increase is indicated by the frame member in the IMAGELISTDRAWPARAMS method. + /// + /// Alpha blends the icon. Alpha blending controls the transparency + /// level of an icon, according to the value of its alpha channel. + /// (Note: does not appear to be implemented). + /// + ILS_ALPHA = (0x00000008) //The value of the alpha channel is indicated by the frame member in the IMAGELISTDRAWPARAMS method. The alpha channel can be from 0 to 255, with 0 being completely transparent, and 255 being completely opaque. + } + + private const uint CLR_DEFAULT = 0xFF000000; + + /// + /// Draws an image using the specified flags and state on XP systems. + /// + /// The image list from which an item will be drawn + /// Device context to draw to + /// Index of image to draw + /// X Position to draw at + /// Y Position to draw at + /// Drawing flags + /// Width to draw + /// Height to draw + /// State flags + public static bool DrawImage(ImageList il, IntPtr hdc, int index, int x, int y, ImageListDrawItemConstants flags, int cx, int cy, ImageListDrawStateConstants stateFlags) { + IMAGELISTDRAWPARAMS pimldp = new IMAGELISTDRAWPARAMS(); + pimldp.hdcDst = hdc; + pimldp.cbSize = Marshal.SizeOf(pimldp.GetType()); + pimldp.i = index; + pimldp.x = x; + pimldp.y = y; + pimldp.cx = cx; + pimldp.cy = cy; + pimldp.rgbFg = CLR_DEFAULT; + pimldp.fStyle = (uint) flags; + pimldp.fState = (uint) stateFlags; + pimldp.himl = il.Handle; + return ImageList_DrawIndirect(ref pimldp); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + public static void ForceSubItemImagesExStyle(ListView list) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES); + } + + /// + /// Change the virtual list size of the given ListView (which must be in virtual mode) + /// + /// This will not change the scroll position + /// The listview to send a message to + /// How many rows should the list have? + public static void SetItemCount(ListView list, int count) { + SendMessage(list.Handle, LVM_SETITEMCOUNT, count, LVSICF_NOSCROLL); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + /// + /// + public static void SetExtendedStyle(ListView list, int style, int styleMask) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, styleMask, style); + } + + /// + /// Calculates the number of items that can fit vertically in the visible area of a list-view (which + /// must be in details or list view. + /// + /// The listView + /// Number of visible items per page + public static int GetCountPerPage(ListView list) { + return (int)SendMessage(list.Handle, LVM_GETCOUNTPERPAGE, 0, 0); + } + /// + /// For the given item and subitem, make it display the given image + /// + /// The listview to send a m to + /// row number (0 based) + /// subitem (0 is the item itself) + /// index into the image list + public static void SetSubItemImage(ListView list, int itemIndex, int subItemIndex, int imageIndex) { + LVITEM lvItem = new LVITEM(); + lvItem.mask = LVIF_IMAGE; + lvItem.iItem = itemIndex; + lvItem.iSubItem = subItemIndex; + lvItem.iImage = imageIndex; + SendMessageLVItem(list.Handle, LVM_SETITEM, 0, ref lvItem); + } + + /// + /// Setup the given column of the listview to show the given image to the right of the text. + /// If the image index is -1, any previous image is cleared + /// + /// The listview to send a m to + /// Index of the column to modify + /// + /// Index into the small image list + public static void SetColumnImage(ListView list, int columnIndex, SortOrder order, int imageIndex) { + IntPtr hdrCntl = NativeMethods.GetHeaderControl(list); + if (hdrCntl.ToInt32() == 0) + return; + + HDITEM item = new HDITEM(); + item.mask = HDI_FORMAT; + IntPtr result = SendMessageHDItem(hdrCntl, HDM_GETITEM, columnIndex, ref item); + + item.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN | HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + + if (NativeMethods.HasBuiltinSortIndicators()) { + if (order == SortOrder.Ascending) + item.fmt |= HDF_SORTUP; + if (order == SortOrder.Descending) + item.fmt |= HDF_SORTDOWN; + } else { + item.mask |= HDI_IMAGE; + item.fmt |= (HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + item.iImage = imageIndex; + } + + result = SendMessageHDItem(hdrCntl, HDM_SETITEM, columnIndex, ref item); + } + + /// + /// Does this version of the operating system have builtin sort indicators? + /// + /// Are there builtin sort indicators + /// XP and later have these + public static bool HasBuiltinSortIndicators() { + return OSFeature.Feature.GetVersionPresent(OSFeature.Themes) != null; + } + + /// + /// Return the bounds of the update region on the given control. + /// + /// The BeginPaint() system call validates the update region, effectively wiping out this information. + /// So this call has to be made before the BeginPaint() call. + /// The control whose update region is be calculated + /// A rectangle + public static Rectangle GetUpdateRect(Control cntl) { + Rectangle r = new Rectangle(); + GetUpdateRectInternal(cntl.Handle, ref r, false); + return r; + } + + /// + /// Validate an area of the given control. A validated area will not be repainted at the next redraw. + /// + /// The control to be validated + /// The area of the control to be validated + public static void ValidateRect(Control cntl, Rectangle r) { + ValidatedRectInternal(cntl.Handle, ref r); + } + + /// + /// Select all rows on the given listview + /// + /// The listview whose items are to be selected + public static void SelectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, LVIS_SELECTED); + } + + /// + /// Deselect all rows on the given listview + /// + /// The listview whose items are to be deselected + public static void DeselectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, 0); + } + + /// + /// Deselect a single row + /// + /// + /// + public static void DeselectOneItem(ListView list, int index) { + NativeMethods.SetItemState(list, index, LVIS_SELECTED, 0); + } + + /// + /// Set the item state on the given item + /// + /// The listview whose item's state is to be changed + /// The index of the item to be changed + /// Which bits of the value are to be set? + /// The value to be set + public static void SetItemState(ListView list, int itemIndex, int mask, int value) { + LVITEM lvItem = new LVITEM(); + lvItem.stateMask = mask; + lvItem.state = value; + SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem); + } + + /// + /// Scroll the given listview by the given deltas + /// + /// + /// + /// + /// true if the scroll succeeded + public static bool Scroll(ListView list, int dx, int dy) { + return SendMessage(list.Handle, LVM_SCROLL, dx, dy) != IntPtr.Zero; + } + + /// + /// Return the handle to the header control on the given list + /// + /// The listview whose header control is to be returned + /// The handle to the header control + public static IntPtr GetHeaderControl(ListView list) { + return SendMessage(list.Handle, LVM_GETHEADER, 0, 0); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetColumnSides(ObjectListView lv, int columnIndex) { + Point sides = new Point(-1, -1); + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + return new Point(r.left, r.right); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetScrolledColumnSides(ListView lv, int columnIndex) { + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + IntPtr result = NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + int scrollH = NativeMethods.GetScrollPosition(lv, true); + return new Point(r.left - scrollH, r.right - scrollH); + } + + /// + /// Return the index of the column of the header that is under the given point. + /// Return -1 if no column is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the column under the point, or -1 if no column header is under that point + public static int GetColumnUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONHEADER = 2; + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONHEADER | HHT_ONDIVIDER); + } + + private static int HeaderControlHitTest(IntPtr handle, Point pt, int flag) { + HDHITTESTINFO testInfo = new HDHITTESTINFO(); + testInfo.pt_x = pt.X; + testInfo.pt_y = pt.Y; + IntPtr result = NativeMethods.SendMessageHDHITTESTINFO(handle, HDM_HITTEST, IntPtr.Zero, testInfo); + if ((testInfo.flags & flag) != 0) + return testInfo.iItem; + else + return -1; + } + + /// + /// Return the index of the divider under the given point. Return -1 if no divider is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the divider under the point, or -1 if no divider is under that point + public static int GetDividerUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONDIVIDER); + } + + /// + /// Get the scroll position of the given scroll bar + /// + /// + /// + /// + public static int GetScrollPosition(ListView lv, bool horizontalBar) { + int fnBar = (horizontalBar ? SB_HORZ : SB_VERT); + + SCROLLINFO scrollInfo = new SCROLLINFO(); + scrollInfo.fMask = SIF_POS; + if (GetScrollInfo(lv.Handle, fnBar, scrollInfo)) + return scrollInfo.nPos; + else + return -1; + } + + /// + /// Change the z-order to the window 'toBeMoved' so it appear directly on top of 'reference' + /// + /// + /// + /// + public static bool ChangeZOrder(IWin32Window toBeMoved, IWin32Window reference) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, reference.Handle, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Make the given control/window a topmost window + /// + /// + /// + public static bool MakeTopMost(IWin32Window toBeMoved) { + IntPtr HWND_TOPMOST = (IntPtr)(-1); + return NativeMethods.SetWindowPos(toBeMoved.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Change the size of the window without affecting any other attributes + /// + /// + /// + /// + /// + public static bool ChangeSize(IWin32Window toBeMoved, int width, int height) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, IntPtr.Zero, 0, 0, width, height, SWP_SIZEONLY); + } + + /// + /// Show the given window without activating it + /// + /// The window to show + static public void ShowWithoutActivate(IWin32Window win) { + const int SW_SHOWNA = 8; + NativeMethods.ShowWindow(win.Handle, SW_SHOWNA); + } + + /// + /// Mark the given column as being selected. + /// + /// + /// The OLVColumn or null to clear + /// + /// This method works, but it prevents subitems in the given column from having + /// back colors. + /// + static public void SetSelectedColumn(ListView objectListView, ColumnHeader value) { + NativeMethods.SendMessage(objectListView.Handle, + LVM_SETSELECTEDCOLUMN, (value == null) ? -1 : value.Index, 0); + } + + static public int GetTopIndex(ListView lv) { + return (int)SendMessage(lv.Handle, LVM_GETTOPINDEX, 0, 0); + } + + static public IntPtr GetTooltipControl(ListView lv) { + return SendMessage(lv.Handle, LVM_GETTOOLTIPS, 0, 0); + } + + static public IntPtr SetTooltipControl(ListView lv, ToolTipControl tooltip) { + return SendMessage(lv.Handle, LVM_SETTOOLTIPS, 0, tooltip.Handle); + } + + static public bool HasHorizontalScrollBar(ListView lv) { + const int GWL_STYLE = -16; + const int WS_HSCROLL = 0x00100000; + + return (NativeMethods.GetWindowLong(lv.Handle, GWL_STYLE) & WS_HSCROLL) != 0; + } + + public static int GetWindowLong(IntPtr hWnd, int nIndex) { + if (IntPtr.Size == 4) + return (int)GetWindowLong32(hWnd, nIndex); + else + return (int)(long)GetWindowLongPtr64(hWnd, nIndex); + } + + public static int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong) { + if (IntPtr.Size == 4) + return (int)SetWindowLongPtr32(hWnd, nIndex, dwNewLong); + else + return (int)(long)SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + } + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetBkColor(IntPtr hDC, int clr); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetTextColor(IntPtr hDC, int crColor); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj); + + [DllImport("uxtheme.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetWindowTheme(IntPtr hWnd, string subApp, string subIdList); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool InvalidateRect(IntPtr hWnd, int ignored, bool erase); + + [StructLayout(LayoutKind.Sequential)] + public struct LVITEMINDEX + { + public int iItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential)] + public struct POINT + { + public int x; + public int y; + } + + public static int GetGroupInfo(ObjectListView olv, int groupId, ref LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPINFO, groupId, ref group); + } + + public static GroupState GetGroupState(ObjectListView olv, int groupId, GroupState mask) { + return (GroupState)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPSTATE, groupId, (int)mask); + } + + public static int InsertGroup(ObjectListView olv, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_INSERTGROUP, -1, ref group); + } + + public static int SetGroupInfo(ObjectListView olv, int groupId, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPINFO, groupId, ref group); + } + + public static int SetGroupMetrics(ObjectListView olv, LVGROUPMETRICS metrics) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPMETRICS, 0, ref metrics); + } + + public static void ClearGroups(VirtualObjectListView virtualObjectListView) { + NativeMethods.SendMessage(virtualObjectListView.Handle, LVM_REMOVEALLGROUPS, 0, 0); + } + + public static void SetGroupImageList(ObjectListView olv, ImageList il) { + const int LVSIL_GROUPHEADER = 3; + NativeMethods.SendMessage(olv.Handle, LVM_SETIMAGELIST, LVSIL_GROUPHEADER, il == null ? IntPtr.Zero : il.Handle); + } + + public static int HitTest(ObjectListView olv, ref LVHITTESTINFO hittest) + { + return (int)NativeMethods.SendMessage(olv.Handle, olv.View == View.Details ? LVM_SUBITEMHITTEST : LVM_HITTEST, -1, ref hittest); + } + } +} diff --git a/ObjectListView/Implementation/NullableDictionary.cs b/ObjectListView/Implementation/NullableDictionary.cs new file mode 100644 index 0000000..79b3c1e --- /dev/null +++ b/ObjectListView/Implementation/NullableDictionary.cs @@ -0,0 +1,87 @@ +/* + * NullableDictionary - A simple Dictionary that can handle null as a key + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2017 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace BrightIdeasSoftware { + + /// + /// A simple-minded implementation of a Dictionary that can handle null as a key. + /// + /// The type of the dictionary key + /// The type of the values to be stored + /// This is not a full implementation and is only meant to handle + /// collecting groups by their keys, since groups can have null as a key value. + internal class NullableDictionary : Dictionary { + private bool hasNullKey; + private TValue nullValue; + + new public TValue this[TKey key] { + get { + if (key != null) + return base[key]; + + if (this.hasNullKey) + return this.nullValue; + + throw new KeyNotFoundException(); + } + set { + if (key == null) { + this.hasNullKey = true; + this.nullValue = value; + } else + base[key] = value; + } + } + + new public bool ContainsKey(TKey key) { + return key == null ? this.hasNullKey : base.ContainsKey(key); + } + + new public IList Keys { + get { + ArrayList list = new ArrayList(base.Keys); + if (this.hasNullKey) + list.Add(null); + return list; + } + } + + new public IList Values { + get { + List list = new List(base.Values); + if (this.hasNullKey) + list.Add(this.nullValue); + return list; + } + } + } +} diff --git a/ObjectListView/Implementation/OLVListItem.cs b/ObjectListView/Implementation/OLVListItem.cs new file mode 100644 index 0000000..d488123 --- /dev/null +++ b/ObjectListView/Implementation/OLVListItem.cs @@ -0,0 +1,325 @@ +/* + * OLVListItem - A row in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-09-01 JPP - Handle rare case of getting subitems when there are no columns + * v2.9 + * 2015-08-22 JPP - Added OLVListItem.SelectedBackColor and SelectedForeColor + * 2015-06-09 JPP - Added HasAnyHyperlinks property + * v2.8 + * 2014-09-27 JPP - Remove faulty caching of CheckState + * 2014-05-06 JPP - Added OLVListItem.Enabled flag + * vOld + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// OLVListItems are specialized ListViewItems that know which row object they came from, + /// and the row index at which they are displayed, even when in group view mode. They + /// also know the image they should draw against themselves + /// + public class OLVListItem : ListViewItem { + #region Constructors + + /// + /// Create a OLVListItem for the given row object + /// + public OLVListItem(object rowObject) { + this.rowObject = rowObject; + } + + /// + /// Create a OLVListItem for the given row object, represented by the given string and image + /// + public OLVListItem(object rowObject, string text, Object image) + : base(text, -1) { + this.rowObject = rowObject; + this.imageSelector = image; + } + + #endregion. + + #region Properties + + /// + /// Gets the bounding rectangle of the item, including all subitems + /// + new public Rectangle Bounds { + get { + try { + return base.Bounds; + } + catch (System.ArgumentException) { + // If the item is part of a collapsed group, Bounds will throw an exception + return Rectangle.Empty; + } + } + } + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how the cells of this item will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the checkedness of this item. + /// + /// + /// Virtual lists don't handle checkboxes well, so we have to intercept attempts to change them + /// through the items, and change them into something that will work. + /// Unfortunately, this won't work if this property is set through the base class, since + /// the property is not declared as virtual. + /// + new public bool Checked { + get { + return base.Checked; + } + set { + if (this.Checked != value) { + if (value) + ((ObjectListView)this.ListView).CheckObject(this.RowObject); + else + ((ObjectListView)this.ListView).UncheckObject(this.RowObject); + } + } + } + + /// + /// Enable tri-state checkbox. + /// + /// .NET's Checked property was not built to handle tri-state checkboxes, + /// and will return True for both Checked and Indeterminate states. + public CheckState CheckState { + get { + switch (this.StateImageIndex) { + case 0: + return System.Windows.Forms.CheckState.Unchecked; + case 1: + return System.Windows.Forms.CheckState.Checked; + case 2: + return System.Windows.Forms.CheckState.Indeterminate; + default: + return System.Windows.Forms.CheckState.Unchecked; + } + } + set { + switch (value) { + case System.Windows.Forms.CheckState.Unchecked: + this.StateImageIndex = 0; + break; + case System.Windows.Forms.CheckState.Checked: + this.StateImageIndex = 1; + break; + case System.Windows.Forms.CheckState.Indeterminate: + this.StateImageIndex = 2; + break; + } + } + } + + /// + /// Gets if this item has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + if (this.HasDecoration) + return this.Decorations[0]; + else + return null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Gets whether or not this row can be selected and activated + /// + public bool Enabled + { + get { return this.enabled; } + internal set { this.enabled = value; } + } + private bool enabled; + + /// + /// Gets whether any cell on this item is showing a hyperlink + /// + public bool HasAnyHyperlinks { + get { + foreach (OLVListSubItem subItem in this.SubItems) { + if (!String.IsNullOrEmpty(subItem.Url)) + return true; + } + return false; + } + } + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { + imageSelector = value; + if (value is Int32) + this.ImageIndex = (Int32)value; + else if (value is String) + this.ImageKey = (String)value; + else + this.ImageIndex = -1; + } + } + private Object imageSelector; + + /// + /// Gets or sets the model object that is source of the data for this list item. + /// + public object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + private object rowObject; + + /// + /// Gets or sets the color that will be used for this row's background when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection BackColor will be used. + /// + /// + public Color? SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color? selectedBackColor; + + /// + /// Gets or sets the color that will be used for this row's foreground when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection ForeColor will be used. + /// + /// + public Color? SelectedForeColor + { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color? selectedForeColor; + + #endregion + + #region Accessing + + /// + /// Return the sub item at the given index + /// + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index) { + if (index >= 0 && index < this.SubItems.Count) + // If the control has 0 columns, ListViewItem.SubItems will auto create a + // SubItem of the wrong type. Casting using 'as' handles this rare case. + return this.SubItems[index] as OLVListSubItem; + + return null; + } + + + /// + /// Return bounds of the given subitem + /// + /// This correctly calculates the bounds even for column 0. + public virtual Rectangle GetSubItemBounds(int subItemIndex) { + if (subItemIndex == 0) { + Rectangle r = this.Bounds; + Point sides = NativeMethods.GetScrolledColumnSides(this.ListView, subItemIndex); + r.X = sides.X + 1; + r.Width = sides.Y - sides.X; + return r; + } + + OLVListSubItem subItem = this.GetSubItem(subItemIndex); + return subItem == null ? new Rectangle() : subItem.Bounds; + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/OLVListSubItem.cs b/ObjectListView/Implementation/OLVListSubItem.cs new file mode 100644 index 0000000..e4f5bfe --- /dev/null +++ b/ObjectListView/Implementation/OLVListSubItem.cs @@ -0,0 +1,173 @@ +/* + * OLVListSubItem - A single cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.ComponentModel; + +namespace BrightIdeasSoftware { + + /// + /// A ListViewSubItem that knows which image should be drawn against it. + /// + [Browsable(false)] + public class OLVListSubItem : ListViewItem.ListViewSubItem { + #region Constructors + + /// + /// Create a OLVListSubItem + /// + public OLVListSubItem() { + } + + /// + /// Create a OLVListSubItem that shows the given string and image + /// + public OLVListSubItem(object modelValue, string text, Object image) { + this.ModelValue = modelValue; + this.Text = text; + this.ImageSelector = image; + } + + #endregion + + #region Properties + + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how this cell will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the model value is being displayed by this subitem. + /// + public object ModelValue + { + get { return modelValue; } + private set { modelValue = value; } + } + private object modelValue; + + /// + /// Gets if this subitem has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + return this.HasDecoration ? this.Decorations[0] : null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + private Object imageSelector; + + /// + /// Gets or sets the url that should be invoked when this subitem is clicked + /// + public string Url + { + get { return this.url; } + set { this.url = value; } + } + private string url; + + /// + /// Gets or sets whether this cell is selected + /// + public bool Selected + { + get { return this.selected; } + set { this.selected = value; } + } + private bool selected; + + #endregion + + #region Implementation Properties + + /// + /// Return the state of the animation of the image on this subitem. + /// Null means there is either no image, or it is not an animation + /// + internal ImageRenderer.AnimationState AnimationState; + + #endregion + } + +} diff --git a/ObjectListView/Implementation/OlvListViewHitTestInfo.cs b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs new file mode 100644 index 0000000..7cc28eb --- /dev/null +++ b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs @@ -0,0 +1,388 @@ +/* + * OlvListViewHitTestInfo - All information gathered during a OlvHitTest() operation + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// An indication of where a hit was within ObjectListView cell + /// + public enum HitTestLocation { + /// + /// Nowhere + /// + Nothing, + + /// + /// On the text + /// + Text, + + /// + /// On the image + /// + Image, + + /// + /// On the checkbox + /// + CheckBox, + + /// + /// On the expand button (TreeListView) + /// + ExpandButton, + + /// + /// in a button (cell must have ButtonRenderer) + /// + Button, + + /// + /// in the cell but not in any more specific location + /// + InCell, + + /// + /// UserDefined location1 (used for custom renderers) + /// + UserDefined, + + /// + /// On the expand/collapse widget of the group + /// + GroupExpander, + + /// + /// Somewhere on a group + /// + Group, + + /// + /// Somewhere in a column header + /// + Header, + + /// + /// Somewhere in a column header checkbox + /// + HeaderCheckBox, + + /// + /// Somewhere in a header divider + /// + HeaderDivider, + } + + /// + /// A collection of ListViewHitTest constants + /// + [Flags] + public enum HitTestLocationEx { + /// + /// + /// + LVHT_NOWHERE = 0x00000001, + /// + /// + /// + LVHT_ONITEMICON = 0x00000002, + /// + /// + /// + LVHT_ONITEMLABEL = 0x00000004, + /// + /// + /// + LVHT_ONITEMSTATEICON = 0x00000008, + /// + /// + /// + LVHT_ONITEM = (LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON), + + /// + /// + /// + LVHT_ABOVE = 0x00000008, + /// + /// + /// + LVHT_BELOW = 0x00000010, + /// + /// + /// + LVHT_TORIGHT = 0x00000020, + /// + /// + /// + LVHT_TOLEFT = 0x00000040, + + /// + /// + /// + LVHT_EX_GROUP_HEADER = 0x10000000, + /// + /// + /// + LVHT_EX_GROUP_FOOTER = 0x20000000, + /// + /// + /// + LVHT_EX_GROUP_COLLAPSE = 0x40000000, + /// + /// + /// + LVHT_EX_GROUP_BACKGROUND = -2147483648, // 0x80000000 + /// + /// + /// + LVHT_EX_GROUP_STATEICON = 0x01000000, + /// + /// + /// + LVHT_EX_GROUP_SUBSETLINK = 0x02000000, + /// + /// + /// + LVHT_EX_GROUP = (LVHT_EX_GROUP_BACKGROUND | LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_FOOTER | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD = (LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_ONCONTENTS = 0x04000000, // On item AND not on the background + /// + /// + /// + LVHT_EX_FOOTER = 0x08000000, + } + + /// + /// Instances of this class encapsulate the information gathered during a OlvHitTest() + /// operation. + /// + /// Custom renderers can use HitTestLocation.UserDefined and the UserData + /// object to store more specific locations for use during event handlers. + public class OlvListViewHitTestInfo { + + /// + /// Create a OlvListViewHitTestInfo + /// + public OlvListViewHitTestInfo(OLVListItem olvListItem, OLVListSubItem subItem, int flags, OLVGroup group, int iColumn) + { + this.item = olvListItem; + this.subItem = subItem; + this.location = ConvertNativeFlagsToDotNetLocation(olvListItem, flags); + this.HitTestLocationEx = (HitTestLocationEx)flags; + this.Group = group; + this.ColumnIndex = iColumn; + this.ListView = olvListItem == null ? null : (ObjectListView)olvListItem.ListView; + + switch (location) { + case ListViewHitTestLocations.StateImage: + this.HitTestLocation = HitTestLocation.CheckBox; + break; + case ListViewHitTestLocations.Image: + this.HitTestLocation = HitTestLocation.Image; + break; + case ListViewHitTestLocations.Label: + this.HitTestLocation = HitTestLocation.Text; + break; + default: + if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) == HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) + this.HitTestLocation = HitTestLocation.GroupExpander; + else if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD) != 0) + this.HitTestLocation = HitTestLocation.Group; + else + this.HitTestLocation = HitTestLocation.Nothing; + break; + } + } + + /// + /// Create a OlvListViewHitTestInfo when the header was hit + /// + public OlvListViewHitTestInfo(ObjectListView olv, int iColumn, bool isOverCheckBox, int iDivider) { + this.ListView = olv; + this.ColumnIndex = iColumn; + this.HeaderDividerIndex = iDivider; + this.HitTestLocation = isOverCheckBox ? HitTestLocation.HeaderCheckBox : (iDivider < 0 ? HitTestLocation.Header : HitTestLocation.HeaderDivider); + } + + private static ListViewHitTestLocations ConvertNativeFlagsToDotNetLocation(OLVListItem hitItem, int flags) + { + // Untangle base .NET behaviour. + + // In Windows SDK, the value 8 can have two meanings here: LVHT_ONITEMSTATEICON or LVHT_ABOVE. + // .NET changes these to be: + // - LVHT_ABOVE becomes ListViewHitTestLocations.AboveClientArea (which is 0x100). + // - LVHT_ONITEMSTATEICON becomes ListViewHitTestLocations.StateImage (which is 0x200). + // So, if we see the 8 bit set in flags, we change that to either a state image hit + // (if we hit an item) or to AboveClientAream if nothing was hit. + + if ((8 & flags) == 8) + return (ListViewHitTestLocations)(0xf7 & flags | (hitItem == null ? 0x100 : 0x200)); + + // Mask off the LVHT_EX_XXXX values since ListViewHitTestLocations doesn't have them + return (ListViewHitTestLocations)(flags & 0xffff); + } + + #region Public fields + + /// + /// Where is the hit location? + /// + public HitTestLocation HitTestLocation; + + /// + /// Where is the hit location? + /// + public HitTestLocationEx HitTestLocationEx; + + /// + /// Which group was hit? + /// + public OLVGroup Group; + + /// + /// Custom renderers can use this information to supply more details about the hit location + /// + public Object UserData; + + #endregion + + #region Public read-only properties + + /// + /// Gets the item that was hit + /// + public OLVListItem Item { + get { return item; } + internal set { item = value; } + } + private OLVListItem item; + + /// + /// Gets the subitem that was hit + /// + public OLVListSubItem SubItem { + get { return subItem; } + internal set { subItem = value; } + } + private OLVListSubItem subItem; + + /// + /// Gets the part of the subitem that was hit + /// + public ListViewHitTestLocations Location { + get { return location; } + internal set { location = value; } + } + private ListViewHitTestLocations location; + + /// + /// Gets the ObjectListView that was tested + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the model object that was hit + /// + public Object RowObject { + get { + return this.Item == null ? null : this.Item.RowObject; + } + } + + /// + /// Gets the index of the row under the hit point or -1 + /// + public int RowIndex { + get { return this.Item == null ? -1 : this.Item.Index; } + } + + /// + /// Gets the index of the column under the hit point + /// + public int ColumnIndex { + get { return columnIndex; } + internal set { columnIndex = value; } + } + private int columnIndex; + + /// + /// Gets the index of the header divider + /// + public int HeaderDividerIndex { + get { return headerDividerIndex; } + internal set { headerDividerIndex = value; } + } + private int headerDividerIndex = -1; + + /// + /// Gets the column that was hit + /// + public OLVColumn Column { + get { + int index = this.ColumnIndex; + return index < 0 || this.ListView == null ? null : this.ListView.GetColumn(index); + } + } + + #endregion + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() + { + return string.Format("HitTestLocation: {0}, HitTestLocationEx: {1}, Item: {2}, SubItem: {3}, Location: {4}, Group: {5}, ColumnIndex: {6}", + this.HitTestLocation, this.HitTestLocationEx, this.item, this.subItem, this.location, this.Group, this.ColumnIndex); + } + + internal class HeaderHitTestInfo + { + public int ColumnIndex; + public bool IsOverCheckBox; + public int OverDividerIndex; + } + } +} diff --git a/ObjectListView/Implementation/TreeDataSourceAdapter.cs b/ObjectListView/Implementation/TreeDataSourceAdapter.cs new file mode 100644 index 0000000..e54cf10 --- /dev/null +++ b/ObjectListView/Implementation/TreeDataSourceAdapter.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeDataSourceAdapter knows how to build a tree structure from a binding list. + /// + /// To build a tree + public class TreeDataSourceAdapter : DataSourceAdapter + { + #region Life and death + + /// + /// Create a data source adaptor that knows how to build a tree structure + /// + /// + public TreeDataSourceAdapter(DataTreeListView tlv) + : base(tlv) { + this.treeListView = tlv; + this.treeListView.CanExpandGetter = delegate(object model) { return this.CalculateHasChildren(model); }; + this.treeListView.ChildrenGetter = delegate(object model) { return this.CalculateChildren(model); }; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + public virtual string KeyAspectName { + get { return keyAspectName; } + set { + if (keyAspectName == value) + return; + keyAspectName = value; + this.keyMunger = new Munger(this.KeyAspectName); + this.InitializeDataSource(); + } + } + private string keyAspectName; + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + public virtual string ParentKeyAspectName { + get { return parentKeyAspectName; } + set { + if (parentKeyAspectName == value) + return; + parentKeyAspectName = value; + this.parentKeyMunger = new Munger(this.ParentKeyAspectName); + this.InitializeDataSource(); + } + } + private string parentKeyAspectName; + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. + /// + public virtual object RootKeyValue { + get { return rootKeyValue; } + set { + if (Equals(rootKeyValue, value)) + return; + rootKeyValue = value; + this.InitializeDataSource(); + } + } + private object rootKeyValue; + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + public virtual bool ShowKeyColumns { + get { return showKeyColumns; } + set { showKeyColumns = value; } + } + private bool showKeyColumns = true; + + + #endregion + + #region Implementation properties + + /// + /// Gets the DataTreeListView that is being managed + /// + protected DataTreeListView TreeListView { + get { return treeListView; } + } + private readonly DataTreeListView treeListView; + + #endregion + + #region Implementation + + /// + /// + /// + protected override void InitializeDataSource() { + base.InitializeDataSource(); + this.TreeListView.RebuildAll(true); + } + + /// + /// + /// + protected override void SetListContents() { + this.TreeListView.Roots = this.CalculateRoots(); + } + + /// + /// + /// + /// + /// + protected override bool ShouldCreateColumn(PropertyDescriptor property) { + // If the property is a key column, and we aren't supposed to show keys, don't show it + if (!this.ShowKeyColumns && (property.Name == this.KeyAspectName || property.Name == this.ParentKeyAspectName)) + return false; + + return base.ShouldCreateColumn(property); + } + + /// + /// + /// + /// + protected override void HandleListChangedItemChanged(System.ComponentModel.ListChangedEventArgs e) { + // If the id or the parent id of a row changes, we just rebuild everything. + // We can't do anything more specific. We don't know what the previous values, so we can't + // tell the previous parent to refresh itself. If the id itself has changed, things that used + // to be children will no longer be children. Just rebuild everything. + // It seems PropertyDescriptor is only filled in .NET 4 :( + if (e.PropertyDescriptor != null && + (e.PropertyDescriptor.Name == this.KeyAspectName || + e.PropertyDescriptor.Name == this.ParentKeyAspectName)) + this.InitializeDataSource(); + else + base.HandleListChangedItemChanged(e); + } + + /// + /// + /// + /// + protected override void ChangePosition(int index) { + // We can't use our base method directly, since the normal position management + // doesn't know about our tree structure. They treat our dataset as a flat list + // but we have a collapsible structure. This means that the 5'th row to them + // may not even be visible to us + + // To display the n'th row, we have to make sure that all its ancestors + // are expanded. Then we will be able to select it. + object model = this.CurrencyManager.List[index]; + object parent = this.CalculateParent(model); + while (parent != null && !this.TreeListView.IsExpanded(parent)) { + this.TreeListView.Expand(parent); + parent = this.CalculateParent(parent); + } + + base.ChangePosition(index); + } + + private IEnumerable CalculateRoots() { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(this.RootKeyValue, parentKey)) + yield return x; + } + } + + private bool CalculateHasChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue == null) + return false; + + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + return true; + } + return false; + } + + private IEnumerable CalculateChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue != null) { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + yield return x; + } + } + } + + private object CalculateParent(object model) { + object parentValue = this.GetParentValue(model); + if (parentValue == null) + return null; + + foreach (object x in this.CurrencyManager.List) { + object key = this.GetKeyValue(x); + if (Object.Equals(parentValue, key)) + return x; + } + return null; + } + + private object GetKeyValue(object model) { + return this.keyMunger == null ? null : this.keyMunger.GetValue(model); + } + + private object GetParentValue(object model) { + return this.parentKeyMunger == null ? null : this.parentKeyMunger.GetValue(model); + } + + #endregion + + private Munger keyMunger; + private Munger parentKeyMunger; + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/VirtualGroups.cs b/ObjectListView/Implementation/VirtualGroups.cs new file mode 100644 index 0000000..1466ebb --- /dev/null +++ b/ObjectListView/Implementation/VirtualGroups.cs @@ -0,0 +1,341 @@ +/* + * Virtual groups - Classes and interfaces needed to implement virtual groups + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * 2011-02-21 JPP - Correctly honor group comparer and collapsible groups settings + * v2.3 + * 2009-08-28 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A IVirtualGroups is the interface that a virtual list must implement to support virtual groups + /// + public interface IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + IList GetGroups(GroupingParameters parameters); + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + int GetGroupMember(OLVGroup group, int indexWithinGroup); + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + int GetGroup(int itemIndex); + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + int GetIndexWithinGroup(OLVGroup group, int itemIndex); + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex); + } + + /// + /// This is a safe, do nothing implementation of a grouping strategy + /// + public class AbstractVirtualGroups : IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + public virtual IList GetGroups(GroupingParameters parameters) { + return new List(); + } + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + public virtual int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return -1; + } + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + public virtual int GetGroup(int itemIndex) { + return -1; + } + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + public virtual int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return -1; + } + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + public virtual void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex) { + } + } + + + /// + /// Provides grouping functionality to a FastObjectListView + /// + public class FastListGroupingStrategy : AbstractVirtualGroups + { + /// + /// Create groups for FastListView + /// + /// + /// + public override IList GetGroups(GroupingParameters parameters) { + + // There is a lot of overlap between this method and ObjectListView.MakeGroups() + // Any changes made here may need to be reflected there + + // This strategy can only be used on FastObjectListViews + FastObjectListView folv = (FastObjectListView)parameters.ListView; + + // Separate the list view items into groups, using the group key as the descrimanent + int objectCount = 0; + NullableDictionary> map = new NullableDictionary>(); + foreach (object model in folv.FilteredObjects) { + object key = parameters.GroupByColumn.GetGroupKey(model); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(model); + objectCount++; + } + + // Sort the items within each group + OLVColumn primarySortColumn = parameters.SortItemsByPrimaryColumn ? parameters.ListView.GetColumn(0) : parameters.PrimarySort; + ModelObjectComparer sorter = new ModelObjectComparer(primarySortColumn, parameters.PrimarySortOrder, + parameters.SecondarySort, parameters.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(sorter); + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parameters.CreateGroup(key, map[key].Count, folv.HasCollapsibleGroups); + lvg.Contents = map[key].ConvertAll(delegate(object x) { return folv.IndexOf(x); }); + lvg.VirtualItemCount = map[key].Count; + if (parameters.GroupByColumn.GroupFormatter != null) + parameters.GroupByColumn.GroupFormatter(lvg, parameters); + groups.Add(lvg); + } + + // Sort the groups + if (parameters.GroupByOrder != SortOrder.None) + groups.Sort(parameters.GroupComparer ?? new OLVGroupComparer(parameters.GroupByOrder)); + + // Build an array that remembers which group each item belongs to. + this.indexToGroupMap = new List(objectCount); + this.indexToGroupMap.AddRange(new int[objectCount]); + + for (int i = 0; i < groups.Count; i++) { + OLVGroup group = groups[i]; + List members = (List)group.Contents; + foreach (int j in members) + this.indexToGroupMap[j] = i; + } + + return groups; + } + private List indexToGroupMap; + + /// + /// + /// + /// + /// + /// + public override int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return (int)group.Contents[indexWithinGroup]; + } + + /// + /// + /// + /// + /// + public override int GetGroup(int itemIndex) { + return this.indexToGroupMap[itemIndex]; + } + + /// + /// + /// + /// + /// + /// + public override int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return group.Contents.IndexOf(itemIndex); + } + } + + + /// + /// This is the COM interface that a ListView must be given in order for groups in virtual lists to work. + /// + /// + /// This interface is NOT documented by MS. It was found on Greg Chapell's site. This means that there is + /// no guarantee that it will work on future versions of Windows, nor continue to work on current ones. + /// + [ComImport(), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown), + Guid("44C09D56-8D3B-419D-A462-7B956B105B47")] + internal interface IOwnerDataCallback + { + /// + /// Not sure what this does + /// + /// + /// + void GetItemPosition(int i, out NativeMethods.POINT pt); + + /// + /// Not sure what this does + /// + /// + /// + void SetItemPosition(int t, NativeMethods.POINT pt); + + /// + /// Get the index of the item that occurs at the n'th position of the indicated group. + /// + /// Index of the group + /// Index within the group + /// Index of the item within the whole list + void GetItemInGroup(int groupIndex, int n, out int itemIndex); + + /// + /// Get the index of the group to which the given item belongs + /// + /// Index of the item within the whole list + /// Which occurrences of the item is wanted + /// Index of the group + void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex); + + /// + /// Get the number of groups that contain the given item + /// + /// Index of the item within the whole list + /// How many groups does it occur within + void GetItemGroupCount(int itemIndex, out int occurrenceCount); + + /// + /// A hint to prepare any cache for the given range of requests + /// + /// + /// + void OnCacheHint(NativeMethods.LVITEMINDEX i, NativeMethods.LVITEMINDEX j); + } + + /// + /// A default implementation of the IOwnerDataCallback interface + /// + [Guid("6FC61F50-80E8-49b4-B200-3F38D3865ABD")] + internal class OwnerDataCallbackImpl : IOwnerDataCallback + { + public OwnerDataCallbackImpl(VirtualObjectListView olv) { + this.olv = olv; + } + VirtualObjectListView olv; + + #region IOwnerDataCallback Members + + public void GetItemPosition(int i, out NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("GetItemPosition"); + throw new NotSupportedException(); + } + + public void SetItemPosition(int t, NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("SetItemPosition"); + throw new NotSupportedException(); + } + + public void GetItemInGroup(int groupIndex, int n, out int itemIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("-> GetItemInGroup({0}, {1})", groupIndex, n)); + itemIndex = this.olv.GroupingStrategy.GetGroupMember(this.olv.OLVGroups[groupIndex], n); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", itemIndex)); + } + + public void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroup({0}, {1})", itemIndex, occurrenceCount)); + groupIndex = this.olv.GroupingStrategy.GetGroup(itemIndex); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", groupIndex)); + } + + public void GetItemGroupCount(int itemIndex, out int occurrenceCount) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroupCount({0})", itemIndex)); + occurrenceCount = 1; + } + + public void OnCacheHint(NativeMethods.LVITEMINDEX from, NativeMethods.LVITEMINDEX to) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnCacheHint({0}, {1}, {2}, {3})", from.iGroup, from.iItem, to.iGroup, to.iItem)); + this.olv.GroupingStrategy.CacheHint(from.iGroup, from.iItem, to.iGroup, to.iItem); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/VirtualListDataSource.cs b/ObjectListView/Implementation/VirtualListDataSource.cs new file mode 100644 index 0000000..7bc378d --- /dev/null +++ b/ObjectListView/Implementation/VirtualListDataSource.cs @@ -0,0 +1,349 @@ +/* + * VirtualListDataSource - Encapsulate how data is provided to a virtual list + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * v2.4 + * 2010-04-01 JPP - Added IFilterableDataSource + * v2.3 + * 2009-08-28 JPP - Initial version (Separated from VirtualObjectListView.cs) + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A VirtualListDataSource is a complete manner to provide functionality to a virtual list. + /// An object that implements this interface provides a VirtualObjectListView with all the + /// information it needs to be fully functional. + /// + /// Implementors must provide functioning implementations of at least GetObjectCount() + /// and GetNthObject(), otherwise nothing will appear in the list. + public interface IVirtualListDataSource + { + /// + /// Return the object that should be displayed at the n'th row. + /// + /// The index of the row whose object is to be returned. + /// The model object at the n'th row, or null if the fetching was unsuccessful. + Object GetNthObject(int n); + + /// + /// Return the number of rows that should be visible in the virtual list + /// + /// The number of rows the list view should have. + int GetObjectCount(); + + /// + /// Get the index of the row that is showing the given model object + /// + /// The model object sought + /// The index of the row showing the model, or -1 if the object could not be found. + int GetObjectIndex(Object model); + + /// + /// The ListView is about to request the given range of items. Do + /// whatever caching seems appropriate. + /// + /// + /// + void PrepareCache(int first, int last); + + /// + /// Find the first row that "matches" the given text in the given range. + /// + /// The text typed by the user + /// Start searching from this index. This may be greater than the 'to' parameter, + /// in which case the search should descend + /// Do not search beyond this index. This may be less than the 'from' parameter. + /// The column that should be considered when looking for a match. + /// Return the index of row that was matched, or -1 if no match was found + int SearchText(string value, int first, int last, OLVColumn column); + + /// + /// Sort the model objects in the data source. + /// + /// + /// + void Sort(OLVColumn column, SortOrder order); + + //----------------------------------------------------------------------------------- + // Modification commands + // THINK: Should we split these four into a separate interface? + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + void AddObjects(ICollection modelObjects); + + /// + /// Insert the given collection of model objects to this control at the position + /// + /// Index where the collection will be added + /// A collection of model objects + void InsertObjects(int index, ICollection modelObjects); + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + void RemoveObjects(ICollection modelObjects); + + /// + /// Set the collection of objects that this control will show. + /// + /// + void SetObjects(IEnumerable collection); + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + void UpdateObject(int index, object modelObject); + } + + /// + /// This extension allow virtual lists to filter their contents + /// + public interface IFilterableDataSource + { + /// + /// All subsequent retrievals on this data source should be filtered + /// through the given filters. null means no filtering of that kind. + /// + /// + /// + void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter); + } + + /// + /// A do-nothing implementation of the VirtualListDataSource interface. + /// + public class AbstractVirtualListDataSource : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Creates an AbstractVirtualListDataSource + /// + /// + public AbstractVirtualListDataSource(VirtualObjectListView listView) { + this.listView = listView; + } + + /// + /// The list view that this data source is giving information to. + /// + protected VirtualObjectListView listView; + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return -1; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int from, int to) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + } + + /// + /// + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void SetObjects(IEnumerable collection) { + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public virtual void UpdateObject(int index, object modelObject) { + } + + /// + /// This is a useful default implementation of SearchText method, intended to be called + /// by implementors of IVirtualListDataSource. + /// + /// + /// + /// + /// + /// + /// + static public int DefaultSearchText(string value, int first, int last, OLVColumn column, IVirtualListDataSource source) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + virtual public void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter) { + } + + #endregion + } + + /// + /// This class mimics the behavior of VirtualObjectListView v1.x. + /// + public class VirtualListVersion1DataSource : AbstractVirtualListDataSource + { + /// + /// Creates a VirtualListVersion1DataSource + /// + /// + public VirtualListVersion1DataSource(VirtualObjectListView listView) + : base(listView) { + } + + #region Public properties + + /// + /// How will the n'th object of the data source be fetched? + /// + public RowGetterDelegate RowGetter { + get { return rowGetter; } + set { rowGetter = value; } + } + private RowGetterDelegate rowGetter; + + #endregion + + #region IVirtualListDataSource implementation + + /// + /// + /// + /// + /// + public override object GetNthObject(int n) { + if (this.RowGetter == null) + return null; + else + return this.RowGetter(n); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string value, int first, int last, OLVColumn column) { + return DefaultSearchText(value, first, last, column, this); + } + + #endregion + } +} diff --git a/ObjectListView/OLVColumn.cs b/ObjectListView/OLVColumn.cs new file mode 100644 index 0000000..21ce4f9 --- /dev/null +++ b/ObjectListView/OLVColumn.cs @@ -0,0 +1,1909 @@ +/* + * OLVColumn - A column in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-05-05 JPP - Added EditorCreator to OLVColumn + * 2015-06-12 JPP - HeaderTextAlign became nullable so that it can be "not set" (this was always the intent) + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-27 JPP - Added Sortable, Hideable, Groupable, Searchable, ShowTextInHeader properties + * 2011-04-12 JPP - Added HasFilterIndicator + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Diagnostics; +using System.Drawing.Design; + +namespace BrightIdeasSoftware { + + // TODO + //[TypeConverter(typeof(ExpandableObjectConverter))] + //public class CheckBoxSettings + //{ + // private bool useSettings; + // private Image checkedImage; + + // public bool UseSettings { + // get { return useSettings; } + // set { useSettings = value; } + // } + + // public Image CheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image UncheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image IndeterminateImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + //} + + /// + /// An OLVColumn knows which aspect of an object it should present. + /// + /// + /// The column knows how to: + /// + /// extract its aspect from the row object + /// convert an aspect to a string + /// calculate the image for the row object + /// extract a group "key" from the row object + /// convert a group "key" into a title for the group + /// + /// For sorting to work correctly, aspects from the same column + /// must be of the same type, that is, the same aspect cannot sometimes + /// return strings and other times integers. + /// + [Browsable(false)] + public partial class OLVColumn : ColumnHeader { + + /// + /// How should the button be sized? + /// + public enum ButtonSizingMode + { + /// + /// Every cell will have the same sized button, as indicated by ButtonSize property + /// + FixedBounds, + + /// + /// Every cell will draw a button that fills the cell, inset by ButtonPadding + /// + CellBounds, + + /// + /// Each button will be resized to contain the text of the Aspect + /// + TextBounds + } + + #region Life and death + + /// + /// Create an OLVColumn + /// + public OLVColumn() { + } + + /// + /// Initialize a column to have the given title, and show the given aspect + /// + /// The title of the column + /// The aspect to be shown in the column + public OLVColumn(string title, string aspect) + : this() { + this.Text = title; + this.AspectName = aspect; + } + + #endregion + + #region Public Properties + + /// + /// This delegate will be used to extract a value to be displayed in this column. + /// + /// + /// If this is set, AspectName is ignored. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectGetterDelegate AspectGetter { + get { return aspectGetter; } + set { aspectGetter = value; } + } + private AspectGetterDelegate aspectGetter; + + /// + /// Remember if this aspect getter for this column was generated internally, and can therefore + /// be regenerated at will + /// + [Obsolete("This property is no longer maintained", true), + Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AspectGetterAutoGenerated { + get { return aspectGetterAutoGenerated; } + set { aspectGetterAutoGenerated = value; } + } + private bool aspectGetterAutoGenerated; + + /// + /// The name of the property or method that should be called to get the value to display in this column. + /// This is only used if a ValueGetterDelegate has not been given. + /// + /// This name can be dotted to chain references to properties or parameter-less methods. + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(null)] + public string AspectName { + get { return aspectName; } + set { + aspectName = value; + this.aspectMunger = null; + } + } + private string aspectName; + + /// + /// This delegate will be used to put an edited value back into the model object. + /// + /// + /// This does nothing if IsEditable == false. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { aspectPutter = value; } + } + private AspectPutterDelegate aspectPutter; + + /// + /// The delegate that will be used to translate the aspect to display in this column into a string. + /// + /// If this value is set, AspectToStringFormat will be ignored. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectToStringConverterDelegate AspectToStringConverter { + get { return aspectToStringConverter; } + set { aspectToStringConverter = value; } + } + private AspectToStringConverterDelegate aspectToStringConverter; + + /// + /// This format string will be used to convert an aspect to its string representation. + /// + /// + /// This string is passed as the first parameter to the String.Format() method. + /// This is only used if AspectToStringConverter has not been set. + /// "{0:C}" to convert a number to currency + [Category("ObjectListView"), + Description("The format string that will be used to convert an aspect to its string representation"), + DefaultValue(null)] + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(true)] + public bool AutoCompleteEditor { + get { return this.AutoCompleteEditorMode != AutoCompleteMode.None; } + set { + if (value) { + if (this.AutoCompleteEditorMode == AutoCompleteMode.None) + this.AutoCompleteEditorMode = AutoCompleteMode.Append; + } else + this.AutoCompleteEditorMode = AutoCompleteMode.None; + } + } + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(AutoCompleteMode.Append)] + public AutoCompleteMode AutoCompleteEditorMode { + get { return autoCompleteEditorMode; } + set { autoCompleteEditorMode = value; } + } + private AutoCompleteMode autoCompleteEditorMode = AutoCompleteMode.Append; + + /// + /// Gets whether this column can be hidden by user actions + /// + /// This take into account both the Hideable property and whether this column + /// is the primary column of the listview (column 0). + [Browsable(false)] + public bool CanBeHidden { + get { + return this.Hideable && (this.Index != 0); + } + } + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false (the default) and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// If this property is not set on the column, the value from the control will be used + /// + /// This value is only used when the control is in Details view. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(null)] + public virtual bool? CellEditUseWholeCell + { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool? cellEditUseWholeCell; + + /// + /// Get whether the whole cell should be used when editing a cell in this column + /// + /// This calculates the current effective value, which may be different to CellEditUseWholeCell + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CellEditUseWholeCellEffective { + get { + bool? columnSpecificValue = this.ListView.View == View.Details ? this.CellEditUseWholeCell : (bool?) null; + return (columnSpecificValue ?? ((ObjectListView) this.ListView).CellEditUseWholeCell); + } + } + + /// + /// Gets or sets how many pixels will be left blank around this cells in this column + /// + /// This setting only takes effect when the control is owner drawn. + [Category("ObjectListView"), + Description("How many pixels will be left blank around the cells in this column?"), + DefaultValue(null)] + public Rectangle? CellPadding + { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells in this column will be vertically aligned. + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// + /// If this is not set, the value from the control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets whether this column will show a checkbox. + /// + /// + /// Setting this on column 0 has no effect. Column 0 check box is controlled + /// by the CheckBoxes property on the ObjectListView itself. + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a checkbox, rather than a string?"), + DefaultValue(false)] + public virtual bool CheckBoxes { + get { return checkBoxes; } + set { + if (this.checkBoxes == value) + return; + + this.checkBoxes = value; + if (this.checkBoxes) { + if (this.Renderer == null) + this.Renderer = new CheckStateRenderer(); + } else { + if (this.Renderer is CheckStateRenderer) + this.Renderer = null; + } + } + } + private bool checkBoxes; + + /// + /// Gets or sets the clustering strategy used for this column. + /// + /// + /// + /// The clustering strategy is used to build a Filtering menu for this item. + /// If this is null, a useful default will be chosen. + /// + /// + /// To disable filtering on this column, set UseFiltering to false. + /// + /// + /// Cluster strategies belong to a particular column. The same instance + /// cannot be shared between multiple columns. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IClusteringStrategy ClusteringStrategy { + get { + if (this.clusteringStrategy == null) + this.ClusteringStrategy = this.DecideDefaultClusteringStrategy(); + return clusteringStrategy; + } + set { + this.clusteringStrategy = value; + if (this.clusteringStrategy != null) + this.clusteringStrategy.Column = this; + } + } + private IClusteringStrategy clusteringStrategy; + + /// + /// Gets or sets a delegate that will create an editor for a cell in this column. + /// + /// + /// If you need different editors for different cells in the same column, this + /// delegate is your solution. Return null to use the default editor for the cell. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public EditorCreatorDelegate EditorCreator { + get { return editorCreator; } + set { editorCreator = value; } + } + private EditorCreatorDelegate editorCreator; + + /// + /// Gets or sets whether the button in this column (if this column is drawing buttons) will be enabled + /// even if the row itself is disabled + /// + [Category("ObjectListView"), + Description("If this column contains a button, should the button be enabled even if the row is disabled?"), + DefaultValue(false)] + public bool EnableButtonWhenItemIsDisabled + { + get { return this.enableButtonWhenItemIsDisabled; } + set { this.enableButtonWhenItemIsDisabled = value; } + } + private bool enableButtonWhenItemIsDisabled; + + /// + /// Should this column resize to fill the free space in the listview? + /// + /// + /// + /// If you want two (or more) columns to equally share the available free space, set this property to True. + /// If you want this column to have a larger or smaller share of the free space, you must + /// set the FreeSpaceProportion property explicitly. + /// + /// + /// Space filling columns are still governed by the MinimumWidth and MaximumWidth properties. + /// + /// /// + [Category("ObjectListView"), + Description("Will this column resize to fill unoccupied horizontal space in the listview?"), + DefaultValue(false)] + public bool FillsFreeSpace { + get { return this.FreeSpaceProportion > 0; } + set { this.FreeSpaceProportion = value ? 1 : 0; } + } + + /// + /// What proportion of the unoccupied horizontal space in the control should be given to this column? + /// + /// + /// + /// There are situations where it would be nice if a column (normally the rightmost one) would expand as + /// the list view expands, so that as much of the column was visible as possible without having to scroll + /// horizontally (you should never, ever make your users have to scroll anything horizontally!). + /// + /// + /// A space filling column is resized to occupy a proportion of the unoccupied width of the listview (the + /// unoccupied width is the width left over once all the non-filling columns have been given their space). + /// This property indicates the relative proportion of that unoccupied space that will be given to this column. + /// The actual value of this property is not important -- only its value relative to the value in other columns. + /// For example: + /// + /// + /// If there is only one space filling column, it will be given all the free space, regardless of the value in FreeSpaceProportion. + /// + /// + /// If there are two or more space filling columns and they all have the same value for FreeSpaceProportion, + /// they will share the free space equally. + /// + /// + /// If there are three space filling columns with values of 3, 2, and 1 + /// for FreeSpaceProportion, then the first column with occupy half the free space, the second will + /// occupy one-third of the free space, and the third column one-sixth of the free space. + /// + /// + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { freeSpaceProportion = Math.Max(0, value); } + } + private int freeSpaceProportion; + + /// + /// Gets or sets whether groups will be rebuild on this columns values when this column's header is clicked. + /// + /// + /// This setting is only used when ShowGroups is true. + /// + /// If this is false, clicking the header will not rebuild groups. It will not provide + /// any feedback as to why the list is not being regrouped. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeCreatingGroups events are still fired, which can be used to allow grouping + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will the list create groups when this header is clicked?"), + DefaultValue(true)] + public bool Groupable { + get { return groupable; } + set { groupable = value; } + } + private bool groupable = true; + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupFormatterDelegate GroupFormatter { + get { return groupFormatter; } + set { groupFormatter = value; } + } + private GroupFormatterDelegate groupFormatter; + + /// + /// This delegate is called to get the object that is the key for the group + /// to which the given row belongs. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { groupKeyGetter = value; } + } + private GroupKeyGetterDelegate groupKeyGetter; + + /// + /// This delegate is called to convert a group key into a title for that group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyToTitleConverterDelegate GroupKeyToTitleConverter { + get { return groupKeyToTitleConverter; } + set { groupKeyToTitleConverter = value; } + } + private GroupKeyToTitleConverterDelegate groupKeyToTitleConverter; + + /// + /// When the listview is grouped by this column and group title has an item count, + /// how should the label be formatted? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Gets this.GroupWithItemCountFormat or a reasonable default + /// + /// + /// If GroupWithItemCountFormat is not set, its value will be taken from the ObjectListView if possible. + /// + [Browsable(false)] + public string GroupWithItemCountFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountFormat)) + return this.GroupWithItemCountFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountFormat = ((ObjectListView)this.ListView).GroupWithItemCountFormatOrDefault; + return cachedGroupWithItemCountFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountFormat ?? "{0} [{1} items]"; + } + } + private string cachedGroupWithItemCountFormat; + + /// + /// When the listview is grouped by this column and a group title has an item count, + /// how should the label be formatted if there is only one item in the group? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Get this.GroupWithItemCountSingularFormat or a reasonable default + /// + /// + /// If this value is not set, the values from the list view will be used + /// + [Browsable(false)] + public string GroupWithItemCountSingularFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat)) + return this.GroupWithItemCountSingularFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountSingularFormat = ((ObjectListView)this.ListView).GroupWithItemCountSingularFormatOrDefault; + return cachedGroupWithItemCountSingularFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountSingularFormat ?? "{0} [{1} item]"; + } + } + private string cachedGroupWithItemCountSingularFormat; + + /// + /// Gets whether this column should be drawn with a filter indicator in the column header. + /// + [Browsable(false)] + public bool HasFilterIndicator { + get { + return this.UseFiltering && this.ValuesChosenForFiltering != null && this.ValuesChosenForFiltering.Count > 0; + } + } + + /// + /// Gets or sets a delegate that will be used to own draw header column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public HeaderDrawingDelegate HeaderDrawing { + get { return headerDrawing; } + set { headerDrawing = value; } + } + private HeaderDrawingDelegate headerDrawing; + + /// + /// Gets or sets the style that will be used to draw the header for this column + /// + /// This is only uses when the owning ObjectListView has HeaderUsesThemes set to false. + [Category("ObjectListView"), + Description("What style will be used to draw the header of this column"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the font in which the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Which font will be used to draw the header?"), + DefaultValue(null)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the color in which the text of the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("In what color will the header text be drawn?"), + DefaultValue(typeof(Color), "")] + public Color HeaderForeColor { + get { return this.HeaderFormatStyle == null ? Color.Empty : this.HeaderFormatStyle.Normal.ForeColor; } + set { + if (value.IsEmpty && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetForeColor(value); + } + } + + /// + /// Gets or sets the ImageList key of the image that will be drawn in the header of this column. + /// + /// This is only taken into account when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Name of the image that will be shown in the column header."), + DefaultValue(null), + TypeConverter(typeof(ImageKeyConverter)), + Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), + RefreshProperties(RefreshProperties.Repaint)] + public string HeaderImageKey { + get { return headerImageKey; } + set { headerImageKey = value; } + } + private string headerImageKey; + + + /// + /// Gets or sets how the text of the header will be drawn? + /// + [Category("ObjectListView"), + Description("How will the header text be aligned? If this is not set, the alignment of the header will follow the alignment of the column"), + DefaultValue(null)] + public HorizontalAlignment? HeaderTextAlign { + get { return headerTextAlign; } + set { headerTextAlign = value; } + } + private HorizontalAlignment? headerTextAlign; + + /// + /// Return the text alignment of the header. This will either have been set explicitly, + /// or will follow the alignment of the text in the column + /// + [Browsable(false)] + public HorizontalAlignment HeaderTextAlignOrDefault + { + get { return headerTextAlign.HasValue ? headerTextAlign.Value : this.TextAlign; } + } + + /// + /// Gets the header alignment converted to a StringAlignment + /// + [Browsable(false)] + public StringAlignment HeaderTextAlignAsStringAlignment { + get { + switch (this.HeaderTextAlignOrDefault) { + case HorizontalAlignment.Left: return StringAlignment.Near; + case HorizontalAlignment.Center: return StringAlignment.Center; + case HorizontalAlignment.Right: return StringAlignment.Far; + default: return StringAlignment.Near; + } + } + } + + /// + /// Gets whether or not this column has an image in the header + /// + [Browsable(false)] + public bool HasHeaderImage { + get { + return (this.ListView != null && + this.ListView.SmallImageList != null && + this.ListView.SmallImageList.Images.ContainsKey(this.HeaderImageKey)); + } + } + + /// + /// Gets or sets whether this header will place a checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderCheckBox + { + get { return headerCheckBox; } + set { headerCheckBox = value; } + } + private bool headerCheckBox; + + /// + /// Gets or sets whether this header will place a tri-state checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a tri-state checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderTriStateCheckBox + { + get { return headerTriStateCheckBox; } + set { headerTriStateCheckBox = value; } + } + private bool headerTriStateCheckBox; + + /// + /// Gets or sets the checkedness of the checkbox in the header of this column + /// + [Category("ObjectListView"), + Description("Checkedness of the header checkbox"), + DefaultValue(CheckState.Unchecked)] + public CheckState HeaderCheckState + { + get { return headerCheckState; } + set { headerCheckState = value; } + } + private CheckState headerCheckState = CheckState.Unchecked; + + /// + /// Gets or sets whether the + /// checking/unchecking the value of the header's checkbox will result in the + /// checkboxes for all cells in this column being set to the same checked/unchecked. + /// Defaults to true. + /// + /// + /// + /// There is no reverse of this function that automatically updates the header when the + /// checkedness of a cell changes. + /// + /// + /// This property's behaviour on a TreeListView is probably best describes as undefined + /// and should be avoided. + /// + /// + /// The performance of this action (checking/unchecking all rows) is O(n) where n is the + /// number of rows. It will work on large virtual lists, but it may take some time. + /// + /// + [Category("ObjectListView"), + Description("Update row checkboxes when the header checkbox is clicked by the user"), + DefaultValue(true)] + public bool HeaderCheckBoxUpdatesRowCheckBoxes { + get { return headerCheckBoxUpdatesRowCheckBoxes; } + set { headerCheckBoxUpdatesRowCheckBoxes = value; } + } + private bool headerCheckBoxUpdatesRowCheckBoxes = true; + + /// + /// Gets or sets whether the checkbox in the header is disabled + /// + /// + /// Clicking on a disabled checkbox does not change its value, though it does raise + /// a HeaderCheckBoxChanging event, which allows the programmer the opportunity to do + /// something appropriate. + [Category("ObjectListView"), + Description("Is the checkbox in the header of this column disabled"), + DefaultValue(false)] + public bool HeaderCheckBoxDisabled + { + get { return headerCheckBoxDisabled; } + set { headerCheckBoxDisabled = value; } + } + private bool headerCheckBoxDisabled; + + /// + /// Gets or sets whether this column can be hidden by the user. + /// + /// + /// Column 0 can never be hidden, regardless of this setting. + /// + [Category("ObjectListView"), + Description("Will the user be able to choose to hide this column?"), + DefaultValue(true)] + public bool Hideable { + get { return hideable; } + set { hideable = value; } + } + private bool hideable = true; + + /// + /// Gets or sets whether the text values in this column will act like hyperlinks + /// + [Category("ObjectListView"), + Description("Will the text values in the cells of this column act like hyperlinks?"), + DefaultValue(false)] + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// This is the name of property that will be invoked to get the image selector of the + /// image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// + /// This is ignored if ImageGetter is not null. + /// The property can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Category("ObjectListView"), + Description("The name of the property that holds the image selector"), + DefaultValue(null)] + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// This delegate is called to get the image selector of the image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// This delegate can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { imageGetter = value; } + } + private ImageGetterDelegate imageGetter; + + /// + /// Gets or sets whether this column will draw buttons in its cells + /// + /// + /// + /// When this is set to true, the renderer for the column is become a ColumnButtonRenderer + /// if it isn't already. If this is set to false, any previous button renderer will be discarded + /// + /// If the cell's aspect is null or empty, nothing will be drawn in the cell. + [Category("ObjectListView"), + Description("Does this column draw its cells as buttons?"), + DefaultValue(false)] + public bool IsButton { + get { return isButton; } + set { + isButton = value; + if (value) { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) { + this.Renderer = this.CreateColumnButtonRenderer(); + this.FillInColumnButtonRenderer(); + } + } else { + if (this.Renderer is ColumnButtonRenderer) + this.Renderer = null; + } + } + } + private bool isButton; + + /// + /// Create a ColumnButtonRenderer to draw buttons in this column + /// + /// + protected virtual ColumnButtonRenderer CreateColumnButtonRenderer() { + return new ColumnButtonRenderer(); + } + + /// + /// Fill in details to our ColumnButtonRenderer based on the properties set on the column + /// + protected virtual void FillInColumnButtonRenderer() { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) + return; + + buttonRenderer.SizingMode = this.ButtonSizing; + buttonRenderer.ButtonSize = this.ButtonSize; + buttonRenderer.ButtonPadding = this.ButtonPadding; + buttonRenderer.MaxButtonWidth = this.ButtonMaxWidth; + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int ButtonMaxWidth { + get { return this.buttonMaxWidth; } + set { + this.buttonMaxWidth = value; + FillInColumnButtonRenderer(); + } + } + private int buttonMaxWidth = -1; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds"), + DefaultValue(null)] + public Size? ButtonPadding { + get { return this.buttonPadding; } + set { + this.buttonPadding = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonPadding; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize { + get { return this.buttonSize; } + set { + this.buttonSize = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonSize; + + /// + /// Gets or sets how each button will be sized if this column is displaying buttons + /// + [Category("ObjectListView"), + Description("If this column is showing buttons, how each button will be sized"), + DefaultValue(ButtonSizingMode.TextBounds)] + public ButtonSizingMode ButtonSizing { + get { return this.buttonSizing; } + set { + this.buttonSizing = value; + this.FillInColumnButtonRenderer(); + } + } + private ButtonSizingMode buttonSizing = ButtonSizingMode.TextBounds; + + /// + /// Can the values shown in this column be edited? + /// + /// This defaults to true, since the primary means to control the editability of a listview + /// is on the listview itself. Once a listview is editable, all the columns are too, unless the + /// programmer explicitly marks them as not editable + [Category("ObjectListView"), + Description("Can the value in this column be edited?"), + DefaultValue(true)] + public bool IsEditable + { + get { return isEditable; } + set { isEditable = value; } + } + private bool isEditable = true; + + /// + /// Is this column a fixed width column? + /// + [Browsable(false)] + public bool IsFixedWidth { + get { + return (this.MinimumWidth != -1 && this.MaximumWidth != -1 && this.MinimumWidth >= this.MaximumWidth); + } + } + + /// + /// Get/set whether this column should be used when the view is switched to tile view. + /// + /// Column 0 is always included in tileview regardless of this setting. + /// Tile views do not work well with many "columns" of information. + /// Two or three works best. + [Category("ObjectListView"), + Description("Will this column be used when the view is switched to tile view"), + DefaultValue(false)] + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// Gets or sets whether the text of this header should be rendered vertically. + /// + /// + /// If this is true, it is a good idea to set ToolTipText to the name of the column so it's easy to read. + /// Vertical headers are text only. They do not draw their image. + /// + [Category("ObjectListView"), + Description("Will the header for this column be drawn vertically?"), + DefaultValue(false)] + public bool IsHeaderVertical { + get { return isHeaderVertical; } + set { isHeaderVertical = value; } + } + private bool isHeaderVertical; + + /// + /// Can this column be seen by the user? + /// + /// After changing this value, you must call RebuildColumns() before the changes will take effect. + [Category("ObjectListView"), + Description("Can this column be seen by the user?"), + DefaultValue(true)] + public bool IsVisible { + get { return isVisible; } + set + { + if (isVisible == value) + return; + + isVisible = value; + OnVisibilityChanged(EventArgs.Empty); + } + } + private bool isVisible = true; + + /// + /// Where was this column last positioned within the Detail view columns + /// + /// DisplayIndex is volatile. Once a column is removed from the control, + /// there is no way to discover where it was in the display order. This property + /// guards that information even when the column is not in the listview's active columns. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int LastDisplayIndex { + get { return this.lastDisplayIndex; } + set { this.lastDisplayIndex = value; } + } + private int lastDisplayIndex = -1; + + /// + /// What is the maximum width that the user can give to this column? + /// + /// -1 means there is no maximum width. Give this the same value as MinimumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the maximum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MaximumWidth { + get { return maxWidth; } + set { + maxWidth = value; + if (maxWidth != -1 && this.Width > maxWidth) + this.Width = maxWidth; + } + } + private int maxWidth = -1; + + /// + /// What is the minimum width that the user can give to this column? + /// + /// -1 means there is no minimum width. Give this the same value as MaximumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the minimum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MinimumWidth { + get { return minWidth; } + set { + minWidth = value; + if (this.Width < minWidth) + this.Width = minWidth; + } + } + private int minWidth = -1; + + /// + /// Get/set the renderer that will be invoked when a cell needs to be redrawn + /// + [Category("ObjectListView"), + Description("The renderer will draw this column when the ListView is owner drawn"), + DefaultValue(null)] + public IRenderer Renderer { + get { return renderer; } + set { renderer = value; } + } + private IRenderer renderer; + + /// + /// This delegate is called when a cell needs to be drawn in OwnerDrawn mode. + /// + /// This method is kept primarily for backwards compatibility. + /// New code should implement an IRenderer, though this property will be maintained. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public RenderDelegate RendererDelegate { + get { + Version1Renderer version1Renderer = this.Renderer as Version1Renderer; + return version1Renderer != null ? version1Renderer.RenderDelegate : null; + } + set { + this.Renderer = value == null ? null : new Version1Renderer(value); + } + } + + /// + /// Gets or sets whether the text in this column's cell will be used when doing text searching. + /// + /// + /// + /// If this is false, text filters will not trying searching this columns cells when looking for matches. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the cells in this column be considered when searching?"), + DefaultValue(true)] + public bool Searchable { + get { return searchable; } + set { searchable = value; } + } + private bool searchable = true; + + /// + /// Gets or sets a delegate which will return the array of text values that should be + /// considered for text matching when using a text based filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public SearchValueGetterDelegate SearchValueGetter { + get { return searchValueGetter; } + set { searchValueGetter = value; } + } + private SearchValueGetterDelegate searchValueGetter; + + /// + /// Gets or sets whether the header for this column will include the column's Text. + /// + /// + /// + /// If this is false, the only thing rendered in the column header will be the image from . + /// + /// This setting is only considered when is false on the owning ObjectListView. + /// + [Category("ObjectListView"), + Description("Will the header for this column include text?"), + DefaultValue(true)] + public bool ShowTextInHeader { + get { return showTextInHeader; } + set { showTextInHeader = value; } + } + private bool showTextInHeader = true; + + /// + /// Gets or sets whether the contents of the list will be resorted when the user clicks the + /// header of this column. + /// + /// + /// + /// If this is false, clicking the header will not sort the list, but will not provide + /// any feedback as to why the list is not being sorted. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeSorting events are still fired, which can be used to allow sorting + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will clicking this columns header resort the list?"), + DefaultValue(true)] + public bool Sortable { + get { return sortable; } + set { sortable = value; } + } + private bool sortable = true; + + /// + /// Gets or sets the horizontal alignment of the contents of the column. + /// + /// .NET will not allow column 0 to have any alignment except + /// to the left. We can't change the basic behaviour of the listview, + /// but when owner drawn, column 0 can now have other alignments. + new public HorizontalAlignment TextAlign { + get { + return this.textAlign.HasValue ? this.textAlign.Value : base.TextAlign; + } + set { + this.textAlign = value; + base.TextAlign = value; + } + } + private HorizontalAlignment? textAlign; + + /// + /// Gets the StringAlignment equivalent of the column text alignment + /// + [Browsable(false)] + public StringAlignment TextStringAlign { + get { + switch (this.TextAlign) { + case HorizontalAlignment.Center: + return StringAlignment.Center; + case HorizontalAlignment.Left: + return StringAlignment.Near; + case HorizontalAlignment.Right: + return StringAlignment.Far; + default: + return StringAlignment.Near; + } + } + } + + /// + /// What string should be displayed when the mouse is hovered over the header of this column? + /// + /// If a HeaderToolTipGetter is installed on the owning ObjectListView, this + /// value will be ignored. + [Category("ObjectListView"), + Description("The tooltip to show when the mouse is hovered over the header of this column"), + DefaultValue((String)null), + Localizable(true)] + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// Should this column have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + } + } + private bool triStateCheckBoxes; + + /// + /// Group objects by the initial letter of the aspect of the column + /// + /// + /// One common pattern is to group column by the initial letter of the value for that group. + /// The aspect must be a string (obviously). + /// + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(false)] + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// Gets or sets whether or not this column should be user filterable + /// + [Category("ObjectListView"), + Description("Does this column want to show a Filter menu item when its header is right clicked"), + DefaultValue(true)] + public bool UseFiltering { + get { return useFiltering; } + set { useFiltering = value; } + } + private bool useFiltering = true; + + /// + /// Gets or sets a filter that will only include models where the model's value + /// for this column is one of the values in ValuesChosenForFiltering + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IModelFilter ValueBasedFilter { + get { + if (!this.UseFiltering) + return null; + + if (valueBasedFilter != null) + return valueBasedFilter; + + if (this.ClusteringStrategy == null) + return null; + + if (this.ValuesChosenForFiltering == null || this.ValuesChosenForFiltering.Count == 0) + return null; + + return this.ClusteringStrategy.CreateFilter(this.ValuesChosenForFiltering); + } + set { valueBasedFilter = value; } + } + private IModelFilter valueBasedFilter; + + /// + /// Gets or sets the values that will be used to generate a filter for this + /// column. For a model to be included by the generated filter, its value for this column + /// must be in this list. If the list is null or empty, this column will + /// not be used for filtering. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList ValuesChosenForFiltering { + get { return this.valuesChosenForFiltering; } + set { this.valuesChosenForFiltering = value; } + } + private IList valuesChosenForFiltering = new ArrayList(); + + /// + /// What is the width of this column? + /// + [Category("ObjectListView"), + Description("The width in pixels of this column"), + DefaultValue(60)] + public new int Width { + get { return base.Width; } + set { + if (this.MaximumWidth != -1 && value > this.MaximumWidth) + base.Width = this.MaximumWidth; + else + base.Width = Math.Max(this.MinimumWidth, value); + } + } + + /// + /// Gets or set whether the contents of this column's cells should be word wrapped + /// + /// If this column uses a custom IRenderer (that is, one that is not descended + /// from BaseRenderer), then that renderer is responsible for implementing word wrapping. + [Category("ObjectListView"), + Description("Draw this column cell's word wrapped"), + DefaultValue(false)] + public bool WordWrap { + get { return wordWrap; } + set { wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Object commands + + /// + /// For a given group value, return the string that should be used as the groups title. + /// + /// The group key that is being converted to a title + /// string + public string ConvertGroupKeyToTitle(object value) { + if (this.groupKeyToTitleConverter != null) + return this.groupKeyToTitleConverter(value); + + return value == null ? ObjectListView.GroupTitleDefault : this.ValueToString(value); + } + + /// + /// Get the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// The checkedness of the object + public CheckState GetCheckState(object rowObject) { + if (!this.CheckBoxes) + return CheckState.Unchecked; + + bool? aspectAsBool = this.GetValue(rowObject) as bool?; + if (aspectAsBool.HasValue) { + if (aspectAsBool.Value) + return CheckState.Checked; + else + return CheckState.Unchecked; + } else + return CheckState.Indeterminate; + } + + /// + /// Put the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// + /// The checkedness of the object + public void PutCheckState(object rowObject, CheckState newState) { + if (newState == CheckState.Checked) + this.PutValue(rowObject, true); + else + if (newState == CheckState.Unchecked) + this.PutValue(rowObject, false); + else + this.PutValue(rowObject, null); + } + + /// + /// For a given row object, extract the value indicated by the AspectName property of this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect named by AspectName + public object GetAspectByName(object rowObject) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + return this.aspectMunger.GetValue(rowObject); + } + private Munger aspectMunger; + + /// + /// For a given row object, return the object that is the key of the group that this row belongs to. + /// + /// The row object that is being displayed + /// Group key object + public object GetGroupKey(object rowObject) { + if (this.groupKeyGetter != null) + return this.groupKeyGetter(rowObject); + + object key = this.GetValue(rowObject); + + if (this.UseInitialLetterForGroup) { + String keyAsString = key as String; + if (!String.IsNullOrEmpty(keyAsString)) + return keyAsString.Substring(0, 1).ToUpper(); + } + + return key; + } + + /// + /// For a given row object, return the image selector of the image that should displayed in this column. + /// + /// The row object that is being displayed + /// int or string or Image. int or string will be used as index into image list. null or -1 means no image + public Object GetImage(object rowObject) { + if (this.CheckBoxes) + return this.GetCheckStateImage(rowObject); + + if (this.ImageGetter != null) + return this.ImageGetter(rowObject); + + if (!String.IsNullOrEmpty(this.ImageAspectName)) { + if (this.imageAspectMunger == null) + this.imageAspectMunger = new Munger(this.ImageAspectName); + + return this.imageAspectMunger.GetValue(rowObject); + } + + // I think this is wrong. ImageKey is meant for the image in the header, not in the rows + if (!String.IsNullOrEmpty(this.ImageKey)) + return this.ImageKey; + + return this.ImageIndex; + } + private Munger imageAspectMunger; + + /// + /// Return the image that represents the check box for the given model + /// + /// + /// + public string GetCheckStateImage(Object rowObject) { + CheckState checkState = this.GetCheckState(rowObject); + + if (checkState == CheckState.Checked) + return ObjectListView.CHECKED_KEY; + + if (checkState == CheckState.Unchecked) + return ObjectListView.UNCHECKED_KEY; + + return ObjectListView.INDETERMINATE_KEY; + } + + /// + /// For a given row object, return the strings that will be searched when trying to filter by string. + /// + /// + /// This will normally be the simple GetStringValue result, but if this column is non-textual (e.g. image) + /// you might want to install a SearchValueGetter delegate which can return something that could be used + /// for text filtering. + /// + /// + /// The array of texts to be searched. If this returns null, search will not match that object. + public string[] GetSearchValues(object rowObject) { + if (this.SearchValueGetter != null) + return this.SearchValueGetter(rowObject); + + var stringValue = this.GetStringValue(rowObject); + + DescribedTaskRenderer dtr = this.Renderer as DescribedTaskRenderer; + if (dtr != null) { + return new string[] { stringValue, dtr.GetDescription(rowObject) }; + } + + return new string[] { stringValue }; + } + + /// + /// For a given row object, return the string representation of the value shown in this column. + /// + /// + /// For aspects that are string (e.g. aPerson.Name), the aspect and its string representation are the same. + /// For non-strings (e.g. aPerson.DateOfBirth), the string representation is very different. + /// + /// + /// + public string GetStringValue(object rowObject) + { + return this.ValueToString(this.GetValue(rowObject)); + } + + /// + /// For a given row object, return the object that is to be displayed in this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect to be displayed + public object GetValue(object rowObject) { + if (this.AspectGetter == null) + return this.GetAspectByName(rowObject); + else + return this.AspectGetter(rowObject); + } + + /// + /// Update the given model object with the given value using the column's + /// AspectName. + /// + /// The model object to be updated + /// The value to be put into the model + public void PutAspectByName(Object rowObject, Object newValue) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + this.aspectMunger.PutValue(rowObject, newValue); + } + + /// + /// Update the given model object with the given value + /// + /// The model object to be updated + /// The value to be put into the model + public void PutValue(Object rowObject, Object newValue) { + if (this.aspectPutter == null) + this.PutAspectByName(rowObject, newValue); + else + this.aspectPutter(rowObject, newValue); + } + + /// + /// Convert the aspect object to its string representation. + /// + /// + /// If the column has been given a AspectToStringConverter, that will be used to do + /// the conversion, otherwise just use ToString(). + /// The returned value will not be null. Nulls are always converted + /// to empty strings. + /// + /// The value of the aspect that should be displayed + /// A string representation of the aspect + public string ValueToString(object value) { + // Give the installed converter a chance to work (even if the value is null) + if (this.AspectToStringConverter != null) + return this.AspectToStringConverter(value) ?? String.Empty; + + // Without a converter, nulls become simple empty strings + if (value == null) + return String.Empty; + + string fmt = this.AspectToStringFormat; + if (String.IsNullOrEmpty(fmt)) + return value.ToString(); + else + return String.Format(fmt, value); + } + + #endregion + + #region Utilities + + /// + /// Decide the clustering strategy that will be used for this column + /// + /// + private IClusteringStrategy DecideDefaultClusteringStrategy() { + if (!this.UseFiltering) + return null; + + if (this.DataType == typeof(DateTime)) + return new DateTimeClusteringStrategy(); + + return new ClustersFromGroupsStrategy(); + } + + /// + /// Gets or sets the type of data shown in this column. + /// + /// If this is not set, it will try to get the type + /// by looking through the rows of the listview. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Type DataType { + get { + if (this.dataType == null) { + ObjectListView olv = this.ListView as ObjectListView; + if (olv != null) { + object value = olv.GetFirstNonNullValue(this); + if (value != null) + return value.GetType(); // THINK: Should we cache this? + } + } + return this.dataType; + } + set { + this.dataType = value; + } + } + private Type dataType; + + #region Events + + /// + /// This event is triggered when the visibility of this column changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when the visibility of the column changes.")] + public event EventHandler VisibilityChanged; + + /// + /// Tell the world when visibility of a column changes. + /// + public virtual void OnVisibilityChanged(EventArgs e) + { + if (this.VisibilityChanged != null) + this.VisibilityChanged(this, e); + } + + #endregion + + /// + /// Create groupies + /// This is an untyped version to help with Generator and OLVColumn attributes + /// + /// + /// + public void MakeGroupies(object[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images) { + this.MakeGroupies(values, descriptions, images, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles) { + this.MakeGroupies(values, descriptions, images, subtitles, null); + } + + /// + /// Create groupies. + /// Install delegates that will group the columns aspects into progressive partitions. + /// If an aspect is less than value[n], it will be grouped with description[n]. + /// If an aspect has a value greater than the last element in "values", it will be grouped + /// with the last element in "descriptions". + /// + /// Array of values. Values must be able to be + /// compared to the aspect (using IComparable) + /// The description for the matching value. The last element is the default description. + /// If there are n values, there must be n+1 descriptions. + /// + /// this.salaryColumn.MakeGroupies( + /// new UInt32[] { 20000, 100000 }, + /// new string[] { "Lowly worker", "Middle management", "Rarified elevation"}); + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length + 1 != descriptions.Length) + throw new ArgumentException("descriptions must have one more element than values."); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + Object aspect = this.GetValue(row); + if (aspect == null || aspect == DBNull.Value) + return -1; + IComparable comparable = (IComparable)aspect; + for (int i = 0; i < values.Length; i++) { + if (comparable.CompareTo(values[i]) < 0) + return i; + } + + // Display the last element in the array + return descriptions.Length - 1; + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + if ((int)key < 0) + return ""; + + return descriptions[(int)key]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + /// + /// Create groupies based on exact value matches. + /// + /// + /// Install delegates that will group rows into partitions based on equality of this columns aspects. + /// If an aspect is equal to value[n], it will be grouped with description[n]. + /// If an aspect is not equal to any value, it will be grouped with "[other]". + /// + /// Array of values. Values must be able to be + /// equated to the aspect + /// The description for the matching value. + /// + /// this.marriedColumn.MakeEqualGroupies( + /// new MaritalStatus[] { MaritalStatus.Single, MaritalStatus.Married, MaritalStatus.Divorced, MaritalStatus.Partnered }, + /// new string[] { "Looking", "Content", "Looking again", "Mostly content" }); + /// + /// + /// + /// + /// + public void MakeEqualGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length != descriptions.Length) + throw new ArgumentException("descriptions must have the same number of elements as values."); + + ArrayList valuesArray = new ArrayList(values); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + return valuesArray.IndexOf(this.GetValue(row)); + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + int intKey = (int)key; // we know this is an int since we created it in GroupKeyGetter + return (intKey < 0) ? "[other]" : descriptions[intKey]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.DesignTime.cs b/ObjectListView/ObjectListView.DesignTime.cs new file mode 100644 index 0000000..2fac113 --- /dev/null +++ b/ObjectListView/ObjectListView.DesignTime.cs @@ -0,0 +1,550 @@ +/* + * DesignSupport - Design time support for the various classes within ObjectListView + * + * Author: Phillip Piper + * Date: 12/08/2009 8:36 PM + * + * Change log: + * 2012-08-27 JPP - Fall back to more specific type name for the ListViewDesigner if + * the first GetType() fails. + * v2.5.1 + * 2012-04-26 JPP - Filter group events from TreeListView since it can't have groups + * 2011-06-06 JPP - Vastly improved ObjectListViewDesigner, based off information in + * "'Inheriting' from an Internal WinForms Designer" on CodeProject. + * v2.3 + * 2009-08-12 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Windows.Forms.Design; + +namespace BrightIdeasSoftware.Design +{ + + /// + /// Designer for and its subclasses. + /// + /// + /// + /// This designer removes properties and events that are available on ListView but that are not + /// useful on ObjectListView. + /// + /// + /// We can't inherit from System.Windows.Forms.Design.ListViewDesigner, since it is marked internal. + /// So, this class uses reflection to create a ListViewDesigner and then forwards messages to that designer. + /// + /// + public class ObjectListViewDesigner : ControlDesigner + { + + #region Initialize & Dispose + + /// + /// Initialises the designer with the specified component. + /// + /// The to associate the designer with. This component must always be an instance of, or derive from, . + public override void Initialize(IComponent component) { + // Debug.WriteLine("ObjectListViewDesigner.Initialize"); + + // Use reflection to bypass the "internal" marker on ListViewDesigner + // If we can't get the unversioned designer, look specifically for .NET 4.0 version of it. + Type tListViewDesigner = Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design") ?? + Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design, " + + "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + if (tListViewDesigner == null) throw new ArgumentException("Could not load ListViewDesigner"); + + this.listViewDesigner = (ControlDesigner)Activator.CreateInstance(tListViewDesigner, BindingFlags.Instance | BindingFlags.Public, null, null, null); + this.designerFilter = this.listViewDesigner; + + // Fetch the methods from the ListViewDesigner that we know we want to use + this.listViewDesignGetHitTest = tListViewDesigner.GetMethod("GetHitTest", BindingFlags.Instance | BindingFlags.NonPublic); + this.listViewDesignWndProc = tListViewDesigner.GetMethod("WndProc", BindingFlags.Instance | BindingFlags.NonPublic); + + Debug.Assert(this.listViewDesignGetHitTest != null, "Required method (GetHitTest) not found on ListViewDesigner"); + Debug.Assert(this.listViewDesignWndProc != null, "Required method (WndProc) not found on ListViewDesigner"); + + // Tell the Designer to use properties of default designer as well as the properties of this class (do before base.Initialize) + TypeDescriptor.CreateAssociation(component, this.listViewDesigner); + + IServiceContainer site = (IServiceContainer)component.Site; + if (site != null && GetService(typeof(DesignerCommandSet)) == null) { + site.AddService(typeof(DesignerCommandSet), new CDDesignerCommandSet(this)); + } else { + Debug.Fail("site != null && GetService(typeof (DesignerCommandSet)) == null"); + } + + this.listViewDesigner.Initialize(component); + base.Initialize(component); + + RemoveDuplicateDockingActionList(); + } + + /// + /// Initialises a newly created component. + /// + /// A name/value dictionary of default values to apply to properties. May be null if no default values are specified. + public override void InitializeNewComponent(IDictionary defaultValues) { + // Debug.WriteLine("ObjectListViewDesigner.InitializeNewComponent"); + base.InitializeNewComponent(defaultValues); + this.listViewDesigner.InitializeNewComponent(defaultValues); + } + + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) { + // Debug.WriteLine("ObjectListViewDesigner.Dispose"); + if (disposing) { + if (this.listViewDesigner != null) { + this.listViewDesigner.Dispose(); + // Normally we would now null out the designer, but this designer + // still has methods called AFTER it is disposed. + } + } + + base.Dispose(disposing); + } + + /// + /// Removes the duplicate DockingActionList added by this designer to the . + /// + /// + /// adds an internal DockingActionList : 'Dock/Undock in Parent Container'. + /// But the default designer has already added that action list. So we need to remove one. + /// + private void RemoveDuplicateDockingActionList() { + // This is a true hack -- in a class that is basically a huge hack itself. + // Reach into the bowel of our base class, get a private field, and use that fields value to + // remove an action from the designer. + // In ControlDesigner, there is "private DockingActionList dockingAction;" + // Don't you just love Reflector?! + FieldInfo fi = typeof(ControlDesigner).GetField("dockingAction", BindingFlags.Instance | BindingFlags.NonPublic); + if (fi != null) { + DesignerActionList dockingAction = (DesignerActionList)fi.GetValue(this); + if (dockingAction != null) { + DesignerActionService service = (DesignerActionService)GetService(typeof(DesignerActionService)); + if (service != null) { + service.Remove(this.Control, dockingAction); + } + } + } + } + + #endregion + + #region IDesignerFilter overrides + + /// + /// Adjusts the set of properties the component exposes through a . + /// + /// An containing the properties for the class of the component. + protected override void PreFilterProperties(IDictionary properties) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterProperties"); + + // Always call the base PreFilterProperties implementation + // before you modify the properties collection. + base.PreFilterProperties(properties); + + // Give the listviewdesigner a chance to filter the properties + // (though we already know it's not going to do anything) + this.designerFilter.PreFilterProperties(properties); + + // I'd like to just remove the redundant properties, but that would + // break backward compatibility. The deserialiser that handles the XXX.Designer.cs file + // works off the designer, so even if the property exists in the class, the deserialiser will + // throw an error if the associated designer actually removes that property. + // So we shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + + List unwantedProperties = new List(new string[] { + "BackgroundImage", "BackgroundImageTiled", "HotTracking", "HoverSelection", + "LabelEdit", "VirtualListSize", "VirtualMode" }); + + // Also hid Tooltip properties, since giving a tooltip to the control through the IDE + // messes up the tooltip handling + foreach (string propertyName in properties.Keys) { + if (propertyName.StartsWith("ToolTip")) { + unwantedProperties.Add(propertyName); + } + } + + // If we are looking at a TreeListView, remove group related properties + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwantedProperties.AddRange(new string[] { + "GroupImageList", "GroupWithItemCountFormat", "GroupWithItemCountSingularFormat", "HasCollapsibleGroups", + "SpaceBetweenGroups", "ShowGroups", "SortGroupItemsByPrimaryColumn", "ShowItemCountOnGroups" + }); + } + + // Shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + foreach (string unwantedProperty in unwantedProperties) { + PropertyDescriptor propertyDesc = TypeDescriptor.CreateProperty( + typeof(ObjectListView), + (PropertyDescriptor)properties[unwantedProperty], + new BrowsableAttribute(false)); + properties[unwantedProperty] = propertyDesc; + } + } + + /// + /// Allows a designer to add to the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PreFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterEvents"); + base.PreFilterEvents(events); + this.designerFilter.PreFilterEvents(events); + + // Remove the events that don't make sense for an ObjectListView. + // See PreFilterProperties() for why we do this dance rather than just remove the event. + List unwanted = new List(new string[] { + "AfterLabelEdit", + "BeforeLabelEdit", + "DrawColumnHeader", + "DrawItem", + "DrawSubItem", + "RetrieveVirtualItem", + "SearchForVirtualItem", + "VirtualItemsSelectionRangeChanged" + }); + + // If we are looking at a TreeListView, remove group related events + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwanted.AddRange(new string[] { + "AboutToCreateGroups", + "AfterCreatingGroups", + "BeforeCreatingGroups", + "GroupTaskClicked", + "GroupExpandingCollapsing", + "GroupStateChanged" + }); + } + + foreach (string unwantedEvent in unwanted) { + EventDescriptor eventDesc = TypeDescriptor.CreateEvent( + typeof(ObjectListView), + (EventDescriptor)events[unwantedEvent], + new BrowsableAttribute(false)); + events[unwantedEvent] = eventDesc; + } + } + + /// + /// Allows a designer to change or remove items from the set of attributes that it exposes through a . + /// + /// The attributes for the class of the component. + protected override void PostFilterAttributes(IDictionary attributes) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterAttributes"); + this.designerFilter.PostFilterAttributes(attributes); + base.PostFilterAttributes(attributes); + } + + /// + /// Allows a designer to change or remove items from the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PostFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterEvents"); + this.designerFilter.PostFilterEvents(events); + base.PostFilterEvents(events); + } + + #endregion + + #region Overrides + + /// + /// Gets the design-time action lists supported by the component associated with the designer. + /// + /// + /// The design-time action lists supported by the component associated with the designer. + /// + public override DesignerActionListCollection ActionLists { + get { + // We want to change the first action list so it only has the commands we want + DesignerActionListCollection actionLists = this.listViewDesigner.ActionLists; + if (actionLists.Count > 0 && !(actionLists[0] is ListViewActionListAdapter)) { + actionLists[0] = new ListViewActionListAdapter(this, actionLists[0]); + } + return actionLists; + } + } + + /// + /// Gets the collection of components associated with the component managed by the designer. + /// + /// + /// The components that are associated with the component managed by the designer. + /// + public override ICollection AssociatedComponents { + get { + ArrayList components = new ArrayList(base.AssociatedComponents); + components.AddRange(this.listViewDesigner.AssociatedComponents); + return components; + } + } + + /// + /// Indicates whether a mouse click at the specified point should be handled by the control. + /// + /// + /// true if a click at the specified point is to be handled by the control; otherwise, false. + /// + /// A indicating the position at which the mouse was clicked, in screen coordinates. + protected override bool GetHitTest(Point point) { + // The ListViewDesigner wants to allow column dividers to be resized + return (bool)this.listViewDesignGetHitTest.Invoke(listViewDesigner, new object[] { point }); + } + + /// + /// Processes Windows messages and optionally routes them to the control. + /// + /// The to process. + protected override void WndProc(ref Message m) { + switch (m.Msg) { + case 0x4e: + case 0x204e: + // The listview designer is interested in HDN_ENDTRACK notifications + this.listViewDesignWndProc.Invoke(listViewDesigner, new object[] { m }); + break; + default: + base.WndProc(ref m); + break; + } + } + + #endregion + + #region Implementation variables + + private ControlDesigner listViewDesigner; + private IDesignerFilter designerFilter; + private MethodInfo listViewDesignGetHitTest; + private MethodInfo listViewDesignWndProc; + + #endregion + + #region Custom action list + + /// + /// This class modifies a ListViewActionList, by removing the "Edit Items" and "Edit Groups" actions. + /// + /// + /// + /// That class is internal, so we cannot simply subclass it, which would be simpler. + /// + /// + /// Action lists use reflection to determine if that action can be executed, so we not + /// only have to modify the returned collection of actions, but we have to implement + /// the properties and commands that the returned actions use. + /// + private class ListViewActionListAdapter : DesignerActionList + { + public ListViewActionListAdapter(ObjectListViewDesigner designer, DesignerActionList wrappedList) + : base(wrappedList.Component) { + this.designer = designer; + this.wrappedList = wrappedList; + } + + public override DesignerActionItemCollection GetSortedActionItems() { + DesignerActionItemCollection items = wrappedList.GetSortedActionItems(); + items.RemoveAt(2); // remove Edit Groups + items.RemoveAt(0); // remove Edit Items + return items; + } + + private void EditValue(ComponentDesigner componentDesigner, IComponent iComponent, string propertyName) { + // One more complication. The ListViewActionList classes uses an internal class, EditorServiceContext, to + // edit the items/columns/groups collections. So, we use reflection to bypass the data hiding. + Type tEditorServiceContext = Type.GetType("System.Windows.Forms.Design.EditorServiceContext, System.Design"); + tEditorServiceContext.InvokeMember("EditValue", BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object[] { componentDesigner, iComponent, propertyName }); + } + + private void SetValue(object target, string propertyName, object value) { + TypeDescriptor.GetProperties(target)[propertyName].SetValue(target, value); + } + + public void InvokeColumnsDialog() { + EditValue(this.designer, base.Component, "Columns"); + } + + // Don't need these since we removed their corresponding actions from the list. + // Keep the methods just in case. + + //public void InvokeGroupsDialog() { + // EditValue(this.designer, base.Component, "Groups"); + //} + + //public void InvokeItemsDialog() { + // EditValue(this.designer, base.Component, "Items"); + //} + + public ImageList LargeImageList { + get { return ((ListView)base.Component).LargeImageList; } + set { SetValue(base.Component, "LargeImageList", value); } + } + + public ImageList SmallImageList { + get { return ((ListView)base.Component).SmallImageList; } + set { SetValue(base.Component, "SmallImageList", value); } + } + + public View View { + get { return ((ListView)base.Component).View; } + set { SetValue(base.Component, "View", value); } + } + + ObjectListViewDesigner designer; + DesignerActionList wrappedList; + } + + #endregion + + #region DesignerCommandSet + + private class CDDesignerCommandSet : DesignerCommandSet + { + + public CDDesignerCommandSet(ComponentDesigner componentDesigner) { + this.componentDesigner = componentDesigner; + } + + public override ICollection GetCommands(string name) { + // Debug.WriteLine("CDDesignerCommandSet.GetCommands:" + name); + if (componentDesigner != null) { + if (name.Equals("Verbs")) { + return componentDesigner.Verbs; + } + if (name.Equals("ActionLists")) { + return componentDesigner.ActionLists; + } + } + return base.GetCommands(name); + } + + private readonly ComponentDesigner componentDesigner; + } + + #endregion + } + + /// + /// This class works in conjunction with the OLVColumns property to allow OLVColumns + /// to be added to the ObjectListView. + /// + public class OLVColumnCollectionEditor : System.ComponentModel.Design.CollectionEditor + { + /// + /// Create a OLVColumnCollectionEditor + /// + /// + public OLVColumnCollectionEditor(Type t) + : base(t) { + } + + /// + /// What type of object does this editor create? + /// + /// + protected override Type CreateCollectionItemType() { + return typeof(OLVColumn); + } + + /// + /// Edit a given value + /// + /// + /// + /// + /// + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + if (context == null) + throw new ArgumentNullException("context"); + if (provider == null) + throw new ArgumentNullException("provider"); + + // Figure out which ObjectListView we are working on. This should be the Instance of the context. + ObjectListView olv = context.Instance as ObjectListView; + Debug.Assert(olv != null, "Instance must be an ObjectListView"); + + // Edit all the columns, not just the ones that are visible + base.EditValue(context, provider, olv.AllColumns); + + // Set the columns on the ListView to just the visible columns + List newColumns = olv.GetFilteredColumns(View.Details); + olv.Columns.Clear(); + olv.Columns.AddRange(newColumns.ToArray()); + + return olv.Columns; + } + + /// + /// What text should be shown in the list for the given object? + /// + /// + /// + protected override string GetDisplayText(object value) { + OLVColumn col = value as OLVColumn; + if (col == null || String.IsNullOrEmpty(col.AspectName)) + return base.GetDisplayText(value); + + return String.Format("{0} ({1})", base.GetDisplayText(value), col.AspectName); + } + } + + /// + /// Control how the overlay is presented in the IDE + /// + internal class OverlayConverter : ExpandableObjectConverter + { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { + return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); + } + + public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { + if (destinationType == typeof(string)) { + ImageOverlay imageOverlay = value as ImageOverlay; + if (imageOverlay != null) { + return imageOverlay.Image == null ? "(none)" : "(set)"; + } + TextOverlay textOverlay = value as TextOverlay; + if (textOverlay != null) { + return String.IsNullOrEmpty(textOverlay.Text) ? "(none)" : "(set)"; + } + } + + return base.ConvertTo(context, culture, value, destinationType); + } + } +} diff --git a/ObjectListView/ObjectListView.FxCop b/ObjectListView/ObjectListView.FxCop new file mode 100644 index 0000000..b5653dd --- /dev/null +++ b/ObjectListView/ObjectListView.FxCop @@ -0,0 +1,3521 @@ + + + + True + c:\program files\microsoft fxcop 1.36\Xml\FxCopReport.xsl + + + + + + True + True + True + 10 + 1 + + False + + False + 120 + True + 2.0 + + + + $(ProjectDir)/trunk/ObjectListView/bin/Debug/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 'ObjectListView.dll' + + + + + + + + + + + 'BarRenderer' + 'Pen' + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(int, int, Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BackgroundColor' + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + + + + + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetForegroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetImageSelector()' + + + + + + + + + 'BaseRenderer.GetText()' + + + + + + + + + + + + + + 'BaseRenderer.GetTextBackgroundColor()' + + + + + + + + + + + + + + + + 'BorderDecoration' + 'SolidBrush' + + + + + + + + + 'CellEditEventHandler' + + + + + + + + + + + + + + + + 'g' + 'CheckStateRenderer.CalculateCheckBoxBounds(Graphics, Rectangle)' + + + + + + + + + + + 'ColumnRightClickEventHandler' + + + + + + + + + + + + + + + + + + 'ComboBoxItem.Key.get()' + + + + + + + + + + + + + + + 'DataListView.currencyManager_ListChanged(object, ListChangedEventArgs)' + + + + + + + + + 'DataListView.currencyManager_MetaDataChanged(object, EventArgs)' + + + + + + + + + 'DataListView.currencyManager_PositionChanged(object, EventArgs)' + + + + + + + + + + + + + 'DescribedTaskRenderer.GetDescription()' + + + + + + + + + + + 'DropTargetLocation' + + + + + + + + + + + 'collection' + 'ICollection' + 'FastObjectListDataSource.EnumerableToArray(IEnumerable)' + castclass + + + + + + + + + + + 'FastObjectListDataSource.FilteredObjectList.get()' + + + + + + + + + + + + + Flag + 'FlagRenderer' + + + + + + + + + + + + + 'FloatCellEditor.Value.get()' + + + + + + + + + + + + + + 'FloatCellEditor.Value.set(double)' + + + + + + + + + + + + + + + + + + + + + + 'GlassPanelForm.CreateParams.get()' + 'Form.CreateParams.get()' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GlassPanelForm.WndProc(ref Message)' + 'Form.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GroupMetricsMask' + 'GroupMetricsMask.LVGMF_NONE' + + + + + + + + + + 'GroupMetricsMask' + + + + + + + + + + + + + + 'GroupState' + 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 + + + + + 'GroupState' + 'GroupState.LVGS_NORMAL' + + + + + 'GroupState' + + + + + + + + + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.AssignHandle(IntPtr)' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.NativeWindow()' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + + + + + + + + + + + + 'g' + 'HeaderControl.CalculateHeight(Graphics)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawHeaderText(Graphics, Rectangle, OLVColumn, HeaderStateStyle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedBackground(Graphics, Rectangle, int, bool)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedSortIndicator(Graphics, Rectangle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedBackground(Graphics, Rectangle, int, bool, HeaderStateStyle)' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedSortIndicator(Graphics, Rectangle)' + + + + + + + + + 'm' + 'HeaderControl.HandleDestroy(ref Message)' + + + + + + + + + 'm' + 'HeaderControl.HandleMouseMove(ref Message)' + + + + + 'm' + + + + + + + + + + + + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.LParam.get()' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + + + 'value' + 'HeaderControl.HotFontStyle.set(FontStyle)' + + + + + + + + + + + Flags + 'HeaderControl.TextFormatFlags' + + + + + + + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'HeaderControl.WndProc(ref Message)' + 'Message.Msg.get()' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'text' + 'HighlightTextRenderer.HighlightTextRenderer(string)' + + + + + + + + + + + 'value' + 'HighlightTextRenderer.StringComparison.set(StringComparison)' + + + + + + + + + + + + + 'value' + 'HighlightTextRenderer.TextToHighlight.set(string)' + + + + + + + + + + + + + + + + + 'HyperlinkEventArgs.Column.set(OLVColumn)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ColumnIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Item.set(OLVListItem)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ListView.set(ObjectListView)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Model.set(object)' + + + + + + + + + + + + + 'HyperlinkEventArgs.RowIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.SubItem.set(OLVListSubItem)' + + + + + + + + + + + 'HyperlinkEventArgs.Url' + + + + + + + + + 'HyperlinkEventArgs.Url.set(string)' + + + + + + + + + + + + + + + 'ImageRenderer.GetImageFromAspect()' + + + + + + + + + + + + + + + + + + + + 'IntUpDown.Value.get()' + + + + + + + + + + + + + + 'IntUpDown.Value.set(int)' + + + + + + + + + + + + + + + + + + + + 'IVirtualListDataSource.GetObjectCount()' + + + + + + + + + + + + + + + + Multi + 'MultiImageRenderer' + + + + + + + + + + + + + + 'MultiImageRenderer.ImageSelector' + 'BaseRenderer.GetImageSelector()' + + + + + + + + + + + + + 'Munger.GetValue(object)' + 'object' + + + + + + + + + + + + + + 'Munger.PutValue(object, object)' + 'object' + + + 'Munger.PutValue(object, object)' + 'object' + + + + + + + + + + + + + + + + + + 'NativeMethods.ChangeSize(IWin32Window, int, int)' + + + + + + + + + 'NativeMethods.ChangeZOrder(IWin32Window, IWin32Window)' + + + + + + + + + 'NativeMethods.DeleteObject(IntPtr)' + + + + + + + + + 'NativeMethods.DrawImageList(Graphics, ImageList, int, int, int, bool)' + + + + + + + + + 'NativeMethods.GetClientRect(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + 'Point' + + + + + + + + + 'NativeMethods.GetGroupInfo(ObjectListView, int, ref NativeMethods.LVGROUP2)' + + + + + + + + + 'NativeMethods.GetScrollInfo(IntPtr, int, NativeMethods.SCROLLINFO)' + + + + + + + + + 'NativeMethods.GetUpdateRect(Control)' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'eraseBackground' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'NativeMethods.GetWindowLong32(IntPtr, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'NativeMethods.GetWindowLongPtr64(IntPtr, int)' + 'user32.dll' + GetWindowLongPtr + + + + + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + + + + + 'erase' + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP2)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUPMETRICS)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, IntPtr)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, IntPtr, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageHDItem(IntPtr, int, int, ref NativeMethods.HDITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + + + + + 'lParam' + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + + + + + 'wParam' + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageLVItem(IntPtr, int, int, ref NativeMethods.LVITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageRECT(IntPtr, int, int, ref NativeMethods.RECT)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageString(IntPtr, int, int, string)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageTOOLINFO(IntPtr, int, int, NativeMethods.TOOLINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SetBackgroundImage(ListView, Image)' + + + + + + + + + 'NativeMethods.SetBkColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetSelectedColumn(ListView, ColumnHeader)' + + + + + + + + + 'NativeMethods.SetTextColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetTooltipControl(ListView, ToolTipControl)' + + + + + + + + + 'NativeMethods.SetWindowLongPtr32(IntPtr, int, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'dwNewLong' + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 'user32.dll' + SetWindowLongPtr + + + + + + + + + 'NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, uint)' + + + + + + + + + 'NativeMethods.SetWindowTheme(IntPtr, string, string)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + 'subApp' + + + + + 'subIdList' + + + + + + + + + 'NativeMethods.ShowWindow(IntPtr, int)' + + + + + + + + + 'NativeMethods.ValidatedRectInternal(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.ValidateRect(Control, Rectangle)' + + + + + + + + + + + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.ColumnIndexUnderCursor.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.IsCursorOverLockedDivider.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'OLVListItem.GetSubItemBounds(int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellTextBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.OlvHitTest(int, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'TintedColumnDecoration.Draw(ObjectListView, Graphics, Rectangle)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.EnsureGroupVisible(ListViewGroup)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleBeginScroll(ref Message)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleKeyDown(ref Message)' + + + + + + + + + + + + + + + + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.AddTool(IWin32Window)' + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.RemoveToolTip(IWin32Window)' + + + + + + + + + + + + + + + + + + 'ObjectListView.AllColumns' + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.AllColumns' + + + + + + + + + + + + + + 'rowIndex' + 'ObjectListView.ApplyHyperlinkStyle(int, OLVListItem)' + + + + + + + + + 'ObjectListView.BooleanCheckStateGetter' + + + + + + + + + 'ObjectListView.BooleanCheckStatePutter' + + + + + + + + + 'item' + 'ObjectListView.CalculateCellBounds(OLVListItem, int)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'ObjectListView.CellEditor' + 'ObjectListView.GetCellEditor(OLVListItem, int)' + + + + + + + + + 'ObjectListView.CellEditor_Validating(object, CancelEventArgs)' + + + + + + + + + 'ObjectListView.CellToolTip' + 'ObjectListView.GetCellToolTip(int, int)' + + + + + + + + + 'ObjectListView.CheckedObject' + 'ObjectListView.GetCheckedObject()' + + + + + + + + + 'ObjectListView.CheckedObjects' + 'ObjectListView.GetCheckedObjects()' + + + + + 'ObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.ColumnsInDisplayOrder' + + + + + + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn)' + tb + 'tb' + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn, int)' + tb + 'tb' + + + + + + + + + 'List<OLVListItem>' + 'ObjectListView.DrawAllDecorations(Graphics, List<OLVListItem>)' + + + + + + + + + 'ObjectListView.EditorRegistry' + + + + + + + + + 'ObjectListView.EnsureGroupVisible(ListViewGroup)' + lvg + 'lvg' + + + + + + + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aListFilter' + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aModelFilter' + + + + + + + + + 'control' + 'CheckBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'ComboBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'TextBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.GetFilteredColumns(View)' + + + + + + + + + + + + + + 'selectedColumn' + + + + + + + + + + + + + + 'ObjectListView.GetItemCount()' + + + + + + + + + + + + + + 'ObjectListView.GetLastItemInDisplayOrder()' + + + + + + + + + 'ObjectListView.GetSelectedObject()' + + + + + + + + + + + + + + 'ObjectListView.GetSelectedObjects()' + + + + + + + + + + + + + + 'ObjectListView.HandleApplicationIdle(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleApplicationIdle_ResizeColumns(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleCellToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleChar(ref Message)' + 'Control.ProcessKeyEventArgs(ref Message)' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + 'ObjectListView.HandleChar(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleColumnClick(object, ColumnClickEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanged(object, ColumnWidthChangedEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanging(object, ColumnWidthChangingEventArgs)' + + + + + + + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleHeaderToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleLayout(object, LayoutEventArgs)' + + + + + + + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.PtrToStructure(IntPtr, Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'NativeWindow.Handle.get()' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HeaderToolTip' + 'ObjectListView.GetHeaderToolTip(int)' + + + + + + + + + 'url' + 'ObjectListView.IsUrlVisited(string)' + + + + + + + + + 'url' + 'ObjectListView.MarkUrlVisited(string)' + + + + + + + + + Unsort + 'ObjectListView.MenuLabelUnsort' + + + + + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)] + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + ->'ObjectListView.ProcessDialogKey(Keys)' ->'ObjectListView.ProcessDialogKey(Keys)' + + + + + + + + + + + + + + 'ObjectListView.SelectedObject' + 'ObjectListView.GetSelectedObject()' + + + + + + + + + 'ObjectListView.SelectedObjects' + 'ObjectListView.GetSelectedObjects()' + + + + + 'ObjectListView.SelectedObjects' + + + + + + + + + + + + + + 'control' + 'ComboBox' + 'ObjectListView.SetControlValue(Control, object, string)' + castclass + + + + + + + + + Checkedness + 'ObjectListView.SetObjectCheckedness(object, CheckState)' + + + + + + + + + + + + + + 'item' + 'ObjectListView.SetSubItemImages(int, OLVListItem, bool)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'columnToSort' + 'ObjectListView.ShowSortIndicator(OLVColumn, SortOrder)' + 'OLVColumn' + 'ColumnHeader' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_DOWN_KEY' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_UP_KEY' + + + + + + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.BeginInit()' + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.EndInit()' + + + + + + + + + Renderering + 'ObjectListView.TextRendereringHint' + + + + + + + + + Unsort + 'ObjectListView.Unsort()' + + + + + + + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'ObjectListView.WndProc(ref Message)' + 'Control.DefWndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'Message.Msg.get()' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'ObjectListView.ObjectListViewState.VersionNumber' + + + + + + + + + + + + + + + + 'OLVColumnAttribute' + + + + + 'OLVColumnAttribute.Title' + 'title' + + + + + 'OLVColumnAttribute' + + + + + + + + + Cutoffs + 'OLVColumnAttribute.GroupCutoffs' + + + + + 'OLVColumnAttribute.GroupCutoffs' + + + + + + + + + 'OLVColumnAttribute.GroupDescriptions' + + + + + + + + + + + + + 'OLVDataObject.ConvertToHtmlFragment(string)' + 'string.IndexOf(string)' + 'string.IndexOf(string, StringComparison)' + + + + + + + + + + + + + 'OLVGroup.GetState()' + + + + + + + + + 'OLVGroup.State' + 'OLVGroup.GetState()' + + + + + + + + + Subseted + 'OLVGroup.Subseted' + + + + + + + + + + + 'OLVListItem' + + + + + + + + + 'OLVListItem.Bounds' + 'ListViewItem.GetBounds(ItemBoundsPortion)' + + + + + + + + + + + 'value' + 'string' + 'OLVListItem.ImageSelector.set(object)' + castclass + + + + + + + + + + + + + + + 'OLVListSubItem.Url' + + + + + + + + + + + 'SimpleDropSink' + 'Timer' + + + + + + + + + 'Timer.Interval.set(int)' + 'SimpleDropSink.SimpleDropSink()' + + + + + + + + + + + 'TextAdornment' + 'StringFormat' + + + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[])' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, TextMatchFilter.MatchKind)' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.Columns' + + + + + + + + + 'TextMatchFilter.IsIncluded(OLVColumn)' + + + + + + + + + + + 'TextMatchFilter.MatchKind' + + + + + + + + + + + + + + 'TintedColumnDecoration' + 'SolidBrush' + + + + + + + + + + + Disp + 'ToolTipControl.HandleGetDispInfo(ref Message)' + + + + + + + + + + + + + + 'window' + 'ToolTipControl.PopToolTip(IWin32Window)' + + + + + + + + + + + 'ToolTipControl.StandardIcons' + + + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.ChildBranches' + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.FilteredChildBranches' + + + + + + + + + Flag + 'TreeListView.Branch.ManageLastChildFlag(MethodInvoker)' + + + + + + + + + + + Flags + 'TreeListView.Branch.BranchFlags' + + + + + + + + + + + 'TreeListView.Tree.GetBranchComparer()' + + + + + + + + + + + + + + + + + + 'TreeListView.TreeRenderer.PIXELS_PER_LEVEL' + + + + + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStateGetter' + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStatePutter' + + + + + + + + + 'TypedObjectListView<T>.CellToolTipGetter' + + + + + + + + + 'TypedObjectListView<T>.CheckedObjects' + + + + + + + + + + + + + + 'TypedObjectListView<T>.SelectedObjects' + + + + + + + + + + + + + + + + + + + + 'UintUpDown.Value.get()' + + + + + + + + + + + + + + 'UintUpDown.Value.set(uint)' + + + + + + + + + + + + + + + + + + + + 'VirtualObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'VirtualObjectListView.HandleCacheVirtualItems(object, CacheVirtualItemsEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleRetrieveVirtualItem(object, RetrieveVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleSearchForVirtualItem(object, SearchForVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.SetVirtualListSize(int)' + 'Exception' + + + + + + + + + + + + + + + + + + + + + These should be methods rather than properties + The out parameter is necessary since this method returns two pieces of information: the item under the point and the subitem item too + This is used to ensure we understand the newly load state. + All these properties should be assignable. + Our project is build with unsafe code enabled, so it automatically has the SecurityProperty set + These initializations are not unnecessary + We have to pass the windows message by reference + Instances of this class do not need to be disposable + These are utility methods that could well be used at runtime + Old style constants. Can't change now + These are OK like this. We need List<>, not IList<> since only List has a ToArray() method + Legacy cases that have to be kept like this + These are acceptable as methods rather than properties + windows messages should be passed by reference + This is not a security risk + There are several problems that can occur here and we want to ignore them all + These spellings are acceptable + These will only be used by OL types + + + Not appropriate here + Can't change now + we want to catch everthing + MS! + not flags + MS! + MS + + + + + Sign {0} with a strong name key. + + + Consider a design that does not require that {0} be an out parameter. + + + {0} appears to have no upstream public or protected callers. + + + Seal {0}, if possible. + + + It appears that field {0} is never used or is only ever assigned to. Use this field or remove it. + + + Change {0} to be read-only by removing the property setter. + + + Consider changing the type of parameter {0} in {1} from {2} to its base type {3}. This method appears to only require base class members in its implementation. Suppress this violation if there is a compelling reason to require the more derived type in the method signature. + + + Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. + + + {0}, a parameter, is cast to type {1} multiple times in method {2}. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant {3} instruction. + + + Modify {0} to catch a more specific exception than {1} or rethrow the exception. + + + Change {0} in {1} to use Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V> + + + {0} calls {1} but does not use the HRESULT or error code that the method returns. This could lead to unexpected behavior in error conditions or low-resource situations. Use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method. + {0} creates a new instance of {1} which is never used. Pass the instance as an argument to another method, assign the instance to a variable, or remove the object creation if it is unnecessary. + + + + {0} initializes field {1} of type {2} to {3}. Remove this initialization because it will be done automatically by the runtime. + + + {0} is marked with FlagsAttribute but a discrete member cannot be found for every settable bit that is used across the range of enum values. Remove FlagsAttribute from the type or define new members for the following (currently missing) values: {1} + + + + Modify the call to {0} in method {1} to set the timer interval to a value that's greater than or equal to one second. + + + In enum {0}, change the name of {1} to 'None'. + + + If enumeration name {0} is singular, change it to a plural form. + + + Correct the spelling of '{0}' in member name {1} or remove it entirely if it represents any sort of Hungarian notation. + In method {0}, correct the spelling of '{1}' in parameter name {2} or remove it entirely if it represents any sort of Hungarian notation. + Correct the spelling of '{0}' in type name {1}. + + + + Make {0} sealed (a breaking change if this class has previously shipped), implement the method non-explicitly, or implement a new method that exposes the functionality of {1} and is visible to derived classes. + + + Specify AttributeUsage on {0}. + + + Add the MarshalAsAttribute to parameter {0} of P/Invoke {1}. If the corresponding unmanaged parameter is a 4-byte Win32 'BOOL', use [MarshalAs(UnmanagedType.Bool)]. For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + Add the MarshalAsAttribute to the return type of P/Invoke {0}. If the corresponding unmanaged return type is a 4-byte Win32 'BOOL', use MarshalAs(UnmanagedType.Bool). For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + + + The constituent members of {0} appear to represent flags that can be combined rather than discrete values. If this is correct, mark the enumeration with FlagsAttribute. + + + Add [Serializable] to {0} as this type implements ISerializable. + + + Consider making {0} non-public or a constant. + + + If the name {0} is plural, change it to its singular form. + + + Add the following security attribute to {0} in order to match a LinkDemand on base method {1}: {2}. + + + As it is declared in your code, parameter {0} of P/Invoke {1} will be {2} bytes wide on {3} platforms. This is not correct, as the actual native declaration of this API indicates it should be {4} bytes wide on {3} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {5}. + As it is declared in your code, the return type of P/Invoke {0} will be {1} bytes wide on {2} platforms. This is not correct, as the actual native declaration of this API indicates it should be {3} bytes wide on {2} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {4}. + + + Correct the declaration of {0} so that it correctly points to an existing entry point in {1}. The unmanaged entry point name currently linked to is {2}. + + + Because property {0} is write-only, either add a property getter with an accessibility that is greater than or equal to its setter or convert this property into a method. + + + Change {0} to return a collection or make it a method. + + + The property name {0} is confusing given the existence of inherited method {1}. Rename or remove this property. + The property name {0} is confusing given the existence of method {1}. Rename or remove one of these members. + + + Parameter {0} of {1} is never used. Remove the parameter or use it in the method body. + + + Consider making {0} not externally visible. + + + To reduce security risk, marshal parameter {0} as Unicode, by setting DllImport.CharSet to CharSet.Unicode, or by explicitly marshaling the parameter as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, set BestFitMapping=false; for added security, also set ThrowOnUnmappableChar=true. + + + {0} makes a call to {1} that does not explicitly provide a StringComparison. This should be replaced with a call to {2}. + + + Implement IDisposable on {0} because it creates members of the following IDisposable types: {1}. If {0} has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers. + + + Change the type of parameter {0} of method {1} from string to System.Uri, or provide an overload of {1}, that allows {0} to be passed as a System.Uri object. + + + Change the type of property {0} from string to System.Uri. + + + Remove {0} and replace its usage with EventHandler<T> + + + {0} passes {1} as an argument to {2}. Replace this usage with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase if appropriate. + + + Replace the term '{0}' in member name {1} with an appropriate alternate or remove it entirely. + Replace the term '{0}' in type name {1} with an appropriate alternate or remove it entirely. + + + Change {0} to a property if appropriate. + + + + diff --git a/ObjectListView/ObjectListView.cs b/ObjectListView/ObjectListView.cs new file mode 100644 index 0000000..7b4bbe5 --- /dev/null +++ b/ObjectListView/ObjectListView.cs @@ -0,0 +1,10924 @@ +/* + * ObjectListView - A listview to show various aspects of a collection of objects + * + * Author: Phillip Piper + * Date: 9/10/2006 11:15 AM + * + * Change log + * 2018-10-06 JPP - InsertObjects() when in a non-Detail View now correctly positions the items (SF bug #154) + * 2018-09-01 JPP - Hardened code against the rare case of the control having no columns (SF bug #174) + * The underlying ListView does not like having rows when there are no columns and throws exceptions.j + * 2018-05-05 JPP - Added OLVColumn.EditorCreator to allow fine control over what control is used to edit + * a particular cell. + * - Added IOlvEditor to allow custom editor to easily integrate with our editing scheme + * - ComboBoxes resize drop downs to show the widest entry via ControlUtilities.AutoResizeDropDown() + * 2018-05-03 JPP - Extend OnColumnRightClick so the event handler can tweak the menu to be shown + * 2018-04-27 JPP - Sorting now works when grouping is locked on a column AND SortGroupItemsByPrimaryColumn is true + * - Correctly report right clicks on group headers via CellRightClick events. + * v2.9.2 + * 2016-06-02 JPP - Cell editors now respond to mouse wheel events. Set AllowCellEditorsToProcessMouseWheel + * to false revert to previous behaviour. + * - Fixed issue in PauseAnimations() that prevented it from working until + * after the control had been rendered at least once. + * - CellEditUseWholeCell now has correct default value (true). + * - Dropping on a subitem when CellEditActivation is set to SingleClick no longer + * initiates a cell edit + * v2.9.1 + * 2015-12-30 JPP - Added CellRendererGetter to allow each cell to have a different renderer. + * - Obsolete properties are no longer code-gen'ed. + * + * v2.9.0 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * - Renamed properties related to selection colours: + * - HighlightBackgroundColor -> SelectedBackColor + * - HighlightForegroundColor -> SelectedForeColor + * - UnfocusedHighlightBackgroundColor -> UnfocusedSelectedBackColor + * - UnfocusedHighlightForegroundColor -> UnfocusedSelectedForeColor + * - UseCustomSelectionColors is no longer used + * 2015-08-03 JPP - Added ObjectListView.CellEditFinished event + * - Added EditorRegistry.Unregister() + * 2015-07-08 JPP - All ObjectListViews are now OwnerDrawn by default. This allows all the great features + * of ObjectListView to work correctly at the slight cost of more processing at render time. + * It also avoids the annoying "hot item background ignored in column 0" behaviour that native + * ListView has. Programmers can still turn it back off if they wish. + * 2015-06-27 JPP - Yet another attempt to disable ListView's "shift click toggles checkboxes" behaviour. + * The last strategy (fake right click) worked, but had nasty side effects. This one works + * by intercepting a HITTEST message so that it fails. It no longer creates fake right mouse events. + * - Trigger SelectionChanged when filter is changed + * 2015-06-23 JPP - [BIG] Added support for Buttons + * 2015-06-22 JPP - Added OLVColumn.SearchValueGetter to allow the text used when text filtering to be customised + * - The default DefaultRenderer is now a HighlightTextRenderer, since that seems more generally useful + * 2015-06-17 JPP - Added FocusedObject property + * - Hot item is now always applied to the row even if FullRowSelect is false + * 2015-06-11 JPP - Added DefaultHotItemStyle property + * 2015-06-07 JPP - Added HeaderMinimumHeight property + * - Added ObjectListView.CellEditUsesWholeCell and OLVColumn.CellEditUsesWholeCell properties. + * 2015-05-15 JPP - Allow ImageGetter to return an Image (which I can't believe didn't work from the beginning!) + * 2015-04-27 JPP - Fix bug where setting View to LargeIcon in the designer was not persisted + * 2015-04-07 JPP - Ensure changes to row.Font in FormatRow are not wiped out by FormatCell (SF #141) + * + * v2.8.1 + * 2014-10-15 JPP - Added CellEditActivateMode.SingleClickAlways mode + * - Fire Filter event even if ModelFilter and ListFilter are null (SF #126) + * - Fixed issue where single-click editing didn't work (SF #128) + * v2.8.0 + * 2014-10-11 JPP - Fixed some XP-only flicker issues + * 2014-09-26 JPP - Fixed intricate bug involving checkboxes on non-owner-drawn virtual lists. + * - Fixed long standing (but previously unreported) error on non-details virtual lists where + * users could not click on checkboxes. + * 2014-09-07 JPP - (Major) Added ability to have checkboxes in headers + * - CellOver events are raised when the mouse moves over the header. Set TriggerCellOverEventsWhenOverHeader + * to false to disable this behaviour. + * - Freeze/Unfreeze now use BeginUpdate/EndUpdate to disable Window level drawing + * - Changed default value of ObjectListView.HeaderUsesThemes from true to false. Too many people were + * being confused, trying to make something interesting appear in the header and nothing showing up + * 2014-08-04 JPP - Final attempt to fix the multiple hyperlink events being raised. This involves turning + * a NM_CLICK notification into a NM_RCLICK. + * 2014-05-21 JPP - (Major) Added ability to disable rows. DisabledObjects, DisableObjects(), DisabledItemStyle. + * 2014-04-25 JPP - Fixed issue where virtual lists containing a single row didn't update hyperlinks on MouseOver + * - Added sanity check before BuildGroups() + * 2014-03-22 JPP - Fixed some subtle bugs resulting from misuse of TryGetValue() + * 2014-03-09 JPP - Added CollapsedGroups property + * - Several minor Resharper complaints quiesced. + * v2.7 + * 2014-02-14 JPP - Fixed issue with ShowHeaderInAllViews (another one!) where setting it to false caused the list to lose + * its other extended styles, leading to nasty flickering and worse. + * 2014-02-06 JPP - Fix issue on virtual lists where the filter was not correctly reapplied after columns were added or removed. + * - Made disposing of cell editors optional (defaults to true). This allows controls to be cached and reused. + * - Bracketed column resizing with BeginUpdate/EndUpdate to smooth redraws (thanks to Davide) + * 2014-02-01 JPP - Added static property ObjectListView.GroupTitleDefault to allow the default group title to be localised. + * 2013-09-24 JPP - Fixed issue in RefreshObjects() when model objects overrode the Equals()/GetHashCode() methods. + * - Made sure get state checker were used when they should have been + * 2013-04-21 JPP - Clicking on a non-groupable column header when showing groups will now sort + * the group contents by that column. + * v2.6 + * 2012-08-16 JPP - Added ObjectListView.EditModel() -- a convenience method to start an edit operation on a model + * 2012-08-10 JPP - Don't trigger selection changed events during sorting/grouping or add/removing columns + * 2012-08-06 JPP - Don't start a cell edit operation when the user clicks on the background of a checkbox cell. + * - Honor values from the BeforeSorting event when calling a CustomSorter + * 2012-08-02 JPP - Added CellVerticalAlignment and CellPadding properties. + * 2012-07-04 JPP - Fixed issue with cell editing where the cell editing didn't finish until the first idle event. + * This meant that if you clicked and held on the scroll thumb to finish a cell edit, the editor + * wouldn't be removed until the mouse was released. + * 2012-07-03 JPP - Fixed issue with SingleClick cell edit mode where the cell editing would not begin until the + * mouse moved after the click. + * 2012-06-25 JPP - Fixed bug where removing a column from a LargeIcon or SmallIcon view would crash the control. + * 2012-06-15 JPP - Added Reset() method, which definitively removes all rows *and* columns from an ObjectListView. + * 2012-06-11 JPP - Added FilteredObjects property which returns the collection of objects that survives any installed filters. + * 2012-06-04 JPP - [Big] Added UseNotifyPropertyChanged to allow OLV to listen for INotifyPropertyChanged events on models. + * 2012-05-30 JPP - Added static property ObjectListView.IgnoreMissingAspects. If this is set to true, all + * ObjectListViews will silently ignore missing aspect errors. Read the remarks to see why this would be useful. + * 2012-05-23 JPP - Setting UseFilterIndicator to true now sets HeaderUsesTheme to false. + * Also, changed default value of UseFilterIndicator to false. Previously, HeaderUsesTheme and UseFilterIndicator + * defaulted to true, which was pointless since when the HeaderUsesTheme is true, UseFilterIndicator does nothing. + * v2.5.1 + * 2012-05-06 JPP - Fix bug where collapsing the first group would cause decorations to stop being drawn (SR #3502608) + * 2012-04-23 JPP - Trigger GroupExpandingCollapsing event to allow the expand/collapse to be cancelled + * - Fixed SetGroupSpacing() so it corrects updates the space between all groups. + * - ResizeLastGroup() now does nothing since it was broken and I can't remember what it was + * even supposed to do :) + * 2012-04-18 JPP - Upgraded hit testing to include hits on groups. + * - HotItemChanged is now correctly recalculated on each mouse move. Includes "hot" group information. + * 2012-04-14 JPP - Added GroupStateChanged event. Useful for knowing when a group is collapsed/expanded. + * - Added AdditionalFilter property. This filter is combined with the Excel-like filtering that + * the end user might enact at runtime. + * 2012-04-10 JPP - Added PersistentCheckBoxes property to allow primary checkboxes to remember their values + * across list rebuilds. + * 2012-04-05 JPP - Reverted some code to .NET 2.0 standard. + * - Tweaked some code + * 2012-02-05 JPP - Fixed bug when selecting a separator on a drop down menu + * 2011-06-24 JPP - Added CanUseApplicationIdle property to cover cases where Application.Idle events + * are not triggered. For example, when used within VS (and probably Office) extensions + * Application.Idle is never triggered. Set CanUseApplicationIdle to false to handle + * these cases. + * - Handle cases where a second tool tip is installed onto the ObjectListView. + * - Correctly recolour rows after an Insert or Move + * - Removed m.LParam cast which could cause overflow issues on Win7/64 bit. + * v2.5.0 + * 2011-05-31 JPP - SelectObject() and SelectObjects() no longer deselect all other rows. + Set the SelectedObject or SelectedObjects property to do that. + * - Added CheckedObjectsEnumerable + * - Made setting CheckedObjects more efficient on large collections + * - Deprecated GetSelectedObject() and GetSelectedObjects() + * 2011-04-25 JPP - Added SubItemChecking event + * - Fixed bug in handling of NewValue on CellEditFinishing event + * 2011-04-12 JPP - Added UseFilterIndicator + * - Added some more localizable messages + * 2011-04-10 JPP - FormatCellEventArgs now has a CellValue property, which is the model value displayed + * by the cell. For example, for the Birthday column, the CellValue might be + * DateTime(1980, 12, 31), whereas the cell's text might be 'Dec 31, 1980'. + * 2011-04-04 JPP - Tweaked UseTranslucentSelection and UseTranslucentHotItem to look (a little) more + * like Vista/Win7. + * - Alternate colours are now only applied in Details view (as they always should have been) + * - Alternate colours are now correctly recalculated after removing objects + * 2011-03-29 JPP - Added SelectColumnsOnRightClickBehaviour to allow the selecting of columns mechanism + * to be changed. Can now be InlineMenu (the default), SubMenu, or ModelDialog. + * - ColumnSelectionForm was moved from the demo into the ObjectListView project itself. + * - Ctrl-C copying is now able to use the DragSource to create the data transfer object. + * 2011-03-19 JPP - All model object comparisons now use Equals rather than == (thanks to vulkanino) + * - [Small Break] GetNextItem() and GetPreviousItem() now accept and return OLVListView + * rather than ListViewItems. + * 2011-03-07 JPP - [Big] Added Excel-style filtering. Right click on a header to show a Filtering menu. + * - Added CellEditKeyEngine to allow key handling when cell editing to be completely customised. + * Add CellEditTabChangesRows and CellEditEnterChangesRows to show some of these abilities. + * 2011-03-06 JPP - Added OLVColumn.AutoCompleteEditorMode in preference to AutoCompleteEditor + * (which is now just a wrapper). Thanks to Clive Haskins + * - Added lots of docs to new classes + * 2011-02-25 JPP - Preserve word wrap settings on TreeListView + * - Resize last group to keep it on screen (thanks to ?) + * 2010-11-16 JPP - Fixed (once and for all) DisplayIndex problem with Generator + * - Changed the serializer used in SaveState()/RestoreState() so that it resolves on + * class name alone. + * - Fixed bug in GroupWithItemCountSingularFormatOrDefault + * - Fixed strange flickering in grouped, owner drawn OLV's using RefreshObject() + * v2.4.1 + * 2010-08-25 JPP - Fixed bug where setting OLVColumn.CheckBoxes to false gave it a renderer + * specialized for checkboxes. Oddly, this made Generator created owner drawn + * lists appear to be completely empty. + * - In IDE, all ObjectListView properties are now in a single "ObjectListView" category, + * rather than splitting them between "Appearance" and "Behavior" categories. + * - Added GroupingParameters.GroupComparer to allow groups to be sorted in a customizable fashion. + * - Sorting of items within a group can be disabled by setting + * GroupingParameters.PrimarySortOrder to None. + * 2010-08-24 JPP - Added OLVColumn.IsHeaderVertical to make a column draw its header vertical. + * - Added OLVColumn.HeaderTextAlign to control the alignment of a column's header text. + * - Added HeaderMaximumHeight to limit how tall the header section can become + * 2010-08-18 JPP - Fixed long standing bug where having 0 columns caused a InvalidCast exception. + * - Added IncludeAllColumnsInDataObject property + * - Improved BuildList(bool) so that it preserves scroll position even when + * the listview is grouped. + * 2010-08-08 JPP - Added OLVColumn.HeaderImageKey to allow column headers to have an image. + * - CellEdit validation and finish events now have NewValue property. + * 2010-08-03 JPP - Subitem checkboxes improvements: obey IsEditable, can be hot, can be disabled. + * - No more flickering of selection when tabbing between cells + * - Added EditingCellBorderDecoration to make it clearer which cell is being edited. + * 2010-08-01 JPP - Added ObjectListView.SmoothingMode to control the smoothing of all graphics + * operations + * - Columns now cache their group item format strings so that they still work as + * grouping columns after they have been removed from the listview. This cached + * value is only used when the column is not part of the listview. + * 2010-07-25 JPP - Correctly trigger a Click event when the mouse is clicked. + * 2010-07-16 JPP - Invalidate the control before and after cell editing to make sure it looks right + * 2010-06-23 JPP - Right mouse clicks on checkboxes no longer confuse them + * 2010-06-21 JPP - Avoid bug in underlying ListView control where virtual lists in SmallIcon view + * generate GETTOOLINFO msgs with invalid item indices. + * - Fixed bug where FastObjectListView would throw an exception when showing hyperlinks + * in any view except Details. + * 2010-06-15 JPP - Fixed bug in ChangeToFilteredColumns() that resulted in column display order + * being lost when a column was hidden. + * - Renamed IsVista property to IsVistaOrLater which more accurately describes its function. + * v2.4 + * 2010-04-14 JPP - Prevent object disposed errors when mouse event handlers cause the + * ObjectListView to be destroyed (e.g. closing a form during a + * double click event). + * - Avoid checkbox munging bug in standard ListView when shift clicking on non-primary + * columns when FullRowSelect is true. + * 2010-04-12 JPP - Fixed bug in group sorting (thanks Mike). + * 2010-04-07 JPP - Prevent hyperlink processing from triggering spurious MouseUp events. + * This showed itself by launching the same url multiple times. + * 2010-04-06 JPP - Space filling columns correctly resize upon initial display + * - ShowHeaderInAllViews is better but still not working reliably. + * See comments on property for more details. + * 2010-03-23 JPP - Added ObjectListView.HeaderFormatStyle and OLVColumn.HeaderFormatStyle. + * This makes HeaderFont and HeaderForeColor properties unnecessary -- + * they will be marked obsolete in the next version and removed after that. + * 2010-03-16 JPP - Changed object checking so that objects can be pre-checked before they + * are added to the list. Normal ObjectListViews managed "checkedness" in + * the ListViewItem, so this won't work for them, unless check state getters + * and putters have been installed. It will work not on virtual lists (thus fast lists and + * tree views) since they manage their own check state. + * 2010-03-06 JPP - Hide "Items" and "Groups" from the IDE properties grid since they shouldn't be set like that. + * They can still be accessed through "Custom Commands" and there's nothing we can do + * about that. + * 2010-03-05 JPP - Added filtering + * 2010-01-18 JPP - Overlays can be turned off. They also only work on 32-bit displays + * v2.3 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * 2009-10-28 JPP - Fix bug when right clicking in the empty area of the header + * 2009-10-20 JPP - Redraw the control after setting EmptyListMsg property + * v2.3 + * 2009-09-30 JPP - Added Dispose() method to properly release resources + * 2009-09-16 JPP - Added OwnerDrawnHeader, which you can set to true if you want to owner draw + * the header yourself. + * 2009-09-15 JPP - Added UseExplorerTheme, which allow complete visual compliance with Vista explorer. + * But see property documentation for its many limitations. + * - Added ShowHeaderInAllViews. To make this work, Columns are no longer + * changed when switching to/from Tile view. + * 2009-09-11 JPP - Added OLVColumn.AutoCompleteEditor to allow the autocomplete of cell editors + * to be disabled. + * 2009-09-01 JPP - Added ObjectListView.TextRenderingHint property which controls the + * text rendering hint of all drawn text. + * 2009-08-28 JPP - [BIG] Added group formatting to supercharge what is possible with groups + * - [BIG] Virtual groups now work + * - Extended MakeGroupies() to handle more aspects of group creation + * 2009-08-19 JPP - Added ability to show basic column commands when header is right clicked + * - Added SelectedRowDecoration, UseTranslucentSelection and UseTranslucentHotItem. + * - Added PrimarySortColumn and PrimarySortOrder + * 2009-08-15 JPP - Correct problems with standard hit test and subitems + * 2009-08-14 JPP - [BIG] Support Decorations + * - [BIG] Added header formatting capabilities: font, color, word wrap + * - Gave ObjectListView its own designer to hide unwanted properties + * - Separated design time stuff into separate file + * - Added FormatRow and FormatCell events + * 2009-08-09 JPP - Get around bug in HitTest when not FullRowSelect + * - Added OLVListItem.GetSubItemBounds() method which works correctly + * for all columns including column 0 + * 2009-08-07 JPP - Added Hot* properties that track where the mouse is + * - Added HotItemChanged event + * - Overrode TextAlign on columns so that column 0 can have something other + * than just left alignment. This is only honored when owner drawn. + * v2.2.1 + * 2009-08-03 JPP - Subitem edit rectangles always allowed for an image in the cell, even if there was none. + * Now they only allow for an image when there actually is one. + * - Added Bounds property to OLVListItem which handles items being part of collapsed groups. + * 2009-07-29 JPP - Added GetSubItem() methods to ObjectListView and OLVListItem + * 2009-07-26 JPP - Avoided bug in .NET framework involving column 0 of owner drawn listviews not being + * redrawn when the listview was scrolled horizontally (this was a LOT of work to track + * down and fix!) + * - The cell edit rectangle is now correctly calculated when the listview is scrolled + * horizontally. + * 2009-07-14 JPP - If the user clicks/double clicks on a tree list cell, an edit operation will no longer begin + * if the click was to the left of the expander. This is implemented in such a way that + * other renderers can have similar "dead" zones. + * 2009-07-11 JPP - CalculateCellBounds() messed with the FullRowSelect property, which confused the + * tooltip handling on the underlying control. It no longer does this. + * - The cell edit rectangle is now correctly calculated for owner-drawn, non-Details views. + * 2009-07-08 JPP - Added Cell events (CellClicked, CellOver, CellRightClicked) + * - Made BuildList(), AddObject() and RemoveObject() thread-safe + * 2009-07-04 JPP - Space bar now properly toggles checkedness of selected rows + * 2009-07-02 JPP - Fixed bug with tooltips when the underlying Windows control was destroyed. + * - CellToolTipShowing events are now triggered in all views. + * v2.2 + * 2009-06-02 JPP - BeforeSortingEventArgs now has a Handled property to let event handlers do + * the item sorting themselves. + * - AlwaysGroupByColumn works again, as does SortGroupItemsByPrimaryColumn and all their + * various permutations. + * - SecondarySortOrder and SecondarySortColumn are now "null" by default + * 2009-05-15 JPP - Fixed bug so that KeyPress events are again triggered + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-07 JPP - Don't use glass panel for overlays when in design mode. It's too confusing. + * 2009-05-05 JPP - Added Scroll event (thanks to Christophe Hosten for the complete patch to implement this) + * - Added Unfocused foreground and background colors (also thanks to Christophe Hosten) + * 2009-04-29 JPP - Added SelectedColumn property, which puts a slight tint on that column. Combine + * this with TintSortColumn property and the sort column is automatically tinted. + * - Use an overlay to implement "empty list" msg. Default empty list msg is now prettier. + * 2009-04-28 JPP - Fixed bug where DoubleClick events were not triggered when CheckBoxes was true + * 2009-04-23 JPP - Fixed various bugs under Vista. + * - Made groups collapsible - Vista only. Thanks to Crustyapplesniffer. + * - Forward events from DropSink to the control itself. This allows handlers to be defined + * within the IDE for drop events + * 2009-04-16 JPP - Made several properties localizable. + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-11 JPP - Implemented overlay architecture, based on CustomDraw scheme. + * This unified drag drop feedback, empty list msgs and overlay images. + * - Added OverlayImage and friends, which allows an image to be drawn + * transparently over the listview + * 2009-04-10 JPP - Fixed long-standing annoying flicker on owner drawn virtual lists! + * This means, amongst other things, that grid lines no longer get confused, + * and drag-select no longer flickers. + * 2009-04-07 JPP - Calculate edit rectangles more accurately + * 2009-04-06 JPP - Double-clicking no longer toggles the checkbox + * - Double-clicking on a checkbox no longer confuses the checkbox + * 2009-03-16 JPP - Optimized the build of autocomplete lists + * v2.1 + * 2009-02-24 JPP - Fix bug where double-clicking VERY quickly on two different cells + * could give two editors + * - Maintain focused item when rebuilding list (SF #2547060) + * 2009-02-22 JPP - Reworked checkboxes so that events are triggered for virtual lists + * 2009-02-15 JPP - Added ObjectListView.ConfigureAutoComplete utility method + * 2009-02-02 JPP - Fixed bug with AlwaysGroupByColumn where column header clicks would not resort groups. + * 2009-02-01 JPP - OLVColumn.CheckBoxes and TriStateCheckBoxes now work. + * 2009-01-28 JPP - Complete overhaul of renderers! + * - Use IRenderer + * - Added ObjectListView.ItemRenderer to draw whole items + * 2009-01-23 JPP - Simple Checkboxes now work properly + * - Added TriStateCheckBoxes property to control whether the user can + * set the row checkbox to have the Indeterminate value + * - CheckState property is now just a wrapper around the StateImageIndex property + * 2009-01-20 JPP - Changed to always draw columns when owner drawn, rather than falling back on DrawDefault. + * This simplified several owner drawn problems + * - Added DefaultRenderer property to help with the above + * - HotItem background color is applied to all cells even when FullRowSelect is false + * - Allow grouping by CheckedAspectName columns + * - Commented out experimental animations. Still needs work. + * 2009-01-17 JPP - Added HotItemStyle and UseHotItem to highlight the row under the cursor + * - Added UseCustomSelectionColors property + * - Owner draw mode now honors ForeColor and BackColor settings on the list + * 2009-01-16 JPP - Changed to use EditorRegistry rather than hard coding cell editors + * 2009-01-10 JPP - Changed to use Equals() method rather than == to compare model objects. + * v2.0.1 + * 2009-01-08 JPP - Fixed long-standing "multiple columns generated" problem. + * Thanks to pinkjones for his help with solving this one! + * - Added EnsureGroupVisible() + * 2009-01-07 JPP - Made all public and protected methods virtual + * - FinishCellEditing, PossibleFinishCellEditing and CancelCellEditing are now public + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-12-19 JPP - Fixed bug with space filling columns and layout events + * - Fixed RowHeight so that it only changes the row height, not the width of the images. + * v2.0 + * 2008-12-10 JPP - Handle Backspace key. Resets the search-by-typing state without delay + * - Made some changes to the column collection editor to try and avoid + * the multiple column generation problem. + * - Updated some documentation + * 2008-12-07 JPP - Search-by-typing now works when showing groups + * - Added BeforeSearching and AfterSearching events which are triggered when the user types + * into the list. + * - Added secondary sort information to Before/AfterSorting events + * - Reorganized group sorting code. Now triggers Sorting events. + * - Added GetItemIndexInDisplayOrder() + * - Tweaked in the interaction of the column editor with the IDE so that we (normally) + * don't rely on a hack to find the owning ObjectListView + * - Changed all 'DefaultValue(typeof(Color), "Empty")' to 'DefaultValue(typeof(Color), "")' + * since the first does not given Color.Empty as I thought, but the second does. + * 2008-11-28 JPP - Fixed long standing bug with horizontal scrollbar when shrinking the window. + * (thanks to Bartosz Borowik) + * 2008-11-25 JPP - Added support for dynamic tooltips + * - Split out comparers and header controls stuff into their own files + * 2008-11-21 JPP - Fixed bug where enabling grouping when there was not a sort column would not + * produce a grouped list. Grouping column now defaults to column 0. + * - Preserve selection on virtual lists when sorting + * 2008-11-20 JPP - Added ability to search by sort column to ObjectListView. Unified this with + * ability that was already in VirtualObjectListView + * 2008-11-19 JPP - Fixed bug in ChangeToFilteredColumns() where DisplayOrder was not always restored correctly. + * 2008-10-29 JPP - Event argument blocks moved to directly within the namespace, rather than being + * nested inside ObjectListView class. + * - Removed OLVColumn.CellEditor since it was never used. + * - Marked OLVColumn.AspectGetterAutoGenerated as obsolete (it has not been used for + * several versions now). + * 2008-10-28 JPP - SelectedObjects is now an IList, rather than an ArrayList. This allows + * it to accept generic list (e.g. List). + * 2008-10-09 JPP - Support indeterminate checkbox values. + * [BREAKING CHANGE] CheckStateGetter/CheckStatePutter now use CheckState types only. + * BooleanCheckStateGetter and BooleanCheckStatePutter added to ease transition. + * 2008-10-08 JPP - Added setFocus parameter to SelectObject(), which allows focus to be set + * at the same time as selecting. + * 2008-09-27 JPP - BIG CHANGE: Fissioned this file into separate files for each component + * 2008-09-24 JPP - Corrected bug with owner drawn lists where a column 0 with a renderer + * would draw at column 0 even if column 0 was dragged to another position. + * - Correctly handle space filling columns when columns are added/removed + * 2008-09-16 JPP - Consistently use try..finally for BeginUpdate()/EndUpdate() pairs + * 2008-08-24 JPP - If LastSortOrder is None when adding objects, don't force a resort. + * 2008-08-22 JPP - Catch and ignore some problems with setting TopIndex on FastObjectListViews. + * 2008-08-05 JPP - In the right-click column select menu, columns are now sorted by display order, rather than alphabetically + * v1.13 + * 2008-07-23 JPP - Consistently use copy-on-write semantics with Add/RemoveObject methods + * 2008-07-10 JPP - Enable validation on cell editors through a CellEditValidating event. + * (thanks to Artiom Chilaru for the initial suggestion and implementation). + * 2008-07-09 JPP - Added HeaderControl.Handle to allow OLV to be used within UserControls. + * (thanks to Michael Coffey for tracking this down). + * 2008-06-23 JPP - Split the more generally useful CopyObjectsToClipboard() method + * out of CopySelectionToClipboard() + * 2008-06-22 JPP - Added AlwaysGroupByColumn and AlwaysGroupBySortOrder, which + * force the list view to always be grouped by a particular column. + * 2008-05-31 JPP - Allow check boxes on FastObjectListViews + * - Added CheckedObject and CheckedObjects properties + * 2008-05-11 JPP - Allow selection foreground and background colors to be changed. + * Windows doesn't allow this, so we can only make it happen when owner + * drawing. Set the HighlightForegroundColor and HighlightBackgroundColor + * properties and then call EnableCustomSelectionColors(). + * v1.12 + * 2008-05-08 JPP - Fixed bug where the column select menu would not appear if the + * ObjectListView has a context menu installed. + * 2008-05-05 JPP - Non detail views can now be owner drawn. The renderer installed for + * primary column is given the chance to render the whole item. + * See BusinessCardRenderer in the demo for an example. + * - BREAKING CHANGE: RenderDelegate now returns a bool to indicate if default + * rendering should be done. Previously returned void. Only important if your + * code used RendererDelegate directly. Renderers derived from BaseRenderer + * are unchanged. + * 2008-05-03 JPP - Changed cell editing to use values directly when the values are Strings. + * Previously, values were always handed to the AspectToStringConverter. + * - When editing a cell, tabbing no longer tries to edit the next subitem + * when not in details view! + * 2008-05-02 JPP - MappedImageRenderer can now handle a Aspects that return a collection + * of values. Each value will be drawn as its own image. + * - Made AddObjects() and RemoveObjects() work for all flavours (or at least not crash) + * - Fixed bug with clearing virtual lists that has been scrolled vertically + * - Made TopItemIndex work with virtual lists. + * 2008-05-01 JPP - Added AddObjects() and RemoveObjects() to allow faster mods to the list + * - Reorganised public properties. Now alphabetical. + * - Made the class ObjectListViewState internal, as it always should have been. + * v1.11 + * 2008-04-29 JPP - Preserve scroll position when building the list or changing columns. + * - Added TopItemIndex property. Due to problems with the underlying control, this + * property is not always reliable. See property docs for info. + * 2008-04-27 JPP - Added SelectedIndex property. + * - Use a different, more general strategy to handle Invoke(). Removed all delegates + * that were only declared to support Invoke(). + * - Check all native structures for 64-bit correctness. + * 2008-04-25 JPP - Released on SourceForge. + * 2008-04-13 JPP - Added ColumnRightClick event. + * - Made the assembly CLS-compliant. To do this, our cell editors were made internal, and + * the constraint on FlagRenderer template parameter was removed (the type must still + * be an IConvertible, but if it isn't, the error will be caught at runtime, not compile time). + * 2008-04-12 JPP - Changed HandleHeaderRightClick() to have a columnIndex parameter, which tells + * exactly which column was right-clicked. + * 2008-03-31 JPP - Added SaveState() and RestoreState() + * - When cell editing, scrolling with a mouse wheel now ends the edit operation. + * v1.10 + * 2008-03-25 JPP - Added space filling columns. See OLVColumn.FreeSpaceProportion property for details. + * A space filling columns fills all (or a portion) of the width unoccupied by other columns. + * 2008-03-23 JPP - Finished tinkering with support for Mono. Compile with conditional compilation symbol 'MONO' + * to enable. On Windows, current problems with Mono: + * - grid lines on virtual lists crashes + * - when grouped, items sometimes are not drawn when any item is scrolled out of view + * - i can't seem to get owner drawing to work + * - when editing cell values, the editing controls always appear behind the listview, + * where they function fine -- the user just can't see them :-) + * 2008-03-16 JPP - Added some methods suggested by Chris Marlowe (thanks for the suggestions Chris) + * - ClearObjects() + * - GetCheckedObject(), GetCheckedObjects() + * - GetItemAt() variation that gets both the item and the column under a point + * 2008-02-28 JPP - Fixed bug with subitem colors when using OwnerDrawn lists and a RowFormatter. + * v1.9.1 + * 2008-01-29 JPP - Fixed bug that caused owner-drawn virtual lists to use 100% CPU + * - Added FlagRenderer to help draw bitwise-OR'ed flag values + * 2008-01-23 JPP - Fixed bug (introduced in v1.9) that made alternate row colour with groups not quite right + * - Ensure that DesignerSerializationVisibility.Hidden is set on all non-browsable properties + * - Make sure that sort indicators are shown after changing which columns are visible + * 2008-01-21 JPP - Added FastObjectListView + * v1.9 + * 2008-01-18 JPP - Added IncrementalUpdate() + * 2008-01-16 JPP - Right clicking on column header will allow the user to choose which columns are visible. + * Set SelectColumnsOnRightClick to false to prevent this behaviour. + * - Added ImagesRenderer to draw more than one images in a column + * - Changed the positioning of the empty list m to use all the client area. Thanks to Matze. + * 2007-12-13 JPP - Added CopySelectionToClipboard(). Ctrl-C invokes this method. Supports text + * and HTML formats. + * 2007-12-12 JPP - Added support for checkboxes via CheckStateGetter and CheckStatePutter properties. + * - Made ObjectListView and OLVColumn into partial classes so that others can extend them. + * 2007-12-09 JPP - Added ability to have hidden columns, i.e. columns that the ObjectListView knows + * about but that are not visible to the user. Controlled by OLVColumn.IsVisible. + * Added ColumnSelectionForm to the project to show how it could be used in an application. + * + * v1.8 + * 2007-11-26 JPP - Cell editing fully functional + * 2007-11-21 JPP - Added SelectionChanged event. This event is triggered once when the + * selection changes, no matter how many items are selected or deselected (in + * contrast to SelectedIndexChanged which is called once for every row that + * is selected or deselected). Thanks to lupokehl42 (Daniel) for his suggestions and + * improvements on this idea. + * 2007-11-19 JPP - First take at cell editing + * 2007-11-17 JPP - Changed so that items within a group are not sorted if lastSortOrder == None + * - Only call MakeSortIndicatorImages() if we haven't already made the sort indicators + * (Corrected misspelling in the name of the method too) + * 2007-11-06 JPP - Added ability to have secondary sort criteria when sorting + * (SecondarySortColumn and SecondarySortOrder properties) + * - Added SortGroupItemsByPrimaryColumn to allow group items to be sorted by the + * primary column. Previous default was to sort by the grouping column. + * v1.7 + * No big changes to this version but made to work with ListViewPrinter and released with it. + * + * 2007-11-05 JPP - Changed BaseRenderer to use DrawString() rather than TextRenderer, since TextRenderer + * does not work when printing. + * v1.6 + * 2007-11-03 JPP - Fixed some bugs in the rebuilding of DataListView. + * 2007-10-31 JPP - Changed to use builtin sort indicators on XP and later. This also avoids alignment + * problems on Vista. (thanks to gravybod for the suggestion and example implementation) + * 2007-10-21 JPP - Added MinimumWidth and MaximumWidth properties to OLVColumn. + * - Added ability for BuildList() to preserve selection. Calling BuildList() directly + * tries to preserve selection; calling SetObjects() does not. + * - Added SelectAll() and DeselectAll() methods. Useful for working with large lists. + * 2007-10-08 JPP - Added GetNextItem() and GetPreviousItem(), which walk sequentially through the + * listview items, even when the view is grouped. + * - Added SelectedItem property + * 2007-09-28 JPP - Optimized aspect-to-string conversion. BuildList() 15% faster. + * - Added empty implementation of RefreshObjects() to VirtualObjectListView since + * RefreshObjects() cannot work on virtual lists. + * 2007-09-13 JPP - Corrected bug with custom sorter in VirtualObjectListView (thanks for mpgjunky) + * 2007-09-07 JPP - Corrected image scaling bug in DrawAlignedImage() (thanks to krita970) + * 2007-08-29 JPP - Allow item count labels on groups to be set per column (thanks to cmarlow for idea) + * 2007-08-14 JPP - Major rework of DataListView based on Ian Griffiths's great work + * 2007-08-11 JPP - When empty, the control can now draw a "List Empty" m + * - Added GetColumn() and GetItem() methods + * v1.5 + * 2007-08-03 JPP - Support animated GIFs in ImageRenderer + * - Allow height of rows to be specified - EXPERIMENTAL! + * 2007-07-26 JPP - Optimised redrawing of owner-drawn lists by remembering the update rect + * - Allow sort indicators to be turned off + * 2007-06-30 JPP - Added RowFormatter delegate + * - Allow a different label when there is only one item in a group (thanks to cmarlow) + * v1.4 + * 2007-04-12 JPP - Allow owner drawn on steriods! + * - Column headers now display sort indicators + * - ImageGetter delegates can now return ints, strings or Images + * (Images are only visible if the list is owner drawn) + * - Added OLVColumn.MakeGroupies to help with group partitioning + * - All normal listview views are now supported + * - Allow dotted aspect names, e.g. Owner.Workgroup.Name (thanks to OlafD) + * - Added SelectedObject and SelectedObjects properties + * v1.3 + * 2007-03-01 JPP - Added DataListView + * - Added VirtualObjectListView + * - Added Freeze/Unfreeze capabilities + * - Allowed sort handler to be installed + * - Simplified sort comparisons: handles 95% of cases with only 6 lines of code! + * - Fixed bug with alternative line colors on unsorted lists (thanks to cmarlow) + * 2007-01-13 JPP - Fixed bug with lastSortOrder (thanks to Kwan Fu Sit) + * - Non-OLVColumns are no longer allowed + * 2007-01-04 JPP - Clear sorter before rebuilding list. 10x faster! (thanks to aaberg) + * - Include GetField in GetAspectByName() so field values can be Invoked too. + * - Fixed subtle bug in RefreshItem() that erased background colors. + * 2006-11-01 JPP - Added alternate line colouring + * 2006-10-20 JPP - Refactored all sorting comparisons and made it extendable. See ComparerManager. + * - Improved IDE integration + * - Made control DoubleBuffered + * - Added object selection methods + * 2006-10-13 JPP Implemented grouping and column sorting + * 2006-10-09 JPP Initial version + * + * TO DO: + * - Support undocumented group features: subseted groups, group footer items + * + * Copyright (C) 2006-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Serialization.Formatters.Binary; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Runtime.Serialization.Formatters; +using System.Threading; + +namespace BrightIdeasSoftware +{ + /// + /// An ObjectListView is a much easier to use, and much more powerful, version of the ListView. + /// + /// + /// + /// An ObjectListView automatically populates a ListView control with information taken + /// from a given collection of objects. It can do this because each column is configured + /// to know which bit of the model object (the "aspect") it should be displaying. Columns similarly + /// understand how to sort the list based on their aspect, and how to construct groups + /// using their aspect. + /// + /// + /// Aspects are extracted by giving the name of a method to be called or a + /// property to be fetched. These names can be simple names or they can be dotted + /// to chain property access e.g. "Owner.Address.Postcode". + /// Aspects can also be extracted by installing a delegate. + /// + /// + /// An ObjectListView can show a "this list is empty" message when there is nothing to show in the list, + /// so that the user knows the control is supposed to be empty. + /// + /// + /// Right clicking on a column header should present a menu which can contain: + /// commands (sort, group, ungroup); filtering; and column selection. Whether these + /// parts of the menu appear is controlled by ShowCommandMenuOnRightClick, + /// ShowFilterMenuOnRightClick and SelectColumnsOnRightClick respectively. + /// + /// + /// The groups created by an ObjectListView can be configured to include other formatting + /// information, including a group icon, subtitle and task button. Using some undocumented + /// interfaces, these groups can even on virtual lists. + /// + /// + /// ObjectListView supports dragging rows to other places, including other application. + /// Special support is provide for drops from other ObjectListViews in the same application. + /// In many cases, an ObjectListView becomes a full drag source by setting to + /// true. Similarly, to accept drops, it is usually enough to set to true, + /// and then handle the and events (or the and + /// events, if you only want to handle drops from other ObjectListViews in your application). + /// + /// + /// For these classes to build correctly, the project must have references to these assemblies: + /// + /// + /// System + /// System.Data + /// System.Design + /// System.Drawing + /// System.Windows.Forms (obviously) + /// + /// + [Designer(typeof(BrightIdeasSoftware.Design.ObjectListViewDesigner))] + public partial class ObjectListView : ListView, ISupportInitialize { + + #region Life and death + + /// + /// Create an ObjectListView + /// + public ObjectListView() { + this.ColumnClick += new ColumnClickEventHandler(this.HandleColumnClick); + this.Layout += new LayoutEventHandler(this.HandleLayout); + this.ColumnWidthChanging += new ColumnWidthChangingEventHandler(this.HandleColumnWidthChanging); + this.ColumnWidthChanged += new ColumnWidthChangedEventHandler(this.HandleColumnWidthChanged); + + base.View = View.Details; + + // Turn on owner draw so that we are responsible for our own fates (and isolated from bugs in the underlying ListView) + this.OwnerDraw = true; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.DoubleBuffered = true; // kill nasty flickers. hiss... me hates 'em + this.ShowSortIndicators = true; + + // Setup the overlays that will be controlled by the IDE settings + this.InitializeStandardOverlays(); + this.InitializeEmptyListMsgOverlay(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + } + + /// + /// Dispose of any resources this instance has been using + /// + /// + protected override void Dispose(bool disposing) { + base.Dispose(disposing); + + if (!disposing) + return; + + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Unbind(); + glassPanel.Dispose(); + } + this.glassPanels.Clear(); + + this.UnsubscribeNotifications(null); + } + + #endregion + + // TODO + //public CheckBoxSettings CheckBoxSettings { + // get { return checkBoxSettings; } + // private set { checkBoxSettings = value; } + //} + + #region Static properties + + /// + /// Gets whether or not the left mouse button is down at this very instant + /// + public static bool IsLeftMouseDown { + get { return (Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left; } + } + + /// + /// Gets whether the program running on Vista or later? + /// + public static bool IsVistaOrLater { + get { + if (!ObjectListView.sIsVistaOrLater.HasValue) + ObjectListView.sIsVistaOrLater = Environment.OSVersion.Version.Major >= 6; + return ObjectListView.sIsVistaOrLater.Value; + } + } + private static bool? sIsVistaOrLater; + + /// + /// Gets whether the program running on Win7 or later? + /// + public static bool IsWin7OrLater { + get { + if (!ObjectListView.sIsWin7OrLater.HasValue) { + // For some reason, Win7 is v6.1, not v7.0 + Version version = Environment.OSVersion.Version; + ObjectListView.sIsWin7OrLater = version.Major > 6 || (version.Major == 6 && version.Minor > 0); + } + return ObjectListView.sIsWin7OrLater.Value; + } + } + private static bool? sIsWin7OrLater; + + /// + /// Gets or sets how what smoothing mode will be applied to graphic operations. + /// + public static System.Drawing.Drawing2D.SmoothingMode SmoothingMode { + get { return ObjectListView.sSmoothingMode; } + set { ObjectListView.sSmoothingMode = value; } + } + private static System.Drawing.Drawing2D.SmoothingMode sSmoothingMode = + System.Drawing.Drawing2D.SmoothingMode.HighQuality; + + /// + /// Gets or sets how should text be rendered. + /// + public static System.Drawing.Text.TextRenderingHint TextRenderingHint { + get { return ObjectListView.sTextRendereringHint; } + set { ObjectListView.sTextRendereringHint = value; } + } + private static System.Drawing.Text.TextRenderingHint sTextRendereringHint = + System.Drawing.Text.TextRenderingHint.SystemDefault; + + /// + /// Gets or sets the string that will be used to title groups when the group key is null. + /// Exposed so it can be localized. + /// + public static string GroupTitleDefault { + get { return ObjectListView.sGroupTitleDefault; } + set { ObjectListView.sGroupTitleDefault = value ?? "{null}"; } + } + private static string sGroupTitleDefault = "{null}"; + + /// + /// Convert the given enumerable into an ArrayList as efficiently as possible + /// + /// The source collection + /// If true, this method will always create a new + /// collection. + /// An ArrayList with the same contents as the given collection. + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static ArrayList EnumerableToArray(IEnumerable collection, bool alwaysCreate) { + if (collection == null) + return new ArrayList(); + + if (!alwaysCreate) { + ArrayList array = collection as ArrayList; + if (array != null) + return array; + + IList iList = collection as IList; + if (iList != null) + return ArrayList.Adapter(iList); + } + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return new ArrayList(iCollection); + + ArrayList newObjects = new ArrayList(); + foreach (object x in collection) + newObjects.Add(x); + return newObjects; + } + + + /// + /// Return the count of items in the given enumerable + /// + /// + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + public static int EnumerableCount(IEnumerable collection) { + if (collection == null) + return 0; + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return iCollection.Count; + + int i = 0; +// ReSharper disable once UnusedVariable + foreach (object x in collection) + i++; + return i; + } + + /// + /// Return whether or not the given enumerable is empty. A string is regarded as + /// an empty collection. + /// + /// + /// True if the given collection is null or empty + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static bool IsEnumerableEmpty(IEnumerable collection) { + return collection == null || (collection is string) || !collection.GetEnumerator().MoveNext(); + } + + /// + /// Gets or sets whether all ObjectListViews will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if an ObjectListView is asked to display an aspect + /// (i.e. a field/property/method) + /// that does not exist from a model, it displays an error message in that cell, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error -- in those cases, set this to true and ObjectListView will + /// simply display an empty cell. + /// + /// Be warned: if you set this to true, it can be very difficult to track down + /// typing mistakes or name changes in AspectNames. + /// + public static bool IgnoreMissingAspects { + get { return Munger.IgnoreMissingAspects; } + set { Munger.IgnoreMissingAspects = value; } + } + + /// + /// Gets or sets whether the control will draw a rectangle in each cell showing the cell padding. + /// + /// + /// + /// This can help with debugging display problems from cell padding. + /// + /// As with all cell padding, this setting only takes effect when the control is owner drawn. + /// + public static bool ShowCellPaddingBounds { + get { return sShowCellPaddingBounds; } + set { sShowCellPaddingBounds = value; } + } + private static bool sShowCellPaddingBounds; + + /// + /// Gets the style that will be used by default to format disabled rows + /// + public static SimpleItemStyle DefaultDisabledItemStyle { + get { + if (sDefaultDisabledItemStyle == null) { + sDefaultDisabledItemStyle = new SimpleItemStyle(); + sDefaultDisabledItemStyle.ForeColor = Color.DarkGray; + } + return sDefaultDisabledItemStyle; + } + } + private static SimpleItemStyle sDefaultDisabledItemStyle; + + /// + /// Gets the style that will be used by default to format hot rows + /// + public static HotItemStyle DefaultHotItemStyle { + get { + if (sDefaultHotItemStyle == null) { + sDefaultHotItemStyle = new HotItemStyle(); + sDefaultHotItemStyle.BackColor = Color.FromArgb(224, 235, 253); + } + return sDefaultHotItemStyle; + } + } + private static HotItemStyle sDefaultHotItemStyle; + + #endregion + + #region Public properties + + /// + /// Gets or sets an model filter that is combined with any column filtering that the end-user specifies. + /// + /// This is different from the ModelFilter property, since setting that will replace + /// any column filtering, whereas setting this will combine this filter with the column filtering + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter AdditionalFilter + { + get { return this.additionalFilter; } + set + { + if (this.additionalFilter == value) + return; + this.additionalFilter = value; + this.UpdateColumnFiltering(); + } + } + private IModelFilter additionalFilter; + + /// + /// Get or set all the columns that this control knows about. + /// Only those columns where IsVisible is true will be seen by the user. + /// + /// + /// + /// If you want to add new columns programmatically, add them to + /// AllColumns and then call RebuildColumns(). Normally, you do not have to + /// deal with this property directly. Just use the IDE. + /// + /// If you do add or remove columns from the AllColumns collection, + /// you have to call RebuildColumns() to make those changes take effect. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public virtual List AllColumns { + get { return this.allColumns; } + set { this.allColumns = value ?? new List(); } + } + private List allColumns = new List(); + + /// + /// Gets or sets whether or not ObjectListView will allow cell editors to response to mouse wheel events. Default is true. + /// If this is true, cell editors that respond to mouse wheel events (e.g. numeric edit, DateTimeEditor, combo boxes) will operate + /// as expected. + /// If this is false, a mouse wheel event is interpreted as a request to scroll the control vertically. This will automatically + /// finish any cell edit operation that was in flight. This was the default behaviour prior to v2.9. + /// + [Category("ObjectListView"), + Description("Should ObjectListView allow cell editors to response to mouse wheel events (default: true)"), + DefaultValue(true)] + public virtual bool AllowCellEditorsToProcessMouseWheel + { + get { return allowCellEditorsToProcessMouseWheel; } + set { allowCellEditorsToProcessMouseWheel = value; } + } + private bool allowCellEditorsToProcessMouseWheel = true; + + /// + /// Gets or sets the background color of every second row + /// + [Category("ObjectListView"), + Description("If using alternate colors, what color should the background of alternate rows be?"), + DefaultValue(typeof(Color), "")] + public Color AlternateRowBackColor { + get { return alternateRowBackColor; } + set { alternateRowBackColor = value; } + } + private Color alternateRowBackColor = Color.Empty; + + /// + /// Gets the alternate row background color that has been set, or the default color + /// + [Browsable(false)] + public virtual Color AlternateRowBackColorOrDefault { + get { + return this.alternateRowBackColor == Color.Empty ? Color.LemonChiffon : this.alternateRowBackColor; + } + } + + /// + /// This property forces the ObjectListView to always group items by the given column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn AlwaysGroupByColumn { + get { return alwaysGroupByColumn; } + set { alwaysGroupByColumn = value; } + } + private OLVColumn alwaysGroupByColumn; + + /// + /// If AlwaysGroupByColumn is not null, this property will be used to decide how + /// those groups are sorted. If this property has the value SortOrder.None, then + /// the sort order will toggle according to the users last header click. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder AlwaysGroupBySortOrder { + get { return alwaysGroupBySortOrder; } + set { alwaysGroupBySortOrder = value; } + } + private SortOrder alwaysGroupBySortOrder = SortOrder.None; + + /// + /// Give access to the image list that is actually being used by the control + /// + /// + /// Normally, it is preferable to use SmallImageList. Only use this property + /// if you know exactly what you are doing. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ImageList BaseSmallImageList { + get { return base.SmallImageList; } + set { base.SmallImageList = value; } + } + + /// + /// How does the user indicate that they want to edit a cell? + /// None means that the listview cannot be edited. + /// + /// Columns can also be marked as editable. + [Category("ObjectListView"), + Description("How does the user indicate that they want to edit a cell?"), + DefaultValue(CellEditActivateMode.None)] + public virtual CellEditActivateMode CellEditActivation { + get { return cellEditActivation; } + set { + cellEditActivation = value; + if (this.Created) + this.Invalidate(); + } + } + private CellEditActivateMode cellEditActivation = CellEditActivateMode.None; + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// Defaults to true. + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// Each column can have a different value for property. This value from the control is only + /// used when a column is not specified one way or another. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(true)] + public virtual bool CellEditUseWholeCell { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool cellEditUseWholeCell = true; + + /// + /// Gets or sets the engine that will handle key presses during a cell edit operation. + /// Settings this to null will reset it to default value. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public CellEditKeyEngine CellEditKeyEngine { + get { return this.cellEditKeyEngine ?? (this.cellEditKeyEngine = new CellEditKeyEngine()); } + set { this.cellEditKeyEngine = value; } + } + private CellEditKeyEngine cellEditKeyEngine; + + /// + /// Gets the control that is currently being used for editing a cell. + /// + /// This will obviously be null if no cell is being edited. + [Browsable(false)] + public Control CellEditor { + get { + return this.cellEditor; + } + } + + /// + /// Gets or sets the behaviour of the Tab key when editing a cell on the left or right + /// edge of the control. If this is false (the default), pressing Tab will wrap to the other side + /// of the same row. If this is true, pressing Tab when editing the right most cell will advance + /// to the next row + /// and Shift-Tab when editing the left-most cell will change to the previous row. + /// + [Category("ObjectListView"), + Description("Should Tab/Shift-Tab change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditTabChangesRows { + get { return cellEditTabChangesRows; } + set { + cellEditTabChangesRows = value; + if (cellEditTabChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.ChangeRow); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab|Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.ChangeRow); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.Wrap); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab | Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.Wrap); + } + } + } + private bool cellEditTabChangesRows; + + /// + /// Gets or sets the behaviour of the Enter keys while editing a cell. + /// If this is false (the default), pressing Enter will simply finish the editing operation. + /// If this is true, Enter will finish the edit operation and start a new edit operation + /// on the cell below the current cell, wrapping to the top of the next row when at the bottom cell. + /// + [Category("ObjectListView"), + Description("Should Enter change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditEnterChangesRows { + get { return cellEditEnterChangesRows; } + set { + cellEditEnterChangesRows = value; + if (cellEditEnterChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.ChangeRowDown, CellEditAtEdgeBehaviour.ChangeColumn); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.ChangeRowUp, CellEditAtEdgeBehaviour.ChangeColumn); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + } + } + } + private bool cellEditEnterChangesRows; + + /// + /// Gets the tool tip control that shows tips for the cells + /// + [Browsable(false)] + public ToolTipControl CellToolTip { + get { + if (this.cellToolTip == null) { + this.CreateCellToolTip(); + } + return this.cellToolTip; + } + } + private ToolTipControl cellToolTip; + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item. + /// Cell contents are aligned after padding has been taken into account. + /// + /// + /// Each value of the given rectangle will be treated as an inset from + /// the corresponding side. The width of the rectangle is the padding for the + /// right cell edge. The height of the rectangle is the padding for the bottom + /// cell edge. + /// + /// + /// So, this.olv1.CellPadding = new Rectangle(1, 2, 3, 4); will leave one pixel + /// of space to the left of the cell, 2 pixels at the top, 3 pixels of space + /// on the right edge, and 4 pixels of space at the bottom of each cell. + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// This setting only affects the contents of the cell. The background is + /// not affected. + /// If you set this to a foolish value, your control will appear to be empty. + /// + [Category("ObjectListView"), + Description("How much padding will be applied to each cell in this control?"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells will be vertically aligned by default. + /// + /// This setting only takes effect when the control is owner drawn. It will only be noticeable + /// when RowHeight has been set such that there is some vertical space in each row. + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(StringAlignment.Center)] + public virtual StringAlignment CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment cellVerticalAlignment = StringAlignment.Center; + + /// + /// Should this list show checkboxes? + /// + public new bool CheckBoxes { + get { return base.CheckBoxes; } + set { + // Due to code in the base ListView class, turning off CheckBoxes on a virtual + // list always throws an InvalidOperationException. We have to do some major hacking + // to get around that + if (this.VirtualMode) { + // Leave virtual mode + this.StateImageList = null; + this.VirtualListSize = 0; + this.VirtualMode = false; + + // Change the CheckBox setting while not in virtual mode + base.CheckBoxes = value; + + // Reinstate virtual mode + this.VirtualMode = true; + + // Re-enact the bits that we lost by switching to virtual mode + this.ShowGroups = this.ShowGroups; + this.BuildList(true); + } else { + base.CheckBoxes = value; + // Initialize the state image list so we can display indeterminate values. + this.InitializeStateImageList(); + } + } + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object CheckedObject { + get { + IList checkedObjects = this.CheckedObjects; + return checkedObjects.Count == 1 ? checkedObjects[0] : null; + } + set { + this.CheckedObjects = new ArrayList(new Object[] { value }); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// .NET's CheckedItems property is not helpful. It is just a short-hand for + /// iterating through the list looking for items that are checked. + /// + /// + /// The performance of the get method is O(n), where n is the number of items + /// in the control. The performance of the set method is + /// O(n + m) where m is the number of objects being checked. Be careful on long lists. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList CheckedObjects { + get { + ArrayList list = new ArrayList(); + if (this.CheckBoxes) { + for (int i = 0; i < this.GetItemCount(); i++) { + OLVListItem olvi = this.GetItem(i); + if (olvi.CheckState == CheckState.Checked) + list.Add(olvi.RowObject); + } + } + return list; + } + set { + if (!this.CheckBoxes) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + foreach (Object x in this.Objects) { + this.SetObjectCheckedness(x, table.ContainsKey(x) ? CheckState.Checked : CheckState.Unchecked); + } + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + + } + } + + /// + /// Gets or sets the checked objects from an enumerable. + /// + /// + /// Useful for checking all objects in the list. + /// + /// + /// this.olv1.CheckedObjectsEnumerable = this.olv1.Objects; + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable CheckedObjectsEnumerable { + get { + return this.CheckedObjects; + } + set { + this.CheckedObjects = ObjectListView.EnumerableToArray(value, true); + } + } + + /// + /// Gets Columns for this list. We hide the original so we can associate + /// a specialised editor with it. + /// + [Editor("BrightIdeasSoftware.Design.OLVColumnCollectionEditor", "System.Drawing.Design.UITypeEditor")] + public new ListView.ColumnHeaderCollection Columns { + get { + return base.Columns; + } + } + + /// + /// Get/set the list of columns that should be used when the list switches to tile view. + /// + [Browsable(false), + Obsolete("Use GetFilteredColumns() and OLVColumn.IsTileViewColumn instead"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public List ColumnsForTileView { + get { return this.GetFilteredColumns(View.Tile); } + } + + /// + /// Return the visible columns in the order they are displayed to the user + /// + [Browsable(false)] + public virtual List ColumnsInDisplayOrder { + get { + OLVColumn[] columnsInDisplayOrder = new OLVColumn[this.Columns.Count]; + foreach (OLVColumn col in this.Columns) { + columnsInDisplayOrder[col.DisplayIndex] = col; + } + return new List(columnsInDisplayOrder); + } + } + + + /// + /// Get the area of the control that shows the list, minus any header control + /// + [Browsable(false)] + public Rectangle ContentRectangle { + get { + Rectangle r = this.ClientRectangle; + + // If the listview has a header control, remove the header from the control area + if ((this.View == View.Details || this.ShowHeaderInAllViews) && this.HeaderControl != null) { + Rectangle hdrBounds = new Rectangle(); + NativeMethods.GetClientRect(this.HeaderControl.Handle, ref hdrBounds); + r.Y = hdrBounds.Height; + r.Height = r.Height - hdrBounds.Height; + } + + return r; + } + } + + /// + /// Gets or sets if the selected rows should be copied to the clipboard when the user presses Ctrl-C + /// + [Category("ObjectListView"), + Description("Should the control copy the selection to the clipboard when the user presses Ctrl-C?"), + DefaultValue(true)] + public virtual bool CopySelectionOnControlC { + get { return copySelectionOnControlC; } + set { copySelectionOnControlC = value; } + } + private bool copySelectionOnControlC = true; + + + /// + /// Gets or sets whether the Control-C copy to clipboard functionality should use + /// the installed DragSource to create the data object that is placed onto the clipboard. + /// + /// This is normally what is desired, unless a custom DragSource is installed + /// that does some very specialized drag-drop behaviour. + [Category("ObjectListView"), + Description("Should the Ctrl-C copy process use the DragSource to create the Clipboard data object?"), + DefaultValue(true)] + public bool CopySelectionOnControlCUsesDragSource { + get { return this.copySelectionOnControlCUsesDragSource; } + set { this.copySelectionOnControlCUsesDragSource = value; } + } + private bool copySelectionOnControlCUsesDragSource = true; + + /// + /// Gets the list of decorations that will be drawn the ListView + /// + /// + /// + /// Do not modify the contents of this list directly. Use the AddDecoration() and RemoveDecoration() methods. + /// + /// + /// A decoration scrolls with the list contents. An overlay is fixed in place. + /// + /// + [Browsable(false)] + protected IList Decorations { + get { return this.decorations; } + } + private readonly List decorations = new List(); + + /// + /// When owner drawing, this renderer will draw columns that do not have specific renderer + /// given to them + /// + /// If you try to set this to null, it will revert to a HighlightTextRenderer + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IRenderer DefaultRenderer { + get { return this.defaultRenderer; } + set { this.defaultRenderer = value ?? new HighlightTextRenderer(); } + } + private IRenderer defaultRenderer = new HighlightTextRenderer(); + + /// + /// Get the renderer to be used to draw the given cell. + /// + /// The row model for the row + /// The column to be drawn + /// The renderer used for drawing a cell. Must not return null. + public IRenderer GetCellRenderer(object model, OLVColumn column) { + IRenderer renderer = this.CellRendererGetter == null ? null : this.CellRendererGetter(model, column); + return renderer ?? column.Renderer ?? this.DefaultRenderer; + } + + /// + /// Gets or sets the style that will be applied to disabled items. + /// + /// If this is not set explicitly, will be used. + [Category("ObjectListView"), + Description("The style that will be applied to disabled items"), + DefaultValue(null)] + public SimpleItemStyle DisabledItemStyle + { + get { return disabledItemStyle; } + set { disabledItemStyle = value; } + } + private SimpleItemStyle disabledItemStyle; + + /// + /// Gets or sets the list of model objects that are disabled. + /// Disabled objects cannot be selected or activated. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable DisabledObjects + { + get + { + return disabledObjects.Keys; + } + set + { + this.disabledObjects.Clear(); + DisableObjects(value); + } + } + private readonly Hashtable disabledObjects = new Hashtable(); + + /// + /// Is this given model object disabled? + /// + /// + /// + public bool IsDisabled(object model) + { + return model != null && this.disabledObjects.ContainsKey(model); + } + + /// + /// Disable the given model object. + /// Disabled objects cannot be selected or activated. + /// + /// Must not be null + public void DisableObject(object model) { + ArrayList list = new ArrayList(); + list.Add(model); + this.DisableObjects(list); + } + + /// + /// Disable all the given model objects + /// + /// + public void DisableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model == null) + continue; + + this.disabledObjects[model] = true; + int modelIndex = this.IndexOf(model); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + this.RefreshObjects(list); + } + + /// + /// Enable the given model object, so it can be selected and activated again. + /// + /// Must not be null + public void EnableObject(object model) + { + this.disabledObjects.Remove(model); + this.RefreshObject(model); + } + + /// + /// Enable all the given model objects + /// + /// + public void EnableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model != null) + this.disabledObjects.Remove(model); + } + this.RefreshObjects(list); + } + + /// + /// Forget all disabled objects. This does not trigger a redraw or rebuild + /// + protected void ClearDisabledObjects() + { + this.disabledObjects.Clear(); + } + + /// + /// Gets or sets the object that controls how drags start from this control + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDragSource DragSource { + get { return this.dragSource; } + set { this.dragSource = value; } + } + private IDragSource dragSource; + + /// + /// Gets or sets the object that controls how drops are accepted and processed + /// by this ListView. + /// + /// + /// + /// If the given sink is an instance of SimpleDropSink, then events from the drop sink + /// will be automatically forwarded to the ObjectListView (which means that handlers + /// for those event can be configured within the IDE). + /// + /// If this is set to null, the control will not accept drops. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDropSink DropSink { + get { return this.dropSink; } + set { + if (this.dropSink == value) + return; + + // Stop listening for events on the old sink + SimpleDropSink oldSink = this.dropSink as SimpleDropSink; + if (oldSink != null) { + oldSink.CanDrop -= new EventHandler(this.DropSinkCanDrop); + oldSink.Dropped -= new EventHandler(this.DropSinkDropped); + oldSink.ModelCanDrop -= new EventHandler(this.DropSinkModelCanDrop); + oldSink.ModelDropped -= new EventHandler(this.DropSinkModelDropped); + } + + this.dropSink = value; + this.AllowDrop = (value != null); + if (this.dropSink != null) + this.dropSink.ListView = this; + + // Start listening for events on the new sink + SimpleDropSink newSink = value as SimpleDropSink; + if (newSink != null) { + newSink.CanDrop += new EventHandler(this.DropSinkCanDrop); + newSink.Dropped += new EventHandler(this.DropSinkDropped); + newSink.ModelCanDrop += new EventHandler(this.DropSinkModelCanDrop); + newSink.ModelDropped += new EventHandler(this.DropSinkModelDropped); + } + } + } + private IDropSink dropSink; + + // Forward events from the drop sink to the control itself + void DropSinkCanDrop(object sender, OlvDropEventArgs e) { this.OnCanDrop(e); } + void DropSinkDropped(object sender, OlvDropEventArgs e) { this.OnDropped(e); } + void DropSinkModelCanDrop(object sender, ModelDropEventArgs e) { this.OnModelCanDrop(e); } + void DropSinkModelDropped(object sender, ModelDropEventArgs e) { this.OnModelDropped(e); } + + /// + /// This registry decides what control should be used to edit what cells, based + /// on the type of the value in the cell. + /// + /// + /// All instances of ObjectListView share the same editor registry. +// ReSharper disable FieldCanBeMadeReadOnly.Global + public static EditorRegistry EditorRegistry = new EditorRegistry(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + + /// + /// Gets or sets the text that should be shown when there are no items in this list view. + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("When the list has no items, show this message in the control"), + DefaultValue(null), + Localizable(true)] + public virtual String EmptyListMsg { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Text; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) { + overlay.Text = value; + this.Invalidate(); + } + } + } + + /// + /// Gets or sets the font in which the List Empty message should be drawn + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("What font should the 'list empty' message be drawn in?"), + DefaultValue(null)] + public virtual Font EmptyListMsgFont { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Font; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) + overlay.Font = value; + } + } + + /// + /// Return the font for the 'list empty' message or a reasonable default + /// + [Browsable(false)] + public virtual Font EmptyListMsgFontOrDefault { + get { + return this.EmptyListMsgFont ?? new Font("Tahoma", 14); + } + } + + /// + /// Gets or sets the overlay responsible for drawing the List Empty msg. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IOverlay EmptyListMsgOverlay { + get { return this.emptyListMsgOverlay; } + set { + if (this.emptyListMsgOverlay != value) { + this.emptyListMsgOverlay = value; + this.Invalidate(); + } + } + } + private IOverlay emptyListMsgOverlay; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + /// + /// + /// This collection is the result of filtering the current list of objects. + /// It is not a snapshot of the filtered list that was last used to build the control. + /// + /// + /// Normal warnings apply when using this with virtual lists. It will work, but it + /// may take a while. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable FilteredObjects { + get { + if (this.UseFiltering) + return this.FilterObjects(this.Objects, this.ModelFilter, this.ListFilter); + + return this.Objects; + } + } + + /// + /// Gets or sets the strategy object that will be used to build the Filter menu + /// + /// If this is null, no filter menu will be built. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public FilterMenuBuilder FilterMenuBuildStrategy { + get { return filterMenuBuilder; } + set { filterMenuBuilder = value; } + } + private FilterMenuBuilder filterMenuBuilder = new FilterMenuBuilder(); + + /// + /// Gets or sets the row that has keyboard focus + /// + /// + /// + /// Setting an object to be focused does *not* select it. If you want to select and focus a row, + /// use . + /// + /// + /// This property is not generally used and is only useful in specialized situations. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object FocusedObject { + get { return this.FocusedItem == null ? null : ((OLVListItem)this.FocusedItem).RowObject; } + set { + OLVListItem item = this.ModelToItem(value); + if (item != null) + item.Focused = true; + } + } + + /// + /// Hide the Groups collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewGroupCollection Groups { + get { return base.Groups; } + } + + /// + /// Gets or sets the image list from which group header will take their images + /// + /// If this is not set, then group headers will not show any images. + [Category("ObjectListView"), + Description("The image list from which group header will take their images"), + DefaultValue(null)] + public ImageList GroupImageList { + get { return this.groupImageList; } + set { + this.groupImageList = value; + if (this.Created) { + NativeMethods.SetGroupImageList(this, value); + } + } + } + private ImageList groupImageList; + + /// + /// Gets how the group label should be formatted when a group is empty or + /// contains more than one item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Return this.GroupWithItemCountFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountFormat) ? "{0} [{1} items]" : this.GroupWithItemCountFormat; + } + } + + /// + /// Gets how the group label should be formatted when a group contains only a single item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Gets GroupWithItemCountSingularFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountSingularFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat) ? "{0} [{1} item]" : this.GroupWithItemCountSingularFormat; + } + } + + /// + /// Gets or sets whether or not the groups in this ObjectListView should be collapsible. + /// + /// + /// This feature only works under Vista and later. + /// + [Browsable(true), + Category("ObjectListView"), + Description("Should the groups in this control be collapsible (Vista and later only)."), + DefaultValue(true)] + public bool HasCollapsibleGroups { + get { return hasCollapsibleGroups; } + set { hasCollapsibleGroups = value; } + } + private bool hasCollapsibleGroups = true; + + /// + /// Does this listview have a message that should be drawn when the list is empty? + /// + [Browsable(false)] + public virtual bool HasEmptyListMsg { + get { return !String.IsNullOrEmpty(this.EmptyListMsg); } + } + + /// + /// Get whether there are any overlays to be drawn + /// + [Browsable(false)] + public bool HasOverlays { + get { + return (this.Overlays.Count > 2 || + this.imageOverlay.Image != null || + !String.IsNullOrEmpty(this.textOverlay.Text)); + } + } + + /// + /// Gets the header control for the ListView + /// + [Browsable(false)] + public HeaderControl HeaderControl { + get { return this.headerControl ?? (this.headerControl = new HeaderControl(this)); } + } + private HeaderControl headerControl; + + /// + /// Gets or sets the font in which the text of the column headers will be drawn + /// + /// Individual columns can override this through their HeaderFormatStyle property. + [DefaultValue(null)] + [Browsable(false)] + [Obsolete("Use a HeaderFormatStyle instead", false)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the style that will be used to draw the column headers of the listview + /// + /// + /// + /// This is only used when HeaderUsesThemes is false. + /// + /// + /// Individual columns can override this through their HeaderFormatStyle property. + /// + /// + [Category("ObjectListView"), + Description("What style will be used to draw the control's header"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the maximum height of the header. -1 means no maximum. + /// + [Category("ObjectListView"), + Description("What is the maximum height of the header? -1 means no maximum"), + DefaultValue(-1)] + public int HeaderMaximumHeight + { + get { return headerMaximumHeight; } + set { headerMaximumHeight = value; } + } + private int headerMaximumHeight = -1; + + /// + /// Gets or sets the minimum height of the header. -1 means no minimum. + /// + [Category("ObjectListView"), + Description("What is the minimum height of the header? -1 means no minimum"), + DefaultValue(-1)] + public int HeaderMinimumHeight + { + get { return headerMinimumHeight; } + set { headerMinimumHeight = value; } + } + private int headerMinimumHeight = -1; + + /// + /// Gets or sets whether the header will be drawn strictly according to the OS's theme. + /// + /// + /// + /// If this is set to true, the header will be rendered completely by the system, without + /// any of ObjectListViews fancy processing -- no images in header, no filter indicators, + /// no word wrapping, no header styling, no checkboxes. + /// + /// If this is set to false, ObjectListView will render the header as it thinks best. + /// If no special features are required, then ObjectListView will delegate rendering to the OS. + /// Otherwise, ObjectListView will draw the header according to the configuration settings. + /// + /// + /// The effect of not being themed will be different from OS to OS. At + /// very least, the sort indicator will not be standard. + /// + /// + [Category("ObjectListView"), + Description("Will the column headers be drawn strictly according to OS theme?"), + DefaultValue(false)] + public bool HeaderUsesThemes { + get { return this.headerUsesThemes; } + set { this.headerUsesThemes = value; } + } + private bool headerUsesThemes; + + /// + /// Gets or sets the whether the text in the header will be word wrapped. + /// + /// + /// Line breaks will be applied between words. Words that are too long + /// will still be ellipsed. + /// + /// As with all settings that make the header look different, HeaderUsesThemes must be set to false, otherwise + /// the OS will be responsible for drawing the header, and it does not allow word wrapped text. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the column headers be word wrapped?"), + DefaultValue(false)] + public bool HeaderWordWrap { + get { return this.headerWordWrap; } + set { + this.headerWordWrap = value; + if (this.headerControl != null) + this.headerControl.WordWrap = value; + } + } + private bool headerWordWrap; + + /// + /// Gets the tool tip that shows tips for the column headers + /// + [Browsable(false)] + public ToolTipControl HeaderToolTip { + get { + return this.HeaderControl.ToolTip; + } + } + + /// + /// Gets the index of the row that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotRowIndex { + get { return this.hotRowIndex; } + protected set { this.hotRowIndex = value; } + } + private int hotRowIndex; + + /// + /// Gets the index of the subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotColumnIndex { + get { return this.hotColumnIndex; } + protected set { this.hotColumnIndex = value; } + } + private int hotColumnIndex; + + /// + /// Gets the part of the item/subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocation HotCellHitLocation { + get { return this.hotCellHitLocation; } + protected set { this.hotCellHitLocation = value; } + } + private HitTestLocation hotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocationEx HotCellHitLocationEx + { + get { return this.hotCellHitLocationEx; } + protected set { this.hotCellHitLocationEx = value; } + } + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the group that the mouse is over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVGroup HotGroup + { + get { return hotGroup; } + internal set { hotGroup = value; } + } + private OLVGroup hotGroup; + + /// + /// The index of the item that is 'hot', i.e. under the cursor. -1 means no item. + /// + [Browsable(false), + Obsolete("Use HotRowIndex instead", false)] + public virtual int HotItemIndex { + get { return this.HotRowIndex; } + } + + /// + /// What sort of formatting should be applied to the row under the cursor? + /// + /// + /// + /// This only takes effect when UseHotItem is true. + /// + /// If the style has an overlay, it must be set + /// *before* assigning it to this property. Adding it afterwards will be ignored. + /// + [Category("ObjectListView"), + Description("How should the row under the cursor be highlighted"), + DefaultValue(null)] + public virtual HotItemStyle HotItemStyle { + get { return this.hotItemStyle; } + set { + if (this.HotItemStyle != null) + this.RemoveOverlay(this.HotItemStyle.Overlay); + this.hotItemStyle = value; + if (this.HotItemStyle != null) + this.AddOverlay(this.HotItemStyle.Overlay); + } + } + private HotItemStyle hotItemStyle; + + /// + /// Gets the installed hot item style or a reasonable default. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HotItemStyle HotItemStyleOrDefault { + get { return this.HotItemStyle ?? ObjectListView.DefaultHotItemStyle; } + } + + /// + /// What sort of formatting should be applied to hyperlinks? + /// + [Category("ObjectListView"), + Description("How should hyperlinks be drawn"), + DefaultValue(null)] + public virtual HyperlinkStyle HyperlinkStyle { + get { return this.hyperlinkStyle; } + set { this.hyperlinkStyle = value; } + } + private HyperlinkStyle hyperlinkStyle; + + /// + /// What color should be used for the background of selected rows? + /// + [Category("ObjectListView"), + Description("The background of selected rows when the control is owner drawn"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color selectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedBackColorOrDefault { + get { + return this.SelectedBackColor.IsEmpty ? SystemColors.Highlight : this.SelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows (when the control is owner drawn)"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedForeColor { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color selectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedForeColorOrDefault { + get { + return this.SelectedForeColor.IsEmpty ? SystemColors.HighlightText : this.SelectedForeColor; + } + } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedBackColor instead")] + public virtual Color HighlightBackgroundColor { get { return this.SelectedBackColor; } set { this.SelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedBackColorOrDefault instead")] + public virtual Color HighlightBackgroundColorOrDefault { get { return this.SelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedForeColor instead")] + public virtual Color HighlightForegroundColor { get { return this.SelectedForeColor; } set { this.SelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedForeColorOrDefault instead")] + public virtual Color HighlightForegroundColorOrDefault { get { return this.SelectedForeColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedBackColor instead")] + public virtual Color UnfocusedHighlightBackgroundColor { get { return this.UnfocusedSelectedBackColor; } set { this.UnfocusedSelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedBackColorOrDefault instead")] + public virtual Color UnfocusedHighlightBackgroundColorOrDefault { get { return this.UnfocusedSelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedForeColor instead")] + public virtual Color UnfocusedHighlightForegroundColor { get { return this.UnfocusedSelectedForeColor; } set { this.UnfocusedSelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedForeColorOrDefault instead")] + public virtual Color UnfocusedHighlightForegroundColorOrDefault { get { return this.UnfocusedSelectedForeColorOrDefault; } } + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied or dragged, will data in hidden columns be included in the text? If this is false, only visible columns will be included."), + DefaultValue(false)] + public virtual bool IncludeHiddenColumnsInDataTransfer + { + get { return includeHiddenColumnsInDataTransfer; } + set { includeHiddenColumnsInDataTransfer = value; } + } + private bool includeHiddenColumnsInDataTransfer; + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied, will column headers be in the text?."), + DefaultValue(false)] + public virtual bool IncludeColumnHeadersInCopy + { + get { return includeColumnHeadersInCopy; } + set { includeColumnHeadersInCopy = value; } + } + private bool includeColumnHeadersInCopy; + + /// + /// Return true if a cell edit operation is currently happening + /// + [Browsable(false)] + public virtual bool IsCellEditing { + get { return this.cellEditor != null; } + } + + /// + /// Return true if the ObjectListView is being used within the development environment. + /// + [Browsable(false)] + public virtual bool IsDesignMode { + get { return this.DesignMode; } + } + + /// + /// Gets whether or not the current list is filtering its contents + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool IsFiltering { + get { return this.UseFiltering && (this.ModelFilter != null || this.ListFilter != null); } + } + + /// + /// When the user types into a list, should the values in the current sort column be searched to find a match? + /// If this is false, the primary column will always be used regardless of the sort column. + /// + /// When this is true, the behavior is like that of ITunes. + [Category("ObjectListView"), + Description("When the user types into a list, should the values in the current sort column be searched to find a match?"), + DefaultValue(true)] + public virtual bool IsSearchOnSortColumn { + get { return isSearchOnSortColumn; } + set { isSearchOnSortColumn = value; } + } + private bool isSearchOnSortColumn = true; + + /// + /// Gets or sets if this control will use a SimpleDropSink to receive drops + /// + /// + /// + /// Setting this replaces any previous DropSink. + /// + /// + /// After setting this to true, the SimpleDropSink will still need to be configured + /// to say when it can accept drops and what should happen when something is dropped. + /// The need to do these things makes this property mostly useless :( + /// + /// + [Category("ObjectListView"), + Description("Should this control will use a SimpleDropSink to receive drops."), + DefaultValue(false)] + public virtual bool IsSimpleDropSink { + get { return this.DropSink != null; } + set { + this.DropSink = value ? new SimpleDropSink() : null; + } + } + + /// + /// Gets or sets if this control will use a SimpleDragSource to initiate drags + /// + /// Setting this replaces any previous DragSource + [Category("ObjectListView"), + Description("Should this control use a SimpleDragSource to initiate drags out from this control"), + DefaultValue(false)] + public virtual bool IsSimpleDragSource { + get { return this.DragSource != null; } + set { + this.DragSource = value ? new SimpleDragSource() : null; + } + } + + /// + /// Hide the Items collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewItemCollection Items { + get { return base.Items; } + } + + /// + /// This renderer draws the items when in the list is in non-details view. + /// In details view, the renderers for the individuals columns are responsible. + /// + [Category("ObjectListView"), + Description("The owner drawn renderer that draws items when the list is in non-Details view."), + DefaultValue(null)] + public IRenderer ItemRenderer { + get { return itemRenderer; } + set { itemRenderer = value; } + } + private IRenderer itemRenderer; + + /// + /// Which column did we last sort by + /// + /// This is an alias for PrimarySortColumn + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn LastSortColumn { + get { return this.PrimarySortColumn; } + set { this.PrimarySortColumn = value; } + } + + /// + /// Which direction did we last sort + /// + /// This is an alias for PrimarySortOrder + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder LastSortOrder { + get { return this.PrimarySortOrder; } + set { this.PrimarySortOrder = value; } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// + /// + /// The list is updated immediately to reflect this filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IListFilter ListFilter { + get { return listFilter; } + set { + listFilter = value; + if (this.UseFiltering) + this.UpdateFiltering(); + } + } + private IListFilter listFilter; + + /// + /// Gets or sets the filter that is applied to each model objects in the list + /// + /// + /// You may want to consider using instead of this property, + /// since AdditionalFilter combines with column filtering at runtime. Setting this property simply + /// replaces any column filter the user may have given. + /// + /// The list is updated immediately to reflect this filter. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter ModelFilter { + get { return modelFilter; } + set { + modelFilter = value; + this.NotifyNewModelFilter(); + if (this.UseFiltering) { + this.UpdateFiltering(); + + // When the filter changes, it's likely/possible that the selection has also changed. + // It's expensive to see if the selection has actually changed (for large virtual lists), + // so we just fake a selection changed event, just in case. SF #144 + this.OnSelectedIndexChanged(EventArgs.Empty); + } + } + } + private IModelFilter modelFilter; + + /// + /// Gets the hit test info last time the mouse was moved. + /// + /// Useful for hot item processing. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OlvListViewHitTestInfo MouseMoveHitTest { + get { return mouseMoveHitTest; } + private set { mouseMoveHitTest = value; } + } + private OlvListViewHitTestInfo mouseMoveHitTest; + + /// + /// Gets or sets the list of groups shown by the listview. + /// + /// + /// This property does not work like the .NET Groups property. It should + /// be treated as a read-only property. + /// Changes made to the list are NOT reflected in the ListView itself -- it is pointless to add + /// or remove groups to/from this list. Such modifications will do nothing. + /// To do such things, you must listen for + /// BeforeCreatingGroups or AboutToCreateGroups events, and change the list of + /// groups in those events. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList OLVGroups { + get { return this.olvGroups; } + set { this.olvGroups = value; } + } + private IList olvGroups; + + /// + /// Gets or sets the collection of OLVGroups that are collapsed. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable CollapsedGroups { + get + { + if (this.OLVGroups != null) + { + foreach (OLVGroup group in this.OLVGroups) + { + if (group.Collapsed) + yield return group; + } + } + } + set + { + if (this.OLVGroups == null) + return; + + Hashtable shouldCollapse = new Hashtable(); + if (value != null) + { + foreach (OLVGroup group in value) + shouldCollapse[group.Key] = true; + } + foreach (OLVGroup group in this.OLVGroups) + { + group.Collapsed = shouldCollapse.ContainsKey(group.Key); + } + + } + } + + /// + /// Gets or sets whether the user wants to owner draw the header control + /// themselves. If this is false (the default), ObjectListView will use + /// custom drawing to render the header, if needed. + /// + /// + /// If you listen for the DrawColumnHeader event, you need to set this to true, + /// otherwise your event handler will not be called. + /// + [Category("ObjectListView"), + Description("Should the DrawColumnHeader event be triggered"), + DefaultValue(false)] + public bool OwnerDrawnHeader { + get { return ownerDrawnHeader; } + set { ownerDrawnHeader = value; } + } + private bool ownerDrawnHeader; + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists: setting is problem-free, but if you try to get it + /// and the list has 10 million objects, it may take some time to return. + /// This collection is unfiltered. Use to access just those objects + /// that survive any installed filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Objects { + get { return this.objects; } + set { this.SetObjects(value, true); } + } + private IEnumerable objects; + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable ObjectsForClustering { + get { return this.Objects; } + } + + /// + /// Gets or sets the image that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The image that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public ImageOverlay OverlayImage { + get { return this.imageOverlay; } + set { + if (this.imageOverlay == value) + return; + + this.RemoveOverlay(this.imageOverlay); + this.imageOverlay = value; + this.AddOverlay(this.imageOverlay); + } + } + private ImageOverlay imageOverlay; + + /// + /// Gets or sets the text that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public TextOverlay OverlayText { + get { return this.textOverlay; } + set { + if (this.textOverlay == value) + return; + + this.RemoveOverlay(this.textOverlay); + this.textOverlay = value; + this.AddOverlay(this.textOverlay); + } + } + private TextOverlay textOverlay; + + /// + /// Gets or sets the transparency of all the overlays. + /// 0 is completely transparent, 255 is completely opaque. + /// + /// + /// This is obsolete. Use Transparency on each overlay. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int OverlayTransparency { + get { return this.overlayTransparency; } + set { this.overlayTransparency = Math.Min(255, Math.Max(0, value)); } + } + private int overlayTransparency = 128; + + /// + /// Gets the list of overlays that will be drawn on top of the ListView + /// + /// + /// You can add new overlays and remove overlays that you have added, but + /// don't mess with the overlays that you didn't create. + /// + [Browsable(false)] + protected IList Overlays { + get { return this.overlays; } + } + private readonly List overlays = new List(); + + /// + /// Gets or sets whether the ObjectListView will be owner drawn. Defaults to true. + /// + /// + /// + /// When this is true, all of ObjectListView's neat features are available. + /// + /// We have to reimplement this property, even though we just call the base + /// property, in order to change the [DefaultValue] to true. + /// + /// + [Category("Appearance"), + Description("Should the ListView do its own rendering"), + DefaultValue(true)] + public new bool OwnerDraw { + get { return base.OwnerDraw; } + set { base.OwnerDraw = value; } + } + + /// + /// Gets or sets whether or not primary checkboxes will persistent their values across list rebuild + /// and filtering operations. + /// + /// + /// + /// This property is only useful when you don't explicitly set CheckStateGetter/Putter. + /// If you use CheckStateGetter/Putter, the checkedness of a row will already be persisted + /// by those methods. + /// + /// This defaults to true. If this is false, checkboxes will lose their values when the + /// list if rebuild or filtered. + /// If you set it to false on virtual lists, + /// you have to install CheckStateGetter/Putters. + /// + [Category("ObjectListView"), + Description("Will primary checkboxes persistent their values across list rebuilds"), + DefaultValue(true)] + public virtual bool PersistentCheckBoxes { + get { return persistentCheckBoxes; } + set { + if (persistentCheckBoxes == value) + return; + persistentCheckBoxes = value; + this.ClearPersistentCheckState(); + } + } + private bool persistentCheckBoxes = true; + + /// + /// Gets or sets a dictionary that remembers the check state of model objects + /// + /// This is used when PersistentCheckBoxes is true and for virtual lists. + protected Dictionary CheckStateMap { + get { return checkStateMap ?? (checkStateMap = new Dictionary()); } + set { checkStateMap = value; } + } + private Dictionary checkStateMap; + + /// + /// Which column did we last sort by + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn PrimarySortColumn { + get { return this.primarySortColumn; } + set { + this.primarySortColumn = value; + if (this.TintSortColumn) + this.SelectedColumn = value; + } + } + private OLVColumn primarySortColumn; + + /// + /// Which direction did we last sort + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder PrimarySortOrder { + get { return primarySortOrder; } + set { primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets if non-editable checkboxes are drawn as disabled. Default is false. + /// + /// + /// This only has effect in owner drawn mode. + /// + [Category("ObjectListView"), + Description("Should non-editable checkboxes be drawn as disabled?"), + DefaultValue(false)] + public virtual bool RenderNonEditableCheckboxesAsDisabled { + get { return renderNonEditableCheckboxesAsDisabled; } + set { renderNonEditableCheckboxesAsDisabled = value; } + } + private bool renderNonEditableCheckboxesAsDisabled; + + /// + /// Specify the height of each row in the control in pixels. + /// + /// The row height in a listview is normally determined by the font size and the small image list size. + /// This setting allows that calculation to be overridden (within reason: you still cannot set the line height to be + /// less than the line height of the font used in the control). + /// Setting it to -1 means use the normal calculation method. + /// This feature is experimental! Strange things may happen to your program, + /// your spouse or your pet if you use it. + /// + [Category("ObjectListView"), + Description("Specify the height of each row in pixels. -1 indicates default height"), + DefaultValue(-1)] + public virtual int RowHeight { + get { return rowHeight; } + set { + if (value < 1) + rowHeight = -1; + else + rowHeight = value; + if (this.DesignMode) + return; + this.SetupBaseImageList(); + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + } + private int rowHeight = -1; + + /// + /// How many pixels high is each row? + /// + [Browsable(false)] + public virtual int RowHeightEffective { + get { + switch (this.View) { + case View.List: + case View.SmallIcon: + case View.Details: + return Math.Max(this.SmallImageSize.Height, this.Font.Height); + + case View.Tile: + return this.TileSize.Height; + + case View.LargeIcon: + if (this.LargeImageList == null) + return this.Font.Height; + + return Math.Max(this.LargeImageList.ImageSize.Height, this.Font.Height); + + default: + // This should never happen + return 0; + } + } + } + + /// + /// How many rows appear on each page of this control + /// + [Browsable(false)] + public virtual int RowsPerPage { + get { + return NativeMethods.GetCountPerPage(this); + } + } + + /// + /// Get/set the column that will be used to resolve comparisons that are equal when sorting. + /// + /// There is no user interface for this setting. It must be set programmatically. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn SecondarySortColumn { + get { return this.secondarySortColumn; } + set { this.secondarySortColumn = value; } + } + private OLVColumn secondarySortColumn; + + /// + /// When the SecondarySortColumn is used, in what order will it compare results? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder = SortOrder.None; + + /// + /// Gets or sets if all rows should be selected when the user presses Ctrl-A + /// + [Category("ObjectListView"), + Description("Should the control select all rows when the user presses Ctrl-A?"), + DefaultValue(true)] + public virtual bool SelectAllOnControlA { + get { return selectAllOnControlA; } + set { selectAllOnControlA = value; } + } + private bool selectAllOnControlA = true; + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose which columns will be shown in the view? + /// + /// This is just a compatibility wrapper for the SelectColumnsOnRightClickBehaviour + /// property. + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to choose which columns will be shown in the view?"), + DefaultValue(true)] + public virtual bool SelectColumnsOnRightClick { + get { return this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None; } + set { + if (value) { + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.None) + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + } else { + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.None; + } + } + } + + /// + /// Gets or sets how the user will be able to select columns when the header is right clicked + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, how will the user be able to select columns?"), + DefaultValue(ColumnSelectBehaviour.InlineMenu)] + public virtual ColumnSelectBehaviour SelectColumnsOnRightClickBehaviour { + get { return selectColumnsOnRightClickBehaviour; } + set { selectColumnsOnRightClickBehaviour = value; } + } + private ColumnSelectBehaviour selectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + + /// + /// When the column select menu is open, should it stay open after an item is selected? + /// Staying open allows the user to turn more than one column on or off at a time. + /// + /// This only works when SelectColumnsOnRightClickBehaviour is set to InlineMenu. + /// It has no effect when the behaviour is set to SubMenu. + [Category("ObjectListView"), + Description("When the column select inline menu is open, should it stay open after an item is selected?"), + DefaultValue(true)] + public virtual bool SelectColumnsMenuStaysOpen { + get { return selectColumnsMenuStaysOpen; } + set { selectColumnsMenuStaysOpen = value; } + } + private bool selectColumnsMenuStaysOpen = true; + + /// + /// Gets or sets the column that is drawn with a slight tint. + /// + /// + /// + /// If TintSortColumn is true, the sort column will automatically + /// be made the selected column. + /// + /// + /// The colour of the tint is controlled by SelectedColumnTint. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn SelectedColumn { + get { return this.selectedColumn; } + set { + this.selectedColumn = value; + if (value == null) { + this.RemoveDecoration(this.selectedColumnDecoration); + } else { + if (!this.HasDecoration(this.selectedColumnDecoration)) + this.AddDecoration(this.selectedColumnDecoration); + } + } + } + private OLVColumn selectedColumn; + private readonly TintedColumnDecoration selectedColumnDecoration = new TintedColumnDecoration(); + + /// + /// Gets or sets the decoration that will be drawn on all selected rows + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IDecoration SelectedRowDecoration { + get { return this.selectedRowDecoration; } + set { this.selectedRowDecoration = value; } + } + private IDecoration selectedRowDecoration; + + /// + /// What color should be used to tint the selected column? + /// + /// + /// The tint color must be alpha-blendable, so if the given color is solid + /// (i.e. alpha = 255), it will be changed to have a reasonable alpha value. + /// + [Category("ObjectListView"), + Description("The color that will be used to tint the selected column"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedColumnTint { + get { return selectedColumnTint; } + set { + this.selectedColumnTint = value.A == 255 ? Color.FromArgb(15, value) : value; + this.selectedColumnDecoration.Tint = this.selectedColumnTint; + } + } + private Color selectedColumnTint = Color.Empty; + + /// + /// Gets or sets the index of the row that is currently selected. + /// When getting the index, if no row is selected,or more than one is selected, return -1. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int SelectedIndex { + get { return this.SelectedIndices.Count == 1 ? this.SelectedIndices[0] : -1; } + set { + this.SelectedIndices.Clear(); + if (value >= 0 && value < this.Items.Count) + this.SelectedIndices.Add(value); + } + } + + /// + /// Gets or sets the ListViewItem that is currently selected . If no row is selected, or more than one is selected, return null. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVListItem SelectedItem { + get { + return this.SelectedIndices.Count == 1 ? this.GetItem(this.SelectedIndices[0]) : null; + } + set { + this.SelectedIndices.Clear(); + if (value != null) + this.SelectedIndices.Add(value.Index); + } + } + + /// + /// Gets the model object from the currently selected row, if there is only one row selected. + /// If no row is selected, or more than one is selected, returns null. + /// When setting, this will select the row that is displaying the given model object and focus on it. + /// All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object SelectedObject { + get { + return this.SelectedIndices.Count == 1 ? this.GetModelObject(this.SelectedIndices[0]) : null; + } + set { + // If the given model is already selected, don't do anything else (prevents an flicker) + object selectedObject = this.SelectedObject; + if (selectedObject != null && selectedObject.Equals(value)) + return; + + this.SelectedIndices.Clear(); + this.SelectObject(value, true); + } + } + + /// + /// Get the model objects from the currently selected rows. If no row is selected, the returned List will be empty. + /// When setting this value, select the rows that is displaying the given model objects. All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList SelectedObjects { + get { + ArrayList list = new ArrayList(); + foreach (int index in this.SelectedIndices) + list.Add(this.GetModelObject(index)); + return list; + } + set { + this.SelectedIndices.Clear(); + this.SelectObjects(value); + } + } + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose common tasks to perform on the listview? + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to perform common tasks on the listview?"), + DefaultValue(false)] + public virtual bool ShowCommandMenuOnRightClick { + get { return showCommandMenuOnRightClick; } + set { showCommandMenuOnRightClick = value; } + } + private bool showCommandMenuOnRightClick; + + /// + /// Gets or sets whether this ObjectListView will show Excel like filtering + /// menus when the header control is right clicked + /// + [Category("ObjectListView"), + Description("If this is true, right clicking on a column header will show a Filter menu option"), + DefaultValue(true)] + public bool ShowFilterMenuOnRightClick { + get { return showFilterMenuOnRightClick; } + set { showFilterMenuOnRightClick = value; } + } + private bool showFilterMenuOnRightClick = true; + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + public new virtual bool ShowGroups { + get { return base.ShowGroups; } + set { + this.GroupImageList = this.GroupImageList; + base.ShowGroups = value; + } + } + + /// + /// Should the list view show a bitmap in the column header to show the sort direction? + /// + /// + /// The only reason for not wanting to have sort indicators is that, on pre-XP versions of + /// Windows, having sort indicators required the ListView to have a small image list, and + /// as soon as you give a ListView a SmallImageList, the text of column 0 is bumped 16 + /// pixels to the right, even if you never used an image. + /// + [Category("ObjectListView"), + Description("Should the list view show sort indicators in the column headers?"), + DefaultValue(true)] + public virtual bool ShowSortIndicators { + get { return showSortIndicators; } + set { showSortIndicators = value; } + } + private bool showSortIndicators; + + /// + /// Should the list view show images on subitems? + /// + /// + /// Virtual lists have to be owner drawn in order to show images on subitems + /// + [Category("ObjectListView"), + Description("Should the list view show images on subitems?"), + DefaultValue(false)] + public virtual bool ShowImagesOnSubItems { + get { return showImagesOnSubItems; } + set { + showImagesOnSubItems = value; + if (this.Created) + this.ApplyExtendedStyles(); + if (value && this.VirtualMode) + this.OwnerDraw = true; + } + } + private bool showImagesOnSubItems; + + /// + /// This property controls whether group labels will be suffixed with a count of items. + /// + /// + /// The format of the suffix is controlled by GroupWithItemCountFormat/GroupWithItemCountSingularFormat properties + /// + [Category("ObjectListView"), + Description("Will group titles be suffixed with a count of the items in the group?"), + DefaultValue(false)] + public virtual bool ShowItemCountOnGroups { + get { return showItemCountOnGroups; } + set { showItemCountOnGroups = value; } + } + private bool showItemCountOnGroups; + + /// + /// Gets or sets whether the control will show column headers in all + /// views (true), or only in Details view (false) + /// + /// + /// + /// This property is not working correctly. JPP 2010/04/06. + /// It works fine if it is set before the control is created. + /// But if it turned off once the control is created, the control + /// loses its checkboxes (weird!) + /// + /// + /// To changed this setting after the control is created, things + /// are complicated. If it is off and we want it on, we have + /// to change the View and the header will appear. If it is currently + /// on and we want to turn it off, we have to both change the view + /// AND recreate the handle. Recreating the handle is a problem + /// since it makes our checkbox style disappear. + /// + /// + /// This property doesn't work on XP. + /// + [Category("ObjectListView"), + Description("Will the control will show column headers in all views?"), + DefaultValue(true)] + public bool ShowHeaderInAllViews { + get { return ObjectListView.IsVistaOrLater && showHeaderInAllViews; } + set { + if (showHeaderInAllViews == value) + return; + + showHeaderInAllViews = value; + + // If the control isn't already created, everything is fine. + if (!this.Created) + return; + + // If the header is being hidden, we have to recreate the control + // to remove the style (not sure why this is) + if (showHeaderInAllViews) + this.ApplyExtendedStyles(); + else + this.RecreateHandle(); + + // Still more complications. The change doesn't become visible until the View is changed + if (this.View != View.Details) { + View temp = this.View; + this.View = View.Details; + this.View = temp; + } + } + } + private bool showHeaderInAllViews = true; + + /// + /// Override the SmallImageList property so we can correctly shadow its operations. + /// + /// If you use the RowHeight property to specify the row height, the SmallImageList + /// must be fully initialised before setting/changing the RowHeight. If you add new images to the image + /// list after setting the RowHeight, you must assign the imagelist to the control again. Something as simple + /// as this will work: + /// listView1.SmallImageList = listView1.SmallImageList; + /// + public new ImageList SmallImageList { + get { return this.shadowedImageList; } + set { + this.shadowedImageList = value; + if (this.UseSubItemCheckBoxes) + this.SetupSubItemCheckBoxes(); + this.SetupBaseImageList(); + } + } + private ImageList shadowedImageList; + + /// + /// Return the size of the images in the small image list or a reasonable default + /// + [Browsable(false)] + public virtual Size SmallImageSize { + get { + return this.BaseSmallImageList == null ? new Size(16, 16) : this.BaseSmallImageList.ImageSize; + } + } + + /// + /// When the listview is grouped, should the items be sorted by the primary column? + /// If this is false, the items will be sorted by the same column as they are grouped. + /// + /// + /// + /// The primary column is always column 0 and is unrelated to the PrimarySort column. + /// + /// + [Category("ObjectListView"), + Description("When the listview is grouped, should the items be sorted by the primary column? If this is false, the items will be sorted by the same column as they are grouped."), + DefaultValue(true)] + public virtual bool SortGroupItemsByPrimaryColumn { + get { return this.sortGroupItemsByPrimaryColumn; } + set { this.sortGroupItemsByPrimaryColumn = value; } + } + private bool sortGroupItemsByPrimaryColumn = true; + + /// + /// When the listview is grouped, how many pixels should exist between the end of one group and the + /// beginning of the next? + /// + [Category("ObjectListView"), + Description("How many pixels of space will be between groups"), + DefaultValue(0)] + public virtual int SpaceBetweenGroups { + get { return this.spaceBetweenGroups; } + set { + if (this.spaceBetweenGroups == value) + return; + + this.spaceBetweenGroups = value; + this.SetGroupSpacing(); + } + } + private int spaceBetweenGroups; + + private void SetGroupSpacing() { + if (!this.IsHandleCreated) + return; + + NativeMethods.LVGROUPMETRICS metrics = new NativeMethods.LVGROUPMETRICS(); + metrics.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUPMETRICS))); + metrics.mask = (uint)GroupMetricsMask.LVGMF_BORDERSIZE; + metrics.Bottom = (uint)this.SpaceBetweenGroups; + NativeMethods.SetGroupMetrics(this, metrics); + } + + /// + /// Should the sort column show a slight tinge? + /// + [Category("ObjectListView"), + Description("Should the sort column show a slight tinting?"), + DefaultValue(false)] + public virtual bool TintSortColumn { + get { return this.tintSortColumn; } + set { + this.tintSortColumn = value; + if (value && this.PrimarySortColumn != null) + this.SelectedColumn = this.PrimarySortColumn; + else + this.SelectedColumn = null; + } + } + private bool tintSortColumn; + + /// + /// Should each row have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). Otherwise, user clicks + /// alternate between checked and unchecked. CheckStateGetter can still return Indeterminate when this + /// setting is false. + /// + [Category("ObjectListView"), + Description("Should the primary column have a checkbox that behaves as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + this.InitializeStateImageList(); + } + } + private bool triStateCheckBoxes; + + /// + /// Get or set the index of the top item of this listview + /// + /// + /// + /// This property only works when the listview is in Details view and not showing groups. + /// + /// + /// The reason that it does not work when showing groups is that, when groups are enabled, + /// the Windows msg LVM_GETTOPINDEX always returns 0, regardless of the + /// scroll position. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int TopItemIndex { + get { + if (this.View == View.Details && this.IsHandleCreated) + return NativeMethods.GetTopIndex(this); + + return -1; + } + set { + int newTopIndex = Math.Min(value, this.GetItemCount() - 1); + if (this.View != View.Details || newTopIndex < 0) + return; + + try { + this.TopItem = this.Items[newTopIndex]; + + // Setting the TopItem sometimes gives off by one errors, + // that (bizarrely) are correct on a second attempt + if (this.TopItem != null && this.TopItem.Index != newTopIndex) + this.TopItem = this.GetItem(newTopIndex); + } + catch (NullReferenceException) { + // There is a bug in the .NET code where setting the TopItem + // will sometimes throw null reference exceptions + // There is nothing we can do to get around it. + } + } + } + + /// + /// Gets or sets whether moving the mouse over the header will trigger CellOver events. + /// Defaults to true. + /// + /// + /// Moving the mouse over the header did not previously trigger CellOver events, since the + /// header is considered a separate control. + /// If this change in behaviour causes your application problems, set this to false. + /// If you are interested in knowing when the mouse moves over the header, set this property to true (the default). + /// + [Category("ObjectListView"), + Description("Should moving the mouse over the header trigger CellOver events?"), + DefaultValue(true)] + public bool TriggerCellOverEventsWhenOverHeader + { + get { return triggerCellOverEventsWhenOverHeader; } + set { triggerCellOverEventsWhenOverHeader = value; } + } + private bool triggerCellOverEventsWhenOverHeader = true; + + /// + /// When resizing a column by dragging its divider, should any space filling columns be + /// resized at each mouse move? If this is false, the filling columns will be + /// updated when the mouse is released. + /// + /// + /// + /// If you have a space filling column + /// is in the left of the column that is being resized, this will look odd: + /// the right edge of the column will be dragged, but + /// its left edge will move since the space filling column is shrinking. + /// + /// This is logical behaviour -- it just looks wrong. + /// + /// + /// Given the above behavior is probably best to turn this property off if your space filling + /// columns aren't the right-most columns. + /// + [Category("ObjectListView"), + Description("When resizing a column by dragging its divider, should any space filling columns be resized at each mouse move?"), + DefaultValue(true)] + public virtual bool UpdateSpaceFillingColumnsWhenDraggingColumnDivider { + get { return updateSpaceFillingColumnsWhenDraggingColumnDivider; } + set { updateSpaceFillingColumnsWhenDraggingColumnDivider = value; } + } + private bool updateSpaceFillingColumnsWhenDraggingColumnDivider = true; + + /// + /// What color should be used for the background of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The background color of selected rows when the control doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedBackColor { + get { return this.unfocusedSelectedBackColor; } + set { this.unfocusedSelectedBackColor = value; } + } + private Color unfocusedSelectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedBackColorOrDefault { + get { + return this.UnfocusedSelectedBackColor.IsEmpty ? SystemColors.Control : this.UnfocusedSelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows when the control is owner drawn and doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedForeColor { + get { return this.unfocusedSelectedForeColor; } + set { this.unfocusedSelectedForeColor = value; } + } + private Color unfocusedSelectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedForeColorOrDefault { + get { + return this.UnfocusedSelectedForeColor.IsEmpty ? SystemColors.ControlText : this.UnfocusedSelectedForeColor; + } + } + + /// + /// Gets or sets whether the list give a different background color to every second row? Defaults to false. + /// + /// The color of the alternate rows is given by AlternateRowBackColor. + /// There is a "feature" in .NET for listviews in non-full-row-select mode, where + /// selected rows are not drawn with their correct background color. + [Category("ObjectListView"), + Description("Should the list view use a different backcolor to alternate rows?"), + DefaultValue(false)] + public virtual bool UseAlternatingBackColors { + get { return useAlternatingBackColors; } + set { useAlternatingBackColors = value; } + } + private bool useAlternatingBackColors; + + /// + /// Should FormatCell events be called for each cell in the control? + /// + /// + /// In many situations, no cell level formatting is performed. ObjectListView + /// can run somewhat faster if it does not trigger a format cell event for every cell + /// unless it is required. So, by default, it does not raise an event for each cell. + /// + /// ObjectListView *does* raise a FormatRow event every time a row is rebuilt. + /// Individual rows can decide whether to raise FormatCell + /// events for every cell in row. + /// + /// + /// Regardless of this setting, FormatCell events are only raised when the ObjectListView + /// is in Details view. + /// + [Category("ObjectListView"), + Description("Should FormatCell events be triggered to every cell that is built?"), + DefaultValue(false)] + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + private bool useCellFormatEvents; + + /// + /// Should the selected row be drawn with non-standard foreground and background colors? + /// + /// v2.9 This property is no longer required + [Category("ObjectListView"), + Description("Should the selected row be drawn with non-standard foreground and background colors?"), + DefaultValue(false)] + public bool UseCustomSelectionColors { + get { return false; } + // ReSharper disable once ValueParameterNotUsed + set { } + } + + /// + /// Gets or sets whether this ObjectListView will use the same hot item and selection + /// mechanism that Vista Explorer does. + /// + /// + /// + /// This property has many imperfections: + /// + /// This only works on Vista and later + /// It does not work well with AlternateRowBackColors. + /// It does not play well with HotItemStyles. + /// It looks a little bit silly is FullRowSelect is false. + /// It doesn't work at all when the list is owner drawn (since the renderers + /// do all the drawing). As such, it won't work with TreeListView's since they *have to be* + /// owner drawn. You can still set it, but it's just not going to be happy. + /// + /// But if you absolutely have to look like Vista/Win7, this is your property. + /// Do not complain if settings this messes up other things. + /// + /// + /// When this property is set to true, the ObjectListView will be not owner drawn. This will + /// disable many of the pretty drawing-based features of ObjectListView. + /// + /// Because of the above, this property should never be set to true for TreeListViews, + /// since they *require* owner drawing to be rendered correctly. + /// + [Category("ObjectListView"), + Description("Should the list use the same hot item and selection mechanism as Vista?"), + DefaultValue(false)] + public bool UseExplorerTheme { + get { return useExplorerTheme; } + set { + useExplorerTheme = value; + if (this.Created) + NativeMethods.SetWindowTheme(this.Handle, value ? "explorer" : "", null); + + this.OwnerDraw = !value; + } + } + private bool useExplorerTheme; + + /// + /// Gets or sets whether the list should enable filtering + /// + [Category("ObjectListView"), + Description("Should the list enable filtering?"), + DefaultValue(false)] + public virtual bool UseFiltering { + get { return useFiltering; } + set { + if (useFiltering == value) + return; + useFiltering = value; + this.UpdateFiltering(); + } + } + private bool useFiltering; + + /// + /// Gets or sets whether the list should put an indicator into a column's header to show that + /// it is filtering on that column + /// + /// If you set this to true, HeaderUsesThemes is automatically set to false, since + /// we can only draw a filter indicator when not using a themed header. + [Category("ObjectListView"), + Description("Should an image be drawn in a column's header when that column is being used for filtering?"), + DefaultValue(false)] + public virtual bool UseFilterIndicator { + get { return useFilterIndicator; } + set { + if (this.useFilterIndicator == value) + return; + useFilterIndicator = value; + if (this.useFilterIndicator) + this.HeaderUsesThemes = false; + this.Invalidate(); + } + } + private bool useFilterIndicator; + + /// + /// Should controls (checkboxes or buttons) that are under the mouse be drawn "hot"? + /// + /// + /// If this is false, control will not be drawn differently when the mouse is over them. + /// + /// If this is false AND UseHotItem is false AND UseHyperlinks is false, then the ObjectListView + /// can skip some processing on mouse move. This make mouse move processing use almost no CPU. + /// + /// + [Category("ObjectListView"), + Description("Should controls (checkboxes or buttons) that are under the mouse be drawn hot?"), + DefaultValue(true)] + public bool UseHotControls { + get { return this.useHotControls; } + set { this.useHotControls = value; } + } + private bool useHotControls = true; + + /// + /// Should the item under the cursor be formatted in a special way? + /// + [Category("ObjectListView"), + Description("Should HotTracking be used? Hot tracking applies special formatting to the row under the cursor"), + DefaultValue(false)] + public bool UseHotItem { + get { return this.useHotItem; } + set { + this.useHotItem = value; + if (value) + this.AddOverlay(this.HotItemStyleOrDefault.Overlay); + else + this.RemoveOverlay(this.HotItemStyleOrDefault.Overlay); + } + } + private bool useHotItem; + + /// + /// Gets or sets whether this listview should show hyperlinks in the cells. + /// + [Category("ObjectListView"), + Description("Should hyperlinks be shown on this control?"), + DefaultValue(false)] + public bool UseHyperlinks { + get { return this.useHyperlinks; } + set { + this.useHyperlinks = value; + if (value && this.HyperlinkStyle == null) + this.HyperlinkStyle = new HyperlinkStyle(); + } + } + private bool useHyperlinks; + + /// + /// Should this control show overlays + /// + /// Overlays are enabled by default and would only need to be disabled + /// if they were causing problems in your development environment. + [Category("ObjectListView"), + Description("Should this control show overlays"), + DefaultValue(true)] + public bool UseOverlays { + get { return this.useOverlays; } + set { this.useOverlays = value; } + } + private bool useOverlays = true; + + /// + /// Should this control be configured to show check boxes on subitems? + /// + /// If this is set to True, the control will be given a SmallImageList if it + /// doesn't already have one. Also, if it is a virtual list, it will be set to owner + /// drawn, since virtual lists can't draw check boxes without being owner drawn. + [Category("ObjectListView"), + Description("Should this control be configured to show check boxes on subitems."), + DefaultValue(false)] + public bool UseSubItemCheckBoxes { + get { return this.useSubItemCheckBoxes; } + set { + this.useSubItemCheckBoxes = value; + if (value) + this.SetupSubItemCheckBoxes(); + } + } + private bool useSubItemCheckBoxes; + + /// + /// Gets or sets if the ObjectListView will use a translucent selection mechanism like Vista. + /// + /// + /// + /// Unlike UseExplorerTheme, this Vista-like scheme works on XP and for both + /// owner and non-owner drawn lists. + /// + /// + /// This will replace any SelectedRowDecoration that has been installed. + /// + /// + /// If you don't like the colours used for the selection, ignore this property and + /// just create your own RowBorderDecoration and assigned it to SelectedRowDecoration, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent selection mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentSelection { + get { return useTranslucentSelection; } + set { + useTranslucentSelection = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.FillBrush = new SolidBrush(Color.FromArgb(48, 163, 217, 225)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + this.SelectedRowDecoration = rbd; + } else + this.SelectedRowDecoration = null; + } + } + private bool useTranslucentSelection; + + /// + /// Gets or sets if the ObjectListView will use a translucent hot row highlighting mechanism like Vista. + /// + /// + /// + /// Setting this will replace any HotItemStyle that has been installed. + /// + /// + /// If you don't like the colours used for the hot item, ignore this property and + /// just create your own HotItemStyle, fill in the values you want, and assigned it to HotItemStyle property, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent hot row highlighting mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentHotItem { + get { return useTranslucentHotItem; } + set { + useTranslucentHotItem = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + rbd.FillGradientFrom = Color.FromArgb(0, 255, 255, 255); + rbd.FillGradientTo = Color.FromArgb(64, 183, 237, 240); + HotItemStyle his = new HotItemStyle(); + his.Decoration = rbd; + this.HotItemStyle = his; + } else + this.HotItemStyle = null; + this.UseHotItem = value; + } + } + private bool useTranslucentHotItem; + + /// + /// Get/set the style of view that this listview is using + /// + /// Switching to tile or details view installs the columns appropriate to that view. + /// Confusingly, in tile view, every column is shown as a row of information. + [Category("Appearance"), + Description("Select the layout of the items within this control)"), + DefaultValue(null)] + public new View View + { + get { return base.View; } + set { + if (base.View == value) + return; + + if (this.Frozen) { + base.View = value; + this.SetupBaseImageList(); + } else { + this.Freeze(); + + if (value == View.Tile) + this.CalculateReasonableTileSize(); + + base.View = value; + this.SetupBaseImageList(); + this.Unfreeze(); + } + } + } + + #endregion + + #region Callbacks + + /// + /// This delegate fetches the checkedness of an object as a boolean only. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStateGetter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.CheckStateGetter = null; + else + this.CheckStateGetter = delegate(Object x) { + return value(x) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// This delegate sets the checkedness of an object as a boolean only. It must return + /// true or false indicating if the object was checked or not. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStatePutter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.CheckStatePutter = null; + else + this.CheckStatePutter = delegate(Object x, CheckState state) { + bool isChecked = (state == CheckState.Checked); + return value(x, isChecked) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public virtual bool CanShowGroups { + get { + return true; + } + } + + /// + /// Gets or sets whether ObjectListView can rely on Application.Idle events + /// being raised. + /// + /// In some host environments (e.g. when running as an extension within + /// VisualStudio and possibly Office), Application.Idle events are never raised. + /// Set this to false when Idle events will not be raised, and ObjectListView will + /// raise those events itself. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CanUseApplicationIdle { + get { return this.canUseApplicationIdle; } + set { this.canUseApplicationIdle = value; } + } + private bool canUseApplicationIdle = true; + + /// + /// This delegate fetches the renderer for a particular cell. + /// + /// + /// + /// If this returns null (or is not installed), the renderer for the column will be used. + /// If the column renderer is null, then will be used. + /// + /// + /// This is called every time any cell is drawn. It must be efficient! + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellRendererGetterDelegate CellRendererGetter + { + get { return this.cellRendererGetter; } + set { this.cellRendererGetter = value; } + } + private CellRendererGetterDelegate cellRendererGetter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular cell. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to show the full text of truncated cell values). + /// + /// + /// Displaying the full text of truncated cell values only work for FullRowSelect listviews. + /// This is MS's behavior, not mine. Don't complain to me :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellToolTipGetterDelegate CellToolTipGetter { + get { return cellToolTipGetter; } + set { cellToolTipGetter = value; } + } + private CellToolTipGetterDelegate cellToolTipGetter; + + /// + /// The name of the property (or field) that holds whether or not a model is checked. + /// + /// + /// The property be modifiable. It must have a return type of bool (or of bool? if + /// TriStateCheckBoxes is true). + /// Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed. + /// Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence + /// over the behavior of this property. + /// + [Category("ObjectListView"), + Description("The name of the property or field that holds the 'checkedness' of the model"), + DefaultValue(null)] + public virtual string CheckedAspectName { + get { return checkedAspectName; } + set { + checkedAspectName = value; + if (String.IsNullOrEmpty(checkedAspectName)) { + this.checkedAspectMunger = null; + this.CheckStateGetter = null; + this.CheckStatePutter = null; + } else { + this.checkedAspectMunger = new Munger(checkedAspectName); + this.CheckStateGetter = delegate(Object modelObject) { + bool? result = this.checkedAspectMunger.GetValue(modelObject) as bool?; + if (result.HasValue) + return result.Value ? CheckState.Checked : CheckState.Unchecked; + return this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + }; + this.CheckStatePutter = delegate(Object modelObject, CheckState newValue) { + if (this.TriStateCheckBoxes && newValue == CheckState.Indeterminate) + this.checkedAspectMunger.PutValue(modelObject, null); + else + this.checkedAspectMunger.PutValue(modelObject, newValue == CheckState.Checked); + return this.CheckStateGetter(modelObject); + }; + } + } + } + private string checkedAspectName; + private Munger checkedAspectMunger; + + /// + /// This delegate will be called whenever the ObjectListView needs to know the check state + /// of the row associated with a given model object. + /// + /// + /// .NET has no support for indeterminate values, but as of v2.0, this class allows + /// indeterminate values. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { checkStateGetter = value; } + } + private CheckStateGetterDelegate checkStateGetter; + + /// + /// This delegate will be called whenever the user tries to change the check state of a row. + /// The delegate should return the state that was actually set, which may be different + /// to the state given. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { checkStatePutter = value; } + } + private CheckStatePutterDelegate checkStatePutter; + + /// + /// This delegate can be used to sort the table in a custom fashion. + /// + /// + /// + /// The delegate must install a ListViewItemSorter on the ObjectListView. + /// Installing the ItemSorter does the actual work of sorting the ListViewItems. + /// See ColumnComparer in the code for an example of what an ItemSorter has to do. + /// + /// + /// Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects() + /// method of the IVirtualListDataSource instead. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortDelegate CustomSorter { + get { return customSorter; } + set { customSorter = value; } + } + private SortDelegate customSorter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular header. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to not show any tooltip). + /// + /// + /// Installing a HeaderToolTipGetter takes precedence over any text in OLVColumn.ToolTipText. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return headerToolTipGetter; } + set { headerToolTipGetter = value; } + } + private HeaderToolTipGetterDelegate headerToolTipGetter; + + /// + /// This delegate can be used to format a OLVListItem before it is added to the control. + /// + /// + /// The model object for the row can be found through the RowObject property of the OLVListItem object. + /// All subitems normally have the same style as list item, so setting the forecolor on one + /// subitem changes the forecolor of all subitems. + /// To allow subitems to have different attributes, do this: + /// myListViewItem.UseItemStyleForSubItems = false;. + /// + /// If UseAlternatingBackColors is true, the backcolor of the listitem will be calculated + /// by the control and cannot be controlled by the RowFormatter delegate. + /// In general, trying to use a RowFormatter + /// when UseAlternatingBackColors is true does not work well. + /// As it says in the summary, this is called before the item is added to the control. + /// Many properties of the OLVListItem itself are not available at that point, including: + /// Index, Selected, Focused, Bounds, Checked, DisplayIndex. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowFormatterDelegate RowFormatter { + get { return rowFormatter; } + set { rowFormatter = value; } + } + private RowFormatterDelegate rowFormatter; + + #endregion + + #region List commands + + /// + /// Add the given model object to this control. + /// + /// The model object to be displayed + /// See AddObjects() for more details + public virtual void AddObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.AddObject(modelObject); }); + else + this.AddObjects(new object[] { modelObject }); + } + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public virtual void AddObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.AddObjects(modelObjects); }); + return; + } + this.InsertObjects(ObjectListView.EnumerableCount(this.Objects), modelObjects); + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Resize the columns to the maximum of the header width and the data. + /// + public virtual void AutoResizeColumns() { + foreach (OLVColumn c in this.Columns) { + this.AutoResizeColumn(c.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + } + } + + /// + /// Set up any automatically initialized column widths (columns that + /// have a width of 0 or -1 will be resized to the width of their + /// contents or header respectively). + /// + /// + /// Obviously, this will only work once. Once it runs, the columns widths will + /// be changed to something else (other than 0 or -1), so it wont do anything the + /// second time through. Use to force all columns + /// to change their size. + /// + public virtual void AutoSizeColumns() { + // If we are supposed to resize to content, but if there is no content, + // resize to the header size instead. + ColumnHeaderAutoResizeStyle resizeToContentStyle = this.GetItemCount() == 0 ? + ColumnHeaderAutoResizeStyle.HeaderSize : + ColumnHeaderAutoResizeStyle.ColumnContent; + foreach (ColumnHeader column in this.Columns) { + switch (column.Width) { + case 0: + this.AutoResizeColumn(column.Index, resizeToContentStyle); + break; + case -1: + this.AutoResizeColumn(column.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + break; + } + } + } + + /// + /// Organise the view items into groups, based on the last sort column or the first column + /// if there is no last sort column + /// + public virtual void BuildGroups() { + this.BuildGroups(this.PrimarySortColumn, this.PrimarySortOrder == SortOrder.None ? SortOrder.Ascending : this.PrimarySortOrder); + } + + /// + /// Organise the view items into groups, based on the given column + /// + /// + /// + /// If the AlwaysGroupByColumn property is not null, + /// the list view items will be organised by that column, + /// and the 'column' parameter will be ignored. + /// + /// This method triggers sorting events: BeforeSorting and AfterSorting. + /// + /// The column whose values should be used for sorting. + /// + public virtual void BuildGroups(OLVColumn column, SortOrder order) { + // Sanity + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(column, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, + args.ColumnToSort, args.SortOrder, args.SecondaryColumnToSort, args.SecondarySortOrder); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + private BeforeSortingEventArgs BuildBeforeSortingEventArgs(OLVColumn column, SortOrder order) { + OLVColumn groupBy = this.AlwaysGroupByColumn ?? column ?? this.GetColumn(0); + SortOrder groupByOrder = this.AlwaysGroupBySortOrder; + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + if (groupByOrder == SortOrder.None) + groupByOrder = order; + + BeforeSortingEventArgs args = new BeforeSortingEventArgs( + groupBy, groupByOrder, + column, order, + this.SecondarySortColumn ?? this.GetColumn(0), + this.SecondarySortOrder == SortOrder.None ? order : this.SecondarySortOrder); + if (column != null) + args.Canceled = !column.Sortable; + return args; + } + + /// + /// Organise the view items into groups, based on the given columns + /// + /// What column will be used for grouping + /// What ordering will be used for groups + /// The column whose values should be used for sorting. Cannot be null + /// The order in which the values from column will be sorted + /// When the values from 'column' are equal, use the values provided by this column + /// How will the secondary values be sorted + /// This method does not trigger sorting events. Use BuildGroups() to do that + public virtual void BuildGroups(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + // Sanity checks + if (groupByColumn == null) + return; + + // Getting the Count forces any internal cache of the ListView to be flushed. Without + // this, iterating over the Items will not work correctly if the ListView handle + // has not yet been created. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int dummy = this.Items.Count; +#pragma warning restore 168 + + // Collect all the information that governs the creation of groups + GroupingParameters parms = this.CollectGroupingParameters(groupByColumn, groupByOrder, + column, order, secondaryColumn, secondaryOrder); + + // Trigger an event to let the world create groups if they want + CreateGroupsEventArgs args = new CreateGroupsEventArgs(parms); + if (parms.GroupByColumn != null) + args.Canceled = !parms.GroupByColumn.Groupable; + this.OnBeforeCreatingGroups(args); + if (args.Canceled) + return; + + // If the event didn't create them for us, use our default strategy + if (args.Groups == null) + args.Groups = this.MakeGroups(parms); + + // Give the world a chance to munge the groups before they are created + this.OnAboutToCreateGroups(args); + if (args.Canceled) + return; + + // Create the groups now + this.OLVGroups = args.Groups; + this.CreateGroups(args.Groups); + + // Tell the world that new groups have been created + this.OnAfterCreatingGroups(args); + lastGroupingParameters = args.Parameters; + } + private GroupingParameters lastGroupingParameters; + + /// + /// Collect and return all the variables that influence the creation of groups + /// + /// + protected virtual GroupingParameters CollectGroupingParameters(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn sortByColumn, SortOrder sortByOrder, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + + // If the user tries to group by a non-groupable column, keep the current group by + // settings, but use the non-groupable column for sorting + if (!groupByColumn.Groupable && lastGroupingParameters != null) { + sortByColumn = groupByColumn; + sortByOrder = groupByOrder; + groupByColumn = lastGroupingParameters.GroupByColumn; + groupByOrder = lastGroupingParameters.GroupByOrder; + } + + string titleFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountFormatOrDefault : null; + string titleSingularFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountSingularFormatOrDefault : null; + GroupingParameters parms = new GroupingParameters(this, groupByColumn, groupByOrder, + sortByColumn, sortByOrder, secondaryColumn, secondaryOrder, + titleFormat, titleSingularFormat, + this.SortGroupItemsByPrimaryColumn && this.AlwaysGroupByColumn == null); + return parms; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// The list of groups to be created + /// This should not change the state of the control. It is possible that the + /// groups created will not be used. They may simply be discarded. + protected virtual IList MakeGroups(GroupingParameters parms) { + + // There is a lot of overlap between this method and FastListGroupingStrategy.MakeGroups() + // Any changes made here may need to be reflected there + + // Separate the list view items into groups, using the group key as the descrimanent + NullableDictionary> map = new NullableDictionary>(); + foreach (OLVListItem olvi in parms.ListView.Items) { + object key = parms.GroupByColumn.GetGroupKey(olvi.RowObject); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(olvi); + } + + // Sort the items within each group (unless specifically turned off) + OLVColumn sortColumn = parms.SortItemsByPrimaryColumn ? parms.ListView.GetColumn(0) : parms.PrimarySort; + if (sortColumn != null && parms.PrimarySortOrder != SortOrder.None) { + IComparer itemSorter = parms.ItemComparer ?? + new ColumnComparer(sortColumn, parms.PrimarySortOrder, parms.SecondarySort, parms.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(itemSorter); + } + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parms.CreateGroup(key, map[key].Count, HasCollapsibleGroups); + lvg.Items = map[key]; + if (parms.GroupByColumn.GroupFormatter != null) + parms.GroupByColumn.GroupFormatter(lvg, parms); + groups.Add(lvg); + } + + // Sort the groups + if (parms.GroupByOrder != SortOrder.None) + groups.Sort(parms.GroupComparer ?? new OLVGroupComparer(parms.GroupByOrder)); + + return groups; + } + + /// + /// Build/rebuild all the list view items in the list, preserving as much state as is possible + /// + public virtual void BuildList() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.BuildList)); + else + this.BuildList(true); + } + + /// + /// Build/rebuild all the list view items in the list + /// + /// If this is true, the control will try to preserve the selection, + /// focused item, and the scroll position (see Remarks) + /// + /// + /// + /// Use this method in situations were the contents of the list is basically the same + /// as previously. + /// + /// + public virtual void BuildList(bool shouldPreserveState) { + if (this.Frozen) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + this.ApplyExtendedStyles(); + this.ClearHotItem(); + int previousTopIndex = this.TopItemIndex; + Point currentScrollPosition = this.LowLevelScrollPosition; + + IList previousSelection = new ArrayList(); + Object previousFocus = null; + if (shouldPreserveState && this.objects != null) { + previousSelection = this.SelectedObjects; + OLVListItem focusedItem = this.FocusedItem as OLVListItem; + if (focusedItem != null) + previousFocus = focusedItem.RowObject; + } + + IEnumerable objectsToDisplay = this.FilteredObjects; + + this.BeginUpdate(); + try { + this.Items.Clear(); + this.ListViewItemSorter = null; + + if (objectsToDisplay != null) { + // Build a list of all our items and then display them. (Building + // a list and then doing one AddRange is about 10-15% faster than individual adds) + List itemList = new List(); // use ListViewItem to avoid co-variant conversion + foreach (object rowObject in objectsToDisplay) { + OLVListItem lvi = new OLVListItem(rowObject); + this.FillInValues(lvi, rowObject); + itemList.Add(lvi); + } + this.Items.AddRange(itemList.ToArray()); + this.Sort(); + + if (shouldPreserveState) { + this.SelectedObjects = previousSelection; + this.FocusedItem = this.ModelToItem(previousFocus); + } + } + } finally { + this.EndUpdate(); + } + + this.RefreshHotItem(); + + // We can only restore the scroll position after the EndUpdate() because + // of caching that the ListView does internally during a BeginUpdate/EndUpdate pair. + if (shouldPreserveState) { + // Restore the scroll position. TopItemIndex is best, but doesn't work + // when the control is grouped. + if (this.ShowGroups) + this.LowLevelScroll(currentScrollPosition.X, currentScrollPosition.Y); + else + this.TopItemIndex = previousTopIndex; + } + + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Building list for {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + /// + /// Clear any cached info this list may have been using + /// + public virtual void ClearCachedInfo() + { + // ObjectListView doesn't currently cache information but subclass do (or might) + } + + /// + /// Apply all required extended styles to our control. + /// + /// + /// + /// Whenever .NET code sets an extended style, it erases all other extended styles + /// that it doesn't use. So, we have to explicit reapply the styles that we have + /// added. + /// + /// + /// Normally, we would override CreateParms property and update + /// the ExStyle member, but ListView seems to ignore all ExStyles that + /// it doesn't already know about. Worse, when we set the LVS_EX_HEADERINALLVIEWS + /// value, bad things happen (the control crashes!). + /// + /// + protected virtual void ApplyExtendedStyles() { + const int LVS_EX_SUBITEMIMAGES = 0x00000002; + //const int LVS_EX_TRANSPARENTBKGND = 0x00400000; + const int LVS_EX_HEADERINALLVIEWS = 0x02000000; + + const int STYLE_MASK = LVS_EX_SUBITEMIMAGES | LVS_EX_HEADERINALLVIEWS; + int style = 0; + + if (this.ShowImagesOnSubItems && !this.VirtualMode) + style ^= LVS_EX_SUBITEMIMAGES; + + if (this.ShowHeaderInAllViews) + style ^= LVS_EX_HEADERINALLVIEWS; + + NativeMethods.SetExtendedStyle(this, style, STYLE_MASK); + } + + /// + /// Give the listview a reasonable size of its tiles, based on the number of lines of + /// information that each tile is going to display. + /// + public virtual void CalculateReasonableTileSize() { + if (this.Columns.Count <= 0) + return; + + List columns = this.AllColumns.FindAll(delegate(OLVColumn x) { + return (x.Index == 0) || x.IsTileViewColumn; + }); + + int imageHeight = (this.LargeImageList == null ? 16 : this.LargeImageList.ImageSize.Height); + int dataHeight = (this.Font.Height + 1) * columns.Count; + int tileWidth = (this.TileSize.Width == 0 ? 200 : this.TileSize.Width); + int tileHeight = Math.Max(this.TileSize.Height, Math.Max(imageHeight, dataHeight)); + this.TileSize = new Size(tileWidth, tileHeight); + } + + /// + /// Rebuild this list for the given view + /// + /// + public virtual void ChangeToFilteredColumns(View view) { + // Store the state + this.SuspendSelectionEvents(); + IList previousSelection = this.SelectedObjects; + int previousTopIndex = this.TopItemIndex; + + this.Freeze(); + this.Clear(); + List columns = this.GetFilteredColumns(view); + if (view == View.Details || this.ShowHeaderInAllViews) { + // Make sure all columns have a reasonable LastDisplayIndex + for (int index = 0; index < columns.Count; index++) + { + if (columns[index].LastDisplayIndex == -1) + columns[index].LastDisplayIndex = index; + } + // ListView will ignore DisplayIndex FOR ALL COLUMNS if there are any errors, + // e.g. duplicates (two columns with the same DisplayIndex) or gaps. + // LastDisplayIndex isn't guaranteed to be unique, so we just sort the columns by + // the last position they were displayed and use that to generate a sequence + // we can use for the DisplayIndex values. + List columnsInDisplayOrder = new List(columns); + columnsInDisplayOrder.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + int i = 0; + foreach (OLVColumn col in columnsInDisplayOrder) + col.DisplayIndex = i++; + } + +// ReSharper disable once CoVariantArrayConversion + this.Columns.AddRange(columns.ToArray()); + if (view == View.Details || this.ShowHeaderInAllViews) + this.ShowSortIndicator(); + this.UpdateFiltering(); + this.Unfreeze(); + + // Restore the state + this.SelectedObjects = previousSelection; + this.TopItemIndex = previousTopIndex; + this.ResumeSelectionEvents(); + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public virtual void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else + this.SetObjects(null); + } + + /// + /// Reset the memory of which URLs have been visited + /// + public virtual void ClearUrlVisited() { + this.visitedUrlMap = new Dictionary(); + } + + /// + /// Copy a text and html representation of the selected rows onto the clipboard. + /// + /// Be careful when using this with virtual lists. If the user has selected + /// 10,000,000 rows, this method will faithfully try to copy all of them to the clipboard. + /// From the user's point of view, your program will appear to have hung. + public virtual void CopySelectionToClipboard() { + IList selection = this.SelectedObjects; + if (selection.Count == 0) + return; + + // Use the DragSource object to create the data object, if so configured. + // This relies on the assumption that DragSource will handle the selected objects only. + // It is legal for StartDrag to return null. + object data = null; + if (this.CopySelectionOnControlCUsesDragSource && this.DragSource != null) + data = this.DragSource.StartDrag(this, MouseButtons.Left, this.ModelToItem(selection[0])); + + Clipboard.SetDataObject(data ?? new OLVDataObject(this, selection)); + } + + /// + /// Copy a text and html representation of the given objects onto the clipboard. + /// + public virtual void CopyObjectsToClipboard(IList objectsToCopy) { + if (objectsToCopy.Count == 0) + return; + + // We don't know where these objects came from, so we can't use the DragSource to create + // the data object, like we do with CopySelectionToClipboard() above. + OLVDataObject dataObject = new OLVDataObject(this, objectsToCopy); + dataObject.CreateTextFormats(); + Clipboard.SetDataObject(dataObject); + } + + /// + /// Return a html representation of the given objects + /// + public virtual string ObjectsToHtml(IList objectsToConvert) { + if (objectsToConvert.Count == 0) + return String.Empty; + + OLVExporter exporter = new OLVExporter(this, objectsToConvert); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Deselect all rows in the listview + /// + public virtual void DeselectAll() { + NativeMethods.DeselectAllItems(this); + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A ListViewItem + public virtual OLVListItem GetNextItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + bool isFound = (itemToFind == null); + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + if (isFound) + return olvi; + isFound = (itemToFind == olvi); + } + } + return null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(0); + if (itemToFind.Index == this.GetItemCount() - 1) + return null; + return this.GetItem(itemToFind.Index + 1); + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public virtual OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return this.GetItem(this.GetItemCount() - 1); + + if (this.Groups.Count > 0) { + ListViewGroup lastGroup = this.Groups[this.Groups.Count - 1]; + if (lastGroup.Items.Count > 0) + return (OLVListItem)lastGroup.Items[lastGroup.Items.Count - 1]; + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.Groups.Count == 0) + return this.GetItem(n); + + foreach (ListViewGroup group in this.Groups) { + if (n < group.Items.Count) + return (OLVListItem)group.Items[n]; + + n -= group.Items.Count; + } + + return null; + } + + /// + /// Return the display index of the given listviewitem index. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups || this.Groups.Count == 0) + return itemIndex; + + // TODO: This could be optimized + int i = 0; + foreach (ListViewGroup lvg in this.Groups) { + foreach (ListViewItem lvi in lvg.Items) { + if (lvi.Index == itemIndex) + return i; + i++; + } + } + + return -1; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public virtual OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + OLVListItem previousItem = null; + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem lvi in group.Items) { + if (lvi == itemToFind) + return previousItem; + + previousItem = lvi; + } + } + return itemToFind == null ? previousItem : null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(this.GetItemCount() - 1); + if (itemToFind.Index == 0) + return null; + return this.GetItem(itemToFind.Index - 1); + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// + /// + /// This operation only makes sense of non-sorted, non-grouped + /// lists, since any subsequent sort/group operation will rearrange + /// the list. + /// + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { + this.InsertObjects(index, modelObjects); + }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToAdd; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + // If we are filtering the list, there is no way to efficiently + // insert the objects, so just put them into our collection and rebuild. + // Sigh -- yet another ListView anomoly. In every view except Details, an item + // inserted into the Items collection always appear at the end regardless of + // their actual insertion index. + if (this.IsFiltering || this.View != View.Details) { + index = Math.Max(0, Math.Min(index, ourObjects.Count)); + ourObjects.InsertRange(index, modelObjects); + this.BuildList(true); + } else { + this.ListViewItemSorter = null; + index = Math.Max(0, Math.Min(index, this.GetItemCount())); + int i = index; + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + ourObjects.Insert(i, modelObject); + OLVListItem lvi = new OLVListItem(modelObject); + this.FillInValues(lvi, modelObject); + this.Items.Insert(i, lvi); + i++; + } + } + + for (i = index; i < this.GetItemCount(); i++) { + OLVListItem lvi = this.GetItem(i); + this.SetSubItemImages(lvi.Index, lvi); + } + + this.PostProcessRows(); + } + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Return true if the row representing the given model is selected + /// + /// The model object to look for + /// Is the row selected + public bool IsSelected(object model) { + OLVListItem item = this.ModelToItem(model); + return item != null && item.Selected; + } + + /// + /// Has the given URL been visited? + /// + /// The string to be consider + /// Has it been visited + public virtual bool IsUrlVisited(string url) { + return this.visitedUrlMap.ContainsKey(url); + } + + /// + /// Scroll the ListView by the given deltas. + /// + /// Horizontal delta + /// Vertical delta + public void LowLevelScroll(int dx, int dy) { + NativeMethods.Scroll(this, dx, dy); + } + + /// + /// Return a point that represents the current horizontal and vertical scroll positions + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Point LowLevelScrollPosition + { + get { + return new Point(NativeMethods.GetScrollPosition(this, true), NativeMethods.GetScrollPosition(this, false)); + } + } + + /// + /// Remember that the given URL has been visited + /// + /// The url to be remembered + /// This does not cause the control be redrawn + public virtual void MarkUrlVisited(string url) { + this.visitedUrlMap[url] = true; + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public virtual void MoveObjects(int index, ICollection modelObjects) { + + // We are going to remove all the given objects from our list + // and then insert them at the given location + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = this.IndexOf(modelObject); + if (i >= 0) { + indicesToRemove.Add(i); + ourObjects.Remove(modelObject); + if (i <= index) + index--; + } + } + } + + // Remove the objects in reverse order so earlier + // deletes don't change the index of later ones + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + try { + this.BeginUpdate(); + foreach (int i in indicesToRemove) { + this.Items.RemoveAt(i); + } + this.InsertObjects(index, modelObjects); + } finally { + this.EndUpdate(); + } + } + + /// + /// Calculate what item is under the given point? + /// + /// + /// + /// + public new ListViewHitTestInfo HitTest(int x, int y) { + // Everything costs something. Playing with the layout of the header can cause problems + // with the hit testing. If the header shrinks, the underlying control can throw a tantrum. + try { + return base.HitTest(x, y); + } catch (ArgumentOutOfRangeException) { + return new ListViewHitTestInfo(null, null, ListViewHitTestLocations.None); + } + } + + /// + /// Perform a hit test using the Windows control's SUBITEMHITTEST message. + /// This provides information about group hits that the standard ListView.HitTest() does not. + /// + /// + /// + /// + protected OlvListViewHitTestInfo LowLevelHitTest(int x, int y) { + + // If it's not even in the control, don't bother with anything else + if (!this.ClientRectangle.Contains(x, y)) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // If there are no columns, also don't bother with anything else + if (this.Columns.Count == 0) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // Is the point over the header? + OlvListViewHitTestInfo.HeaderHitTestInfo headerHitTestInfo = this.HeaderControl.HitTest(x, y); + if (headerHitTestInfo != null) + return new OlvListViewHitTestInfo(this, headerHitTestInfo.ColumnIndex, headerHitTestInfo.IsOverCheckBox, headerHitTestInfo.OverDividerIndex); + + // Call the native hit test method, which is a little confusing. + NativeMethods.LVHITTESTINFO lParam = new NativeMethods.LVHITTESTINFO(); + lParam.pt_x = x; + lParam.pt_y = y; + int index = NativeMethods.HitTest(this, ref lParam); + + // Setup the various values we need to make our hit test structure + bool isGroupHit = (lParam.flags & (int)HitTestLocationEx.LVHT_EX_GROUP) != 0; + OLVListItem hitItem = isGroupHit || index == -1 ? null : this.GetItem(index); + OLVListSubItem subItem = (this.View == View.Details && hitItem != null) ? hitItem.GetSubItem(lParam.iSubItem) : null; + + // Figure out which group is involved in the hit test. This is a little complicated: + // If the list is virtual: + // - the returned value is list view item index + // - iGroup is the *index* of the hit group. + // If the list is not virtual: + // - iGroup is always -1. + // - if the point is over a group, the returned value is the *id* of the hit group. + // - if the point is not over a group, the returned value is list view item index. + OLVGroup group = null; + if (this.ShowGroups && this.OLVGroups != null) { + if (this.VirtualMode) { + group = lParam.iGroup >= 0 && lParam.iGroup < this.OLVGroups.Count ? this.OLVGroups[lParam.iGroup] : null; + } else { + if (isGroupHit) { + foreach (OLVGroup olvGroup in this.OLVGroups) { + if (olvGroup.GroupId == index) { + group = olvGroup; + break; + } + } + } + } + } + OlvListViewHitTestInfo olvListViewHitTest = new OlvListViewHitTestInfo(hitItem, subItem, lParam.flags, group, lParam.iSubItem); + // System.Diagnostics.Debug.WriteLine(String.Format("HitTest({0}, {1})=>{2}", x, y, olvListViewHitTest)); + return olvListViewHitTest; + } + + /// + /// What is under the given point? This takes the various parts of a cell into account, including + /// any custom parts that a custom renderer might use + /// + /// + /// + /// An information block about what is under the point + public virtual OlvListViewHitTestInfo OlvHitTest(int x, int y) { + OlvListViewHitTestInfo hti = this.LowLevelHitTest(x, y); + + // There is a bug/"feature" of the ListView concerning hit testing. + // If FullRowSelect is false and the point is over cell 0 but not on + // the text or icon, HitTest will not register a hit. We could turn + // FullRowSelect on, do the HitTest, and then turn it off again, but + // toggling FullRowSelect in that way messes up the tooltip in the + // underlying control. So we have to find another way. + // + // It's too hard to try to write the hit test from scratch. Grouping (for + // example) makes it just too complicated. So, we have to use HitTest + // but try to get around its limits. + // + // First step is to determine if the point was within column 0. + // If it was, then we only have to determine if there is an actual row + // under the point. If there is, then we know that the point is over cell 0. + // So we try a Battleship-style approach: is there a subcell to the right + // of cell 0? This will return a false negative if column 0 is the rightmost column, + // so we also check for a subcell to the left. But if only column 0 is visible, + // then that will fail too, so we check for something at the very left of the + // control. + // + // This will still fail under pathological conditions. If column 0 fills + // the whole listview and no part of the text column 0 is visible + // (because it is horizontally scrolled offscreen), then the hit test will fail. + + // Are we in the buggy context? Details view, not full row select, and + // failing to find anything + if (hti.Item == null && !this.FullRowSelect && this.View == View.Details) { + // Is the point within the column 0? If it is, maybe it should have been a hit. + // Let's test slightly to the right and then to left of column 0. Hopefully one + // of those will hit a subitem + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + if (x >= sides.X && x <= sides.Y) { + // We look for: + // - any subitem to the right of cell 0? + // - any subitem to the left of cell 0? + // - cell 0 at the left edge of the screen + hti = this.LowLevelHitTest(sides.Y + 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(sides.X - 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(4, y); + + if (hti.Item != null) { + // We hit something! So, the original point must have been in cell 0 + hti.ColumnIndex = 0; + hti.SubItem = hti.Item.GetSubItem(0); + hti.Location = ListViewHitTestLocations.None; + hti.HitTestLocation = HitTestLocation.InCell; + } + } + } + + if (this.OwnerDraw) + this.CalculateOwnerDrawnHitTest(hti, x, y); + else + this.CalculateStandardHitTest(hti, x, y); + + return hti; + } + + /// + /// Perform a hit test when the control is not owner drawn + /// + /// + /// + /// + protected virtual void CalculateStandardHitTest(OlvListViewHitTestInfo hti, int x, int y) { + + // Standard hit test works fine for the primary column + if (this.View != View.Details || hti.ColumnIndex == 0 || + hti.SubItem == null || hti.Column == null) + return; + + Rectangle cellBounds = hti.SubItem.Bounds; + bool hasImage = (this.GetActualImageIndex(hti.SubItem.ImageSelector) != -1); + + // Unless we say otherwise, it was an general incell hit + hti.HitTestLocation = HitTestLocation.InCell; + + // Check if the point is over where an image should be. + // If there is a checkbox or image there, tag it and exit. + Rectangle r = cellBounds; + r.Width = this.SmallImageSize.Width; + if (r.Contains(x, y)) { + if (hti.Column.CheckBoxes) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + if (hasImage) { + hti.HitTestLocation = HitTestLocation.Image; + return; + } + } + + // Figure out where the text actually is and if the point is in it + // The standard HitTest assumes that any point inside a subitem is + // a hit on Text -- which is clearly not true. + Rectangle textBounds = cellBounds; + textBounds.X += 4; + if (hasImage) + textBounds.X += this.SmallImageSize.Width; + + Size proposedSize = new Size(textBounds.Width, textBounds.Height); + Size textSize = TextRenderer.MeasureText(hti.SubItem.Text, this.Font, proposedSize, TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix); + textBounds.Width = textSize.Width; + + switch (hti.Column.TextAlign) { + case HorizontalAlignment.Center: + textBounds.X += (cellBounds.Right - cellBounds.Left - textSize.Width) / 2; + break; + case HorizontalAlignment.Right: + textBounds.X = cellBounds.Right - textSize.Width; + break; + } + if (textBounds.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + } + } + + /// + /// Perform a hit test when the control is owner drawn. This hands off responsibility + /// to the renderer. + /// + /// + /// + /// + protected virtual void CalculateOwnerDrawnHitTest(OlvListViewHitTestInfo hti, int x, int y) { + // If the click wasn't on an item, give up + if (hti.Item == null) + return; + + // If the list is showing column, but they clicked outside the columns, also give up + if (this.View == View.Details && hti.Column == null) + return; + + // Which renderer was responsible for drawing that point + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(hti.RowObject, hti.Column) + : this.ItemRenderer; + + // We can't decide who was responsible. Give up + if (renderer == null) + return; + + // Ask the responsible renderer what is at that point + renderer.HitTest(hti, x, y); + } + + /// + /// Pause (or unpause) all animations in the list + /// + /// true to pause, false to unpause + public virtual void PauseAnimations(bool isPause) { + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + ImageRenderer renderer = col.Renderer as ImageRenderer; + if (renderer != null) { + renderer.ListView = this; + renderer.Paused = isPause; + } + } + } + + /// + /// Rebuild the columns based upon its current view and column visibility settings + /// + public virtual void RebuildColumns() { + this.ChangeToFilteredColumns(this.View); + } + + /// + /// Remove the given model object from the ListView + /// + /// The model to be removed + /// See RemoveObjects() for more details + /// This method is thread-safe. + /// + public virtual void RemoveObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.RemoveObject(modelObject); }); + else + this.RemoveObjects(new object[] { modelObject }); + } + + /// + /// Remove all of the given objects from the control. + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// This method is thread-safe. + /// + public virtual void RemoveObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.RemoveObjects(modelObjects); }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToRemove; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { +// ReSharper disable PossibleMultipleEnumeration + int i = ourObjects.IndexOf(modelObject); + if (i >= 0) + ourObjects.RemoveAt(i); +// ReSharper restore PossibleMultipleEnumeration + i = this.IndexOf(modelObject); + if (i >= 0) + this.Items.RemoveAt(i); + } + } + this.PostProcessRows(); + + // Tell the world that the list has changed + this.UnsubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Select all rows in the listview + /// + public virtual void SelectAll() { + NativeMethods.SelectAllItems(this); + } + + /// + /// Set the given image to be fixed in the bottom right of the list view. + /// This image will not scroll when the list view scrolls. + /// + /// + /// + /// This method uses ListView's native ability to display a background image. + /// It has a few limitations: + /// + /// + /// It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself, + /// including its background, which covers the background image. + /// It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image. + /// It does not work at all on XP. + /// Obviously, it doesn't look good when alternate row background colors are enabled. + /// + /// + /// If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not + /// translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that + /// they work correctly even in MDI applications. + /// + /// Setting this clears any background image. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundWatermark(Image image) { + NativeMethods.SetBackgroundImage(this, image, true, false, 0, 0); + } + + /// + /// Set the given image to be background of the ListView so that it appears at the given + /// percentage offsets within the list. + /// + /// + /// This has the same limitations as described in . Make sure those limitations + /// are understood before using the method. + /// This is very similar to setting the property of the standard .NET ListView, except that the standard + /// BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This + /// method does not have that problem. + /// Setting this clears any background watermark. + /// + /// The image to be drawn. If null, any existing image will be removed. + /// The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// The vertical percentage where the image will be placed. + public void SetNativeBackgroundImage(Image image, int xOffset, int yOffset) { + NativeMethods.SetBackgroundImage(this, image, false, false, xOffset, yOffset); + } + + /// + /// Set the given image to be the tiled background of the ListView. + /// + /// + /// This has the same limitations as described in and . + /// Make sure those limitations + /// are understood before using the method. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundTiledImage(Image image) { + NativeMethods.SetBackgroundImage(this, image, false, true, 0, 0); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + public virtual void SetObjects(IEnumerable collection) { + this.SetObjects(collection, false); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + /// Should the state of the list be preserved as far as is possible. + public virtual void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(this.objects, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + collection = args.NewObjects; + + // If we own the current list and they change to another list, we don't own it any more + if (this.isOwnerOfObjects && !ReferenceEquals(this.objects, collection)) + this.isOwnerOfObjects = false; + this.objects = collection; + this.BuildList(preserveState); + + // Tell the world that the list has changed + this.UpdateNotificationSubscriptions(this.objects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + + /// + /// Update the given model object into the ListView. The model will be added if it doesn't already exist. + /// + /// The model to be updated + /// + /// + /// See for more details + /// + /// This method is thread-safe. + /// This method will cause the list to be resorted. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.UpdateObject(modelObject); }); + else + this.UpdateObjects(new object[] { modelObject }); + } + + /// + /// Update the pre-existing models that are equal to the given objects. If any of the model doesn't + /// already exist in the control, they will be added. + /// + /// Collection of objects to be updated/added + /// + /// This method will cause the list to be resorted. + /// Nulls are silently ignored. + /// This method is thread-safe. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.UpdateObjects(modelObjects); }); + return; + } + if (modelObjects == null || modelObjects.Count == 0) + return; + + this.BeginUpdate(); + try { + this.UnsubscribeNotifications(modelObjects); + + ArrayList objectsToAdd = new ArrayList(); + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = ourObjects.IndexOf(modelObject); + if (i < 0) + objectsToAdd.Add(modelObject); + else { + ourObjects[i] = modelObject; + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + olvi.RowObject = modelObject; + this.RefreshItem(olvi); + } + } + } + } + this.PostProcessRows(); + + this.AddObjects(objectsToAdd); + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change any subscriptions to INotifyPropertyChanged events on our current + /// model objects so that we no longer listen for events on the old models + /// and do listen for events on the given collection. + /// + /// This does nothing if UseNotifyPropertyChanged is false. + /// + protected virtual void UpdateNotificationSubscriptions(IEnumerable collection) { + if (!this.UseNotifyPropertyChanged) + return; + + // We could calculate a symmetric difference between the old models and the new models + // except that we don't have the previous models at this point. + + this.UnsubscribeNotifications(null); + this.SubscribeNotifications(collection ?? this.Objects); + } + + /// + /// Gets or sets whether or not ObjectListView should subscribe to INotifyPropertyChanged + /// events on the model objects that it is given. + /// + /// + /// + /// This should be set before calling SetObjects(). If you set this to false, + /// ObjectListView will unsubscribe to all current model objects. + /// + /// If you set this to true on a virtual list, the ObjectListView will + /// walk all the objects in the list trying to subscribe to change notifications. + /// If you have 10,000,000 items in your virtual list, this may take some time. + /// + [Category("ObjectListView"), + Description("Should ObjectListView listen for property changed events on the model objects?"), + DefaultValue(false)] + public bool UseNotifyPropertyChanged { + get { return this.useNotifyPropertyChanged; } + set { + if (this.useNotifyPropertyChanged == value) + return; + this.useNotifyPropertyChanged = value; + if (value) + this.SubscribeNotifications(this.Objects); + else + this.UnsubscribeNotifications(null); + } + } + private bool useNotifyPropertyChanged; + + /// + /// Subscribe to INotifyPropertyChanges on the given collection of objects. + /// + /// + protected void SubscribeNotifications(IEnumerable models) { + if (!this.UseNotifyPropertyChanged || models == null) + return; + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null && !subscribedModels.ContainsKey(notifier)) { + notifier.PropertyChanged += HandleModelOnPropertyChanged; + subscribedModels[notifier] = notifier; + } + } + } + + /// + /// Unsubscribe from INotifyPropertyChanges on the given collection of objects. + /// If the given collection is null, unsubscribe from all current subscriptions + /// + /// + protected void UnsubscribeNotifications(IEnumerable models) { + if (models == null) { + foreach (INotifyPropertyChanged notifier in this.subscribedModels.Keys) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + } + subscribedModels = new Hashtable(); + } else { + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + subscribedModels.Remove(notifier); + } + } + } + } + + private void HandleModelOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { + // System.Diagnostics.Debug.WriteLine(String.Format("PropertyChanged: '{0}' on '{1}", propertyChangedEventArgs.PropertyName, sender)); + this.RefreshObject(sender); + } + + private Hashtable subscribedModels = new Hashtable(); + + #endregion + + #region Save/Restore State + + /// + /// Return a byte array that represents the current state of the ObjectListView, such + /// that the state can be restored by RestoreState() + /// + /// + /// The state of an ObjectListView includes the attributes that the user can modify: + /// + /// current view (i.e. Details, Tile, Large Icon...) + /// sort column and direction + /// column order + /// column widths + /// column visibility + /// + /// + /// + /// It does not include selection or the scroll position. + /// + /// + /// A byte array representing the state of the ObjectListView + public virtual byte[] SaveState() { + ObjectListViewState olvState = new ObjectListViewState(); + olvState.VersionNumber = 1; + olvState.NumberOfColumns = this.AllColumns.Count; + olvState.CurrentView = this.View; + + // If we have a sort column, it is possible that it is not currently being shown, in which + // case, it's Index will be -1. So we calculate its index directly. Technically, the sort + // column does not even have to a member of AllColumns, in which case IndexOf will return -1, + // which is works fine since we have no way of restoring such a column anyway. + if (this.PrimarySortColumn != null) + olvState.SortColumn = this.AllColumns.IndexOf(this.PrimarySortColumn); + olvState.LastSortOrder = this.PrimarySortOrder; + olvState.IsShowingGroups = this.ShowGroups; + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + foreach (OLVColumn column in this.AllColumns) { + olvState.ColumnIsVisible.Add(column.IsVisible); + olvState.ColumnDisplayIndicies.Add(column.LastDisplayIndex); + olvState.ColumnWidths.Add(column.Width); + } + + // Now that we have stored our state, convert it to a byte array + using (MemoryStream ms = new MemoryStream()) { + BinaryFormatter serializer = new BinaryFormatter(); + serializer.AssemblyFormat = FormatterAssemblyStyle.Simple; + serializer.Serialize(ms, olvState); + return ms.ToArray(); + } + } + + /// + /// Restore the state of the control from the given string, which must have been + /// produced by SaveState() + /// + /// A byte array returned from SaveState() + /// Returns true if the state was restored + public virtual bool RestoreState(byte[] state) { + using (MemoryStream ms = new MemoryStream(state)) { + BinaryFormatter deserializer = new BinaryFormatter(); + ObjectListViewState olvState; + try { + olvState = deserializer.Deserialize(ms) as ObjectListViewState; + } catch (System.Runtime.Serialization.SerializationException) { + return false; + } + // The number of columns has changed. We have no way to match old + // columns to the new ones, so we just give up. + if (olvState == null || olvState.NumberOfColumns != this.AllColumns.Count) + return false; + if (olvState.SortColumn == -1) { + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + } else { + this.PrimarySortColumn = this.AllColumns[olvState.SortColumn]; + this.PrimarySortOrder = olvState.LastSortOrder; + } + for (int i = 0; i < olvState.NumberOfColumns; i++) { + OLVColumn column = this.AllColumns[i]; + column.Width = (int)olvState.ColumnWidths[i]; + column.IsVisible = (bool)olvState.ColumnIsVisible[i]; + column.LastDisplayIndex = (int)olvState.ColumnDisplayIndicies[i]; + } +// ReSharper disable RedundantCheckBeforeAssignment + if (olvState.IsShowingGroups != this.ShowGroups) +// ReSharper restore RedundantCheckBeforeAssignment + this.ShowGroups = olvState.IsShowingGroups; + if (this.View == olvState.CurrentView) + this.RebuildColumns(); + else + this.View = olvState.CurrentView; + } + + return true; + } + + /// + /// Instances of this class are used to store the state of an ObjectListView. + /// + [Serializable] + internal class ObjectListViewState + { +// ReSharper disable NotAccessedField.Global + public int VersionNumber = 1; +// ReSharper restore NotAccessedField.Global + public int NumberOfColumns = 1; + public View CurrentView; + public int SortColumn = -1; + public bool IsShowingGroups; + public SortOrder LastSortOrder = SortOrder.None; +// ReSharper disable FieldCanBeMadeReadOnly.Global + public ArrayList ColumnIsVisible = new ArrayList(); + public ArrayList ColumnDisplayIndicies = new ArrayList(); + public ArrayList ColumnWidths = new ArrayList(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + } + + #endregion + + #region Event handlers + + /// + /// The application is idle. Trigger a SelectionChanged event. + /// + /// + /// + protected virtual void HandleApplicationIdle(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(HandleApplicationIdle); + this.hasIdleHandler = false; + + this.OnSelectionChanged(new EventArgs()); + } + + /// + /// The application is idle. Handle the column resizing event. + /// + /// + /// + protected virtual void HandleApplicationIdleResizeColumns(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(this.HandleApplicationIdleResizeColumns); + this.hasResizeColumnsHandler = false; + + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// Handle the BeginScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleBeginScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + NativeMethods.NMLVSCROLL nmlvscroll = (NativeMethods.NMLVSCROLL)m.GetLParam(typeof(NativeMethods.NMLVSCROLL)); + if (nmlvscroll.dx != 0) { + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionH - nmlvscroll.dx, scrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + + // Force any empty list msg to redraw when the list is scrolled horizontally + if (this.GetItemCount() == 0) + this.Invalidate(); + } + if (nmlvscroll.dy != 0) { + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionV - nmlvscroll.dy, scrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + return false; + } + + /// + /// Handle the EndScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleEndScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + // There is a bug in ListView under XP that causes the gridlines to be incorrectly scrolled + // when the left button is clicked to scroll. This is supposedly documented at + // KB 813791, but I couldn't find it anywhere. You can follow this thread to see the discussion + // http://www.ureader.com/msg/1484143.aspx + + if (!ObjectListView.IsVistaOrLater && ObjectListView.IsLeftMouseDown && this.GridLines) { + this.Invalidate(); + this.Update(); + } + + return false; + } + + /// + /// Handle the LinkClick listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleLinkClick(ref Message m) { + //System.Diagnostics.Debug.WriteLine("HandleLinkClick"); + + NativeMethods.NMLVLINK nmlvlink = (NativeMethods.NMLVLINK)m.GetLParam(typeof(NativeMethods.NMLVLINK)); + + // Find the group that was clicked and trigger an event + foreach (OLVGroup x in this.OLVGroups) { + if (x.GroupId == nmlvlink.iSubItem) { + this.OnGroupTaskClicked(new GroupTaskClickedEventArgs(x)); + return true; + } + } + + return false; + } + + /// + /// The cell tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleCellToolTipShowing(object sender, ToolTipShowingEventArgs e) { + this.BuildCellEvent(e, this.PointToClient(Cursor.Position)); + if (e.Item != null) { + e.Text = this.GetCellToolTip(e.ColumnIndex, e.RowIndex); + this.OnCellToolTip(e); + } + } + + /// + /// Allow the HeaderControl to call back into HandleHeaderToolTipShowing without making that method public + /// + /// + /// + internal void HeaderToolTipShowingCallback(object sender, ToolTipShowingEventArgs e) { + this.HandleHeaderToolTipShowing(sender, e); + } + + /// + /// The header tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleHeaderToolTipShowing(object sender, ToolTipShowingEventArgs e) { + e.ColumnIndex = this.HeaderControl.ColumnIndexUnderCursor; + if (e.ColumnIndex < 0) + return; + + e.RowIndex = -1; + e.Model = null; + e.Column = this.GetColumn(e.ColumnIndex); + e.Text = this.GetHeaderToolTip(e.ColumnIndex); + e.ListView = this; + this.OnHeaderToolTip(e); + } + + /// + /// Event handler for the column click event + /// + protected virtual void HandleColumnClick(object sender, ColumnClickEventArgs e) { + if (!this.PossibleFinishCellEditing()) + return; + + // Toggle the sorting direction on successive clicks on the same column + if (this.PrimarySortColumn != null && e.Column == this.PrimarySortColumn.Index) + this.PrimarySortOrder = (this.PrimarySortOrder == SortOrder.Descending ? SortOrder.Ascending : SortOrder.Descending); + else + this.PrimarySortOrder = SortOrder.Ascending; + + this.BeginUpdate(); + try { + this.Sort(e.Column); + } finally { + this.EndUpdate(); + } + } + + #endregion + + #region Low level Windows Message handling + + /// + /// Override the basic message pump for this control + /// + /// + protected override void WndProc(ref Message m) + { + + // System.Diagnostics.Debug.WriteLine(m.Msg); + switch (m.Msg) { + case 2: // WM_DESTROY + if (!this.HandleDestroy(ref m)) + base.WndProc(ref m); + break; + //case 0x14: // WM_ERASEBKGND + // Can't do anything here since, when the control is double buffered, anything + // done here is immediately over-drawn + // break; + case 0x0F: // WM_PAINT + if (!this.HandlePaint(ref m)) + base.WndProc(ref m); + break; + case 0x46: // WM_WINDOWPOSCHANGING + if (this.PossibleFinishCellEditing() && !this.HandleWindowPosChanging(ref m)) + base.WndProc(ref m); + break; + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref m)) + base.WndProc(ref m); + break; + case 0x0100: // WM_KEY_DOWN + if (!this.HandleKeyDown(ref m)) + base.WndProc(ref m); + break; + case 0x0102: // WM_CHAR + if (!this.HandleChar(ref m)) + base.WndProc(ref m); + break; + case 0x0200: // WM_MOUSEMOVE + if (!this.HandleMouseMove(ref m)) + base.WndProc(ref m); + break; + case 0x0201: // WM_LBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x202: // WM_LBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonUp(ref m)) + base.WndProc(ref m); + break; + case 0x0203: // WM_LBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x0204: // WM_RBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x0205: // WM_RBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONUP"); + base.WndProc(ref m); + break; + case 0x0206: // WM_RBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref m)) + base.WndProc(ref m); + break; + case 0x114: // WM_HSCROLL: + case 0x115: // WM_VSCROLL: + //System.Diagnostics.Debug.WriteLine("WM_VSCROLL"); + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x20A: // WM_MOUSEWHEEL: + case 0x20E: // WM_MOUSEHWHEEL: + if (this.AllowCellEditorsToProcessMouseWheel && this.IsCellEditing) + break; + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x7B: // WM_CONTEXTMENU + if (!this.HandleContextMenu(ref m)) + base.WndProc(ref m); + break; + case 0x1000 + 18: // LVM_HITTEST: + //System.Diagnostics.Debug.WriteLine("LVM_HITTEST"); + if (this.skipNextHitTest) { + //System.Diagnostics.Debug.WriteLine("SKIPPING LVM_HITTEST"); + this.skipNextHitTest = false; + } else { + base.WndProc(ref m); + } + break; + default: + base.WndProc(ref m); + break; + } + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleChar(ref Message m) { + + // Trigger a normal KeyPress event, which listeners can handle if they want. + // Handling the event stops ObjectListView's fancy search-by-typing. + if (this.ProcessKeyEventArgs(ref m)) + return true; + + const int MILLISECONDS_BETWEEN_KEYPRESSES = 1000; + + // What character did the user type and was it part of a longer string? + char character = (char)m.WParam.ToInt32(); //TODO: Will this work on 64 bit or MBCS? + if (character == (char)Keys.Back) { + // Backspace forces the next key to be considered the start of a new search + this.timeLastCharEvent = 0; + return true; + } + + if (System.Environment.TickCount < (this.timeLastCharEvent + MILLISECONDS_BETWEEN_KEYPRESSES)) + this.lastSearchString += character; + else + this.lastSearchString = character.ToString(CultureInfo.InvariantCulture); + + // If this control is showing checkboxes, we want to ignore single space presses, + // since they are used to toggle the selected checkboxes. + if (this.CheckBoxes && this.lastSearchString == " ") { + this.timeLastCharEvent = 0; + return true; + } + + // Where should the search start? + int start = 0; + ListViewItem focused = this.FocusedItem; + if (focused != null) { + start = this.GetDisplayOrderOfItemIndex(focused.Index); + + // If the user presses a single key, we search from after the focused item, + // being careful not to march past the end of the list + if (this.lastSearchString.Length == 1) { + start += 1; + if (start == this.GetItemCount()) + start = 0; + } + } + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(this.lastSearchString, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return true; + + // The parameters of the search may have been changed + string searchString = args.StringToFind; + start = args.StartSearchFrom; + + // Do the actual search + int found = this.FindMatchingRow(searchString, start, SearchDirectionHint.Down); + if (found >= 0) { + // Select and focus on the found item + this.BeginUpdate(); + try { + this.SelectedIndices.Clear(); + OLVListItem lvi = this.GetNthItemInDisplayOrder(found); + if (lvi != null) { + if (lvi.Enabled) + lvi.Selected = true; + lvi.Focused = true; + this.EnsureVisible(lvi.Index); + } + } finally { + this.EndUpdate(); + } + } + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(searchString, found); + this.OnAfterSearching(args2); + if (!args2.Handled) { + if (found < 0) + System.Media.SystemSounds.Beep.Play(); + } + + // When did this event occur? + this.timeLastCharEvent = System.Environment.TickCount; + return true; + } + private int timeLastCharEvent; + private string lastSearchString; + + /// + /// The user wants to see the context menu. + /// + /// The windows m + /// A bool indicating if this m has been handled + /// + /// We want to ignore context menu requests that are triggered by right clicks on the header + /// + protected virtual bool HandleContextMenu(ref Message m) { + // Don't try to handle context menu commands at design time. + if (this.DesignMode) + return false; + + // If the context menu command was generated by the keyboard, LParam will be -1. + // We don't want to process these. + if (m.LParam == this.minusOne) + return false; + + // If the context menu came from somewhere other than the header control, + // we also don't want to ignore it + if (m.WParam != this.HeaderControl.Handle) + return false; + + // OK. Looks like a right click in the header + if (!this.PossibleFinishCellEditing()) + return true; + + int columnIndex = this.HeaderControl.ColumnIndexUnderCursor; + return this.HandleHeaderRightClick(columnIndex); + } + readonly IntPtr minusOne = new IntPtr(-1); + + /// + /// Handle the Custom draw series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleCustomDraw(ref Message m) { + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_PREERASE = 3; + const int CDDS_POSTERASE = 4; + //const int CDRF_NEWFONT = 2; + //const int CDRF_SKIPDEFAULT = 4; + const int CDDS_ITEM = 0x00010000; + const int CDDS_SUBITEM = 0x00020000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + const int CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE); + const int CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE); + const int CDDS_SUBITEMPREPAINT = (CDDS_SUBITEM | CDDS_ITEMPREPAINT); + const int CDDS_SUBITEMPOSTPAINT = (CDDS_SUBITEM | CDDS_ITEMPOSTPAINT); + const int CDRF_NOTIFYPOSTPAINT = 0x10; + //const int CDRF_NOTIFYITEMDRAW = 0x20; + //const int CDRF_NOTIFYSUBITEMDRAW = 0x20; // same value as above! + const int CDRF_NOTIFYPOSTERASE = 0x40; + + // There is a bug in owner drawn virtual lists which causes lots of custom draw messages + // to be sent to the control *outside* of a WmPaint event. AFAIK, these custom draw events + // are spurious and only serve to make the control flicker annoyingly. + // So, we ignore messages that are outside of a paint event. + if (!this.isInWmPaintEvent) + return true; + + // One more complication! Sometimes with owner drawn virtual lists, the act of drawing + // the overlays triggers a second attempt to paint the control -- which makes an annoying + // flicker. So, we only do the custom drawing once per WmPaint event. + if (!this.shouldDoCustomDrawing) + return true; + + NativeMethods.NMLVCUSTOMDRAW nmcustomdraw = (NativeMethods.NMLVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMLVCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("cd: {0:x}, {1}, {2}", nmcustomdraw.nmcd.dwDrawStage, nmcustomdraw.dwItemType, nmcustomdraw.nmcd.dwItemSpec)); + + // Ignore drawing of group items + if (nmcustomdraw.dwItemType == 1) { + // This is the basis of an idea about how to owner draw group headers + + //nmcustomdraw.clrText = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrFace = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrTextBk = ColorTranslator.ToWin32(Color.DeepPink); + //Marshal.StructureToPtr(nmcustomdraw, m.LParam, false); + //using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + // g.DrawRectangle(Pens.Red, Rectangle.FromLTRB(nmcustomdraw.rcText.left, nmcustomdraw.rcText.top, nmcustomdraw.rcText.right, nmcustomdraw.rcText.bottom)); + //} + //m.Result = (IntPtr)((int)m.Result | CDRF_SKIPDEFAULT); + return true; + } + + switch (nmcustomdraw.nmcd.dwDrawStage) { + case CDDS_PREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_PREPAINT"); + // Remember which items were drawn during this paint cycle + if (this.prePaintLevel == 0) + this.drawnItems = new List(); + + // If there are any items, we have to wait until at least one has been painted + // before we draw the overlays. If there aren't any items, there will never be any + // item paint events, so we can draw the overlays whenever + this.isAfterItemPaint = (this.GetItemCount() == 0); + this.prePaintLevel++; + base.WndProc(ref m); + + // Make sure that we get postpaint notifications + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_POSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTPAINT"); + this.prePaintLevel--; + + // When in group view, we have two problems. On XP, the control sends + // a whole heap of PREPAINT/POSTPAINT messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays. + // On Vista, we have a different problem. On Vista, the control nests calls + // to PREPAINT and POSTPAINT. We only want to draw overlays on the outermost + // POSTPAINT. + if (this.prePaintLevel == 0 && (this.isMarqueSelecting || this.isAfterItemPaint)) { + this.shouldDoCustomDrawing = false; + + // Draw our overlays after everything has been drawn + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + this.DrawAllDecorations(g, this.drawnItems); + } + } + break; + + case CDDS_ITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREPAINT"); + + // When in group view on XP, the control send a whole heap of PREPAINT/POSTPAINT + // messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays + this.isAfterItemPaint = true; + + // This scheme of catching custom draw msgs works fine, except + // for Tile view. Something in .NET's handling of Tile view causes lots + // of invalidates and erases. So, we just ignore completely + // .NET's handling of Tile view and let the underlying control + // do its stuff. Strangely, if the Tile view is + // completely owner drawn, those erasures don't happen. + if (this.View == View.Tile) { + if (this.OwnerDraw && this.ItemRenderer != null) + base.WndProc(ref m); + } else { + base.WndProc(ref m); + } + + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_ITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTPAINT"); + // Remember which items have been drawn so we can draw any decorations for them + // once all other painting is finished + if (this.Columns.Count > 0) { + OLVListItem olvi = this.GetItem((int)nmcustomdraw.nmcd.dwItemSpec); + if (olvi != null) + this.drawnItems.Add(olvi); + } + break; + + case CDDS_SUBITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine(String.Format("CDDS_SUBITEMPREPAINT ({0},{1})", (int)nmcustomdraw.nmcd.dwItemSpec, nmcustomdraw.iSubItem)); + + // There is a bug in the .NET framework which appears when column 0 of an owner drawn listview + // is dragged to another column position. + // The bounds calculation always returns the left edge of column 0 as being 0. + // The effects of this bug become apparent + // when the listview is scrolled horizontally: the control can think that column 0 + // is no longer visible (the horizontal scroll position is subtracted from the bounds, giving a + // rectangle that is offscreen). In those circumstances, column 0 is not redraw because + // the control thinks it is not visible and so does not trigger a DrawSubItem event. + + // To fix this problem, we have to detected the situation -- owner drawing column 0 in any column except 0 -- + // trigger our own DrawSubItem, and then prevent the default processing from occurring. + + // Are we owner drawing column 0 when it's in any column except 0? + if (!this.OwnerDraw) + return false; + + int columnIndex = nmcustomdraw.iSubItem; + if (columnIndex != 0) + return false; + + int displayIndex = this.Columns[0].DisplayIndex; + if (displayIndex == 0) + return false; + + int rowIndex = (int)nmcustomdraw.nmcd.dwItemSpec; + OLVListItem item = this.GetItem(rowIndex); + if (item == null) + return false; + + // OK. We have the error condition, so lets do what the .NET framework should do. + // Trigger an event to draw column 0 when it is not at display index 0 + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + + // Correctly calculate the bounds of cell 0 + Rectangle r = item.GetSubItemBounds(0); + + // We can hardcode "0" here since we know we are only doing this for column 0 + DrawListViewSubItemEventArgs args = new DrawListViewSubItemEventArgs(g, r, item, item.SubItems[0], rowIndex, 0, + this.Columns[0], (ListViewItemStates)nmcustomdraw.nmcd.uItemState); + this.OnDrawSubItem(args); + + // If the event handler wants to do the default processing (i.e. DrawDefault = true), we are stuck. + // There is no way we can force the default drawing because of the bug in .NET we are trying to get around. + System.Diagnostics.Trace.Assert(!args.DrawDefault, "Default drawing is impossible in this situation"); + } + m.Result = (IntPtr)4; + + return true; + + case CDDS_SUBITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_SUBITEMPOSTPAINT"); + break; + + // I have included these stages, but it doesn't seem that they are sent for ListViews. + // http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-08/msg00220.html + + case CDDS_PREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_PREERASE"); + break; + + case CDDS_POSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTERASE"); + break; + + case CDDS_ITEMPREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREERASE"); + break; + + case CDDS_ITEMPOSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTERASE"); + break; + } + + return false; + } + bool isAfterItemPaint; + List drawnItems; + + /// + /// Handle the underlying control being destroyed + /// + /// + /// + protected virtual bool HandleDestroy(ref Message m) { + //System.Diagnostics.Debug.WriteLine(String.Format("WM_DESTROY: Disposing={0}, IsDisposed={1}, VirtualMode={2}", Disposing, IsDisposed, VirtualMode)); + + // Recreate the header control when the listview control is destroyed + this.headerControl = null; + + // When the underlying control is destroyed, we need to recreate and reconfigure its tooltip + if (this.cellToolTip != null) { + this.cellToolTip.PushSettings(); + this.BeginInvoke((MethodInvoker)delegate { + this.UpdateCellToolTipHandle(); + this.cellToolTip.PopSettings(); + }); + } + + return false; + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleFindItem(ref Message m) { + // NOTE: As far as I can see, this message is never actually sent to the control, making this + // method redundant! + + const int LVFI_STRING = 0x0002; + + NativeMethods.LVFINDINFO findInfo = (NativeMethods.LVFINDINFO)m.GetLParam(typeof(NativeMethods.LVFINDINFO)); + + // We can only handle string searches + if ((findInfo.flags & LVFI_STRING) != LVFI_STRING) + return false; + + int start = m.WParam.ToInt32(); + m.Result = (IntPtr)this.FindMatchingRow(findInfo.psz, start, SearchDirectionHint.Down); + return true; + } + + /// + /// Find the first row after the given start in which the text value in the + /// comparison column begins with the given text. The comparison column is column 0, + /// unless IsSearchOnSortColumn is true, in which case the current sort column is used. + /// + /// The text to be prefix matched + /// The index of the first row to consider + /// Which direction should be searched? + /// The index of the first row that matched, or -1 + /// The text comparison is a case-insensitive, prefix match. The search will + /// search the every row until a match is found, wrapping at the end if needed. + public virtual int FindMatchingRow(string text, int start, SearchDirectionHint direction) { + // We also can't do anything if we don't have data + if (this.Columns.Count == 0) + return -1; + int rowCount = this.GetItemCount(); + if (rowCount == 0) + return -1; + + // Which column are we going to use for our comparing? + OLVColumn column = this.GetColumn(0); + if (this.IsSearchOnSortColumn && this.View == View.Details && this.PrimarySortColumn != null) + column = this.PrimarySortColumn; + + // Do two searches if necessary to find a match. The second search is the wrap-around part of searching + int i; + if (direction == SearchDirectionHint.Down) { + i = this.FindMatchInRange(text, start, rowCount - 1, column); + if (i == -1 && start > 0) + i = this.FindMatchInRange(text, 0, start - 1, column); + } else { + i = this.FindMatchInRange(text, start, 0, column); + if (i == -1 && start != rowCount) + i = this.FindMatchInRange(text, rowCount - 1, start + 1, column); + } + + return i; + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected virtual int FindMatchInRange(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// Handle the Group Info series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleGroupInfo(ref Message m) + { + NativeMethods.NMLVGROUP nmlvgroup = (NativeMethods.NMLVGROUP)m.GetLParam(typeof(NativeMethods.NMLVGROUP)); + + //System.Diagnostics.Debug.WriteLine(String.Format("group: {0}, old state: {1}, new state: {2}", + // nmlvgroup.iGroupId, StateToString(nmlvgroup.uOldState), StateToString(nmlvgroup.uNewState))); + + // Ignore state changes that aren't related to selection, focus or collapsedness + const uint INTERESTING_STATES = (uint) (GroupState.LVGS_COLLAPSED | GroupState.LVGS_FOCUSED | GroupState.LVGS_SELECTED); + if ((nmlvgroup.uOldState & INTERESTING_STATES) == (nmlvgroup.uNewState & INTERESTING_STATES)) + return false; + + foreach (OLVGroup group in this.OLVGroups) { + if (group.GroupId == nmlvgroup.iGroupId) { + GroupStateChangedEventArgs args = new GroupStateChangedEventArgs(group, (GroupState)nmlvgroup.uOldState, (GroupState)nmlvgroup.uNewState); + this.OnGroupStateChanged(args); + break; + } + } + + return false; + } + + //private static string StateToString(uint state) + //{ + // if (state == 0) + // return Enum.GetName(typeof(GroupState), 0); + // + // List names = new List(); + // foreach (int value in Enum.GetValues(typeof(GroupState))) + // { + // if (value != 0 && (state & value) == value) + // { + // names.Add(Enum.GetName(typeof(GroupState), value)); + // } + // } + // return names.Count == 0 ? state.ToString("x") : String.Join("|", names.ToArray()); + //} + + /// + /// Handle a key down message + /// + /// + /// True if the msg has been handled + protected virtual bool HandleKeyDown(ref Message m) { + + // If this is a checkbox list, toggle the selected rows when the user presses Space + if (this.CheckBoxes && m.WParam.ToInt32() == (int)Keys.Space && this.SelectedIndices.Count > 0) { + this.ToggleSelectedRowCheckBoxes(); + return true; + } + + // Remember the scroll position so we can decide if the listview has scrolled in the + // handling of the event. + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + + base.WndProc(ref m); + + // It's possible that the processing in base.WndProc has actually destroyed this control + if (this.IsDisposed) + return true; + + // If the keydown processing changed the scroll position, trigger a Scroll event + int newScrollPositionH = NativeMethods.GetScrollPosition(this, true); + int newScrollPositionV = NativeMethods.GetScrollPosition(this, false); + + if (scrollPositionH != newScrollPositionH) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionH, newScrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + } + if (scrollPositionV != newScrollPositionV) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionV, newScrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + if (scrollPositionH != newScrollPositionH || scrollPositionV != newScrollPositionV) + this.RefreshHotItem(); + + return true; + } + + /// + /// Toggle the checkedness of the selected rows + /// + /// + /// + /// Actually, this doesn't actually toggle all rows. It toggles the first row, and + /// all other rows get the check state of that first row. This is actually a much + /// more useful behaviour. + /// + /// + /// If no rows are selected, this method does nothing. + /// + /// + public void ToggleSelectedRowCheckBoxes() { + if (this.SelectedIndices.Count == 0) + return; + Object primaryModel = this.GetItem(this.SelectedIndices[0]).RowObject; + this.ToggleCheckObject(primaryModel); + CheckState? state = this.GetCheckState(primaryModel); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + /// + /// Catch the Left Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + // We have to intercept this low level message rather than the more natural + // overridding of OnMouseDown, since ListCtrl's internal mouse down behavior + // is to select (or deselect) rows when the mouse is released. We don't + // want the selection to change when the user checks or unchecks a checkbox, so if the + // mouse down event was to check/uncheck, we have to hide this mouse + // down event from the control. + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + + if (hti.Item == null) + return false; + + // If the click occurs on a button, ignore it so the row isn't selected + if (hti.HitTestLocation == HitTestLocation.Button) { + this.Invalidate(); + + return true; + } + + // If they didn't click checkbox, we can just return + if (hti.HitTestLocation != HitTestLocation.CheckBox) + return false; + + // Disabled rows cannot change checkboxes + if (!hti.Item.Enabled) + return true; + + // Did they click a sub item checkbox? + if (hti.Column != null && hti.Column.Index > 0) { + if (hti.Column.IsEditable && hti.Item.Enabled) + this.ToggleSubItemCheckBox(hti.RowObject, hti.Column); + return true; + } + + // They must have clicked the primary checkbox + this.ToggleCheckObject(hti.RowObject); + + // If they change the checkbox of a selected row, all the rows in the selection + // should be given the same state + if (hti.Item.Selected) { + CheckState? state = this.GetCheckState(hti.RowObject); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + return true; + } + + /// + /// Catch the Left Button up event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonUp(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + if (this.MouseMoveHitTest == null) + return false; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + // Did they click an enabled, non-empty button? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.Button) { + // If a button was hit, Item and Column must be non-null + if (this.MouseMoveHitTest.Item.Enabled || this.MouseMoveHitTest.Column.EnableButtonWhenItemIsDisabled) { + string buttonText = this.MouseMoveHitTest.Column.GetStringValue(this.MouseMoveHitTest.RowObject); + if (!String.IsNullOrEmpty(buttonText)) { + this.Invalidate(); + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, new Point(x, y), this.MouseMoveHitTest); + this.OnButtonClick(args); + return true; + } + } + } + + // Are they trying to expand/collapse a group? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.GroupExpander) { + if (this.TriggerGroupExpandCollapse(this.MouseMoveHitTest.Group)) + return true; + } + + if (ObjectListView.IsVistaOrLater && this.HasCollapsibleGroups) + base.DefWndProc(ref m); + + return false; + } + + /// + /// Trigger a GroupExpandCollapse event and return true if the action was cancelled + /// + /// + /// + protected virtual bool TriggerGroupExpandCollapse(OLVGroup group) + { + GroupExpandingCollapsingEventArgs args = new GroupExpandingCollapsingEventArgs(group); + this.OnGroupExpandingCollapsing(args); + return args.Canceled; + } + + /// + /// Catch the Right Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDown(OlvListViewHitTestInfo hti) { + if (hti.Item == null) + return false; + + // Ignore clicks on checkboxes + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the Left Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDoubleClick(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDoubleClick(OlvListViewHitTestInfo hti) { + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the right Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDoubleClick(ref Message m) { + + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a right mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDoubleClick(OlvListViewHitTestInfo hti) { + + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the MouseMove event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleMouseMove(ref Message m) + { + //int x = m.LParam.ToInt32() & 0xFFFF; + //int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + //this.lastMouseMoveX = x; + //this.lastMouseMoveY = y; + + return false; + } + //private int lastMouseMoveX = -1; + //private int lastMouseMoveY = -1; + + /// + /// Handle notifications that have been reflected back from the parent window + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleReflectNotify(ref Message m) { + const int NM_CLICK = -2; + const int NM_DBLCLK = -3; + const int NM_RDBLCLK = -6; + const int NM_CUSTOMDRAW = -12; + const int NM_RELEASEDCAPTURE = -16; + const int LVN_FIRST = -100; + const int LVN_ITEMCHANGED = LVN_FIRST - 1; + const int LVN_ITEMCHANGING = LVN_FIRST - 0; + const int LVN_HOTTRACK = LVN_FIRST - 21; + const int LVN_MARQUEEBEGIN = LVN_FIRST - 56; + const int LVN_GETINFOTIP = LVN_FIRST - 58; + const int LVN_GETDISPINFO = LVN_FIRST - 77; + const int LVN_BEGINSCROLL = LVN_FIRST - 80; + const int LVN_ENDSCROLL = LVN_FIRST - 81; + const int LVN_LINKCLICK = LVN_FIRST - 84; + const int LVN_GROUPINFO = LVN_FIRST - 88; // undocumented + const int LVIF_STATE = 8; + //const int LVIS_FOCUSED = 1; + const int LVIS_SELECTED = 2; + + bool isMsgHandled = false; + + // TODO: Don't do any logic in this method. Create separate methods for each message + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + //System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr->code)); + + switch (nmhdr.code) { + case NM_CLICK: + // The standard ListView does some strange stuff here when the list has checkboxes. + // If you shift click on non-primary columns when FullRowSelect is true, the + // checkedness of the selected rows changes. + // We can't just not do the base class stuff because it sets up state that is used to + // determine mouse up events later on. + // So, we sabotage the base class's process of the click event. The base class does a HITTEST + // in order to determine which row was clicked -- if that fails, the base class does nothing. + // So when we get a CLICK, we know that the base class is going to send a HITTEST very soon, + // so we ignore the next HITTEST message, which will cause the click processing to fail. + //System.Diagnostics.Debug.WriteLine("NM_CLICK"); + this.skipNextHitTest = true; + break; + + case LVN_BEGINSCROLL: + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + isMsgHandled = this.HandleBeginScroll(ref m); + break; + + case LVN_ENDSCROLL: + isMsgHandled = this.HandleEndScroll(ref m); + break; + + case LVN_LINKCLICK: + isMsgHandled = this.HandleLinkClick(ref m); + break; + + case LVN_MARQUEEBEGIN: + //System.Diagnostics.Debug.WriteLine("LVN_MARQUEEBEGIN"); + this.isMarqueSelecting = true; + break; + + case LVN_GETINFOTIP: + //System.Diagnostics.Debug.WriteLine("LVN_GETINFOTIP"); + // When virtual lists are in SmallIcon view, they generates tooltip message with invalid item indices. + NativeMethods.NMLVGETINFOTIP nmGetInfoTip = (NativeMethods.NMLVGETINFOTIP)m.GetLParam(typeof(NativeMethods.NMLVGETINFOTIP)); + isMsgHandled = nmGetInfoTip.iItem >= this.GetItemCount() || this.Columns.Count == 0; + break; + + case NM_RELEASEDCAPTURE: + //System.Diagnostics.Debug.WriteLine("NM_RELEASEDCAPTURE"); + this.isMarqueSelecting = false; + this.Invalidate(); + break; + + case NM_CUSTOMDRAW: + //System.Diagnostics.Debug.WriteLine("NM_CUSTOMDRAW"); + isMsgHandled = this.HandleCustomDraw(ref m); + break; + + case NM_DBLCLK: + // The default behavior of a .NET ListView with checkboxes is to toggle the checkbox on + // double-click. That's just silly, if you ask me :) + if (this.CheckBoxes) { + // How do we make ListView not do that silliness? We could just ignore the message + // but the last part of the base code sets up state information, and without that + // state, the ListView doesn't trigger MouseDoubleClick events. So we fake a + // right button double click event, which sets up the same state, but without + // toggling the checkbox. + nmhdr.code = NM_RDBLCLK; + Marshal.StructureToPtr(nmhdr, m.LParam, false); + } + break; + + case LVN_ITEMCHANGED: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGED"); + NativeMethods.NMLISTVIEW nmlistviewPtr2 = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr2.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr2.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr2.uNewState); + if (currentValue != newCheckValue) + { + // Remove the state indices so that we don't trigger the OnItemChecked method + // when we call our base method after exiting this method + nmlistviewPtr2.uOldState = (nmlistviewPtr2.uOldState & 0x0FFF); + nmlistviewPtr2.uNewState = (nmlistviewPtr2.uNewState & 0x0FFF); + Marshal.StructureToPtr(nmlistviewPtr2, m.LParam, false); + } + else + { + bool isSelected = (nmlistviewPtr2.uNewState & LVIS_SELECTED) == LVIS_SELECTED; + + if (isSelected) + { + // System.Diagnostics.Debug.WriteLine(String.Format("Selected: {0}", nmlistviewPtr2.iItem)); + bool isShiftDown = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + + // -1 indicates that all rows are to be selected -- in fact, they already have been. + // We now have to deselect all the disabled objects. + if (nmlistviewPtr2.iItem == -1 || isShiftDown) { + Stopwatch sw = Stopwatch.StartNew(); + foreach (object disabledModel in this.DisabledObjects) + { + int modelIndex = this.IndexOf(disabledModel); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Deselecting took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks)); + } + else + { + // If the object just selected is disabled, explicitly de-select it + OLVListItem olvi = this.GetItem(nmlistviewPtr2.iItem); + if (olvi != null && !olvi.Enabled) + NativeMethods.DeselectOneItem(this, nmlistviewPtr2.iItem); + } + } + } + } + break; + + case LVN_ITEMCHANGING: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGING"); + NativeMethods.NMLISTVIEW nmlistviewPtr = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr.uNewState); + + if (currentValue != newCheckValue) { + // Prevent the base method from seeing the state change, + // since we handled it elsewhere + nmlistviewPtr.uChanged &= ~LVIF_STATE; + Marshal.StructureToPtr(nmlistviewPtr, m.LParam, false); + } + } + break; + + case LVN_HOTTRACK: + break; + + case LVN_GETDISPINFO: + break; + + case LVN_GROUPINFO: + //System.Diagnostics.Debug.WriteLine("reflect notify: GROUP INFO"); + isMsgHandled = this.HandleGroupInfo(ref m); + break; + + //default: + //System.Diagnostics.Debug.WriteLine(String.Format("reflect notify: {0}", nmhdr.code)); + //break; + } + + return isMsgHandled; + } + private bool skipNextHitTest; + + private CheckState CalculateCheckState(int state) { + switch ((state & 0xf000) >> 12) { + case 1: + return CheckState.Unchecked; + case 2: + return CheckState.Checked; + case 3: + return CheckState.Indeterminate; + default: + return CheckState.Checked; + } + } + + /// + /// In the notification messages, we handle attempts to change the width of our columns + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected bool HandleNotify(ref Message m) { + bool isMsgHandled = false; + + const int NM_CUSTOMDRAW = -12; + + const int HDN_FIRST = (0 - 300); + const int HDN_ITEMCHANGINGA = (HDN_FIRST - 0); + const int HDN_ITEMCHANGINGW = (HDN_FIRST - 20); + const int HDN_ITEMCLICKA = (HDN_FIRST - 2); + const int HDN_ITEMCLICKW = (HDN_FIRST - 22); + const int HDN_DIVIDERDBLCLICKA = (HDN_FIRST - 5); + const int HDN_DIVIDERDBLCLICKW = (HDN_FIRST - 25); + const int HDN_BEGINTRACKA = (HDN_FIRST - 6); + const int HDN_BEGINTRACKW = (HDN_FIRST - 26); + const int HDN_ENDTRACKA = (HDN_FIRST - 7); + const int HDN_ENDTRACKW = (HDN_FIRST - 27); + const int HDN_TRACKA = (HDN_FIRST - 8); + const int HDN_TRACKW = (HDN_FIRST - 28); + + // Handle the notification, remembering to handle both ANSI and Unicode versions + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Debug.WriteLine(String.Format("not: {0}", nmhdr->code)); + + //if (nmhdr.code < HDN_FIRST) + // System.Diagnostics.Debug.WriteLine(nmhdr.code); + + // In KB Article #183258, MS states that when a header control has the HDS_FULLDRAG style, it will receive + // ITEMCHANGING events rather than TRACK events. Under XP SP2 (at least) this is not always true, which may be + // why MS has withdrawn that particular KB article. It is true that the header is always given the HDS_FULLDRAG + // style. But even while window style set, the control doesn't always received ITEMCHANGING events. + // The controlling setting seems to be the Explorer option "Show Window Contents While Dragging"! + // In the category of "truly bizarre side effects", if the this option is turned on, we will receive + // ITEMCHANGING events instead of TRACK events. But if it is turned off, we receive lots of TRACK events and + // only one ITEMCHANGING event at the very end of the process. + // If we receive HDN_TRACK messages, it's harder to control the resizing process. If we return a result of 1, we + // cancel the whole drag operation, not just that particular track event, which is clearly not what we want. + // If we are willing to compile with unsafe code enabled, we can modify the size of the column in place, using the + // commented out code below. But without unsafe code, the best we can do is allow the user to drag the column to + // any width, and then spring it back to within bounds once they release the mouse button. UI-wise it's very ugly. + switch (nmheader.nhdr.code) { + + case NM_CUSTOMDRAW: + if (!this.OwnerDrawnHeader) + isMsgHandled = this.HeaderControl.HandleHeaderCustomDraw(ref m); + break; + + case HDN_ITEMCLICKA: + case HDN_ITEMCLICKW: + if (!this.PossibleFinishCellEditing()) + { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + break; + + case HDN_DIVIDERDBLCLICKA: + case HDN_DIVIDERDBLCLICKW: + case HDN_BEGINTRACKA: + case HDN_BEGINTRACKW: + if (!this.PossibleFinishCellEditing()) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + break; + } + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + OLVColumn column = this.GetColumn(nmheader.iItem); + // Space filling columns can't be dragged or double-click resized + if (column.FillsFreeSpace) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + break; + case HDN_ENDTRACKA: + case HDN_ENDTRACKW: + //if (this.ShowGroups) + // this.ResizeLastGroup(); + break; + case HDN_TRACKA: + case HDN_TRACKW: + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + if (hditem.cxy < column.MinimumWidth) + hditem.cxy = column.MinimumWidth; + else if (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth) + hditem.cxy = column.MaximumWidth; + Marshal.StructureToPtr(hditem, nmheader.pHDITEM, false); + } + break; + + case HDN_ITEMCHANGINGA: + case HDN_ITEMCHANGINGW: + nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + // Check the mask to see if the width field is valid, and if it is, make sure it's within range + if ((hditem.mask & 1) == 1) { + if (hditem.cxy < column.MinimumWidth || + (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth)) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + } + break; + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("olv TTN_SHOW"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleShow(ref m); + break; + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("olv TTN_POP"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandlePop(ref m); + break; + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("olv TTN_GETDISPINFO"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleGetDispInfo(ref m); + break; + +// default: +// System.Diagnostics.Debug.WriteLine(String.Format("notify: {0}", nmheader.nhdr.code)); +// break; + } + + return isMsgHandled; + } + + /// + /// Create a ToolTipControl to manage the tooltip control used by the listview control + /// + protected virtual void CreateCellToolTip() { + this.cellToolTip = new ToolTipControl(); + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + this.cellToolTip.Showing += new EventHandler(HandleCellToolTipShowing); + this.cellToolTip.SetMaxWidth(); + NativeMethods.MakeTopMost(this.cellToolTip); + } + + /// + /// Update the handle used by our cell tooltip to be the tooltip used by + /// the underlying Windows listview control. + /// + protected virtual void UpdateCellToolTipHandle() { + if (this.cellToolTip != null && this.cellToolTip.Handle == IntPtr.Zero) + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + } + + /// + /// Handle the WM_PAINT event + /// + /// + /// Return true if the msg has been handled and nothing further should be done + protected virtual bool HandlePaint(ref Message m) { + //System.Diagnostics.Debug.WriteLine("> WMPAINT"); + + // We only want to custom draw the control within WmPaint message and only + // once per paint event. We use these bools to insure this. + this.isInWmPaintEvent = true; + this.shouldDoCustomDrawing = true; + this.prePaintLevel = 0; + + this.ShowOverlays(); + + this.HandlePrePaint(); + base.WndProc(ref m); + this.HandlePostPaint(); + this.isInWmPaintEvent = false; + //System.Diagnostics.Debug.WriteLine("< WMPAINT"); + return true; + } + private int prePaintLevel; + + /// + /// Perform any steps needed before painting the control + /// + protected virtual void HandlePrePaint() { + // When we get a WM_PAINT msg, remember the rectangle that is being updated. + // We can't get this information later, since the BeginPaint call wipes it out. + // this.lastUpdateRectangle = NativeMethods.GetUpdateRect(this); // we no longer need this, but keep the code so we can see it later + + //// When the list is empty, we want to handle the drawing of the control by ourselves. + //// Unfortunately, there is no easy way to tell our superclass that we want to do this. + //// So we resort to guile and deception. We validate the list area of the control, which + //// effectively tells our superclass that this area does not need to be painted. + //// Our superclass will then not paint the control, leaving us free to do so ourselves. + //// Without doing this trickery, the superclass will draw the list as empty, + //// and then moments later, we will draw the empty list msg, giving a nasty flicker + //if (this.GetItemCount() == 0 && this.HasEmptyListMsg) + // NativeMethods.ValidateRect(this, this.ClientRectangle); + } + + /// + /// Perform any steps needed after painting the control + /// + protected virtual void HandlePostPaint() { + // This message is no longer necessary, but we keep it for compatibility + } + + /// + /// Handle the window position changing. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleWindowPosChanging(ref Message m) { + const int SWP_NOSIZE = 1; + + NativeMethods.WINDOWPOS pos = (NativeMethods.WINDOWPOS)m.GetLParam(typeof(NativeMethods.WINDOWPOS)); + if ((pos.flags & SWP_NOSIZE) == 0) { + if (pos.cx < this.Bounds.Width) // only when shrinking + // pos.cx is the window width, not the client area width, so we have to subtract the border widths + this.ResizeFreeSpaceFillingColumns(pos.cx - (this.Bounds.Width - this.ClientSize.Width)); + } + + return false; + } + + #endregion + + #region Column header clicking, column hiding and resizing + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + protected virtual bool HandleHeaderRightClick(int columnIndex) { + ToolStripDropDown menu = this.MakeHeaderRightClickMenu(columnIndex); + ColumnRightClickEventArgs eventArgs = new ColumnRightClickEventArgs(columnIndex, menu, Cursor.Position); + this.OnColumnRightClick(eventArgs); + + // Did the event handler stop any further processing? + if (eventArgs.Cancel) + return false; + + return this.ShowHeaderRightClickMenu(columnIndex, eventArgs.MenuStrip, eventArgs.Location); + } + + /// + /// Show a menu that is appropriate when the given column header is clicked. + /// + /// The index of the header that was clicked. This + /// can be -1, indicating that the header was clicked outside of a column + /// Where should the menu be shown + /// True if a menu was displayed + protected virtual bool ShowHeaderRightClickMenu(int columnIndex, ToolStripDropDown menu, Point pt) { + if (menu.Items.Count > 0) { + menu.Show(pt); + return true; + } + + return false; + } + + /// + /// Create the menu that should be displayed when the user right clicks + /// on the given column header. + /// + /// Index of the column that was right clicked. + /// This can be negative, which indicates a click outside of any header. + /// The toolstrip that should be displayed + protected virtual ToolStripDropDown MakeHeaderRightClickMenu(int columnIndex) { + ToolStripDropDown m = new ContextMenuStrip(); + + if (columnIndex >= 0 && this.UseFiltering && this.ShowFilterMenuOnRightClick) + m = this.MakeFilteringMenu(m, columnIndex); + + if (columnIndex >= 0 && this.ShowCommandMenuOnRightClick) + m = this.MakeColumnCommandMenu(m, columnIndex); + + if (this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None) { + m = this.MakeColumnSelectMenu(m); + } + + return m; + } + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + [Obsolete("Use HandleHeaderRightClick(int) instead")] + protected virtual bool HandleHeaderRightClick() { + return false; + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnSelectMenu(Point pt) { + ToolStripDropDown m = this.MakeColumnSelectMenu(new ContextMenuStrip()); + m.Show(pt); + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnCommandMenu(int columnIndex, Point pt) { + ToolStripDropDown m = this.MakeColumnCommandMenu(new ContextMenuStrip(), columnIndex); + if (this.SelectColumnsOnRightClick) { + if (m.Items.Count > 0) + m.Items.Add(new ToolStripSeparator()); + this.MakeColumnSelectMenu(m); + } + m.Show(pt); + } + + /// + /// Gets or set the text to be used for the sorting ascending command + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort ascending by '{0}'"), Localizable(true)] + public string MenuLabelSortAscending { + get { return this.menuLabelSortAscending; } + set { this.menuLabelSortAscending = value; } + } + private string menuLabelSortAscending = "Sort ascending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort descending by '{0}'"), Localizable(true)] + public string MenuLabelSortDescending { + get { return this.menuLabelSortDescending; } + set { this.menuLabelSortDescending = value; } + } + private string menuLabelSortDescending = "Sort descending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Group by '{0}'"), Localizable(true)] + public string MenuLabelGroupBy { + get { return this.menuLabelGroupBy; } + set { this.menuLabelGroupBy = value; } + } + private string menuLabelGroupBy = "Group by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Lock grouping on '{0}'"), Localizable(true)] + public string MenuLabelLockGroupingOn { + get { return this.menuLabelLockGroupingOn; } + set { this.menuLabelLockGroupingOn = value; } + } + private string menuLabelLockGroupingOn = "Lock grouping on '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unlock grouping from '{0}'"), Localizable(true)] + public string MenuLabelUnlockGroupingOn { + get { return this.menuLabelUnlockGroupingOn; } + set { this.menuLabelUnlockGroupingOn = value; } + } + private string menuLabelUnlockGroupingOn = "Unlock grouping from '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Turn off groups"), Localizable(true)] + public string MenuLabelTurnOffGroups { + get { return this.menuLabelTurnOffGroups; } + set { this.menuLabelTurnOffGroups = value; } + } + private string menuLabelTurnOffGroups = "Turn off groups"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unsort"), Localizable(true)] + public string MenuLabelUnsort { + get { return this.menuLabelUnsort; } + set { this.menuLabelUnsort = value; } + } + private string menuLabelUnsort = "Unsort"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Columns"), Localizable(true)] + public string MenuLabelColumns { + get { return this.menuLabelColumns; } + set { this.menuLabelColumns = value; } + } + private string menuLabelColumns = "Columns"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Select Columns..."), Localizable(true)] + public string MenuLabelSelectColumns { + get { return this.menuLabelSelectColumns; } + set { this.menuLabelSelectColumns = value; } + } + private string menuLabelSelectColumns = "Select Columns..."; + + /// + /// Gets or sets the image that will be place next to the Sort Ascending command + /// + public static Bitmap SortAscendingImage = BrightIdeasSoftware.Properties.Resources.SortAscending; + + /// + /// Gets or sets the image that will be placed next to the Sort Descending command + /// + public static Bitmap SortDescendingImage = BrightIdeasSoftware.Properties.Resources.SortDescending; + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnCommandMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + if (strip.Items.Count > 0) + strip.Items.Add(new ToolStripSeparator()); + + string label = String.Format(this.MenuLabelSortAscending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortAscendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Ascending); + }); + } + label = String.Format(this.MenuLabelSortDescending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortDescendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Descending); + }); + } + if (this.CanShowGroups) { + label = String.Format(this.MenuLabelGroupBy, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.PrimarySortColumn = column; + this.PrimarySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + if (this.ShowGroups) { + if (this.AlwaysGroupByColumn == column) { + label = String.Format(this.MenuLabelUnlockGroupingOn, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.AlwaysGroupByColumn = null; + this.AlwaysGroupBySortOrder = SortOrder.None; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelLockGroupingOn, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.AlwaysGroupByColumn = column; + this.AlwaysGroupBySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + label = String.Format(this.MenuLabelTurnOffGroups, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = false; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelUnsort, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label) && this.PrimarySortOrder != SortOrder.None) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.Unsort(); + }); + } + } + + return strip; + } + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnSelectMenu(ToolStripDropDown strip) { + + System.Diagnostics.Debug.Assert(this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None); + + // Append a separator if the menu isn't empty and the last item isn't already a separator + if (strip.Items.Count > 0 && (!(strip.Items[strip.Items.Count-1] is ToolStripSeparator))) + strip.Items.Add(new ToolStripSeparator()); + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.ModelDialog) { + strip.Items.Add(this.MenuLabelSelectColumns, null, delegate(object sender, EventArgs args) { + (new ColumnSelectionForm()).OpenOn(this); + }); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.Submenu) { + ToolStripMenuItem menu = new ToolStripMenuItem(this.MenuLabelColumns); + menu.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Items.Add(menu); + this.AddItemsToColumnSelectMenu(menu.DropDownItems); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.InlineMenu) { + strip.ItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Closing += new ToolStripDropDownClosingEventHandler(this.ColumnSelectMenuClosing); + this.AddItemsToColumnSelectMenu(strip.Items); + } + + return strip; + } + + /// + /// Create the menu items that will allow columns to be choosen and add them to the + /// given collection + /// + /// + protected void AddItemsToColumnSelectMenu(ToolStripItemCollection items) { + + // Sort columns by display order + List columns = new List(this.AllColumns); + columns.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + + // Build menu from sorted columns + foreach (OLVColumn col in columns) { + ToolStripMenuItem mi = new ToolStripMenuItem(col.Text); + mi.Checked = col.IsVisible; + mi.Tag = col; + + // The 'Index' property returns -1 when the column is not visible, so if the + // column isn't visible we have to enable the item. Also the first column can't be turned off + mi.Enabled = !col.IsVisible || col.CanBeHidden; + items.Add(mi); + } + } + + private void ColumnSelectMenuItemClicked(object sender, ToolStripItemClickedEventArgs e) { + this.contextMenuStaysOpen = false; + ToolStripMenuItem menuItemClicked = e.ClickedItem as ToolStripMenuItem; + if (menuItemClicked == null) + return; + OLVColumn col = menuItemClicked.Tag as OLVColumn; + if (col == null) + return; + menuItemClicked.Checked = !menuItemClicked.Checked; + col.IsVisible = menuItemClicked.Checked; + this.contextMenuStaysOpen = this.SelectColumnsMenuStaysOpen; + this.BeginInvoke(new MethodInvoker(this.RebuildColumns)); + } + private bool contextMenuStaysOpen; + + private void ColumnSelectMenuClosing(object sender, ToolStripDropDownClosingEventArgs e) { + e.Cancel = this.contextMenuStaysOpen && e.CloseReason == ToolStripDropDownCloseReason.ItemClicked; + this.contextMenuStaysOpen = false; + } + + /// + /// Create a Filtering menu + /// + /// + /// + /// + public virtual ToolStripDropDown MakeFilteringMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + FilterMenuBuilder strategy = this.FilterMenuBuildStrategy; + if (strategy == null) + return strip; + + return strategy.MakeFilterMenu(strip, this, column); + } + + /// + /// Override the OnColumnReordered method to do what we want + /// + /// + protected override void OnColumnReordered(ColumnReorderedEventArgs e) { + base.OnColumnReordered(e); + + // The internal logic of the .NET code behind a ENDDRAG event means that, + // at this point, the DisplayIndex's of the columns are not yet as they are + // going to be. So we have to invoke a method to run later that will remember + // what the real DisplayIndex's are. + this.BeginInvoke(new MethodInvoker(this.RememberDisplayIndicies)); + } + + private void RememberDisplayIndicies() { + // Remember the display indexes so we can put them back at a later date + foreach (OLVColumn x in this.AllColumns) + x.LastDisplayIndex = x.DisplayIndex; + } + + /// + /// When the column widths are changing, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) { + if (this.UpdateSpaceFillingColumnsWhenDraggingColumnDivider && !this.GetColumn(e.ColumnIndex).FillsFreeSpace) { + // If the width of a column is increasing, resize any space filling columns allowing the extra + // space that the new column width is going to consume + int oldWidth = this.GetColumn(e.ColumnIndex).Width; + if (e.NewWidth > oldWidth) + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width - (e.NewWidth - oldWidth)); + else + this.ResizeFreeSpaceFillingColumns(); + } + } + + /// + /// When the column widths change, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { + if (!this.GetColumn(e.ColumnIndex).FillsFreeSpace) + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// When the size of the control changes, we have to resize our space filling columns. + /// + /// + /// + protected virtual void HandleLayout(object sender, LayoutEventArgs e) { + // We have to delay executing the recalculation of the columns, since virtual lists + // get terribly confused if we resize the column widths during this event. + if (!this.hasResizeColumnsHandler) { + this.hasResizeColumnsHandler = true; + this.RunWhenIdle(this.HandleApplicationIdleResizeColumns); + } + } + + private void RunWhenIdle(EventHandler eventHandler) { + Application.Idle += eventHandler; + if (!this.CanUseApplicationIdle) { + SynchronizationContext.Current.Post(delegate(object x) { Application.RaiseIdle(EventArgs.Empty); }, null); + } + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns() { + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width); + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns(int freeSpace) { + // It's too confusing to dynamically resize columns at design time. + if (this.DesignMode) + return; + + if (this.Frozen) + return; + + this.BeginUpdate(); + + // Calculate the free space available + int totalProportion = 0; + List spaceFillingColumns = new List(); + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + if (col.FillsFreeSpace) { + spaceFillingColumns.Add(col); + totalProportion += col.FreeSpaceProportion; + } else + freeSpace -= col.Width; + } + freeSpace = Math.Max(0, freeSpace); + + // Any space filling column that would hit it's Minimum or Maximum + // width must be treated as a fixed column. + foreach (OLVColumn col in spaceFillingColumns.ToArray()) { + int newWidth = (freeSpace * col.FreeSpaceProportion) / totalProportion; + + if (col.MinimumWidth != -1 && newWidth < col.MinimumWidth) + newWidth = col.MinimumWidth; + else if (col.MaximumWidth != -1 && newWidth > col.MaximumWidth) + newWidth = col.MaximumWidth; + else + newWidth = 0; + + if (newWidth > 0) { + col.Width = newWidth; + freeSpace -= newWidth; + totalProportion -= col.FreeSpaceProportion; + spaceFillingColumns.Remove(col); + } + } + + // Distribute the free space between the columns + foreach (OLVColumn col in spaceFillingColumns) { + col.Width = (freeSpace*col.FreeSpaceProportion)/totalProportion; + } + + this.EndUpdate(); + } + + #endregion + + #region Checkboxes + + /// + /// Check all rows + /// + public virtual void CheckAll() + { + this.CheckedObjects = EnumerableToArray(this.Objects, false); + } + + /// + /// Check the checkbox in the given column header + /// + /// If the given columns header check box is linked to the cell check boxes, + /// then checkboxes in all cells will also be checked. + /// + public virtual void CheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Checked); + } + + /// + /// Mark the checkbox in the given column header as having an indeterminate value + /// + /// + public virtual void CheckIndeterminateHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Indeterminate); + } + + /// + /// Mark the given object as indeterminate check state + /// + /// The model object to be marked indeterminate + public virtual void CheckIndeterminateObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Indeterminate); + } + + /// + /// Mark the given object as checked in the list + /// + /// The model object to be checked + public virtual void CheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Checked); + } + + /// + /// Mark the given objects as checked in the list + /// + /// The model object to be checked + public virtual void CheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.CheckObject(model); + } + + /// + /// Put a check into the check box at the given cell + /// + /// + /// + public virtual void CheckSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Checked); + this.RefreshObject(rowObject); + } + + /// + /// Put an indeterminate check into the check box at the given cell + /// + /// + /// + public virtual void CheckIndeterminateSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Indeterminate); + this.RefreshObject(rowObject); + } + + /// + /// Return true of the given object is checked + /// + /// The model object whose checkedness is returned + /// Is the given object checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsChecked(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Checked; + } + + /// + /// Return true of the given object is indeterminately checked + /// + /// The model object whose checkedness is returned + /// Is the given object indeterminately checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsCheckedIndeterminate(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Indeterminate; + } + + /// + /// Is there a check at the check box at the given cell + /// + /// + /// + public virtual bool IsSubItemChecked(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return false; + return (column.GetCheckState(rowObject) == CheckState.Checked); + } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does not know and the value from the control will be used. + /// + /// + /// + protected virtual CheckState? GetCheckState(Object modelObject) { + if (this.CheckStateGetter != null) + return this.CheckStateGetter(modelObject); + return this.PersistentCheckBoxes ? this.GetPersistentCheckState(modelObject) : (CheckState?)null; + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected virtual CheckState PutCheckState(Object modelObject, CheckState state) { + if (this.CheckStatePutter != null) + return this.CheckStatePutter(modelObject, state); + return this.PersistentCheckBoxes ? this.SetPersistentCheckState(modelObject, state) : state; + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected virtual bool SetObjectCheckedness(object modelObject, CheckState state) { + + if (GetCheckState(modelObject) == state) + return false; + + OLVListItem olvi = this.ModelToItem(modelObject); + + // If we didn't find the given, we still try to record the check state. + if (olvi == null) { + this.PutCheckState(modelObject, state); + return true; + } + + // Trigger checkbox changing event + ItemCheckEventArgs ice = new ItemCheckEventArgs(olvi.Index, state, olvi.CheckState); + this.OnItemCheck(ice); + if (ice.NewValue == olvi.CheckState) + return false; + + olvi.CheckState = this.PutCheckState(modelObject, state); + this.RefreshItem(olvi); + + // Trigger check changed event + this.OnItemChecked(new ItemCheckedEventArgs(olvi)); + return true; + } + + /// + /// Toggle the checkedness of the given object. A checked object becomes + /// unchecked; an unchecked or indeterminate object becomes checked. + /// If the list has tristate checkboxes, the order is: + /// unchecked -> checked -> indeterminate -> unchecked ... + /// + /// The model object to be checked + public virtual void ToggleCheckObject(object modelObject) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi == null) + return; + + CheckState newState = CheckState.Checked; + + if (olvi.CheckState == CheckState.Checked) { + newState = this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + } else { + if (olvi.CheckState == CheckState.Indeterminate && this.TriStateCheckBoxes) + newState = CheckState.Unchecked; + } + this.SetObjectCheckedness(modelObject, newState); + } + + /// + /// Toggle the checkbox in the header of the given column + /// + /// Obviously, this is only useful if the column actually has a header checkbox. + /// + public virtual void ToggleHeaderCheckBox(OLVColumn column) { + if (column == null) + return; + + CheckState newState = CalculateToggledCheckState(column.HeaderCheckState, column.HeaderTriStateCheckBox, column.HeaderCheckBoxDisabled); + ChangeHeaderCheckBoxState(column, newState); + } + + private void ChangeHeaderCheckBoxState(OLVColumn column, CheckState newState) { + // Tell the world the checkbox was clicked + HeaderCheckBoxChangingEventArgs args = new HeaderCheckBoxChangingEventArgs(); + args.Column = column; + args.NewCheckState = newState; + + this.OnHeaderCheckBoxChanging(args); + if (args.Cancel || column.HeaderCheckState == args.NewCheckState) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + column.HeaderCheckState = args.NewCheckState; + this.HeaderControl.Invalidate(column); + + if (column.HeaderCheckBoxUpdatesRowCheckBoxes) { + if (column.Index == 0) + this.UpdateAllPrimaryCheckBoxes(column); + else + this.UpdateAllSubItemCheckBoxes(column); + } + + // Debug.WriteLine(String.Format("PERF - Changing row checkboxes on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + private void UpdateAllPrimaryCheckBoxes(OLVColumn column) { + if (!this.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + if (column.HeaderCheckState == CheckState.Checked) + CheckAll(); + else + UncheckAll(); + } + + private void UpdateAllSubItemCheckBoxes(OLVColumn column) { + if (!column.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + foreach (object model in this.Objects) + column.PutCheckState(model, column.HeaderCheckState); + this.BuildList(true); + } + + /// + /// Toggle the check at the check box of the given cell + /// + /// + /// + public virtual void ToggleSubItemCheckBox(object rowObject, OLVColumn column) { + CheckState currentState = column.GetCheckState(rowObject); + CheckState newState = CalculateToggledCheckState(currentState, column.TriStateCheckBoxes, false); + + SubItemCheckingEventArgs args = new SubItemCheckingEventArgs(column, this.ModelToItem(rowObject), column.Index, currentState, newState); + this.OnSubItemChecking(args); + if (args.Canceled) + return; + + switch (args.NewValue) { + case CheckState.Checked: + this.CheckSubItem(rowObject, column); + break; + case CheckState.Indeterminate: + this.CheckIndeterminateSubItem(rowObject, column); + break; + case CheckState.Unchecked: + this.UncheckSubItem(rowObject, column); + break; + } + } + + /// + /// Uncheck all rows + /// + public virtual void UncheckAll() + { + this.CheckedObjects = null; + } + + /// + /// Mark the given object as unchecked in the list + /// + /// The model object to be unchecked + public virtual void UncheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Unchecked); + } + + /// + /// Mark the given objects as unchecked in the list + /// + /// The model object to be checked + public virtual void UncheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.UncheckObject(model); + } + + /// + /// Uncheck the checkbox in the given column header + /// + /// + public virtual void UncheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Unchecked); + } + + /// + /// Uncheck the check at the given cell + /// + /// + /// + public virtual void UncheckSubItem(object rowObject, OLVColumn column) + { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Unchecked); + this.RefreshObject(rowObject); + } + + #endregion + + #region OLV accessing + + /// + /// Return the column at the given index + /// + /// Index of the column to be returned + /// An OLVColumn, or null if the index is out of bounds + public virtual OLVColumn GetColumn(int index) { + return (index >=0 && index < this.Columns.Count) ? (OLVColumn)this.Columns[index] : null; + } + + /// + /// Return the column at the given title. + /// + /// Name of the column to be returned + /// An OLVColumn + public virtual OLVColumn GetColumn(string name) { + foreach (ColumnHeader column in this.Columns) { + if (column.Text == name) + return (OLVColumn)column; + } + return null; + } + + /// + /// Return a collection of columns that are visible to the given view. + /// Only Tile and Details have columns; all other views have 0 columns. + /// + /// Which view are the columns being calculate for? + /// A list of columns + public virtual List GetFilteredColumns(View view) { + // For both detail and tile view, the first column must be included. Normally, we would + // use the ColumnHeader.Index property, but if the header is not currently part of a ListView + // that property returns -1. So, we track the index of + // the column header, and always include the first header. + + int index = 0; + return this.AllColumns.FindAll(delegate(OLVColumn x) { + return (index++ == 0) || x.IsVisible; + }); + } + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + /// If a filter is installed, this will return the number of items that match the filter. + public virtual int GetItemCount() { + return this.Items.Count; + } + + /// + /// Return the item at the given index + /// + /// Index of the item to be returned + /// An OLVListItem + public virtual OLVListItem GetItem(int index) { + if (index < 0 || index >= this.GetItemCount()) + return null; + + return (OLVListItem)this.Items[index]; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public virtual object GetModelObject(int index) { + OLVListItem item = this.GetItem(index); + return item == null ? null : item.RowObject; + } + + /// + /// Find the item and column that are under the given co-ords + /// + /// X co-ord + /// Y co-ord + /// The column under the given point + /// The item under the given point. Can be null. + public virtual OLVListItem GetItemAt(int x, int y, out OLVColumn hitColumn) { + hitColumn = null; + ListViewHitTestInfo info = this.HitTest(x, y); + if (info.Item == null) + return null; + + if (info.SubItem != null) { + int subItemIndex = info.Item.SubItems.IndexOf(info.SubItem); + hitColumn = this.GetColumn(subItemIndex); + } + + return (OLVListItem)info.Item; + } + + /// + /// Return the sub item at the given index/column + /// + /// Index of the item to be returned + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index, int columnIndex) { + OLVListItem olvi = this.GetItem(index); + return olvi == null ? null : olvi.GetSubItem(columnIndex); + } + + #endregion + + #region Object manipulation + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// This does not work on virtual lists, since virtual lists don't use ListViewGroups + /// for grouping. Use instead. + /// + public virtual void EnsureGroupVisible(ListViewGroup lvg) { + if (!this.ShowGroups || lvg == null) + return; + + int groupIndex = this.Groups.IndexOf(lvg); + if (groupIndex <= 0) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + ListViewGroup previousGroup = this.Groups[groupIndex - 1]; + ListViewItem lastItemInGroup = previousGroup.Items[previousGroup.Items.Count - 1]; + Rectangle r = this.GetItemRect(lastItemInGroup.Index); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Ensure that the given model object is visible + /// + /// The model object to be revealed + public virtual void EnsureModelVisible(Object modelObject) { + int index = this.IndexOf(modelObject); + if (index >= 0) + this.EnsureVisible(index); + } + + /// + /// Return the model object of the row that is selected or null if there is no selection or more than one selection + /// + /// Model object or null + [Obsolete("Use SelectedObject property instead of this method")] + public virtual object GetSelectedObject() { + return this.SelectedObject; + } + + /// + /// Return the model objects of the rows that are selected or an empty collection if there is no selection + /// + /// ArrayList + [Obsolete("Use SelectedObjects property instead of this method")] + public virtual ArrayList GetSelectedObjects() { + return ObjectListView.EnumerableToArray(this.SelectedObjects, false); + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + /// Model object or null + /// Use CheckedObject property instead of this method + [Obsolete("Use CheckedObject property instead of this method")] + public virtual object GetCheckedObject() { + return this.CheckedObject; + } + + /// + /// Get the collection of model objects that are checked. + /// + /// Use CheckedObjects property instead of this method + [Obsolete("Use CheckedObjects property instead of this method")] + public virtual ArrayList GetCheckedObjects() { + return ObjectListView.EnumerableToArray(this.CheckedObjects, false); + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public virtual int IndexOf(Object modelObject) { + for (int i = 0; i < this.GetItemCount(); i++) { + if (this.GetModelObject(i).Equals(modelObject)) + return i; + } + return -1; + } + + /// + /// Rebuild the given ListViewItem with the data from its associated model. + /// + /// This method does not resort or regroup the view. It simply updates + /// the displayed data of the given item + public virtual void RefreshItem(OLVListItem olvi) { + olvi.UseItemStyleForSubItems = true; + olvi.SubItems.Clear(); + this.FillInValues(olvi, olvi.RowObject); + this.PostProcessOneRow(olvi.Index, this.GetDisplayOrderOfItemIndex(olvi.Index), olvi); + } + + /// + /// Rebuild the data on the row that is showing the given object. + /// + /// + /// + /// This method does not resort or regroup the view. + /// + /// + /// The given object is *not* used as the source of data for the rebuild. + /// It is only used to locate the matching model in the collection, + /// then that matching model is used as the data source. This distinction is + /// only important in model classes that have overridden the Equals() method. + /// + /// + /// If you want the given model object to replace the pre-existing model, + /// use . + /// + /// + public virtual void RefreshObject(object modelObject) { + this.RefreshObjects(new object[] { modelObject }); + } + + /// + /// Update the rows that are showing the given objects + /// + /// + /// This method does not resort or regroup the view. + /// This method can safely be called from background threads. + /// + public virtual void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + this.ReplaceModel(olvi, modelObject); + this.RefreshItem(olvi); + } + } + } + + private void ReplaceModel(OLVListItem olvi, object newModel) { + if (ReferenceEquals(olvi.RowObject, newModel)) + return; + + this.TakeOwnershipOfObjects(); + ArrayList array = ObjectListView.EnumerableToArray(this.Objects, false); + int i = array.IndexOf(olvi.RowObject); + if (i >= 0) + array[i] = newModel; + + olvi.RowObject = newModel; + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public virtual void RefreshSelectedObjects() { + foreach (ListViewItem lvi in this.SelectedItems) + this.RefreshItem((OLVListItem)lvi); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject) { + this.SelectObject(modelObject, false); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Should the object be focused as well? + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject, bool setFocus) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) { + olvi.Selected = true; + if (setFocus) + olvi.Focused = true; + } + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + public virtual void SelectObjects(IList modelObjects) { + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) + olvi.Selected = true; + } + } + + #endregion + + #region Freezing/Suspending + + /// + /// Get or set whether or not the listview is frozen. When the listview is + /// frozen, it will not update itself. + /// + /// The Frozen property is similar to the methods Freeze()/Unfreeze() + /// except that setting Frozen property to false immediately unfreezes the control + /// regardless of the number of Freeze() calls outstanding. + /// objectListView1.Frozen = false; // unfreeze the control now! + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool Frozen { + get { return freezeCount > 0; } + set { + if (value) + Freeze(); + else if (freezeCount > 0) { + freezeCount = 1; + Unfreeze(); + } + } + } + private int freezeCount; + + /// + /// Freeze the listview so that it no longer updates itself. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Freeze() { + if (freezeCount == 0) + DoFreeze(); + + freezeCount++; + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Unfreeze the listview. If this call is the outermost Unfreeze(), + /// the contents of the listview will be rebuilt. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Unfreeze() { + if (freezeCount <= 0) + return; + + freezeCount--; + if (freezeCount == 0) + DoUnfreeze(); + + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Do the actual work required when the listview is frozen + /// + protected virtual void DoFreeze() { + this.BeginUpdate(); + } + + /// + /// Do the actual work required when the listview is unfrozen + /// + protected virtual void DoUnfreeze() + { + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + this.BuildList(); + } + + /// + /// Returns true if selection events are currently suspended. + /// While selection events are suspended, neither SelectedIndexChanged + /// or SelectionChanged events will be raised. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected bool SelectionEventsSuspended { + get { return this.suspendSelectionEventCount > 0; } + } + + /// + /// Suspend selection events until a matching ResumeSelectionEvents() + /// is called. + /// + /// Calls to this method nest correctly. Every call to SuspendSelectionEvents() + /// must have a matching ResumeSelectionEvents(). + protected void SuspendSelectionEvents() { + this.suspendSelectionEventCount++; + } + + /// + /// Resume raising selection events. + /// + protected void ResumeSelectionEvents() { + Debug.Assert(this.SelectionEventsSuspended, "Mismatched called to ResumeSelectionEvents()"); + this.suspendSelectionEventCount--; + } + + /// + /// Returns a disposable that will disable selection events + /// during a using() block. + /// + /// + protected IDisposable SuspendSelectionEventsDuring() { + return new SuspendSelectionDisposable(this); + } + + /// + /// Implementation only class that suspends and resumes selection + /// events on instance creation and disposal. + /// + private class SuspendSelectionDisposable : IDisposable { + public SuspendSelectionDisposable(ObjectListView objectListView) { + this.objectListView = objectListView; + this.objectListView.SuspendSelectionEvents(); + } + + public void Dispose() { + this.objectListView.ResumeSelectionEvents(); + } + + private readonly ObjectListView objectListView; + } + + #endregion + + #region Column sorting + + /// + /// Sort the items by the last sort column and order + /// + public new void Sort() { + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The name of the column whose values will be used for the sorting + public virtual void Sort(string columnToSortName) { + this.Sort(this.GetColumn(columnToSortName), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The index of the column whose values will be used for the sorting + public virtual void Sort(int columnToSortIndex) { + if (columnToSortIndex >= 0 && columnToSortIndex < this.Columns.Count) + this.Sort(this.GetColumn(columnToSortIndex), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The column whose values will be used for the sorting + public virtual void Sort(OLVColumn columnToSort) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort); }); + } else { + this.Sort(columnToSort, this.PrimarySortOrder); + } + } + + /// + /// Sort the items in the list view by the values in the given column and by the given order. + /// + /// The column whose values will be used for the sorting. + /// If null, the first column will be used. + /// The ordering to be used for sorting. If this is None, + /// this.Sorting and then SortOrder.Ascending will be used + /// If ShowGroups is true, the rows will be grouped by the given column. + /// If AlwaysGroupsByColumn is not null, the rows will be grouped by that column, + /// and the rows within each group will be sorted by the given column. + public virtual void Sort(OLVColumn columnToSort, SortOrder order) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort, order); }); + } else { + this.DoSort(columnToSort, order); + this.PostProcessRows(); + } + } + + private void DoSort(OLVColumn columnToSort, SortOrder order) { + // Sanity checks + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + // Fill in default values, if the parameters don't make sense + if (this.ShowGroups) { + columnToSort = columnToSort ?? this.GetColumn(0); + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + } + + // Give the world a chance to fiddle with or completely avoid the sorting process + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(columnToSort, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + // Virtual lists don't preserve selection, so we have to do it specifically + // THINK: Do we need to preserve focus too? + IList selection = this.VirtualMode ? this.SelectedObjects : null; + this.SuspendSelectionEvents(); + + this.ClearHotItem(); + + // Finally, do the work of sorting, unless an event handler has already done the sorting for us + if (!args.Handled) { + // Sanity checks + if (args.ColumnToSort != null && args.SortOrder != SortOrder.None) { + if (this.ShowGroups) + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + else if (this.CustomSorter != null) + this.CustomSorter(args.ColumnToSort, args.SortOrder); + else + this.ListViewItemSorter = new ColumnComparer(args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + } + } + + if (this.ShowSortIndicators) + this.ShowSortIndicator(args.ColumnToSort, args.SortOrder); + + this.PrimarySortColumn = args.ColumnToSort; + this.PrimarySortOrder = args.SortOrder; + + if (selection != null && selection.Count > 0) + this.SelectedObjects = selection; + this.ResumeSelectionEvents(); + + this.RefreshHotItem(); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + /// + /// Put a sort indicator next to the text of the sort column + /// + public virtual void ShowSortIndicator() { + if (this.ShowSortIndicators && this.PrimarySortOrder != SortOrder.None) + this.ShowSortIndicator(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Put a sort indicator next to the text of the given column + /// + /// The column to be marked + /// The sort order in effect on that column + protected virtual void ShowSortIndicator(OLVColumn columnToSort, SortOrder sortOrder) { + int imageIndex = -1; + + if (!NativeMethods.HasBuiltinSortIndicators()) { + // If we can't use builtin image, we have to make and then locate the index of the + // sort indicator we want to use. SortOrder.None doesn't show an image. + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(SORT_INDICATOR_UP_KEY)) + MakeSortIndicatorImages(); + + if (this.SmallImageList != null) + { + string key = sortOrder == SortOrder.Ascending ? SORT_INDICATOR_UP_KEY : SORT_INDICATOR_DOWN_KEY; + imageIndex = this.SmallImageList.Images.IndexOfKey(key); + } + } + + // Set the image for each column + for (int i = 0; i < this.Columns.Count; i++) { + if (columnToSort != null && i == columnToSort.Index) + NativeMethods.SetColumnImage(this, i, sortOrder, imageIndex); + else + NativeMethods.SetColumnImage(this, i, SortOrder.None, -1); + } + } + + /// + /// The name of the image used when a column is sorted ascending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_UP_KEY = "sort-indicator-up"; + + /// + /// The name of the image used when a column is sorted descending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_DOWN_KEY = "sort-indicator-down"; + + /// + /// If the sort indicator images don't already exist, this method will make and install them + /// + protected virtual void MakeSortIndicatorImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + // This arrangement of points works well with (16,16) images, and OK with others + int midX = il.ImageSize.Width / 2; + int midY = (il.ImageSize.Height / 2) - 1; + int deltaX = midX - 2; + int deltaY = deltaX / 2; + + if (il.Images.IndexOfKey(SORT_INDICATOR_UP_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY + deltaY); + Point pt2 = new Point(midX, midY - deltaY - 1); + Point pt3 = new Point(midX + deltaX, midY + deltaY); + il.Images.Add(SORT_INDICATOR_UP_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + if (il.Images.IndexOfKey(SORT_INDICATOR_DOWN_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY - deltaY); + Point pt2 = new Point(midX, midY + deltaY); + Point pt3 = new Point(midX + deltaX, midY - deltaY); + il.Images.Add(SORT_INDICATOR_DOWN_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + this.SmallImageList = il; + } + + private Bitmap MakeTriangleBitmap(Size sz, Point[] pts) { + Bitmap bm = new Bitmap(sz.Width, sz.Height); + Graphics g = Graphics.FromImage(bm); + g.FillPolygon(new SolidBrush(Color.Gray), pts); + return bm; + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + public virtual void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.BuildList(); + } + + #endregion + + #region Utilities + + private static CheckState CalculateToggledCheckState(CheckState currentState, bool isTriState, bool isDisabled) + { + if (isDisabled) + return currentState; + switch (currentState) + { + case CheckState.Checked: return isTriState ? CheckState.Indeterminate : CheckState.Unchecked; + case CheckState.Indeterminate: return CheckState.Unchecked; + default: return CheckState.Checked; + } + } + + /// + /// Do the actual work of creating the given list of groups + /// + /// + protected virtual void CreateGroups(IEnumerable groups) { + this.Groups.Clear(); + // The group must be added before it is given items, otherwise an exception is thrown (is this documented?) + foreach (OLVGroup group in groups) { + group.InsertGroupOldStyle(this); + group.SetItemsOldStyle(); + } + } + + /// + /// For some reason, UseItemStyleForSubItems doesn't work for the colors + /// when owner drawing the list, so we have to specifically give each subitem + /// the desired colors + /// + /// The item whose subitems are to be corrected + /// Cells drawn via BaseRenderer don't need this, but it is needed + /// when an owner drawn cell uses DrawDefault=true + protected virtual void CorrectSubItemColors(ListViewItem olvi) { + } + + /// + /// Fill in the given OLVListItem with values of the given row + /// + /// the OLVListItem that is to be stuff with values + /// the model object from which values will be taken + protected virtual void FillInValues(OLVListItem lvi, object rowObject) { + if (this.Columns.Count == 0) + return; + + OLVListSubItem subItem = this.MakeSubItem(rowObject, this.GetColumn(0)); + lvi.SubItems[0] = subItem; + lvi.ImageSelector = subItem.ImageSelector; + + // Give the item the same font/colors as the control + lvi.Font = this.Font; + lvi.BackColor = this.BackColor; + lvi.ForeColor = this.ForeColor; + + // Should the row be selectable? + lvi.Enabled = !this.IsDisabled(rowObject); + + // Only Details and Tile views have subitems + switch (this.View) { + case View.Details: + for (int i = 1; i < this.Columns.Count; i++) { + lvi.SubItems.Add(this.MakeSubItem(rowObject, this.GetColumn(i))); + } + break; + case View.Tile: + for (int i = 1; i < this.Columns.Count; i++) { + OLVColumn column = this.GetColumn(i); + if (column.IsTileViewColumn) + lvi.SubItems.Add(this.MakeSubItem(rowObject, column)); + } + break; + } + + // Should the row be selectable? + if (!lvi.Enabled) { + lvi.UseItemStyleForSubItems = false; + ApplyRowStyle(lvi, this.DisabledItemStyle ?? ObjectListView.DefaultDisabledItemStyle); + } + + // Set the check state of the row, if we are showing check boxes + if (this.CheckBoxes) { + CheckState? state = this.GetCheckState(lvi.RowObject); + if (state.HasValue) + lvi.CheckState = state.Value; + } + + // Give the RowFormatter a chance to mess with the item + if (this.RowFormatter != null) { + this.RowFormatter(lvi); + } + } + + private OLVListSubItem MakeSubItem(object rowObject, OLVColumn column) { + object cellValue = column.GetValue(rowObject); + OLVListSubItem subItem = new OLVListSubItem(cellValue, + column.ValueToString(cellValue), + column.GetImage(rowObject)); + if (this.UseHyperlinks && column.Hyperlink) { + IsHyperlinkEventArgs args = new IsHyperlinkEventArgs(); + args.ListView = this; + args.Model = rowObject; + args.Column = column; + args.Text = subItem.Text; + args.Url = subItem.Text; + args.IsHyperlink = !this.IsDisabled(rowObject); + this.OnIsHyperlink(args); + subItem.Url = args.IsHyperlink ? args.Url : null; + } + + return subItem; + } + + private void ApplyHyperlinkStyle(OLVListItem olvi) { + + for (int i = 0; i < this.Columns.Count; i++) { + OLVListSubItem subItem = olvi.GetSubItem(i); + if (subItem == null) + continue; + OLVColumn column = this.GetColumn(i); + if (column.Hyperlink && !String.IsNullOrEmpty(subItem.Url)) + this.ApplyCellStyle(olvi, i, this.IsUrlVisited(subItem.Url) ? this.HyperlinkStyle.Visited : this.HyperlinkStyle.Normal); + } + } + + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + protected virtual void ForceSubItemImagesExStyle() { + // Virtual lists can't show subitem images natively, so don't turn on this flag + if (!this.VirtualMode) + NativeMethods.ForceSubItemImagesExStyle(this); + } + + /// + /// Convert the given image selector to an index into our image list. + /// Return -1 if that's not possible + /// + /// + /// Index of the image in the imageList, or -1 + protected virtual int GetActualImageIndex(Object imageSelector) { + if (imageSelector == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null && this.SmallImageList != null) + return this.SmallImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given column + /// + /// The column index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetHeaderToolTip(int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return null; + String tooltip = column.ToolTipText; + if (this.HeaderToolTipGetter != null) + tooltip = this.HeaderToolTipGetter(column); + return tooltip; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given cell + /// + /// The column index whose tool tip is to be fetched + /// The row index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetCellToolTip(int columnIndex, int rowIndex) { + if (this.CellToolTipGetter != null) + return this.CellToolTipGetter(this.GetColumn(columnIndex), this.GetModelObject(rowIndex)); + + // Show the URL in the tooltip if it's different to the text + if (columnIndex >= 0) { + OLVListSubItem subItem = this.GetSubItem(rowIndex, columnIndex); + if (subItem != null && !String.IsNullOrEmpty(subItem.Url) && subItem.Url != subItem.Text && + this.HotCellHitLocation == HitTestLocation.Text) + return subItem.Url; + } + + return null; + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public virtual OLVListItem ModelToItem(object modelObject) { + if (modelObject == null) + return null; + + foreach (OLVListItem olvi in this.Items) { + if (olvi.RowObject != null && olvi.RowObject.Equals(modelObject)) + return olvi; + } + return null; + } + + /// + /// Do the work required after the items in a listview have been created + /// + protected virtual void PostProcessRows() { + // If this method is called during a BeginUpdate/EndUpdate pair, changes to the + // Items collection are cached. Getting the Count flushes that cache. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int count = this.Items.Count; +#pragma warning restore 168 + + int i = 0; + if (this.ShowGroups) { + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } else { + foreach (OLVListItem olvi in this.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } + + /// + /// Do the work required after one item in a listview have been created + /// + protected virtual void PostProcessOneRow(int rowIndex, int displayIndex, OLVListItem olvi) { + if (this.Columns.Count == 0) + return; + if (this.UseAlternatingBackColors && this.View == View.Details && olvi.Enabled) { + olvi.UseItemStyleForSubItems = true; + olvi.BackColor = displayIndex % 2 == 1 ? this.AlternateRowBackColorOrDefault : this.BackColor; + } + if (this.ShowImagesOnSubItems && !this.VirtualMode) + this.SetSubItemImages(rowIndex, olvi); + + bool needToTriggerFormatCellEvents = this.TriggerFormatRowEvent(rowIndex, displayIndex, olvi); + + // We only need cell level events if we are in details view + if (this.View != View.Details) + return; + + // If we're going to have per cell formatting, we need to copy the formatting + // of the item into each cell, before triggering the cell format events + if (needToTriggerFormatCellEvents) { + PropagateFormatFromRowToCells(olvi); + this.TriggerFormatCellEvents(rowIndex, displayIndex, olvi); + } + + // Similarly, if any cell in the row has hyperlinks, we have to copy formatting + // from the item into each cell before applying the hyperlink style + if (this.UseHyperlinks && olvi.HasAnyHyperlinks) { + PropagateFormatFromRowToCells(olvi); + this.ApplyHyperlinkStyle(olvi); + } + } + + /// + /// Prepare the listview to show alternate row backcolors + /// + /// We cannot rely on lvi.Index in this method. + /// In a straight list, lvi.Index is the display index, and can be used to determine + /// whether the row should be colored. But when organised by groups, lvi.Index is not + /// usable because it still refers to the position in the overall list, not the display order. + /// + [Obsolete("This method is no longer used. Override PostProcessOneRow() to achieve a similar result")] + protected virtual void PrepareAlternateBackColors() { + } + + /// + /// Setup all subitem images on all rows + /// + [Obsolete("This method is not longer maintained and will be removed", false)] + protected virtual void SetAllSubItemImages() { + //if (!this.ShowImagesOnSubItems || this.OwnerDraw) + // return; + + //this.ForceSubItemImagesExStyle(); + + //for (int rowIndex = 0; rowIndex < this.GetItemCount(); rowIndex++) + // SetSubItemImages(rowIndex, this.GetItem(rowIndex)); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item) { + this.SetSubItemImages(rowIndex, item, false); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + /// will existing images be cleared if no new image is provided? + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item, bool shouldClearImages) { + if (!this.ShowImagesOnSubItems || this.OwnerDraw) + return; + + for (int i = 1; i < item.SubItems.Count; i++) { + this.SetSubItemImage(rowIndex, i, item.GetSubItem(i), shouldClearImages); + } + } + + /// + /// Set the subitem image natively + /// + /// + /// + /// + /// + public virtual void SetSubItemImage(int rowIndex, int subItemIndex, OLVListSubItem subItem, bool shouldClearImages) { + int imageIndex = this.GetActualImageIndex(subItem.ImageSelector); + if (shouldClearImages || imageIndex != -1) + NativeMethods.SetSubItemImage(this, rowIndex, subItemIndex, imageIndex); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// This method has the intentional side-effect of converting our list of objects to an ArrayList. + /// + /// + protected virtual void TakeOwnershipOfObjects() { + if (this.isOwnerOfObjects) + return; + + this.isOwnerOfObjects = true; + + this.objects = ObjectListView.EnumerableToArray(this.objects, true); + } + + /// + /// Trigger FormatRow and possibly FormatCell events for the given item + /// + /// + /// + /// + protected virtual bool TriggerFormatRowEvent(int rowIndex, int displayIndex, OLVListItem olvi) { + FormatRowEventArgs args = new FormatRowEventArgs(); + args.ListView = this; + args.RowIndex = rowIndex; + args.DisplayIndex = displayIndex; + args.Item = olvi; + args.UseCellFormatEvents = this.UseCellFormatEvents; + this.OnFormatRow(args); + return args.UseCellFormatEvents; + } + + /// + /// Trigger FormatCell events for the given item + /// + /// + /// + /// + protected virtual void TriggerFormatCellEvents(int rowIndex, int displayIndex, OLVListItem olvi) { + + PropagateFormatFromRowToCells(olvi); + + // Fire one event per cell + FormatCellEventArgs args2 = new FormatCellEventArgs(); + args2.ListView = this; + args2.RowIndex = rowIndex; + args2.DisplayIndex = displayIndex; + args2.Item = olvi; + for (int i = 0; i < this.Columns.Count; i++) { + args2.ColumnIndex = i; + args2.Column = this.GetColumn(i); + args2.SubItem = olvi.GetSubItem(i); + this.OnFormatCell(args2); + } + } + + private static void PropagateFormatFromRowToCells(OLVListItem olvi) { + // If a cell isn't given its own colors, it *should* use the colors of the item. + // However, there is a bug in the .NET framework where the cell are given + // the colors of the ListView instead of the colors of the row. + + // If we've already done this, don't do it again + if (olvi.UseItemStyleForSubItems == false) + return; + + // So we have to explicitly give each cell the fore and back colors and the font that it should have. + olvi.UseItemStyleForSubItems = false; + Color backColor = olvi.BackColor; + Color foreColor = olvi.ForeColor; + Font font = olvi.Font; + foreach (ListViewItem.ListViewSubItem subitem in olvi.SubItems) { + subitem.BackColor = backColor; + subitem.ForeColor = foreColor; + subitem.Font = font; + } + } + + /// + /// Make the list forget everything -- all rows and all columns + /// + /// Use if you want to remove just the rows. + public virtual void Reset() { + this.Clear(); + this.AllColumns.Clear(); + this.ClearObjects(); + this.PrimarySortColumn = null; + this.SecondarySortColumn = null; + this.ClearDisabledObjects(); + this.ClearPersistentCheckState(); + this.ClearUrlVisited(); + this.ClearHotItem(); + } + + + #endregion + + #region ISupportInitialize Members + + void ISupportInitialize.BeginInit() { + this.Frozen = true; + } + + void ISupportInitialize.EndInit() { + if (this.RowHeight != -1) { + this.SmallImageList = this.SmallImageList; + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + + if (this.UseSubItemCheckBoxes || (this.VirtualMode && this.CheckBoxes)) + this.SetupSubItemCheckBoxes(); + + this.Frozen = false; + } + + #endregion + + #region Image list manipulation + + /// + /// Update our externally visible image list so it holds the same images as our shadow list, but sized correctly + /// + private void SetupBaseImageList() { + // If a row height hasn't been set, or an image list has been give which is the required size, just assign it + if (rowHeight == -1 || + this.View != View.Details || + (this.shadowedImageList != null && this.shadowedImageList.ImageSize.Height == rowHeight)) + this.BaseSmallImageList = this.shadowedImageList; + else { + int width = (this.shadowedImageList == null ? 16 : this.shadowedImageList.ImageSize.Width); + this.BaseSmallImageList = this.MakeResizedImageList(width, rowHeight, shadowedImageList); + } + } + + /// + /// Return a copy of the given source image list, where each image has been resized to be height x height in size. + /// If source is null, an empty image list of the given size is returned + /// + /// Height and width of the new images + /// Height and width of the new images + /// Source of the images (can be null) + /// A new image list + private ImageList MakeResizedImageList(int width, int height, ImageList source) { + ImageList il = new ImageList(); + il.ImageSize = new Size(width, height); + + // If there's nothing to copy, just return the new list + if (source == null) + return il; + + il.TransparentColor = source.TransparentColor; + il.ColorDepth = source.ColorDepth; + + // Fill the imagelist with resized copies from the source + for (int i = 0; i < source.Images.Count; i++) { + Bitmap bm = this.MakeResizedImage(width, height, source.Images[i], source.TransparentColor); + il.Images.Add(bm); + } + + // Give each image the same key it has in the original + foreach (String key in source.Images.Keys) { + il.Images.SetKeyName(source.Images.IndexOfKey(key), key); + } + + return il; + } + + /// + /// Return a bitmap of the given height x height, which shows the given image, centred. + /// + /// Height and width of new bitmap + /// Height and width of new bitmap + /// Image to be centred + /// The background color + /// A new bitmap + private Bitmap MakeResizedImage(int width, int height, Image image, Color transparent) { + Bitmap bm = new Bitmap(width, height); + Graphics g = Graphics.FromImage(bm); + g.Clear(transparent); + int x = Math.Max(0, (bm.Size.Width - image.Size.Width) / 2); + int y = Math.Max(0, (bm.Size.Height - image.Size.Height) / 2); + g.DrawImage(image, x, y, image.Size.Width, image.Size.Height); + return bm; + } + + /// + /// Initialize the state image list with the required checkbox images + /// + protected virtual void InitializeStateImageList() { + if (this.DesignMode) + return; + + if (!this.CheckBoxes) + return; + + if (this.StateImageList == null) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight == -1 ? 16 : this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + if (this.RowHeight != -1 && + this.View == View.Details && + this.StateImageList.ImageSize.Height != this.RowHeight) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + // The internal logic of ListView cycles through the state images when the primary + // checkbox is clicked. So we have to get exactly the right number of images in the + // image list. + if (this.StateImageList.Images.Count == 0) + this.AddCheckStateBitmap(this.StateImageList, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + if (this.StateImageList.Images.Count <= 1) + this.AddCheckStateBitmap(this.StateImageList, CHECKED_KEY, CheckBoxState.CheckedNormal); + if (this.TriStateCheckBoxes && this.StateImageList.Images.Count <= 2) + this.AddCheckStateBitmap(this.StateImageList, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + else { + if (this.StateImageList.Images.ContainsKey(INDETERMINATE_KEY)) + this.StateImageList.Images.RemoveByKey(INDETERMINATE_KEY); + } + } + + /// + /// The name of the image used when a check box is checked + /// + public const string CHECKED_KEY = "checkbox-checked"; + + /// + /// The name of the image used when a check box is unchecked + /// + public const string UNCHECKED_KEY = "checkbox-unchecked"; + + /// + /// The name of the image used when a check box is Indeterminate + /// + public const string INDETERMINATE_KEY = "checkbox-indeterminate"; + + /// + /// Setup this control so it can display check boxes on subitems + /// (or primary checkboxes in virtual mode) + /// + /// This gives the ListView a small image list, if it doesn't already have one. + public virtual void SetupSubItemCheckBoxes() { + this.ShowImagesOnSubItems = true; + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(CHECKED_KEY)) + this.InitializeSubItemCheckBoxImages(); + } + + /// + /// Make sure the small image list for this control has checkbox images + /// (used for sub-item checkboxes). + /// + /// + /// + /// This gives the ListView a small image list, if it doesn't already have one. + /// + /// + /// ObjectListView has to manage checkboxes on subitems separate from the checkboxes on each row. + /// The underlying ListView knows about the per-row checkboxes, and to make them work, OLV has to + /// correctly configure the StateImageList. However, the ListView cannot do checkboxes in subitems, + /// so ObjectListView has to handle them in a different fashion. So, per-row checkboxes are controlled + /// by images in the StateImageList, but per-cell checkboxes are handled by images in the SmallImageList. + /// + /// + protected virtual void InitializeSubItemCheckBoxImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + this.AddCheckStateBitmap(il, CHECKED_KEY, CheckBoxState.CheckedNormal); + this.AddCheckStateBitmap(il, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + this.AddCheckStateBitmap(il, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + + this.SmallImageList = il; + } + + private void AddCheckStateBitmap(ImageList il, string key, CheckBoxState boxState) { + Bitmap b = new Bitmap(il.ImageSize.Width, il.ImageSize.Height); + Graphics g = Graphics.FromImage(b); + g.Clear(il.TransparentColor); + Point location = new Point(b.Width / 2 - 5, b.Height / 2 - 6); + CheckBoxRenderer.DrawCheckBox(g, location, boxState); + il.Images.Add(key, b); + } + + #endregion + + #region Owner drawing + + /// + /// Owner draw the column header + /// + /// + protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { + e.DrawDefault = true; + base.OnDrawColumnHeader(e); + } + + /// + /// Owner draw the item + /// + /// + protected override void OnDrawItem(DrawListViewItemEventArgs e) { + if (this.View == View.Details) + e.DrawDefault = false; + else { + if (this.ItemRenderer == null) + e.DrawDefault = true; + else { + Object row = ((OLVListItem)e.Item).RowObject; + e.DrawDefault = !this.ItemRenderer.RenderItem(e, e.Graphics, e.Bounds, row); + } + } + + if (e.DrawDefault) + base.OnDrawItem(e); + } + + /// + /// Owner draw a single subitem + /// + /// + protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnDrawSubItem ({0}, {1})", e.ItemIndex, e.ColumnIndex)); + // Don't try to do owner drawing at design time + if (this.DesignMode) { + e.DrawDefault = true; + return; + } + + object rowObject = ((OLVListItem)e.Item).RowObject; + + // Calculate where the subitem should be drawn + Rectangle r = e.Bounds; + + // Get the special renderer for this column. If there isn't one, use the default draw mechanism. + OLVColumn column = this.GetColumn(e.ColumnIndex); + IRenderer renderer = this.GetCellRenderer(rowObject, column); + + // Get a graphics context for the renderer to use. + // But we have more complications. Virtual lists have a nasty habit of drawing column 0 + // whenever there is any mouse move events over a row, and doing it in an un-double-buffered manner, + // which results in nasty flickers! There are also some unbuffered draw when a mouse is first + // hovered over column 0 of a normal row. So, to avoid all complications, + // we always manually double-buffer the drawing. + // Except with Mono, which doesn't seem to handle double buffering at all :-( + BufferedGraphics buffer = BufferedGraphicsManager.Current.Allocate(e.Graphics, r); + Graphics g = buffer.Graphics; + + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + // Finally, give the renderer a chance to draw something + e.DrawDefault = !renderer.RenderSubItem(e, g, r, rowObject); + + if (!e.DrawDefault) + buffer.Render(); + buffer.Dispose(); + } + + #endregion + + #region OnEvent Handling + + /// + /// We need the click count in the mouse up event, but that is always 1. + /// So we have to remember the click count from the preceding mouse down event. + /// + /// + protected override void OnMouseDown(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseDown: {0}, {1}", e.Button, e.Clicks)); + this.lastMouseDownClickCount = e.Clicks; + this.lastMouseDownButton = e.Button; + base.OnMouseDown(e); + } + private int lastMouseDownClickCount; + private MouseButtons lastMouseDownButton; + + /// + /// When the mouse leaves the control, remove any hot item highlighting + /// + /// + protected override void OnMouseLeave(EventArgs e) { + base.OnMouseLeave(e); + + if (!this.Created) + return; + + this.UpdateHotItem(new Point(-1,-1)); + } + + // We could change the hot item on the mouse hover event, but it looks wrong. + + //protected override void OnMouseHover(EventArgs e) { + // System.Diagnostics.Debug.WriteLine(String.Format("OnMouseHover")); + // base.OnMouseHover(e); + // this.UpdateHotItem(this.PointToClient(Cursor.Position)); + //} + + /// + /// When the mouse moves, we might need to change the hot item. + /// + /// + protected override void OnMouseMove(MouseEventArgs e) { + base.OnMouseMove(e); + + if (this.Created) + HandleMouseMove(e.Location); + } + + internal void HandleMouseMove(Point pt) { + //System.Diagnostics.Debug.WriteLine(String.Format("HandleMouseMove: {0}", pt)); + + CellOverEventArgs args = new CellOverEventArgs(); + this.BuildCellEvent(args, pt); + this.OnCellOver(args); + this.MouseMoveHitTest = args.HitTest; + + if (!args.Handled) + this.UpdateHotItem(args.HitTest); + } + + /// + /// Check to see if we need to start editing a cell + /// + /// + protected override void OnMouseUp(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseUp: {0}, {1}", e.Button, e.Clicks)); + + base.OnMouseUp(e); + + if (!this.Created) + return; + + // Sigh! More complexity. e.Button is not reliable when clicking on group headers. + // The mouse up event for first click on a group header always reports e.Button as None. + // Subsequent mouse up events report the button from the previous event. + // However, mouse down events are correctly reported, so we use the button value from + // the last mouse down event. + if (this.lastMouseDownButton == MouseButtons.Right) { + this.OnRightMouseUp(e); + return; + } + + // What event should we listen for to start cell editing? + // ------------------------------------------------------ + // + // We can't use OnMouseClick, OnMouseDoubleClick, OnClick, or OnDoubleClick + // since they are not triggered for clicks on subitems without Full Row Select. + // + // We could use OnMouseDown, but selecting rows is done in OnMouseUp. This means + // that if we start the editing during OnMouseDown, the editor will automatically + // lose focus when mouse up happens. + // + + // Tell the world about a cell click. If someone handles it, don't do anything else + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, e.Location); + args.ClickCount = this.lastMouseDownClickCount; + this.OnCellClick(args); + if (args.Handled) + return; + + // Did the user click a hyperlink? + if (this.UseHyperlinks && + args.HitTest.HitTestLocation == HitTestLocation.Text && + args.SubItem != null && + !String.IsNullOrEmpty(args.SubItem.Url)) { + // We have to delay the running of this process otherwise we can generate + // a series of MouseUp events (don't ask me why) + this.BeginInvoke((MethodInvoker)delegate { this.ProcessHyperlinkClicked(args); }); + } + + // No one handled it so check to see if we should start editing. + if (!this.ShouldStartCellEdit(e)) + return; + + // We only start the edit if the user clicked on the image or text. + if (args.HitTest.HitTestLocation == HitTestLocation.Nothing) + return; + + // We don't edit the primary column by single clicks -- only subitems. + if (this.CellEditActivation == CellEditActivateMode.SingleClick && args.ColumnIndex <= 0) + return; + + // Don't start a cell edit operation when the user clicks on the background of a checkbox column -- it just looks wrong. + // If the user clicks on the actual checkbox, changing the checkbox state is handled elsewhere. + if (args.Column != null && args.Column.CheckBoxes) + return; + + this.EditSubItem(args.Item, args.ColumnIndex); + } + + /// + /// Tell the world that a hyperlink was clicked and if the event isn't handled, + /// do the default processing. + /// + /// + protected virtual void ProcessHyperlinkClicked(CellClickEventArgs e) { + HyperlinkClickedEventArgs args = new HyperlinkClickedEventArgs(); + args.HitTest = e.HitTest; + args.ListView = this; + args.Location = new Point(-1, -1); + args.Item = e.Item; + args.SubItem = e.SubItem; + args.Model = e.Model; + args.ColumnIndex = e.ColumnIndex; + args.Column = e.Column; + args.RowIndex = e.RowIndex; + args.ModifierKeys = Control.ModifierKeys; + args.Url = e.SubItem.Url; + this.OnHyperlinkClicked(args); + if (!args.Handled) { + this.StandardHyperlinkClickedProcessing(args); + } + } + + /// + /// Do the default processing for a hyperlink clicked event, which + /// is to try and open the url. + /// + /// + protected virtual void StandardHyperlinkClickedProcessing(HyperlinkClickedEventArgs args) { + Cursor originalCursor = this.Cursor; + try { + this.Cursor = Cursors.WaitCursor; + System.Diagnostics.Process.Start(args.Url); + } catch (Win32Exception) { + System.Media.SystemSounds.Beep.Play(); + // ignore it + } finally { + this.Cursor = originalCursor; + } + this.MarkUrlVisited(args.Url); + this.RefreshHotItem(); + } + + /// + /// The user right clicked on the control + /// + /// + protected virtual void OnRightMouseUp(MouseEventArgs e) { + CellRightClickEventArgs args = new CellRightClickEventArgs(); + this.BuildCellEvent(args, e.Location); + this.OnCellRightClick(args); + if (!args.Handled) { + if (args.MenuStrip != null) { + args.MenuStrip.Show(this, args.Location); + } + } + } + + internal void BuildCellEvent(CellEventArgs args, Point location) { + BuildCellEvent(args, location, this.OlvHitTest(location.X, location.Y)); + } + + internal void BuildCellEvent(CellEventArgs args, Point location, OlvListViewHitTestInfo hitTest) { + args.HitTest = hitTest; + args.ListView = this; + args.Location = location; + args.Item = hitTest.Item; + args.SubItem = hitTest.SubItem; + args.Model = hitTest.RowObject; + args.ColumnIndex = hitTest.ColumnIndex; + args.Column = hitTest.Column; + if (hitTest.Item != null) + args.RowIndex = hitTest.Item.Index; + args.ModifierKeys = Control.ModifierKeys; + + // In non-details view, we want any hit on an item to act as if it was a hit + // on column 0 -- which, effectively, it was. + if (args.Item != null && args.ListView.View != View.Details) { + args.ColumnIndex = 0; + args.Column = args.ListView.GetColumn(0); + args.SubItem = args.Item.GetSubItem(0); + } + } + + /// + /// This method is called every time a row is selected or deselected. This can be + /// a pain if the user shift-clicks 100 rows. We override this method so we can + /// trigger one event for any number of select/deselects that come from one user action + /// + /// + protected override void OnSelectedIndexChanged(EventArgs e) { + if (this.SelectionEventsSuspended) + return; + + base.OnSelectedIndexChanged(e); + + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Schedule a SelectionChanged event to happen after the next idle event, + /// unless we've already scheduled that to happen. + /// + protected virtual void TriggerDeferredSelectionChangedEvent() { + if (this.SelectionEventsSuspended) + return; + + // If we haven't already scheduled an event, schedule it to be triggered + // By using idle time, we will wait until all select events for the same + // user action have finished before triggering the event. + if (!this.hasIdleHandler) { + this.hasIdleHandler = true; + this.RunWhenIdle(HandleApplicationIdle); + } + } + + /// + /// Called when the handle of the underlying control is created + /// + /// + protected override void OnHandleCreated(EventArgs e) { + //Debug.WriteLine("OnHandleCreated"); + base.OnHandleCreated(e); + + this.Invoke((MethodInvoker)this.OnControlCreated); + } + + /// + /// This method is called after the control has been fully created. + /// + protected virtual void OnControlCreated() { + + //Debug.WriteLine("OnControlCreated"); + + // Force the header control to be created when the listview handle is + HeaderControl hc = this.HeaderControl; + hc.WordWrap = this.HeaderWordWrap; + + // Make sure any overlays that are set on the hot item style take effect + this.HotItemStyle = this.HotItemStyle; + + // Arrange for any group images to be installed after the control is created + NativeMethods.SetGroupImageList(this, this.GroupImageList); + + this.UseExplorerTheme = this.UseExplorerTheme; + + this.RememberDisplayIndicies(); + this.SetGroupSpacing(); + + if (this.VirtualMode) + this.ApplyExtendedStyles(); + } + + #endregion + + #region Cell editing + + /// + /// Should we start editing the cell in response to the given mouse button event? + /// + /// + /// + protected virtual bool ShouldStartCellEdit(MouseEventArgs e) { + if (this.IsCellEditing) + return false; + + if (e.Button != MouseButtons.Left && e.Button != MouseButtons.Right) + return false; + + if ((Control.ModifierKeys & (Keys.Shift | Keys.Control | Keys.Alt)) != 0) + return false; + + if (this.lastMouseDownClickCount == 1 && ( + this.CellEditActivation == CellEditActivateMode.SingleClick || + this.CellEditActivation == CellEditActivateMode.SingleClickAlways)) + return true; + + return (this.lastMouseDownClickCount == 2 && this.CellEditActivation == CellEditActivateMode.DoubleClick); + } + + /// + /// Handle a key press on this control. We specifically look for F2 which edits the primary column, + /// or a Tab character during an edit operation, which tries to start editing on the next (or previous) cell. + /// + /// + /// + protected override bool ProcessDialogKey(Keys keyData) { + + if (this.IsCellEditing) + return this.CellEditKeyEngine.HandleKey(this, keyData); + + // Treat F2 as a request to edit the primary column + if (keyData == Keys.F2) { + this.EditSubItem((OLVListItem)this.FocusedItem, 0); + return base.ProcessDialogKey(keyData); + } + + // Treat Ctrl-C as Copy To Clipboard. + if (this.CopySelectionOnControlC && keyData == (Keys.C | Keys.Control)) { + this.CopySelectionToClipboard(); + return true; + } + + // Treat Ctrl-A as Select All. + if (this.SelectAllOnControlA && keyData == (Keys.A | Keys.Control)) { + this.SelectAll(); + return true; + } + + return base.ProcessDialogKey(keyData); + } + + /// + /// Start an editing operation on the first editable column of the given model. + /// + /// + /// + /// + /// If the model doesn't exist, or there are no editable columns, this method + /// will do nothing. + /// + /// This will start an edit operation regardless of CellActivationMode. + /// + /// + public virtual void EditModel(object rowModel) { + OLVListItem olvItem = this.ModelToItem(rowModel); + if (olvItem == null) + return; + + for (int i = 0; i < olvItem.SubItems.Count; i++) { + var olvColumn = this.GetColumn(i); + if (olvColumn != null && olvColumn.IsEditable) { + this.StartCellEdit(olvItem, i); + return; + } + } + } + + /// + /// Begin an edit operation on the given cell. + /// + /// This performs various sanity checks and passes off the real work to StartCellEdit(). + /// The row to be edited + /// The index of the cell to be edited + public virtual void EditSubItem(OLVListItem item, int subItemIndex) { + if (item == null) + return; + + if (this.CellEditActivation == CellEditActivateMode.None) + return; + + OLVColumn olvColumn = this.GetColumn(subItemIndex); + if (olvColumn == null || !olvColumn.IsEditable) + return; + + if (!item.Enabled) + return; + + this.StartCellEdit(item, subItemIndex); + } + + /// + /// Really start an edit operation on a given cell. The parameters are assumed to be sane. + /// + /// The row to be edited + /// The index of the cell to be edited + public virtual void StartCellEdit(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + if (column == null) + return; + Control c = this.GetCellEditor(item, subItemIndex); + Rectangle cellBounds = this.CalculateCellBounds(item, subItemIndex); + c.Bounds = this.CalculateCellEditorBounds(item, subItemIndex, c.PreferredSize); + + // Try to align the control as the column is aligned. Not all controls support this property + Munger.PutProperty(c, "TextAlign", column.TextAlign); + + // Give the control the value from the model + this.SetControlValue(c, column.GetValue(item.RowObject), column.GetStringValue(item.RowObject)); + + // Give the outside world the chance to munge with the process + this.CellEditEventArgs = new CellEditEventArgs(column, c, cellBounds, item, subItemIndex); + this.OnCellEditStarting(this.CellEditEventArgs); + if (this.CellEditEventArgs.Cancel) + return; + + // The event handler may have completely changed the control, so we need to remember it + this.cellEditor = this.CellEditEventArgs.Control; + + this.Invalidate(); + this.Controls.Add(this.cellEditor); + this.ConfigureControl(); + this.PauseAnimations(true); + } + private Control cellEditor; + internal CellEditEventArgs CellEditEventArgs; + + /// + /// Calculate the bounds of the edit control for the given item/column + /// + /// + /// + /// + /// + public Rectangle CalculateCellEditorBounds(OLVListItem item, int subItemIndex, Size preferredSize) { + Rectangle r = CalculateCellBounds(item, subItemIndex); + + // Calculate the width of the cell's current contents + return this.OwnerDraw + ? CalculateCellEditorBoundsOwnerDrawn(item, subItemIndex, r, preferredSize) + : CalculateCellEditorBoundsStandard(item, subItemIndex, r, preferredSize); + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsOwnerDrawn(OLVListItem item, int subItemIndex, Rectangle r, Size preferredSize) { + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(item.RowObject, this.GetColumn(subItemIndex)) + : this.ItemRenderer; + + if (renderer == null) + return r; + + using (Graphics g = this.CreateGraphics()) { + return renderer.GetEditRectangle(g, r, item, subItemIndex, preferredSize); + } + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is not being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsStandard(OLVListItem item, int subItemIndex, Rectangle cellBounds, Size preferredSize) { + if (this.View == View.Tile) + return cellBounds; + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + // Only Details view needs more processing + if (this.View != View.Details) + return cellBounds; + + // Allow for image (if there is one). + int offset = 0; + object imageSelector = null; + if (subItemIndex == 0) + imageSelector = item.ImageSelector; + else { + // We only check for subitem images if we are owner drawn or showing subitem images + if (this.OwnerDraw || this.ShowImagesOnSubItems) + imageSelector = item.GetSubItem(subItemIndex).ImageSelector; + } + if (this.GetActualImageIndex(imageSelector) != -1) { + offset += this.SmallImageSize.Width + 2; + } + + // Allow for checkbox + if (this.CheckBoxes && this.StateImageList != null && subItemIndex == 0) { + offset += this.StateImageList.ImageSize.Width + 2; + } + + // Allow for indent (first column only) + if (subItemIndex == 0 && item.IndentCount > 0) { + offset += (this.SmallImageSize.Width * item.IndentCount); + } + + // Do the adjustment + if (offset > 0) { + cellBounds.X += offset; + cellBounds.Width -= offset; + } + + return cellBounds; + } + + /// + /// Try to give the given value to the provided control. Fall back to assigning a string + /// if the value assignment fails. + /// + /// A control + /// The value to be given to the control + /// The string to be given if the value doesn't work + protected virtual void SetControlValue(Control control, Object value, String stringValue) { + // Does the control implement our custom interface? + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) { + olvEditor.Value = value; + return; + } + + // Handle combobox explicitly + ComboBox cb = control as ComboBox; + if (cb != null) { + if (cb.Created) + cb.SelectedValue = value; + else + this.BeginInvoke(new MethodInvoker(delegate { + cb.SelectedValue = value; + })); + return; + } + + if (Munger.PutProperty(control, "Value", value)) + return; + + // There wasn't a Value property, or we couldn't set it, so set the text instead + try + { + String valueAsString = value as String; + control.Text = valueAsString ?? stringValue; + } + catch (ArgumentOutOfRangeException) { + // The value couldn't be set via the Text property. + } + } + + /// + /// Setup the given control to be a cell editor + /// + protected virtual void ConfigureControl() { + this.cellEditor.Validating += new CancelEventHandler(CellEditor_Validating); + this.cellEditor.Select(); + } + + /// + /// Return the value that the given control is showing + /// + /// + /// + protected virtual Object GetControlValue(Control control) { + if (control == null) + return null; + + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) + return olvEditor.Value; + + TextBox box = control as TextBox; + if (box != null) + return box.Text; + + ComboBox comboBox = control as ComboBox; + if (comboBox != null) + return comboBox.SelectedValue; + + CheckBox checkBox = control as CheckBox; + if (checkBox != null) + return checkBox.Checked; + + try { + return control.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, control, null); + } catch (MissingMethodException) { // Microsoft throws this + return control.Text; + } catch (MissingFieldException) { // Mono throws this + return control.Text; + } + } + + /// + /// Called when the cell editor could be about to lose focus. Time to commit the change + /// + /// + /// + protected virtual void CellEditor_Validating(object sender, CancelEventArgs e) { + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Control.Select(); + e.Cancel = true; + } else + FinishCellEdit(); + } + + /// + /// Return the bounds of the given cell + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex) { + + // It seems on Win7, GetSubItemBounds() does not have the same problems with + // column 0 that it did previously. + + // TODO - Check on XP + + if (this.View != View.Details) + return this.GetItemRect(item.Index, ItemBoundsPortion.Label); + + Rectangle r = item.GetSubItemBounds(subItemIndex); + r.Width -= 1; + r.Height -= 1; + return r; + + // We use ItemBoundsPortion.Label rather than ItemBoundsPortion.Item + // since Label extends to the right edge of the cell, whereas Item gives just the + // current text width. + //return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.Label); + } + + /// + /// Return the bounds of the given cell only until the edge of the current text + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellTextBounds(OLVListItem item, int subItemIndex) { + return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.ItemOnly); + } + + private Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex, ItemBoundsPortion portion) { + // SubItem.Bounds works for every subitem, except the first. + if (subItemIndex > 0) + return item.GetSubItemBounds(subItemIndex); + + // For non detail views, we just use the requested portion + Rectangle r = this.GetItemRect(item.Index, portion); + if (r.Y < -10000000 || r.Y > 10000000) { + r.Y = item.Bounds.Y; + } + if (this.View != View.Details) + return r; + + // Finding the bounds of cell 0 should not be a difficult task, but it is. Problems: + // 1) item.SubItem[0].Bounds is always the full bounds of the entire row, not just cell 0. + // 2) if column 0 has been dragged to some other position, the bounds always has a left edge of 0. + + // We avoid both these problems by using the position of sides the column header to calculate + // the sides of the cell + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + r.X = sides.X + 4; + r.Width = sides.Y - sides.X - 5; + + return r; + } + + /// + /// Calculate the visible bounds of the given column. The column's bottom edge is + /// either the bottom of the last row or the bottom of the control. + /// + /// The bounds of the control itself + /// The column + /// A Rectangle + /// This returns an empty rectangle if the control isn't in Details mode, + /// OR has doesn't have any rows, OR if the given column is hidden. + public virtual Rectangle CalculateColumnVisibleBounds(Rectangle bounds, OLVColumn column) + { + // Sanity checks + if (column == null || + this.View != System.Windows.Forms.View.Details || + this.GetItemCount() == 0 || + !column.IsVisible) + return Rectangle.Empty; + + Point sides = NativeMethods.GetScrolledColumnSides(this, column.Index); + if (sides.X == -1) + return Rectangle.Empty; + + Rectangle columnBounds = new Rectangle(sides.X, bounds.Top, sides.Y - sides.X, bounds.Bottom); + + // Find the bottom of the last item. The column only extends to there. + OLVListItem lastItem = this.GetLastItemInDisplayOrder(); + if (lastItem != null) + { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + return columnBounds; + } + + /// + /// Return a control that can be used to edit the value of the given cell. + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Control to edit the given cell + protected virtual Control GetCellEditor(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + Object value = column.GetValue(item.RowObject); + + // Does the column have its own special way of creating cell editors? + if (column.EditorCreator != null) { + Control customEditor = column.EditorCreator(item.RowObject, column, value); + if (customEditor != null) + return customEditor; + } + + // Ask the registry for an instance of the appropriate editor. + // Use a default editor if the registry can't create one for us. + Control editor = ObjectListView.EditorRegistry.GetEditor(item.RowObject, column, value ?? this.GetFirstNonNullValue(column)); + return editor ?? this.MakeDefaultCellEditor(column); + } + + /// + /// Get the first non-null value of the given column. + /// At most 1000 rows will be considered. + /// + /// + /// The first non-null value, or null if no non-null values were found + internal object GetFirstNonNullValue(OLVColumn column) { + for (int i = 0; i < Math.Min(this.GetItemCount(), 1000); i++) { + object value = column.GetValue(this.GetModelObject(i)); + if (value != null) + return value; + } + return null; + } + + /// + /// Return a TextBox that can be used as a default cell editor. + /// + /// What column does the cell belong to? + /// + protected virtual Control MakeDefaultCellEditor(OLVColumn column) { + TextBox tb = new TextBox(); + if (column.AutoCompleteEditor) + this.ConfigureAutoComplete(tb, column); + return tb; + } + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + public void ConfigureAutoComplete(TextBox tb, OLVColumn column) { + this.ConfigureAutoComplete(tb, column, 1000); + } + + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + /// Consider only this many rows + public void ConfigureAutoComplete(TextBox tb, OLVColumn column, int maxRows) { + // Don't consider more rows than we actually have + maxRows = Math.Min(this.GetItemCount(), maxRows); + + // Reset any existing autocomplete + tb.AutoCompleteCustomSource.Clear(); + + // CONSIDER: Should we use ClusteringStrategy here? + + // Build a list of unique values, to be used as autocomplete on the editor + Dictionary alreadySeen = new Dictionary(); + List values = new List(); + for (int i = 0; i < maxRows; i++) { + string valueAsString = column.GetStringValue(this.GetModelObject(i)); + if (!String.IsNullOrEmpty(valueAsString) && !alreadySeen.ContainsKey(valueAsString)) { + values.Add(valueAsString); + alreadySeen[valueAsString] = true; + } + } + + tb.AutoCompleteCustomSource.AddRange(values.ToArray()); + tb.AutoCompleteSource = AutoCompleteSource.CustomSource; + tb.AutoCompleteMode = column.AutoCompleteEditorMode; + } + + /// + /// Stop editing a cell and throw away any changes. + /// + public virtual void CancelCellEdit() { + if (!this.IsCellEditing) + return; + + // Let the world know that the user has cancelled the edit operation + this.CellEditEventArgs.Cancel = true; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // Now cleanup the editing process + this.CleanupCellEdit(false, this.CellEditEventArgs.AutoDispose); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + public virtual bool PossibleFinishCellEditing() { + return this.PossibleFinishCellEditing(false); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual bool PossibleFinishCellEditing(bool expectingCellEdit) { + if (!this.IsCellEditing) + return true; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) + return false; + + this.FinishCellEdit(expectingCellEdit); + + return true; + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + public virtual void FinishCellEdit() { + this.FinishCellEdit(false); + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual void FinishCellEdit(bool expectingCellEdit) { + if (!this.IsCellEditing) + return; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // If someone doesn't cancel the editing process, write the value back into the model + if (!this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Column.PutValue(this.CellEditEventArgs.RowObject, this.CellEditEventArgs.NewValue); + this.RefreshItem(this.CellEditEventArgs.ListViewItem); + } + + this.CleanupCellEdit(expectingCellEdit, this.CellEditEventArgs.AutoDispose); + + // Tell the world that the cell has been edited + this.OnCellEditFinished(this.CellEditEventArgs); + } + + /// + /// Remove all trace of any existing cell edit operation + /// + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + /// True if the cell editor should be disposed + protected virtual void CleanupCellEdit(bool expectingCellEdit, bool disposeOfCellEditor) { + if (this.cellEditor == null) + return; + + this.cellEditor.Validating -= new CancelEventHandler(CellEditor_Validating); + + Control soonToBeOldCellEditor = this.cellEditor; + this.cellEditor = null; + + // Delay cleaning up the cell editor so that if we are immediately going to + // start a new cell edit (because the user pressed Tab) the new cell editor + // has a chance to grab the focus. Without this, the ListView gains focus + // momentarily (after the cell editor is remove and before the new one is created) + // causing the list's selection to flash momentarily. + EventHandler toBeRun = null; + toBeRun = delegate(object sender, EventArgs e) { + Application.Idle -= toBeRun; + this.Controls.Remove(soonToBeOldCellEditor); + if (disposeOfCellEditor) + soonToBeOldCellEditor.Dispose(); + this.Invalidate(); + + if (!this.IsCellEditing) { + if (this.Focused) + this.Select(); + this.PauseAnimations(false); + } + }; + + // We only want to delay the removal of the control if we are expecting another cell + // to be edited. Otherwise, we remove the control immediately. + if (expectingCellEdit) + this.RunWhenIdle(toBeRun); + else + toBeRun(null, null); + } + + #endregion + + #region Hot row and cell handling + + /// + /// Force the hot item to be recalculated + /// + public virtual void ClearHotItem() { + this.UpdateHotItem(new Point(-1, -1)); + } + + /// + /// Force the hot item to be recalculated + /// + public virtual void RefreshHotItem() { + this.UpdateHotItem(this.PointToClient(Cursor.Position)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// Where is the mouse? + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(Point pt) { + this.UpdateHotItem(this.OlvHitTest(pt.X, pt.Y)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(OlvListViewHitTestInfo hti) { + + // We only need to do the work of this method when the list has hot parts + // (i.e. some element whose visual appearance changes when under the mouse)? + // Hot item decorations and hyperlinks are obvious, but if we have checkboxes + // or buttons, those are also "hot". It's difficult to quickly detect if there are any + // columns that have checkboxes or buttons, so we just abdicate responsibility and + // provide a property (UseHotControls) which lets the programmer say whether to do + // the hot processing or not. + if (!this.UseHotItem && !this.UseHyperlinks && !this.UseHotControls) + return; + + int newHotRow = hti.RowIndex; + int newHotColumn = hti.ColumnIndex; + HitTestLocation newHotCellHitLocation = hti.HitTestLocation; + HitTestLocationEx newHotCellHitLocationEx = hti.HitTestLocationEx; + OLVGroup newHotGroup = hti.Group; + + // In non-details view, we treat any hit on a row as if it were a hit + // on column 0 -- which (effectively) it is! + if (newHotRow >= 0 && this.View != View.Details) + newHotColumn = 0; + + if (this.HotRowIndex == newHotRow && + this.HotColumnIndex == newHotColumn && + this.HotCellHitLocation == newHotCellHitLocation && + this.HotCellHitLocationEx == newHotCellHitLocationEx && + this.HotGroup == newHotGroup) { + return; + } + + // Trigger the hotitem changed event + HotItemChangedEventArgs args = new HotItemChangedEventArgs(); + args.HotCellHitLocation = newHotCellHitLocation; + args.HotCellHitLocationEx = newHotCellHitLocationEx; + args.HotColumnIndex = newHotColumn; + args.HotRowIndex = newHotRow; + args.HotGroup = newHotGroup; + args.OldHotCellHitLocation = this.HotCellHitLocation; + args.OldHotCellHitLocationEx = this.HotCellHitLocationEx; + args.OldHotColumnIndex = this.HotColumnIndex; + args.OldHotRowIndex = this.HotRowIndex; + args.OldHotGroup = this.HotGroup; + this.OnHotItemChanged(args); + + // Update the state of the control + this.HotRowIndex = newHotRow; + this.HotColumnIndex = newHotColumn; + this.HotCellHitLocation = newHotCellHitLocation; + this.HotCellHitLocationEx = newHotCellHitLocationEx; + this.HotGroup = newHotGroup; + + // If the event handler handled it complete, don't do anything else + if (args.Handled) + return; + +// System.Diagnostics.Debug.WriteLine(String.Format("Changed hot item: {0}", args)); + + this.BeginUpdate(); + try { + this.Invalidate(); + if (args.OldHotRowIndex != -1) + this.UnapplyHotItem(args.OldHotRowIndex); + + if (this.HotRowIndex != -1) { + // Virtual lists apply hot item style when fetching their rows + if (this.VirtualMode) { + this.ClearCachedInfo(); + this.RedrawItems(this.HotRowIndex, this.HotRowIndex, true); + } else { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, hti.Item); + } + } + + if (this.UseHotItem && this.HotItemStyleOrDefault.Overlay != null) { + this.RefreshOverlays(); + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the given row using the current hot item information + /// + /// + protected virtual void UpdateHotRow(OLVListItem olvi) { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, olvi); + } + + /// + /// Update the given row using the given hot item information + /// + /// + /// + /// + /// + protected virtual void UpdateHotRow(int rowIndex, int columnIndex, HitTestLocation hitLocation, OLVListItem olvi) { + if (rowIndex < 0 || columnIndex < 0) + return; + + // System.Diagnostics.Debug.WriteLine(String.Format("UpdateHotRow: {0}, {1}, {2}", rowIndex, columnIndex, hitLocation)); + + if (this.UseHyperlinks) { + OLVColumn column = this.GetColumn(columnIndex); + OLVListSubItem subItem = olvi.GetSubItem(columnIndex); + if (column != null && column.Hyperlink && hitLocation == HitTestLocation.Text && !String.IsNullOrEmpty(subItem.Url)) { + this.ApplyCellStyle(olvi, columnIndex, this.HyperlinkStyle.Over); + this.Cursor = this.HyperlinkStyle.OverCursor ?? Cursors.Default; + } else { + this.Cursor = Cursors.Default; + } + } + + if (this.UseHotItem) { + if (!olvi.Selected && olvi.Enabled) { + this.ApplyRowStyle(olvi, this.HotItemStyleOrDefault); + } + } + } + + /// + /// Apply a style to the given row + /// + /// + /// + public virtual void ApplyRowStyle(OLVListItem olvi, IItemStyle style) { + if (style == null) + return; + + Font font = style.Font ?? olvi.Font; + + if (style.FontStyle != FontStyle.Regular) + font = new Font(font ?? this.Font, style.FontStyle); + + if (!Equals(font, olvi.Font)) { + if (olvi.UseItemStyleForSubItems) + olvi.Font = font; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.Font = font; + } + } + + if (!style.ForeColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.ForeColor = style.ForeColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.ForeColor = style.ForeColor; + } + } + + if (!style.BackColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.BackColor = style.BackColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.BackColor = style.BackColor; + } + } + } + + /// + /// Apply a style to a cell + /// + /// + /// + /// + protected virtual void ApplyCellStyle(OLVListItem olvi, int columnIndex, IItemStyle style) { + if (style == null) + return; + + // Don't apply formatting to subitems when not in Details view + if (this.View != View.Details && columnIndex > 0) + return; + + olvi.UseItemStyleForSubItems = false; + + ListViewItem.ListViewSubItem subItem = olvi.SubItems[columnIndex]; + if (style.Font != null) + subItem.Font = style.Font; + + if (style.FontStyle != FontStyle.Regular) + subItem.Font = new Font(subItem.Font ?? olvi.Font ?? this.Font, style.FontStyle); + + if (!style.ForeColor.IsEmpty) + subItem.ForeColor = style.ForeColor; + + if (!style.BackColor.IsEmpty) + subItem.BackColor = style.BackColor; + } + + /// + /// Remove hot item styling from the given row + /// + /// + protected virtual void UnapplyHotItem(int index) { + this.Cursor = Cursors.Default; + // Virtual lists will apply the appropriate formatting when the row is fetched + if (this.VirtualMode) { + if (index < this.VirtualListSize) + this.RedrawItems(index, index, true); + } else { + OLVListItem olvi = this.GetItem(index); + if (olvi != null) { + //this.PostProcessOneRow(index, index, olvi); + this.RefreshItem(olvi); + } + } + } + + + #endregion + + #region Drag and drop + + /// + /// + /// + /// + protected override void OnItemDrag(ItemDragEventArgs e) { + base.OnItemDrag(e); + + if (this.DragSource == null) + return; + + Object data = this.DragSource.StartDrag(this, e.Button, (OLVListItem)e.Item); + if (data != null) { + DragDropEffects effect = this.DoDragDrop(data, this.DragSource.GetAllowedEffects(data)); + this.DragSource.EndDrag(data, effect); + } + } + + /// + /// + /// + /// + protected override void OnDragEnter(DragEventArgs args) { + base.OnDragEnter(args); + + if (this.DropSink != null) + this.DropSink.Enter(args); + } + + /// + /// + /// + /// + protected override void OnDragOver(DragEventArgs args) { + base.OnDragOver(args); + + if (this.DropSink != null) + this.DropSink.Over(args); + } + + /// + /// + /// + /// + protected override void OnDragDrop(DragEventArgs args) { + base.OnDragDrop(args); + + this.lastMouseDownClickCount = 0; // prevent drop events from becoming cell edits + + if (this.DropSink != null) + this.DropSink.Drop(args); + } + + /// + /// + /// + /// + protected override void OnDragLeave(EventArgs e) { + base.OnDragLeave(e); + + if (this.DropSink != null) + this.DropSink.Leave(); + } + + /// + /// + /// + /// + protected override void OnGiveFeedback(GiveFeedbackEventArgs args) { + base.OnGiveFeedback(args); + + if (this.DropSink != null) + this.DropSink.GiveFeedback(args); + } + + /// + /// + /// + /// + protected override void OnQueryContinueDrag(QueryContinueDragEventArgs args) { + base.OnQueryContinueDrag(args); + + if (this.DropSink != null) + this.DropSink.QueryContinue(args); + } + + #endregion + + #region Decorations and Overlays + + /// + /// Add the given decoration to those on this list and make it appear + /// + /// The decoration + /// + /// A decoration scrolls with the listview. An overlay stays fixed in place. + /// + public virtual void AddDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Add(decoration); + this.Invalidate(); + } + + /// + /// Add the given overlay to those on this list and make it appear + /// + /// The overlay + public virtual void AddOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Add(overlay); + this.Invalidate(); + } + + /// + /// Draw all the decorations + /// + /// A Graphics + /// The items that were redrawn and whose decorations should also be redrawn + protected virtual void DrawAllDecorations(Graphics g, List itemsThatWereRedrawn) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + Rectangle contentRectangle = this.ContentRectangle; + + if (this.HasEmptyListMsg && this.GetItemCount() == 0) { + this.EmptyListMsgOverlay.Draw(this, g, contentRectangle); + } + + // Let the drop sink draw whatever feedback it likes + if (this.DropSink != null) { + this.DropSink.DrawFeedback(g, contentRectangle); + } + + // Draw our item and subitem decorations + foreach (OLVListItem olvi in itemsThatWereRedrawn) { + if (olvi.HasDecoration) { + foreach (IDecoration d in olvi.Decorations) { + d.ListItem = olvi; + d.SubItem = null; + d.Draw(this, g, contentRectangle); + } + } + foreach (OLVListSubItem subItem in olvi.SubItems) { + if (subItem.HasDecoration) { + foreach (IDecoration d in subItem.Decorations) { + d.ListItem = olvi; + d.SubItem = subItem; + d.Draw(this, g, contentRectangle); + } + } + } + if (this.SelectedRowDecoration != null && olvi.Selected && olvi.Enabled) { + this.SelectedRowDecoration.ListItem = olvi; + this.SelectedRowDecoration.SubItem = null; + this.SelectedRowDecoration.Draw(this, g, contentRectangle); + } + } + + // Now draw the specifically registered decorations + foreach (IDecoration decoration in this.Decorations) { + decoration.ListItem = null; + decoration.SubItem = null; + decoration.Draw(this, g, contentRectangle); + } + + // Finally, draw any hot item decoration + if (this.UseHotItem) { + IDecoration hotItemDecoration = this.HotItemStyleOrDefault.Decoration; + if (hotItemDecoration != null) { + hotItemDecoration.ListItem = this.GetItem(this.HotRowIndex); + if (hotItemDecoration.ListItem == null || hotItemDecoration.ListItem.Enabled) { + hotItemDecoration.SubItem = hotItemDecoration.ListItem == null ? null : hotItemDecoration.ListItem.GetSubItem(this.HotColumnIndex); + hotItemDecoration.Draw(this, g, contentRectangle); + } + } + } + + // If we are in design mode, we don't want to use the glass panels, + // so we draw the background overlays here + if (this.DesignMode) { + foreach (IOverlay overlay in this.Overlays) { + overlay.Draw(this, g, contentRectangle); + } + } + } + + /// + /// Is the given decoration shown on this list + /// + /// The overlay + public virtual bool HasDecoration(IDecoration decoration) { + return this.Decorations.Contains(decoration); + } + + /// + /// Is the given overlay shown on this list? + /// + /// The overlay + public virtual bool HasOverlay(IOverlay overlay) { + return this.Overlays.Contains(overlay); + } + + /// + /// Hide any overlays. + /// + /// + /// This is only a temporary hiding -- the overlays will be shown + /// the next time the ObjectListView redraws. + /// + public virtual void HideOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.HideGlass(); + } + } + + /// + /// Create and configure the empty list msg overlay + /// + protected virtual void InitializeEmptyListMsgOverlay() { + TextOverlay overlay = new TextOverlay(); + overlay.Alignment = System.Drawing.ContentAlignment.MiddleCenter; + overlay.TextColor = SystemColors.ControlDarkDark; + overlay.BackColor = Color.BlanchedAlmond; + overlay.BorderColor = SystemColors.ControlDark; + overlay.BorderWidth = 2.0f; + this.EmptyListMsgOverlay = overlay; + } + + /// + /// Initialize the standard image and text overlays + /// + protected virtual void InitializeStandardOverlays() { + this.OverlayImage = new ImageOverlay(); + this.AddOverlay(this.OverlayImage); + this.OverlayText = new TextOverlay(); + this.AddOverlay(this.OverlayText); + } + + /// + /// Make sure that any overlays are visible. + /// + public virtual void ShowOverlays() { + // If we shouldn't show overlays, then don't create glass panels + if (!this.ShouldShowOverlays()) + return; + + // Make sure that each overlay has its own glass panels + if (this.Overlays.Count != this.glassPanels.Count) { + foreach (IOverlay overlay in this.Overlays) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel == null) { + glassPanel = new GlassPanelForm(); + glassPanel.Bind(this, overlay); + this.glassPanels.Add(glassPanel); + } + } + } + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.ShowGlass(); + } + } + + private bool ShouldShowOverlays() { + // If we are in design mode, we dont show the overlays + if (this.DesignMode) + return false; + + // If we are explicitly not using overlays, also don't show them + if (!this.UseOverlays) + return false; + + // If there are no overlays, guess... + if (!this.HasOverlays) + return false; + + // If we don't have 32-bit display, alpha blending doesn't work, so again, no overlays + // TODO: This should actually figure out which screen(s) the control is on, and make sure + // that each one is 32-bit. + if (Screen.PrimaryScreen.BitsPerPixel < 32) + return false; + + // Finally, we can show the overlays + return true; + } + + private GlassPanelForm FindGlassPanelForOverlay(IOverlay overlay) { + return this.glassPanels.Find(delegate(GlassPanelForm x) { return x.Overlay == overlay; }); + } + + /// + /// Refresh the display of the overlays + /// + public virtual void RefreshOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Invalidate(); + } + } + + /// + /// Refresh the display of just one overlays + /// + public virtual void RefreshOverlay(IOverlay overlay) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) + glassPanel.Invalidate(); + } + + /// + /// Remove the given decoration from this list + /// + /// The decoration to remove + public virtual void RemoveDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Remove(decoration); + this.Invalidate(); + } + + /// + /// Remove the given overlay to those on this list + /// + /// The overlay + public virtual void RemoveOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Remove(overlay); + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) { + this.glassPanels.Remove(glassPanel); + glassPanel.Unbind(); + glassPanel.Dispose(); + } + } + + #endregion + + #region Filtering + + /// + /// Create a filter that will enact all the filtering currently installed + /// on the visible columns. + /// + public virtual IModelFilter CreateColumnFilter() { + List filters = new List(); + foreach (OLVColumn column in this.Columns) { + IModelFilter filter = column.ValueBasedFilter; + if (filter != null) + filters.Add(filter); + } + return (filters.Count == 0) ? null : new CompositeAllFilter(filters); + } + + /// + /// Do the actual work of filtering + /// + /// + /// + /// + /// + protected virtual IEnumerable FilterObjects(IEnumerable originalObjects, IModelFilter aModelFilter, IListFilter aListFilter) { + // Being cautious + originalObjects = originalObjects ?? new ArrayList(); + + // Tell the world to filter the objects. If they do so, don't do anything else +// ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(originalObjects); + this.OnFilter(args); + if (args.FilteredObjects != null) + return args.FilteredObjects; + + // Apply a filter to the list as a whole + if (aListFilter != null) + originalObjects = aListFilter.Filter(originalObjects); + + // Apply the object filter if there is one + if (aModelFilter != null) { + ArrayList filteredObjects = new ArrayList(); + foreach (object model in originalObjects) { + if (aModelFilter.Filter(model)) + filteredObjects.Add(model); + } + originalObjects = filteredObjects; + } + + return originalObjects; +// ReSharper restore PossibleMultipleEnumeration + } + + /// + /// Remove all column filtering. + /// + public virtual void ResetColumnFiltering() { + foreach (OLVColumn column in this.Columns) { + column.ValuesChosenForFiltering.Clear(); + } + this.UpdateColumnFiltering(); + } + + /// + /// Update the filtering of this ObjectListView based on the value filtering + /// defined in each column + /// + public virtual void UpdateColumnFiltering() { + //List filters = new List(); + //IModelFilter columnFilter = this.CreateColumnFilter(); + //if (columnFilter != null) + // filters.Add(columnFilter); + //if (this.AdditionalFilter != null) + // filters.Add(this.AdditionalFilter); + //this.ModelFilter = filters.Count == 0 ? null : new CompositeAllFilter(filters); + + if (this.AdditionalFilter == null) + this.ModelFilter = this.CreateColumnFilter(); + else { + IModelFilter columnFilter = this.CreateColumnFilter(); + if (columnFilter == null) + this.ModelFilter = this.AdditionalFilter; + else { + List filters = new List(); + filters.Add(columnFilter); + filters.Add(this.AdditionalFilter); + this.ModelFilter = new CompositeAllFilter(filters); + } + } + } + + /// + /// When some setting related to filtering changes, this method is called. + /// + protected virtual void UpdateFiltering() { + this.BuildList(true); + } + + /// + /// Update all renderers with the currently installed model filter + /// + protected virtual void NotifyNewModelFilter() { + IFilterAwareRenderer filterAware = this.DefaultRenderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + + foreach (OLVColumn column in this.AllColumns) { + filterAware = column.Renderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + } + } + + #endregion + + #region Persistent check state + + /// + /// Gets the checkedness of the given model. + /// + /// The model + /// The checkedness of the model. Defaults to unchecked. + protected virtual CheckState GetPersistentCheckState(object model) { + CheckState state; + if (model != null && this.CheckStateMap.TryGetValue(model, out state)) + return state; + return CheckState.Unchecked; + } + + /// + /// Remember the check state of the given model object + /// + /// The model to be remembered + /// The model's checkedness + /// The state given to the method + protected virtual CheckState SetPersistentCheckState(object model, CheckState state) { + if (model == null) + return CheckState.Unchecked; + + this.CheckStateMap[model] = state; + return state; + } + + /// + /// Forget any persistent checkbox state + /// + protected virtual void ClearPersistentCheckState() { + this.CheckStateMap = null; + } + + #endregion + + #region Implementation variables + + private bool isOwnerOfObjects; // does this ObjectListView own the Objects collection? + private bool hasIdleHandler; // has an Idle handler already been installed? + private bool hasResizeColumnsHandler; // has an idle handler been installed which will handle column resizing? + private bool isInWmPaintEvent; // is a WmPaint event currently being handled? + private bool shouldDoCustomDrawing; // should the list do its custom drawing? + private bool isMarqueSelecting; // Is a marque selection in progress? + private int suspendSelectionEventCount; // How many unmatched SuspendSelectionEvents() calls have been made? + + private readonly List glassPanels = new List(); // The transparent panel that draws overlays + private Dictionary visitedUrlMap = new Dictionary(); // Which urls have been visited? + + // TODO + //private CheckBoxSettings checkBoxSettings = new CheckBoxSettings(); + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.shfb b/ObjectListView/ObjectListView.shfb new file mode 100644 index 0000000..514d58b --- /dev/null +++ b/ObjectListView/ObjectListView.shfb @@ -0,0 +1,47 @@ + + + + + + + All ObjectListView appears in this namespace + + + ObjectListViewDemo demonstrates helpful techniques when using an ObjectListView + Summary, Parameter, Returns, AutoDocumentCtors, Namespace + InheritedMembers, Protected, SealedProtected + + + .\Help\ + + + True + True + HtmlHelp1x + True + False + 2.0.50727 + True + False + True + False + + ObjectListView Reference + Documentation + en-US + + (c) Copyright 2006-2008 Phillip Piper All Rights Reserved + phillip.piper@gmail.com + + + Local + Msdn + Blank + Prototype + Guid + CSharp + False + AboveNamespaces + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.csproj b/ObjectListView/ObjectListView2019.csproj new file mode 100644 index 0000000..70e616b --- /dev/null +++ b/ObjectListView/ObjectListView2019.csproj @@ -0,0 +1,54 @@ + + + net6.0-windows + Library + BrightIdeasSoftware + ObjectListView + true + olv-keyfile.snk + %24/ObjectListView/trunk/ObjectListView + . + https://grammarian.visualstudio.com + {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} + false + true + true + + + 1 + bin\Debug\ObjectListView.XML + + + bin\Release\ObjectListView.XML + + + + + + + + + + + + + + Component + + + Component + + + + + + + Designer + + + + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.nuspec b/ObjectListView/ObjectListView2019.nuspec new file mode 100644 index 0000000..3e883c6 --- /dev/null +++ b/ObjectListView/ObjectListView2019.nuspec @@ -0,0 +1,22 @@ + + + + ObjectListView.Official + ObjectListView (Official) + 2.9.2-alpha2 + Phillip Piper + Phillip Piper + http://www.gnu.org/licenses/gpl.html + http://objectlistview.sourceforge.net + http://objectlistview.sourceforge.net/cs/_static/index-icon.png + true + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + More calmly, it is a C# wrapper around a .NET ListView, which makes the ListView much easier to use and teaches it lots of neat new tricks. + v2.9.2 Fixed cell edit bounds problem in TreeListView, plus other small issues. + v2.9.1 Added CellRendererGetter to allow each cell to have a different renderer, plus fixes a few small bugs. + v2.9 adds buttons to cells, fixed some formatting bugs, and completely rewrote the demo to be much easier to understand. + Copyright 2006-2016 Bright Ideas Software + .Net WinForms Net20 Net40 ListView Controls + + \ No newline at end of file diff --git a/ObjectListView/Properties/AssemblyInfo.cs b/ObjectListView/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..515899d --- /dev/null +++ b/ObjectListView/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// 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("ObjectListView")] +[assembly: AssemblyDescription("A much easier to use ListView and friends")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Bright Ideas Software")] +[assembly: AssemblyProduct("ObjectListView")] +[assembly: AssemblyCopyright("Copyright © 2006-2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ef28c7a8-77ae-442d-abc3-bb023fa31e57")] + +// 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 Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("2.9.1.*")] +[assembly: AssemblyFileVersion("2.9.1.0")] +[assembly: AssemblyInformationalVersion("2.9.1")] +[assembly: System.CLSCompliant(true)] diff --git a/ObjectListView/Properties/Resources.Designer.cs b/ObjectListView/Properties/Resources.Designer.cs new file mode 100644 index 0000000..1b86d07 --- /dev/null +++ b/ObjectListView/Properties/Resources.Designer.cs @@ -0,0 +1,113 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace BrightIdeasSoftware.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BrightIdeasSoftware.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ClearFiltering { + get { + object obj = ResourceManager.GetObject("ClearFiltering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ColumnFilterIndicator { + get { + object obj = ResourceManager.GetObject("ColumnFilterIndicator", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap Filtering { + get { + object obj = ResourceManager.GetObject("Filtering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortAscending { + get { + object obj = ResourceManager.GetObject("SortAscending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortDescending { + get { + object obj = ResourceManager.GetObject("SortDescending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/ObjectListView/Properties/Resources.resx b/ObjectListView/Properties/Resources.resx new file mode 100644 index 0000000..b017d6a --- /dev/null +++ b/ObjectListView/Properties/Resources.resx @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\clear-filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + + ..\Resources\filter-icons3.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-ascending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-descending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/ObjectListView/Rendering/Adornments.cs b/ObjectListView/Rendering/Adornments.cs new file mode 100644 index 0000000..a159cfa --- /dev/null +++ b/ObjectListView/Rendering/Adornments.cs @@ -0,0 +1,743 @@ +/* + * Adornments - Adornments are the basis for overlays and decorations -- things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 16/08/2009 1:02 AM + * + * Change log: + * v2.6 + * 2012-08-18 JPP - Correctly dispose of brush and pen resources + * v2.3 + * 2009-09-22 JPP - Added Wrap property to TextAdornment, to allow text wrapping to be disabled + * - Added ShrinkToWidth property to ImageAdornment + * 2009-08-17 JPP - Initial version + * + * To do: + * - Use IPointLocator rather than Corners + * - Add RotationCenter property rather than always using middle center + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// An adornment is the common base for overlays and decorations. + /// + public class GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the corner of the adornment that will be positioned at the reference corner + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment AdornmentCorner { + get { return this.adornmentCorner; } + set { this.adornmentCorner = value; } + } + private System.Drawing.ContentAlignment adornmentCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets location within the reference rectangle where the adornment will be drawn + /// + /// This is a simplified interface to ReferenceCorner and AdornmentCorner + [Category("ObjectListView"), + Description("How will the adornment be aligned"), + DefaultValue(System.Drawing.ContentAlignment.BottomRight), + NotifyParentProperty(true)] + public System.Drawing.ContentAlignment Alignment { + get { return this.alignment; } + set { + this.alignment = value; + this.ReferenceCorner = value; + this.AdornmentCorner = value; + } + } + private System.Drawing.ContentAlignment alignment = System.Drawing.ContentAlignment.BottomRight; + + /// + /// Gets or sets the offset by which the position of the adornment will be adjusted + /// + [Category("ObjectListView"), + Description("The offset by which the position of the adornment will be adjusted"), + DefaultValue(typeof(Size), "0,0")] + public Size Offset { + get { return this.offset; } + set { this.offset = value; } + } + private Size offset = new Size(); + + /// + /// Gets or sets the point of the reference rectangle to which the adornment will be aligned. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment ReferenceCorner { + get { return this.referenceCorner; } + set { this.referenceCorner = value; } + } + private System.Drawing.ContentAlignment referenceCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets the degree of rotation by which the adornment will be transformed. + /// The centre of rotation will be the center point of the adornment. + /// + [Category("ObjectListView"), + Description("The degree of rotation that will be applied to the adornment."), + DefaultValue(0), + NotifyParentProperty(true)] + public int Rotation { + get { return this.rotation; } + set { this.rotation = value; } + } + private int rotation; + + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + [Category("ObjectListView"), + Description("The transparency of this adornment. 0 is completely transparent, 255 is completely opaque."), + DefaultValue(128)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + + #region Calculations + + /// + /// Calculate the location of rectangle of the given size, + /// so that it's indicated corner would be at the given point. + /// + /// The point + /// + /// Which corner will be positioned at the reference point + /// + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.TopLeft) -> Point(50, 100) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.MiddleCenter) -> Point(45, 90) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.BottomRight) -> Point(40, 80) + public virtual Point CalculateAlignedPosition(Point pt, Size size, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return pt; + case System.Drawing.ContentAlignment.TopCenter: + return new Point(pt.X - (size.Width / 2), pt.Y); + case System.Drawing.ContentAlignment.TopRight: + return new Point(pt.X - size.Width, pt.Y); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(pt.X, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(pt.X - size.Width, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(pt.X, pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(pt.X - size.Width, pt.Y - size.Height); + } + + // Should never reach here + return pt; + } + + /// + /// Calculate a rectangle that has the given size which is positioned so that + /// its alignment point is at the reference location of the given rect. + /// + /// + /// + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz) { + return this.CreateAlignedRectangle(r, sz, this.ReferenceCorner, this.AdornmentCorner, this.Offset); + } + + /// + /// Create a rectangle of the given size which is positioned so that + /// its indicated corner is at the indicated corner of the reference rect. + /// + /// + /// + /// + /// + /// + /// + /// + /// Creates a rectangle so that its bottom left is at the centre of the reference: + /// corner=BottomLeft, referenceCorner=MiddleCenter + /// This is a powerful concept that takes some getting used to, but is + /// very neat once you understand it. + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz, + System.Drawing.ContentAlignment corner, System.Drawing.ContentAlignment referenceCorner, Size offset) { + Point referencePt = this.CalculateCorner(r, referenceCorner); + Point topLeft = this.CalculateAlignedPosition(referencePt, sz, corner); + return new Rectangle(topLeft + offset, sz); + } + + /// + /// Return the point at the indicated corner of the given rectangle (it doesn't + /// have to be a corner, but a named location) + /// + /// The reference rectangle + /// Which point of the rectangle should be returned? + /// A point + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.TopLeft) -> Point(0, 0) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.MiddleCenter) -> Point(25, 50) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.BottomRight) -> Point(50, 100) + public virtual Point CalculateCorner(Rectangle r, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return new Point(r.Left, r.Top); + case System.Drawing.ContentAlignment.TopCenter: + return new Point(r.X + (r.Width / 2), r.Top); + case System.Drawing.ContentAlignment.TopRight: + return new Point(r.Right, r.Top); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(r.Left, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(r.X + (r.Width / 2), r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(r.Right, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(r.Left, r.Bottom); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(r.X + (r.Width / 2), r.Bottom); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(r.Right, r.Bottom); + } + + // Should never reach here + return r.Location; + } + + /// + /// Given the item and the subitem, calculate its bounds. + /// + /// + /// + /// + public virtual Rectangle CalculateItemBounds(OLVListItem item, OLVListSubItem subItem) { + if (item == null) + return Rectangle.Empty; + + if (subItem == null) + return item.Bounds; + + return item.GetSubItemBounds(item.SubItems.IndexOf(subItem)); + } + + #endregion + + #region Commands + + /// + /// Apply any specified rotation to the Graphic content. + /// + /// The Graphics to be transformed + /// The rotation will be around the centre of this rect + protected virtual void ApplyRotation(Graphics g, Rectangle r) { + if (this.Rotation == 0) + return; + + // THINK: Do we want to reset the transform? I think we want to push a new transform + g.ResetTransform(); + Matrix m = new Matrix(); + m.RotateAt(this.Rotation, new Point(r.Left + r.Width / 2, r.Top + r.Height / 2)); + g.Transform = m; + } + + /// + /// Reverse the rotation created by ApplyRotation() + /// + /// + protected virtual void UnapplyRotation(Graphics g) { + if (this.Rotation != 0) + g.ResetTransform(); + } + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + public class ImageAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the image that will be drawn + /// + [Category("ObjectListView"), + Description("The image that will be drawn"), + DefaultValue(null), + NotifyParentProperty(true)] + public Image Image { + get { return this.image; } + set { this.image = value; } + } + private Image image; + + /// + /// Gets or sets if the image will be shrunk to fit with its horizontal bounds + /// + [Category("ObjectListView"), + Description("Will the image be shrunk to fit within its width?"), + DefaultValue(false)] + public bool ShrinkToWidth { + get { return this.shrinkToWidth; } + set { this.shrinkToWidth = value; } + } + private bool shrinkToWidth; + + #endregion + + #region Commands + + /// + /// Draw the image in its specified location + /// + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void DrawImage(Graphics g, Rectangle r) { + if (this.ShrinkToWidth) + this.DrawScaledImage(g, r, this.Image, this.Transparency); + else + this.DrawImage(g, r, this.Image, this.Transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image != null) + this.DrawImage(g, r, image, image.Size, transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How big should the image be? + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, Size sz, int transparency) { + if (image == null) + return; + + Rectangle adornmentBounds = this.CreateAlignedRectangle(r, sz); + try { + this.ApplyRotation(g, adornmentBounds); + this.DrawTransparentBitmap(g, adornmentBounds, image, transparency); + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Draw the image in its specified location, scaled so that it is not wider + /// than the given rectangle. Height is scaled proportional to the width. + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawScaledImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image == null) + return; + + // If the image is too wide to be drawn in the space provided, proportionally scale it down. + // Too tall images are not scaled. + Size size = image.Size; + if (image.Width > r.Width) { + float scaleRatio = (float)r.Width / (float)image.Width; + size.Height = (int)((float)image.Height * scaleRatio); + size.Width = r.Width - 1; + } + + this.DrawImage(g, r, image, size, transparency); + } + + /// + /// Utility to draw a bitmap transparently. + /// + /// + /// + /// + /// + protected virtual void DrawTransparentBitmap(Graphics g, Rectangle r, Image image, int transparency) { + ImageAttributes imageAttributes = null; + if (transparency != 255) { + imageAttributes = new ImageAttributes(); + float a = (float)transparency / 255.0f; + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 1, 0, 0}, + new float[] {0, 0, 0, a, 0}, + new float[] {0, 0, 0, 0, 1}}; + + imageAttributes.SetColorMatrix(new ColorMatrix(colorMatrixElements)); + } + + g.DrawImage(image, + r, // destination rectangle + 0, 0, image.Size.Width, image.Size.Height, // source rectangle + GraphicsUnit.Pixel, + imageAttributes); + } + + #endregion + } + + /// + /// An adornment that will draw text + /// + public class TextAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the background color of the text + /// Set this to Color.Empty to not draw a background + /// + [Category("ObjectListView"), + Description("The background color of the text"), + DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush BackgroundBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.BackColor)); + } + } + + /// + /// Gets or sets the color of the border around the billboard. + /// Set this to Color.Empty to remove the border + /// + [Category("ObjectListView"), + Description("The color of the border around the text"), + DefaultValue(typeof(Color), "")] + public Color BorderColor { + get { return this.borderColor; } + set { this.borderColor = value; } + } + private Color borderColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Pen BorderPen { + get { + return new Pen(Color.FromArgb(this.workingTransparency, this.BorderColor), this.BorderWidth); + } + } + + /// + /// Gets or sets the width of the border around the text + /// + [Category("ObjectListView"), + Description("The width of the border around the text"), + DefaultValue(0.0f)] + public float BorderWidth { + get { return this.borderWidth; } + set { this.borderWidth = value; } + } + private float borderWidth; + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + [Category("ObjectListView"), + Description("How rounded should the corners of the border be? 0 means no rounding."), + DefaultValue(16.0f), + NotifyParentProperty(true)] + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the font that will be used to draw the text + /// + [Category("ObjectListView"), + Description("The font that will be used to draw the text"), + DefaultValue(null), + NotifyParentProperty(true)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets the font that will be used to draw the text or a reasonable default + /// + [Browsable(false)] + public Font FontOrDefault { + get { + return this.Font ?? new Font("Tahoma", 16); + } + } + + /// + /// Does this text have a background? + /// + [Browsable(false)] + public bool HasBackground { + get { + return this.BackColor != Color.Empty; + } + } + + /// + /// Does this overlay have a border? + /// + [Browsable(false)] + public bool HasBorder { + get { + return this.BorderColor != Color.Empty && this.BorderWidth > 0; + } + } + + /// + /// Gets or sets the maximum width of the text. Text longer than this will wrap. + /// 0 means no maximum. + /// + [Category("ObjectListView"), + Description("The maximum width the text (0 means no maximum). Text longer than this will wrap"), + DefaultValue(0)] + public int MaximumTextWidth { + get { return this.maximumTextWidth; } + set { this.maximumTextWidth = value; } + } + private int maximumTextWidth; + + /// + /// Gets or sets the formatting that should be used on the text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual StringFormat StringFormat { + get { + if (this.stringFormat == null) { + this.stringFormat = new StringFormat(); + this.stringFormat.Alignment = StringAlignment.Center; + this.stringFormat.LineAlignment = StringAlignment.Center; + this.stringFormat.Trimming = StringTrimming.EllipsisCharacter; + if (!this.Wrap) + this.stringFormat.FormatFlags = StringFormatFlags.NoWrap; + } + return this.stringFormat; + } + set { this.stringFormat = value; } + } + private StringFormat stringFormat; + + /// + /// Gets or sets the text that will be drawn + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DefaultValue(null), + NotifyParentProperty(true), + Localizable(true)] + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush TextBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.TextColor)); + } + } + + /// + /// Gets or sets the color of the text + /// + [Category("ObjectListView"), + Description("The color of the text"), + DefaultValue(typeof(Color), "DarkBlue"), + NotifyParentProperty(true)] + public Color TextColor { + get { return this.textColor; } + set { this.textColor = value; } + } + private Color textColor = Color.DarkBlue; + + /// + /// Gets or sets whether the text will wrap when it exceeds its bounds + /// + [Category("ObjectListView"), + Description("Will the text wrap?"), + DefaultValue(true)] + public bool Wrap { + get { return this.wrap; } + set { this.wrap = value; } + } + private bool wrap = true; + + #endregion + + #region Implementation + + /// + /// Draw our text with our stored configuration in relation to the given + /// reference rectangle + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + public virtual void DrawText(Graphics g, Rectangle r) { + this.DrawText(g, r, this.Text, this.Transparency); + } + + /// + /// Draw the given text with our stored configuration + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + /// The text to draw + /// How opaque should be text be + public virtual void DrawText(Graphics g, Rectangle r, string s, int transparency) { + if (String.IsNullOrEmpty(s)) + return; + + Rectangle textRect = this.CalculateTextBounds(g, r, s); + this.DrawBorderedText(g, textRect, s, transparency); + } + + /// + /// Draw the text with a border + /// + /// The Graphics used for drawing + /// The bounds within which the text should be drawn + /// The text to draw + /// How opaque should be text be + protected virtual void DrawBorderedText(Graphics g, Rectangle textRect, string text, int transparency) { + Rectangle borderRect = textRect; + borderRect.Inflate((int)this.BorderWidth / 2, (int)this.BorderWidth / 2); + borderRect.Y -= 1; // Looker better a little higher + + try { + this.ApplyRotation(g, textRect); + using (GraphicsPath path = this.GetRoundedRect(borderRect, this.CornerRounding)) { + this.workingTransparency = transparency; + if (this.HasBackground) { + using (Brush b = this.BackgroundBrush) + g.FillPath(b, path); + } + + using (Brush b = this.TextBrush) + g.DrawString(text, this.FontOrDefault, b, textRect, this.StringFormat); + + if (this.HasBorder) { + using (Pen p = this.BorderPen) + g.DrawPath(p, path); + } + } + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Return the rectangle that will be the precise bounds of the displayed text + /// + /// + /// + /// + /// The bounds of the text + protected virtual Rectangle CalculateTextBounds(Graphics g, Rectangle r, string s) { + int maxWidth = this.MaximumTextWidth <= 0 ? r.Width : this.MaximumTextWidth; + SizeF sizeF = g.MeasureString(s, this.FontOrDefault, maxWidth, this.StringFormat); + Size size = new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + return this.CreateAlignedRectangle(r, size); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected virtual GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + + private int workingTransparency; + } +} diff --git a/ObjectListView/Rendering/Decorations.cs b/ObjectListView/Rendering/Decorations.cs new file mode 100644 index 0000000..91f21d6 --- /dev/null +++ b/ObjectListView/Rendering/Decorations.cs @@ -0,0 +1,973 @@ +/* + * Decorations - Images, text or other things that can be rendered onto an ObjectListView + * + * Author: Phillip Piper + * Date: 19/08/2009 10:56 PM + * + * Change log: + * 2018-04-30 JPP - Added ColumnEdgeDecoration. + * TintedColumnDecoration now uses common base class, ColumnDecoration. + * v2.5 + * 2011-04-04 JPP - Added ability to have a gradient background on BorderDecoration + * v2.4 + * 2010-04-15 JPP - Tweaked LightBoxDecoration a little + * v2.3 + * 2009-09-23 JPP - Added LeftColumn and RightColumn to RowBorderDecoration + * 2009-08-23 JPP - Added LightBoxDecoration + * 2009-08-19 JPP - Initial version. Separated from Overlays.cs + * + * To do: + * + * Copyright (C) 2009-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A decoration is an overlay that draws itself in relation to a given row or cell. + /// Decorations scroll when the listview scrolls. + /// + public interface IDecoration : IOverlay + { + /// + /// Gets or sets the row that is to be decorated + /// + OLVListItem ListItem { get; set; } + + /// + /// Gets or sets the subitem that is to be decorated + /// + OLVListSubItem SubItem { get; set; } + } + + /// + /// An AbstractDecoration is a safe do-nothing implementation of the IDecoration interface + /// + public class AbstractDecoration : IDecoration + { + #region IDecoration Members + + /// + /// Gets or sets the row that is to be decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the subitem that is to be decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Public properties + + /// + /// Gets the bounds of the decorations row + /// + public Rectangle RowBounds { + get { + if (this.ListItem == null) + return Rectangle.Empty; + else + return this.ListItem.Bounds; + } + } + + /// + /// Get the bounds of the decorations cell + /// + public Rectangle CellBounds { + get { + if (this.ListItem == null || this.SubItem == null) + return Rectangle.Empty; + else + return this.ListItem.GetSubItemBounds(this.ListItem.SubItems.IndexOf(this.SubItem)); + } + } + + #endregion + + #region IOverlay Members + + /// + /// Draw the decoration + /// + /// + /// + /// + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + } + + + /// + /// This decoration draws something over a given column. + /// Subclasses must override DrawDecoration() + /// + public class ColumnDecoration : AbstractDecoration { + #region Constructors + + /// + /// Create a ColumnDecoration + /// + public ColumnDecoration() { + } + + /// + /// Create a ColumnDecoration + /// + /// + public ColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column ?? throw new ArgumentNullException("column"); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the column that will be decorated + /// + public OLVColumn ColumnToDecorate { + get { return this.columnToDecorate; } + set { this.columnToDecorate = value; } + } + private OLVColumn columnToDecorate; + + /// + /// Gets or sets the pen that will be used to draw the column decoration + /// + public Pen Pen { + get { + return this.pen ?? Pens.DarkSlateBlue; + } + set { + if (this.pen == value) + return; + + if (this.pen != null) { + this.pen.Dispose(); + } + + this.pen = value; + } + } + private Pen pen; + + #endregion + + #region IOverlay Members + + /// + /// Draw a decoration over our column + /// + /// + /// This overlay only works when: + /// - the list is in Details view + /// - there is at least one row + /// - there is a selected column (or a specified tint column) + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + + if (olv.View != System.Windows.Forms.View.Details) + return; + + if (olv.GetItemCount() == 0) + return; + + if (this.ColumnToDecorate == null) + return; + + Point sides = NativeMethods.GetScrolledColumnSides(olv, this.ColumnToDecorate.Index); + if (sides.X == -1) + return; + + Rectangle columnBounds = new Rectangle(sides.X, r.Top, sides.Y - sides.X, r.Bottom); + + // Find the bottom of the last item. The decoration should extend only to there. + OLVListItem lastItem = olv.GetLastItemInDisplayOrder(); + if (lastItem != null) { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + // Delegate the drawing of the actual decoration + this.DrawDecoration(olv, g, r, columnBounds); + } + + /// + /// Subclasses should override this to draw exactly what they want + /// + /// + /// + /// + /// + public virtual void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.DrawRectangle(this.Pen, columnBounds); + } + + #endregion + } + + /// + /// This decoration draws a slight tint over a column of the + /// owning listview. If no column is explicitly set, the selected + /// column in the listview will be used. + /// The selected column is normally the sort column, but does not have to be. + /// + public class TintedColumnDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a TintedColumnDecoration + /// + public TintedColumnDecoration() { + this.Tint = Color.FromArgb(15, Color.Blue); + } + + /// + /// Create a TintedColumnDecoration + /// + /// + public TintedColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the color that will be 'tinted' over the selected column + /// + public Color Tint { + get { return this.tint; } + set { + if (this.tint == value) + return; + + if (this.tintBrush != null) { + this.tintBrush.Dispose(); + this.tintBrush = null; + } + + this.tint = value; + this.tintBrush = new SolidBrush(this.tint); + } + } + private Color tint; + private SolidBrush tintBrush; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.FillRectangle(this.tintBrush, columnBounds); + } + + #endregion + } + + /// + /// Specify on which side edge the decoration will be drawn + /// + public enum ColumnEdge { + Left, + Right + } + + /// + /// This decoration draws a line on the edge(s) of its given column + /// + /// + /// Like all decorations, this draws over the contents of list view. + /// If you set the Pen too wide enough, you may overwrite the contents + /// of the column (if alignment is Inside) or the surrounding columns (if alignment is Outside) + /// + public class ColumnEdgeDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a ColumnEdgeDecoration + /// + public ColumnEdgeDecoration() { + } + + /// + /// Create a ColumnEdgeDecoration which draws a line over the right edges of the column (by default) + /// + /// + /// + /// + /// + public ColumnEdgeDecoration(OLVColumn column, Pen pen = null, ColumnEdge edge = ColumnEdge.Right, float xOffset = 0) + : this() { + this.ColumnToDecorate = column; + this.Pen = pen; + this.Edge = edge; + this.XOffset = xOffset; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether this decoration will draw a line on the left or right edge of the column + /// + public ColumnEdge Edge { + get { return edge; } + set { edge = value; } + } + private ColumnEdge edge = ColumnEdge.Right; + + /// + /// Gets or sets the horizontal offset from centered at which the line will be drawn + /// + public float XOffset { + get { return xOffset; } + set { xOffset = value; } + } + private float xOffset; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + float left = CalculateEdge(columnBounds); + g.DrawLine(this.Pen, left, columnBounds.Top, left, columnBounds.Bottom); + + } + + private float CalculateEdge(Rectangle columnBounds) { + float tweak = this.XOffset + (this.Pen.Width <= 2 ? 0 : 1); + int x = this.Edge == ColumnEdge.Left ? columnBounds.Left : columnBounds.Right; + return tweak + x - this.Pen.Width / 2; + } + + #endregion + } + + /// + /// This decoration draws an optionally filled border around a rectangle. + /// Subclasses must override CalculateBounds(). + /// + public class BorderDecoration : AbstractDecoration + { + #region Constructors + + /// + /// Create a BorderDecoration + /// + public BorderDecoration() + : this(new Pen(Color.FromArgb(64, Color.Blue), 1)) { + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + public BorderDecoration(Pen borderPen) { + this.BorderPen = borderPen; + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + /// The brush used to fill the rectangle + public BorderDecoration(Pen borderPen, Brush fill) { + this.BorderPen = borderPen; + this.FillBrush = fill; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the pen that will be used to draw the border + /// + public Pen BorderPen { + get { return this.borderPen; } + set { this.borderPen = value; } + } + private Pen borderPen; + + /// + /// Gets or sets the padding that will be added to the bounds of the item + /// before drawing the border and fill. + /// + public Size BoundsPadding { + get { return this.boundsPadding; } + set { this.boundsPadding = value; } + } + private Size boundsPadding = new Size(-1, 2); + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the brush that will be used to fill the border + /// + /// This value is ignored when using gradient brush + public Brush FillBrush { + get { return this.fillBrush; } + set { this.fillBrush = value; } + } + private Brush fillBrush = new SolidBrush(Color.FromArgb(64, Color.Blue)); + + /// + /// Gets or sets the color that will be used as the start of a gradient fill. + /// + /// This and FillGradientTo must be given value to show a gradient + public Color? FillGradientFrom { + get { return this.fillGradientFrom; } + set { this.fillGradientFrom = value; } + } + private Color? fillGradientFrom; + + /// + /// Gets or sets the color that will be used as the end of a gradient fill. + /// + /// This and FillGradientFrom must be given value to show a gradient + public Color? FillGradientTo { + get { return this.fillGradientTo; } + set { this.fillGradientTo = value; } + } + private Color? fillGradientTo; + + /// + /// Gets or sets the fill mode that will be used for the gradient. + /// + public LinearGradientMode FillGradientMode { + get { return this.fillGradientMode; } + set { this.fillGradientMode = value; } + } + private LinearGradientMode fillGradientMode = LinearGradientMode.Vertical; + + #endregion + + #region IOverlay Members + + /// + /// Draw a filled border + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle bounds = this.CalculateBounds(); + if (!bounds.IsEmpty) + this.DrawFilledBorder(g, bounds); + } + + #endregion + + #region Subclass responsibility + + /// + /// Subclasses should override this to say where the border should be drawn + /// + /// + protected virtual Rectangle CalculateBounds() { + return Rectangle.Empty; + } + + #endregion + + #region Implementation utilities + + /// + /// Do the actual work of drawing the filled border + /// + /// + /// + protected void DrawFilledBorder(Graphics g, Rectangle bounds) { + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillGradientFrom != null && this.FillGradientTo != null) { + if (this.FillBrush != null) + this.FillBrush.Dispose(); + this.FillBrush = new LinearGradientBrush(bounds, this.FillGradientFrom.Value, this.FillGradientTo.Value, this.FillGradientMode); + } + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + /// + /// Create a GraphicsPath that represents a round cornered rectangle. + /// + /// + /// If this is 0 or less, the rectangle will not be rounded. + /// + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter <= 0.0f) { + path.AddRectangle(rect); + } else { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } + + return path; + } + + #endregion + } + + /// + /// Instances of this class draw a border around the decorated row + /// + public class RowBorderDecoration : BorderDecoration + { + /// + /// Gets or sets the index of the left most column to be used for the border + /// + public int LeftColumn { + get { return leftColumn; } + set { leftColumn = value; } + } + private int leftColumn = -1; + + /// + /// Gets or sets the index of the right most column to be used for the border + /// + public int RightColumn { + get { return rightColumn; } + set { rightColumn = value; } + } + private int rightColumn = -1; + + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + Rectangle bounds = this.RowBounds; + if (this.ListItem == null) + return bounds; + + if (this.LeftColumn >= 0) { + Rectangle leftCellBounds = this.ListItem.GetSubItemBounds(this.LeftColumn); + if (!leftCellBounds.IsEmpty) { + bounds.Width = bounds.Right - leftCellBounds.Left; + bounds.X = leftCellBounds.Left; + } + } + + if (this.RightColumn >= 0) { + Rectangle rightCellBounds = this.ListItem.GetSubItemBounds(this.RightColumn); + if (!rightCellBounds.IsEmpty) { + bounds.Width = rightCellBounds.Right - bounds.Left; + } + } + + return bounds; + } + } + + /// + /// Instances of this class draw a border around the decorated subitem. + /// + public class CellBorderDecoration : BorderDecoration + { + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + return this.CellBounds; + } + } + + /// + /// This decoration puts a border around the cell being edited and + /// optionally "lightboxes" the cell (makes the rest of the control dark). + /// + public class EditingCellBorderDecoration : BorderDecoration + { + #region Life and death + + /// + /// Create a EditingCellBorderDecoration + /// + public EditingCellBorderDecoration() { + this.FillBrush = null; + this.BorderPen = new Pen(Color.DarkBlue, 2); + this.CornerRounding = 8; + this.BoundsPadding = new Size(10, 8); + + } + + /// + /// Create a EditingCellBorderDecoration + /// + /// Should the decoration use a lighbox display style? + public EditingCellBorderDecoration(bool useLightBox) : this() + { + this.UseLightbox = useLightbox; + } + + #endregion + + #region Configuration properties + + /// + /// Gets or set whether the decoration should make the rest of + /// the control dark when a cell is being edited + /// + /// If this is true, FillBrush is used to overpaint + /// the control. + public bool UseLightbox { + get { return this.useLightbox; } + set { + if (this.useLightbox == value) + return; + this.useLightbox = value; + if (this.useLightbox) { + if (this.FillBrush == null) + this.FillBrush = new SolidBrush(Color.FromArgb(64, Color.Black)); + } + } + } + private bool useLightbox; + + #endregion + + #region Implementation + + /// + /// Draw the decoration + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!olv.IsCellEditing) + return; + + Rectangle bounds = olv.CellEditor.Bounds; + if (bounds.IsEmpty) + return; + + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillBrush != null) { + if (this.UseLightbox) { + using (Region newClip = new Region(r)) { + newClip.Exclude(path); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } else { + g.FillPath(this.FillBrush, path); + } + } + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + #endregion + } + + /// + /// This decoration causes everything *except* the row under the mouse to be overpainted + /// with a tint, making the row under the mouse stand out in comparison. + /// The darker and more opaque the fill color, the more obvious the + /// decorated row becomes. + /// + public class LightBoxDecoration : BorderDecoration + { + /// + /// Create a LightBoxDecoration + /// + public LightBoxDecoration() { + this.BoundsPadding = new Size(-1, 4); + this.CornerRounding = 8.0f; + this.FillBrush = new SolidBrush(Color.FromArgb(72, Color.Black)); + } + + /// + /// Draw a tint over everything in the ObjectListView except the + /// row under the mouse. + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!r.Contains(olv.PointToClient(Cursor.Position))) + return; + + Rectangle bounds = this.RowBounds; + if (bounds.IsEmpty) { + if (olv.View == View.Tile) + g.FillRectangle(this.FillBrush, r); + return; + } + + using (Region newClip = new Region(r)) { + bounds.Inflate(this.BoundsPadding); + newClip.Exclude(this.GetRoundedRect(bounds, this.CornerRounding)); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } + } + + /// + /// Instances of this class put an Image over the row/cell that it is decorating + /// + public class ImageDecoration : ImageAdornment, IDecoration + { + #region Constructors + + /// + /// Create an image decoration + /// + public ImageDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create an image decoration + /// + /// + public ImageDecoration(Image image) + : this() { + this.Image = image; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, int transparency) + : this() { + this.Image = image; + this.Transparency = transparency; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, ContentAlignment alignment) + : this() { + this.Image = image; + this.Alignment = alignment; + } + + /// + /// Create an image decoration + /// + /// + /// + /// + public ImageDecoration(Image image, int transparency, ContentAlignment alignment) + : this() { + this.Image = image; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawImage(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } + + /// + /// Instances of this class draw some text over the row/cell that they are decorating + /// + public class TextDecoration : TextAdornment, IDecoration + { + #region Constructors + + /// + /// Create a TextDecoration + /// + public TextDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create a TextDecoration + /// + /// + public TextDecoration(string text) + : this() { + this.Text = text; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, int transparency) + : this() { + this.Text = text; + this.Transparency = transparency; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, ContentAlignment alignment) + : this() { + this.Text = text; + this.Alignment = alignment; + } + + /// + /// Create a TextDecoration + /// + /// + /// + /// + public TextDecoration(string text, int transparency, ContentAlignment alignment) + : this() { + this.Text = text; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawText(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Overlays.cs b/ObjectListView/Rendering/Overlays.cs new file mode 100644 index 0000000..d103601 --- /dev/null +++ b/ObjectListView/Rendering/Overlays.cs @@ -0,0 +1,302 @@ +/* + * Overlays - Images, text or other things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * v2.3 + * 2009-08-17 JPP - Overlays now use Adornments + * - Added ITransparentOverlay interface. Overlays can now have separate transparency levels + * 2009-08-10 JPP - Moved decoration related code to new file + * v2.2.1 + * 200-07-24 JPP - TintedColumnDecoration now works when last item is a member of a collapsed + * group (well, it no longer crashes). + * v2.2 + * 2009-06-01 JPP - Make sure that TintedColumnDecoration reaches to the last item in group view + * 2009-05-05 JPP - Unified BillboardOverlay text rendering with that of TextOverlay + * 2009-04-30 JPP - Added TintedColumnDecoration + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// The interface for an object which can draw itself over the top of + /// an ObjectListView. + /// + public interface IOverlay + { + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + void Draw(ObjectListView olv, Graphics g, Rectangle r); + } + + /// + /// An interface for an overlay that supports variable levels of transparency + /// + public interface ITransparentOverlay : IOverlay + { + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + int Transparency { get; set; } + } + + /// + /// A null implementation of the IOverlay interface + /// + public class AbstractOverlay : ITransparentOverlay + { + #region IOverlay Members + + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + + #region ITransparentOverlay Members + + /// + /// How transparent should this overlay be? + /// + [Category("ObjectListView"), + Description("How transparent should this overlay be"), + DefaultValue(128), + NotifyParentProperty(true)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class ImageOverlay : ImageAdornment, ITransparentOverlay + { + /// + /// Create an ImageOverlay + /// + public ImageOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawImage(g, insetRect, this.Image, 255); + } + + #endregion + } + + /// + /// An overlay that will draw text over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class TextOverlay : TextAdornment, ITransparentOverlay + { + /// + /// Create a TextOverlay + /// + public TextOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + /// + /// Gets or sets whether the border will be drawn with rounded corners + /// + [Browsable(false), + Obsolete("Use CornerRounding instead", false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool RoundCorneredBorder { + get { return this.CornerRounding > 0; } + set { + if (value) + this.CornerRounding = 16.0f; + else + this.CornerRounding = 0.0f; + } + } + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawText(g, insetRect, this.Text, 255); + } + + #endregion + } + + /// + /// A Billboard overlay is a TextOverlay positioned at an absolute point + /// + public class BillboardOverlay : TextOverlay + { + /// + /// Create a BillboardOverlay + /// + public BillboardOverlay() { + this.Transparency = 255; + this.BackColor = Color.PeachPuff; + this.TextColor = Color.Black; + this.BorderColor = Color.Empty; + this.Font = new Font("Tahoma", 10); + } + + /// + /// Gets or sets where should the top left of the billboard be placed + /// + public Point Location { + get { return this.location; } + set { this.location = value; } + } + private Point location; + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + // Calculate the bounds of the text, and then move it to where it should be + Rectangle textRect = this.CalculateTextBounds(g, r, this.Text); + textRect.Location = this.Location; + + // Make sure the billboard is within the bounds of the List, as far as is possible + if (textRect.Right > r.Width) + textRect.X = Math.Max(r.Left, r.Width - textRect.Width); + if (textRect.Bottom > r.Height) + textRect.Y = Math.Max(r.Top, r.Height - textRect.Height); + + this.DrawBorderedText(g, textRect, this.Text, 255); + } + } +} diff --git a/ObjectListView/Rendering/Renderers.cs b/ObjectListView/Rendering/Renderers.cs new file mode 100644 index 0000000..dac6a62 --- /dev/null +++ b/ObjectListView/Rendering/Renderers.cs @@ -0,0 +1,3887 @@ +/* + * Renderers - A collection of useful renderers that are used to owner draw a cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2018-10-06 JPP - Fix rendering so that OLVColumn.WordWrap works when using customised Renderers + * 2018-05-01 JPP - Use ITextMatchFilter interface rather than TextMatchFilter concrete class. + * v2.9.2 + * 2016-06-02 JPP - CalculateImageWidth() no longer adds 2 to the image width + * 2016-05-29 JPP - Fix calculation of cell edit boundaries on TreeListView controls + * v2.9 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * 2015-06-23 JPP - Added ColumnButtonRenderer plus general support for Buttons + * 2015-06-22 JPP - Added BaseRenderer.ConfigureItem() and ConfigureSubItem() to easily allow + * other renderers to be chained for use within a primary renderer. + * - Lots of tightening of hit tests and edit rectangles + * 2015-05-15 JPP - Handle rendering an Image when that Image is returned as an aspect. + * v2.8 + * 2014-09-26 JPP - Dispose of animation timer in a more robust fashion. + * 2014-05-20 JPP - Handle rendering disabled rows + * v2.7 + * 2013-04-29 JPP - Fixed bug where Images were not vertically aligned + * v2.6 + * 2012-10-26 JPP - Hit detection will no longer report check box hits on columns without checkboxes. + * 2012-07-13 JPP - [Breaking change] Added preferedSize parameter to IRenderer.GetEditRectangle(). + * v2.5.1 + * 2012-07-14 JPP - Added CellPadding to various places. Replaced DescribedTaskRenderer.CellPadding. + * 2012-07-11 JPP - Added CellVerticalAlignment to various places allow cell contents to be vertically + * aligned (rather than always being centered). + * v2.5 + * 2010-08-24 JPP - CheckBoxRenderer handles hot boxes and correctly vertically centers the box. + * 2010-06-23 JPP - Major rework of HighlightTextRenderer. Now uses TextMatchFilter directly. + * Draw highlighting underneath text to improve legibility. Works with new + * TextMatchFilter capabilities. + * v2.4 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * v2.3 + * 2009-09-28 JPP - Added DescribedTaskRenderer + * 2009-09-01 JPP - Correctly handle an ImageRenderer's handling of an aspect that holds + * the image to be displayed at Byte[]. + * 2009-08-29 JPP - Fixed bug where some of a cell's background was not erased. + * 2009-08-15 JPP - Correctly MeasureText() using the appropriate graphic context + * - Handle translucent selection setting + * v2.2.1 + * 2009-07-24 JPP - Try to honour CanWrap setting when GDI rendering text. + * 2009-07-11 JPP - Correctly calculate edit rectangle for subitems of a tree view + * (previously subitems were indented in the same way as the primary column) + * v2.2 + * 2009-06-06 JPP - Tweaked text rendering so that column 0 isn't ellipsed unnecessarily. + * 2009-05-05 JPP - Added Unfocused foreground and background colors + * (thanks to Christophe Hosten) + * 2009-04-21 JPP - Fixed off-by-1 error when calculating text widths. This caused + * middle and right aligned columns to always wrap one character + * when printed using ListViewPrinter (SF#2776634). + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-06 JPP - Allow for item indent when calculating edit rectangle + * v2.1 + * 2009-02-24 JPP - Work properly with ListViewPrinter again + * 2009-01-26 JPP - AUSTRALIA DAY (why aren't I on holidays!) + * - Major overhaul of renderers. Now uses IRenderer interface. + * - ImagesRenderer and FlagsRenderer are now defunct. + * The names are retained for backward compatibility. + * 2009-01-23 JPP - Align bitmap AND text according to column alignment (previously + * only text was aligned and bitmap was always to the left). + * 2009-01-21 JPP - Changed to use TextRenderer rather than native GDI routines. + * 2009-01-20 JPP - Draw images directly from image list if possible. 30% faster! + * - Tweaked some spacings to look more like native ListView + * - Text highlight for non FullRowSelect is now the right color + * when the control doesn't have focus. + * - Commented out experimental animations. Still needs work. + * 2009-01-19 JPP - Changed to draw text using GDI routines. Looks more like + * native control this way. Set UseGdiTextRendering to false to + * revert to previous behavior. + * 2009-01-15 JPP - Draw background correctly when control is disabled + * - Render checkboxes using CheckBoxRenderer + * v2.0.1 + * 2008-12-29 JPP - Render text correctly when HideSelection is true. + * 2008-12-26 JPP - BaseRenderer now works correctly in all Views + * 2008-12-23 JPP - Fixed two small bugs in BarRenderer + * v2.0 + * 2008-10-26 JPP - Don't owner draw when in Design mode + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2018 Phillip Piper + * + * TO DO: + * - Hit detection on renderers doesn't change the controls standard selection behavior + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using Timer = System.Threading.Timer; + +namespace BrightIdeasSoftware { + /// + /// Renderers are the mechanism used for owner drawing cells. As such, they can also handle + /// hit detection and positioning of cell editing rectangles. + /// + public interface IRenderer { + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, Object rowObject); + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, Object rowObject); + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + void HitTest(OlvListViewHitTestInfo hti, int x, int y); + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize); + } + + /// + /// Renderers that implement this interface will have the filter property updated, + /// each time the filter on the ObjectListView is updated. + /// + public interface IFilterAwareRenderer + { + /// + /// Gets or sets the filter that is currently active + /// + IModelFilter Filter { get; set; } + } + + /// + /// An AbstractRenderer is a do-nothing implementation of the IRenderer interface. + /// + [Browsable(true), + ToolboxItem(false)] + public class AbstractRenderer : Component, IRenderer { + #region IRenderer Members + + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject) { + return true; + } + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + return false; + } + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + public virtual void HitTest(OlvListViewHitTestInfo hti, int x, int y) {} + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + public virtual Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return cellBounds; + } + + #endregion + } + + /// + /// This class provides compatibility for v1 RendererDelegates + /// + [ToolboxItem(false)] + internal class Version1Renderer : AbstractRenderer { + public Version1Renderer(RenderDelegate renderDelegate) { + this.RenderDelegate = renderDelegate; + } + + /// + /// The renderer delegate that this renderer wraps + /// + public RenderDelegate RenderDelegate; + + #region IRenderer Members + + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + if (this.RenderDelegate == null) + return base.RenderSubItem(e, g, cellBounds, rowObject); + else + return this.RenderDelegate(e, g, cellBounds, rowObject); + } + + #endregion + } + + /// + /// A BaseRenderer provides useful base level functionality for any custom renderer. + /// + /// + /// Subclasses will normally override the Render or OptionalRender method, and use the other + /// methods as helper functions. + /// + [Browsable(true), + ToolboxItem(true)] + public class BaseRenderer : AbstractRenderer { + internal const TextFormatFlags NormalTextFormatFlags = TextFormatFlags.NoPrefix | + TextFormatFlags.EndEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + + #region Configuration Properties + + /// + /// Can the renderer wrap lines that do not fit completely within the cell? + /// + /// + /// If this is not set specifically, the value will be taken from Column.WordWrap + /// + /// Wrapping text doesn't work with the GDI renderer, so if this set to true, GDI+ rendering will used. + /// The difference between GDI and GDI+ rendering can give word wrapped columns a slight different appearance. + /// + /// + [Category("Appearance"), + Description("Can the renderer wrap text that does not fit completely within the cell"), + DefaultValue(null)] + public bool? CanWrap { + get { return canWrap; } + set { canWrap = value; } + } + + private bool? canWrap; + + /// + /// Get the actual value that should be used right now for CanWrap + /// + [Browsable(false)] + protected bool CanWrapOrDefault { + get { + return this.CanWrap ?? this.Column != null && this.Column.WordWrap; + } + } + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// for more details. + /// + [Category("ObjectListView"), + Description("The number of pixels that renderer will leave empty around the edge of the cell"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets the horizontal alignment of the column + /// + [Browsable(false)] + public HorizontalAlignment CellHorizontalAlignment + { + get { return this.Column == null ? HorizontalAlignment.Left : this.Column.TextAlign; } + } + + /// + /// Gets or sets how cells drawn by this renderer will be vertically aligned. + /// + /// + /// + /// If this is not set, the value from the column or control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets the optional padding that this renderer should apply before drawing. + /// This property considers all possible sources of padding + /// + [Browsable(false)] + protected virtual Rectangle? EffectiveCellPadding { + get { + if (this.cellPadding.HasValue) + return this.cellPadding.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellPadding.HasValue) + return this.OLVSubItem.CellPadding.Value; + + if (this.ListItem != null && this.ListItem.CellPadding.HasValue) + return this.ListItem.CellPadding.Value; + + if (this.Column != null && this.Column.CellPadding.HasValue) + return this.Column.CellPadding.Value; + + if (this.ListView != null && this.ListView.CellPadding.HasValue) + return this.ListView.CellPadding.Value; + + return null; + } + } + + /// + /// Gets the vertical cell alignment that should govern the rendering. + /// This property considers all possible sources. + /// + [Browsable(false)] + protected virtual StringAlignment EffectiveCellVerticalAlignment { + get { + if (this.cellVerticalAlignment.HasValue) + return this.cellVerticalAlignment.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellVerticalAlignment.HasValue) + return this.OLVSubItem.CellVerticalAlignment.Value; + + if (this.ListItem != null && this.ListItem.CellVerticalAlignment.HasValue) + return this.ListItem.CellVerticalAlignment.Value; + + if (this.Column != null && this.Column.CellVerticalAlignment.HasValue) + return this.Column.CellVerticalAlignment.Value; + + if (this.ListView != null) + return this.ListView.CellVerticalAlignment; + + return StringAlignment.Center; + } + } + + /// + /// Gets or sets the image list from which keyed images will be fetched + /// + [Category("Appearance"), + Description("The image list from which keyed images will be fetched for drawing. If this is not given, the small ImageList from the ObjectListView will be used"), + DefaultValue(null)] + public ImageList ImageList { + get { return imageList; } + set { imageList = value; } + } + + private ImageList imageList; + + /// + /// When rendering multiple images, how many pixels should be between each image? + /// + [Category("Appearance"), + Description("When rendering multiple images, how many pixels should be between each image?"), + DefaultValue(1)] + public int Spacing { + get { return spacing; } + set { spacing = value; } + } + + private int spacing = 1; + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + /// Even if this is set to true, it will return false if the renderer + /// is set to word wrap, since GDI doesn't handle wrapping. + [Category("Appearance"), + Description("Should text be rendered using GDI routines?"), + DefaultValue(true)] + public virtual bool UseGdiTextRendering { + get { + // Can't use GDI routines on a GDI+ printer context or when word wrapping is required + return !this.IsPrinting && !this.CanWrapOrDefault && useGdiTextRendering; + } + set { useGdiTextRendering = value; } + } + private bool useGdiTextRendering = true; + + #endregion + + #region State Properties + + /// + /// Get or set the aspect of the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object Aspect { + get { + if (aspect == null) + aspect = column.GetValue(this.rowObject); + return aspect; + } + set { aspect = value; } + } + + private Object aspect; + + /// + /// What are the bounds of the cell that is being drawn? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Rectangle Bounds { + get { return bounds; } + set { bounds = value; } + } + + private Rectangle bounds; + + /// + /// Get or set the OLVColumn that this renderer will draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn Column { + get { return column; } + set { column = value; } + } + + private OLVColumn column; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewItemEventArgs DrawItemEvent { + get { return drawItemEventArgs; } + set { drawItemEventArgs = value; } + } + + private DrawListViewItemEventArgs drawItemEventArgs; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewSubItemEventArgs Event { + get { return eventArgs; } + set { eventArgs = value; } + } + + private DrawListViewSubItemEventArgs eventArgs; + + /// + /// Gets or sets the font to be used for text in this cell + /// + /// + /// + /// In general, this property should be treated as internal. + /// If you do set this, the given font will be used without any other consideration. + /// All other factors -- selection state, hot item, hyperlinks -- will be ignored. + /// + /// + /// A better way to set the font is to change either ListItem.Font or SubItem.Font + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Font Font { + get { + if (this.font != null || this.ListItem == null) + return this.font; + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.Font; + + return this.SubItem.Font; + } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets the image list from which keyed images will be fetched + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageList ImageListOrDefault { + get { return this.ImageList ?? this.ListView.SmallImageList; } + } + + /// + /// Should this renderer fill in the background before drawing? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDrawBackground { + get { return !this.IsPrinting; } + } + + /// + /// Cache whether or not our item is selected + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsItemSelected { + get { return isItemSelected; } + set { isItemSelected = value; } + } + + private bool isItemSelected; + + /// + /// Is this renderer being used on a printer context? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrinting { + get { return isPrinting; } + set { isPrinting = value; } + } + + private bool isPrinting; + + /// + /// Get or set the listitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + + private OLVListItem listItem; + + /// + /// Get/set the listview for which the drawing is to be done + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + + private ObjectListView objectListView; + + /// + /// Get the specialized OLVSubItem that this renderer is drawing + /// + /// This returns null for column 0. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem OLVSubItem { + get { return listSubItem as OLVListSubItem; } + } + + /// + /// Get or set the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + + private Object rowObject; + + /// + /// Get or set the list subitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem SubItem { + get { return listSubItem; } + set { listSubItem = value; } + } + + private OLVListSubItem listSubItem; + + /// + /// The brush that will be used to paint the text + /// + /// + /// + /// In general, this property should be treated as internal. It will be reset after each render. + /// + /// + /// + /// In particular, don't set it to configure the color of the text on the control. That should be done via SubItem.ForeColor + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush TextBrush { + get { + if (textBrush == null) + return new SolidBrush(this.GetForegroundColor()); + else + return this.textBrush; + } + set { textBrush = value; } + } + + private Brush textBrush; + + /// + /// Will this renderer use the custom images from the parent ObjectListView + /// to draw the checkbox images. + /// + /// + /// + /// If this is true, the renderer will use the images from the + /// StateImageList to represent checkboxes. 0 - unchecked, 1 - checked, 2 - indeterminate. + /// + /// If this is false (the default), then the renderer will use .NET's standard + /// CheckBoxRenderer. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool UseCustomCheckboxImages { + get { return useCustomCheckboxImages; } + set { useCustomCheckboxImages = value; } + } + + private bool useCustomCheckboxImages; + + private void ClearState() { + this.Event = null; + this.DrawItemEvent = null; + this.Aspect = null; + this.TextBrush = null; + } + + #endregion + + #region Utilities + + /// + /// Align the second rectangle with the first rectangle, + /// according to the alignment of the column + /// + /// The cell's bounds + /// The rectangle to be aligned within the bounds + /// An aligned rectangle + protected virtual Rectangle AlignRectangle(Rectangle outer, Rectangle inner) { + Rectangle r = new Rectangle(outer.Location, inner.Size); + + // Align horizontally depending on the column alignment + if (inner.Width < outer.Width) { + r.X = AlignHorizontally(outer, inner); + } + + // Align vertically too + if (inner.Height < outer.Height) { + r.Y = AlignVertically(outer, inner); + } + + return r; + } + + /// + /// Calculate the left edge of the rectangle that aligns the outer rectangle with the inner one + /// according to this renderer's horizontal alignment + /// + /// + /// + /// + protected int AlignHorizontally(Rectangle outer, Rectangle inner) { + HorizontalAlignment alignment = this.CellHorizontalAlignment; + switch (alignment) { + case HorizontalAlignment.Left: + return outer.Left + 1; + case HorizontalAlignment.Center: + return outer.Left + ((outer.Width - inner.Width) / 2); + case HorizontalAlignment.Right: + return outer.Right - inner.Width - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with the inner rectangle + /// according to this renders vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, Rectangle inner) { + return AlignVertically(outer, inner.Height); + } + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with a rectangle of the given height + /// according to this renderer's vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, int innerHeight) { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return outer.Top + 1; + case StringAlignment.Center: + return outer.Top + ((outer.Height - innerHeight) / 2); + case StringAlignment.Far: + return outer.Bottom - innerHeight - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + /// + /// Calculate the space that our rendering will occupy and then align that space + /// with the given rectangle, according to the Column alignment + /// + /// + /// Pre-padded bounds of the cell + /// + protected virtual Rectangle CalculateAlignedRectangle(Graphics g, Rectangle r) { + if (this.Column == null) + return r; + + Rectangle contentRectangle = new Rectangle(Point.Empty, this.CalculateContentSize(g, r)); + return this.AlignRectangle(r, contentRectangle); + } + + /// + /// Calculate the size of the content of this cell. + /// + /// + /// Pre-padded bounds of the cell + /// The width and height of the content + protected virtual Size CalculateContentSize(Graphics g, Rectangle r) + { + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + Size imageSize = this.CalculateImageSize(g, this.GetImageSelector()); + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width - (checkBoxSize.Width + imageSize.Width)); + + // If the combined width is greater than the whole cell, we just use the cell itself + + int width = Math.Min(r.Width, checkBoxSize.Width + imageSize.Width + textSize.Width); + int componentMaxHeight = Math.Max(checkBoxSize.Height, Math.Max(imageSize.Height, textSize.Height)); + int height = Math.Min(r.Height, componentMaxHeight); + + return new Size(width, height); + } + + /// + /// Calculate the bounds of a checkbox given the (pre-padded) cell bounds + /// + /// + /// Pre-padded cell bounds + /// + protected Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + return this.AlignRectangle(cellBounds, new Rectangle(0, 0, checkBoxSize.Width, checkBoxSize.Height)); + } + + + /// + /// How much space will the check box for this cell occupy? + /// + /// Only column 0 can have check boxes. Sub item checkboxes are + /// treated as images + /// + /// + protected virtual Size CalculateCheckBoxSize(Graphics g) + { + if (UseCustomCheckboxImages && this.ListView.StateImageList != null) + return this.ListView.StateImageList.ImageSize; + + return CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); + } + + /// + /// How much space will the check box for this row occupy? + /// If the list doesn't have checkboxes, or this isn't the primary column, + /// this returns an empty size. + /// + /// + /// + protected virtual Size CalculatePrimaryCheckBoxSize(Graphics g) { + if (!this.ListView.CheckBoxes || !this.ColumnIsPrimary) + return Size.Empty; + + Size size = this.CalculateCheckBoxSize(g); + size.Width += 6; + return size; + } + + /// + /// How much horizontal space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageWidth(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Width; + } + + /// + /// How much vertical space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageHeight(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Height; + } + + /// + /// How much space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual Size CalculateImageSize(Graphics g, object imageSelector) + { + if (imageSelector == null || imageSelector == DBNull.Value) + return Size.Empty; + + // Check for the image in the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) + { + int selectorAsInt = -1; + + if (imageSelector is Int32) + selectorAsInt = (Int32)imageSelector; + else + { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + if (selectorAsInt >= 0) + return il.ImageSize; + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image != null) + return image.Size; + + return Size.Empty; + } + + /// + /// How much horizontal space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual int CalculateTextWidth(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return 0; + + return CalculateTextSize(g, txt, width).Width; + } + + /// + /// How much space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual Size CalculateTextSize(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return Size.Empty; + + if (this.UseGdiTextRendering) + { + Size proposedSize = new Size(width, Int32.MaxValue); + return TextRenderer.MeasureText(g, txt, this.Font, proposedSize, NormalTextFormatFlags); + } + + // Using GDI+ rendering + using (StringFormat fmt = new StringFormat()) { + fmt.Trimming = StringTrimming.EllipsisCharacter; + SizeF sizeF = g.MeasureString(txt, this.Font, width, fmt); + return new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + } + } + + /// + /// Return the Color that is the background color for this item's cell + /// + /// The background color of the subitem + public virtual Color GetBackgroundColor() { + if (!this.ListView.Enabled) + return SystemColors.Control; + + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection && this.ListView.FullRowSelect) + return this.GetSelectedBackgroundColor(); + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.BackColor; + + return this.SubItem.BackColor; + } + + /// + /// Return the color of the background color when the item is selected + /// + /// The background color of the subitem + public virtual Color GetSelectedBackgroundColor() { + if (this.ListView.Focused) + return this.ListItem.SelectedBackColor ?? this.ListView.SelectedBackColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedBackColorOrDefault; + + return this.ListItem.BackColor; + } + + /// + /// Return the color to be used for text in this cell + /// + /// The text color of the subitem + public virtual Color GetForegroundColor() { + if (this.IsItemSelected && + !this.ListView.UseTranslucentSelection && + (this.ColumnIsPrimary || this.ListView.FullRowSelect)) + return this.GetSelectedForegroundColor(); + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the color of the foreground color when the item is selected + /// + /// The foreground color of the subitem + public virtual Color GetSelectedForegroundColor() + { + if (this.ListView.Focused) + return this.ListItem.SelectedForeColor ?? this.ListView.SelectedForeColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedForeColorOrDefault; + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the image that should be drawn against this subitem + /// + /// An Image or null if no image should be drawn. + protected virtual Image GetImage() { + return this.GetImage(this.GetImageSelector()); + } + + /// + /// Return the actual image that should be drawn when keyed by the given image selector. + /// An image selector can be: + /// an int, giving the index into the image list + /// a string, giving the image key into the image list + /// an Image, being the image itself + /// + /// + /// The value that indicates the image to be used + /// An Image or null + protected virtual Image GetImage(Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return null; + + ImageList il = this.ImageListOrDefault; + if (il != null) { + if (imageSelector is Int32) { + Int32 index = (Int32) imageSelector; + if (index < 0 || index >= il.Images.Count) + return null; + + return il.Images[index]; + } + + String str = imageSelector as String; + if (str != null) { + if (il.Images.ContainsKey(str)) + return il.Images[str]; + + return null; + } + } + + return imageSelector as Image; + } + + /// + /// + protected virtual Object GetImageSelector() { + return this.ColumnIsPrimary ? this.ListItem.ImageSelector : this.OLVSubItem.ImageSelector; + } + + /// + /// Return the string that should be drawn within this + /// + /// + protected virtual string GetText() { + return this.SubItem == null ? this.ListItem.Text : this.SubItem.Text; + } + + /// + /// Return the Color that is the background color for this item's text + /// + /// The background color of the subitem's text + [Obsolete("Use GetBackgroundColor() instead")] + protected virtual Color GetTextBackgroundColor() { + return Color.Red; // just so it shows up if it is used + } + + #endregion + + #region IRenderer members + + /// + /// Render the whole item in a non-details view. + /// + /// + /// + /// + /// + /// + public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object model) { + this.ConfigureItem(e, itemBounds, model); + return this.OptionalRender(g, itemBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureItem(DrawListViewItemEventArgs e, Rectangle itemBounds, object model) + { + this.ClearState(); + + this.DrawItemEvent = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = null; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = this.ListView.GetColumn(0); + this.RowObject = model; + this.Bounds = itemBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Render one cell + /// + /// + /// + /// + /// + /// + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object model) { + this.ConfigureSubItem(e, cellBounds, model); + return this.OptionalRender(g, cellBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + this.ClearState(); + + this.Event = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = (OLVListSubItem)e.SubItem; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = (OLVColumn)e.Header; + this.RowObject = model; + this.Bounds = cellBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Calculate which part of this cell was hit + /// + /// + /// + /// + public override void HitTest(OlvListViewHitTestInfo hti, int x, int y) { + this.ClearState(); + + this.ListView = hti.ListView; + this.ListItem = hti.Item; + this.SubItem = hti.SubItem; + this.Column = hti.Column; + this.RowObject = hti.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + if (this.SubItem == null) + this.Bounds = this.ListItem.Bounds; + else + this.Bounds = this.ListItem.GetSubItemBounds(this.Column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) { + this.HandleHitTest(g, hti, x, y); + } + } + + /// + /// Calculate the edit rectangle + /// + /// + /// + /// + /// + /// + /// + public override Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + this.ClearState(); + + this.ListView = (ObjectListView) item.ListView; + this.ListItem = item; + this.SubItem = item.GetSubItem(subItemIndex); + this.Column = this.ListView.GetColumn(subItemIndex); + this.RowObject = item.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + this.Bounds = cellBounds; + + return this.HandleGetEditRectangle(g, cellBounds, item, subItemIndex, preferredSize); + } + + #endregion + + #region IRenderer implementation + + // Subclasses will probably want to override these methods rather than the IRenderer + // interface methods. + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method. + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + /// Returns whether the rendering has already taken place. + /// If this returns false, the default processing will take over. + /// + public virtual bool OptionalRender(Graphics g, Rectangle r) { + if (this.ListView.View != View.Details) + return false; + + this.Render(g, r); + return true; + } + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method if they never want + /// to fall back on the default processing + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + public virtual void Render(Graphics g, Rectangle r) { + this.StandardRender(g, r); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected virtual void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateAlignedRectangle(g, ApplyCellPadding(this.Bounds)); + this.StandardHitTest(g, hti, r, x, y); + } + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected virtual Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + // MAINTAINER NOTE: This type testing is wrong (design-wise). The base class should return cell bounds, + // and a more specialized class should return StandardGetEditRectangle(). But BaseRenderer is used directly + // to draw most normal cells, as well as being directly subclassed for user implemented renderers. And this + // method needs to return different bounds in each of those cases. We should have a StandardRenderer and make + // BaseRenderer into an ABC -- but that would break too much existing code. And so we have this hack :( + + // If we are a standard renderer, return the position of the text, otherwise, use the whole cell. + if (this.GetType() == typeof (BaseRenderer)) + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + return cellBounds; + } + + #endregion + + #region Standard IRenderer implementations + + /// + /// Draw the standard "[checkbox] [image] [text]" cell after the state properties have been initialized. + /// + /// + /// + protected void StandardRender(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + // Adjust the first columns rectangle to match the padding used by the native mode of the ListView + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left ) { + r.X += 3; + r.Width -= 1; + } + r = this.ApplyCellPadding(r); + this.DrawAlignedImageAndText(g, r); + + // Show where the bounds of the cell padding are (debugging) + if (ObjectListView.ShowCellPaddingBounds) + g.DrawRectangle(Pens.Purple, r); + } + + /// + /// Change the bounds of the given rectangle to take any cell padding into account + /// + /// + /// + public virtual Rectangle ApplyCellPadding(Rectangle r) { + Rectangle? padding = this.EffectiveCellPadding; + if (!padding.HasValue) + return r; + // The two subtractions below look wrong, but are correct! + Rectangle paddingRectangle = padding.Value; + r.Width -= paddingRectangle.Right; + r.Height -= paddingRectangle.Bottom; + r.Offset(paddingRectangle.Location); + return r; + } + + /// + /// Perform normal hit testing relative to the given aligned content bounds + /// + /// + /// + /// + /// + /// + protected virtual void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle alignedContentRectangle, int x, int y) { + Rectangle r = alignedContentRectangle; + + // Match tweaking from renderer + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left && !(this is TreeListView.TreeRenderer)) { + r.X += 3; + r.Width -= 1; + } + int width = 0; + + // Did they hit a check box on the primary column? + if (this.ColumnIsPrimary && this.ListView.CheckBoxes) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + int checkBoxTop = this.AlignVertically(r, checkBoxSize.Height); + Rectangle r3 = new Rectangle(r.X, checkBoxTop, checkBoxSize.Width, checkBoxSize.Height); + width = r3.Width + 6; + // g.DrawRectangle(Pens.DarkGreen, r3); + if (r3.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + } + + // Did they hit the image? If they hit the image of a + // non-primary column that has a checkbox, it counts as a + // checkbox hit + r.X += width; + r.Width -= width; + width = this.CalculateImageWidth(g, this.GetImageSelector()); + Rectangle rTwo = r; + rTwo.Width = width; + //g.DrawRectangle(Pens.Red, rTwo); + if (rTwo.Contains(x, y)) { + if (this.Column != null && (this.Column.Index > 0 && this.Column.CheckBoxes)) + hti.HitTestLocation = HitTestLocation.CheckBox; + else + hti.HitTestLocation = HitTestLocation.Image; + return; + } + + // Did they hit the text? + r.X += width; + r.Width -= width; + width = this.CalculateTextWidth(g, this.GetText(), r.Width); + rTwo = r; + rTwo.Width = width; + // g.DrawRectangle(Pens.Blue, rTwo); + if (rTwo.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + return; + } + + hti.HitTestLocation = HitTestLocation.InCell; + } + + /// + /// This method calculates the bounds of the text within a standard layout + /// (i.e. optional checkbox, optional image, text) + /// + /// This method only works correctly if the state of the renderer + /// has been fully initialized (see BaseRenderer.GetEditRectangle) + /// + /// + /// + /// + protected virtual Rectangle StandardGetEditRectangle(Graphics g, Rectangle cellBounds, Size preferredSize) { + + Size contentSize = this.CalculateContentSize(g, cellBounds); + int contentWidth = this.Column.CellEditUseWholeCellEffective ? cellBounds.Width : contentSize.Width; + Rectangle editControlBounds = this.CalculatePaddedAlignedBounds(g, cellBounds, new Size(contentWidth, preferredSize.Height)); + + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + int imageWidth = this.CalculateImageWidth(g, this.GetImageSelector()); + + int width = checkBoxSize.Width + imageWidth + 2; + + // Indent the primary column by the required amount + if (this.ColumnIsPrimary && this.ListItem.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * this.ListItem.IndentCount; + editControlBounds.X += indentWidth; + } + + editControlBounds.X += width; + editControlBounds.Width -= width; + + if (editControlBounds.Width < 50) + editControlBounds.Width = 50; + if (editControlBounds.Right > cellBounds.Right) + editControlBounds.Width = cellBounds.Right - editControlBounds.Left; + + return editControlBounds; + } + + /// + /// Apply any padding to the given bounds, and then align a rectangle of the given + /// size within that padded area. + /// + /// + /// + /// + /// + protected Rectangle CalculatePaddedAlignedBounds(Graphics g, Rectangle cellBounds, Size preferredSize) { + Rectangle r = ApplyCellPadding(cellBounds); + r = this.AlignRectangle(r, new Rectangle(Point.Empty, preferredSize)); + return r; + } + + #endregion + + #region Drawing routines + + /// + /// Draw the given image aligned horizontally within the column. + /// + /// + /// Over tall images are scaled to fit. Over-wide images are + /// truncated. This is by design! + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The image to be drawn + protected virtual void DrawAlignedImage(Graphics g, Rectangle r, Image image) { + if (image == null) + return; + + // By default, the image goes in the top left of the rectangle + Rectangle imageBounds = new Rectangle(r.Location, image.Size); + + // If the image is too tall to be drawn in the space provided, proportionally scale it down. + // Too wide images are not scaled. + if (image.Height > r.Height) { + float scaleRatio = (float) r.Height / (float) image.Height; + imageBounds.Width = (int) ((float) image.Width * scaleRatio); + imageBounds.Height = r.Height - 1; + } + + // Align and draw our (possibly scaled) image + Rectangle alignRectangle = this.AlignRectangle(r, imageBounds); + if (this.ListItem.Enabled) + g.DrawImage(image, alignRectangle); + else + ControlPaint.DrawImageDisabled(g, image, alignRectangle.X, alignRectangle.Y, GetBackgroundColor()); + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Pre-padded bounds of the cell + protected virtual void DrawAlignedImageAndText(Graphics g, Rectangle r) { + this.DrawImageAndText(g, this.CalculateAlignedRectangle(g, r)); + } + + /// + /// Fill in the background of this cell + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawBackground(Graphics g, Rectangle r) { + if (!this.IsDrawBackground) + return; + + Color backgroundColor = this.GetBackgroundColor(); + + using (Brush brush = new SolidBrush(backgroundColor)) { + g.FillRectangle(brush, r.X - 1, r.Y - 1, r.Width + 2, r.Height + 2); + } + } + + /// + /// Draw the primary check box of this row (checkboxes in other sub items use a different method) + /// + /// Graphics context to use for drawing + /// The pre-aligned and padded target rectangle + protected virtual int DrawCheckBox(Graphics g, Rectangle r) { + // The odd constants are to match checkbox placement in native mode (on XP at least) + // TODO: Unify this with CheckStateRenderer + + // The rectangle r is already horizontally aligned. We still need to align it vertically. + Size checkBoxSize = this.CalculateCheckBoxSize(g); + Point checkBoxLocation = new Point(r.X, this.AlignVertically(r, checkBoxSize.Height)); + + if (this.IsPrinting || this.UseCustomCheckboxImages) { + int imageIndex = this.ListItem.StateImageIndex; + if (this.ListView.StateImageList == null || imageIndex < 0 || imageIndex >= this.ListView.StateImageList.Images.Count) + return 0; + + return this.DrawImage(g, new Rectangle(checkBoxLocation, checkBoxSize), this.ListView.StateImageList.Images[imageIndex]) + 4; + } + + CheckBoxState boxState = this.GetCheckBoxState(this.ListItem.CheckState); + CheckBoxRenderer.DrawCheckBox(g, checkBoxLocation, boxState); + return checkBoxSize.Width; + } + + /// + /// Calculate the CheckBoxState we need to correctly draw the given state + /// + /// + /// + protected virtual CheckBoxState GetCheckBoxState(CheckState checkState) { + + // Should the checkbox be drawn as disabled? + if (this.IsCheckBoxDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the cursor currently over this checkbox? + if (this.IsCheckboxHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + + } + + /// + /// Should this checkbox be drawn as disabled? + /// + protected virtual bool IsCheckBoxDisabled { + get { + if (this.ListItem != null && !this.ListItem.Enabled) + return true; + + if (!this.ListView.RenderNonEditableCheckboxesAsDisabled) + return false; + + return (this.ListView.CellEditActivation == ObjectListView.CellEditActivateMode.None || + (this.Column != null && !this.Column.IsEditable)); + } + } + + /// + /// Is the current item hot (i.e. under the mouse)? + /// + protected bool IsCellHot { + get { + return this.ListView != null && + this.ListView.HotRowIndex == this.ListItem.Index && + this.ListView.HotColumnIndex == (this.Column == null ? 0 : this.Column.Index); + } + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsCheckboxHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.CheckBox; + } + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The optional image to be drawn + protected virtual int DrawImage(Graphics g, Rectangle r, Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return 0; + + // Draw from the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) { + + // Try to translate our imageSelector into a valid ImageList index + int selectorAsInt = -1; + if (imageSelector is Int32) { + selectorAsInt = (Int32) imageSelector; + if (selectorAsInt >= il.Images.Count) + selectorAsInt = -1; + } else { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + + // If we found a valid index into the ImageList, draw it. + // We want to draw using the native DrawImageList calls, since that let's us do some nice effects + // But the native call does not work on PrinterDCs, so if we're printing we have to skip this bit. + if (selectorAsInt >= 0) { + if (!this.IsPrinting) { + if (il.ImageSize.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, il.ImageSize)); + + // If we are not printing, it's probable that the given Graphics object is double buffered using a BufferedGraphics object. + // But the ImageList.Draw method doesn't honor the Translation matrix that's probably in effect on the buffered + // graphics. So we have to calculate our drawing rectangle, relative to the cells natural boundaries. + // This effectively simulates the Translation matrix. + + Rectangle r2 = new Rectangle(r.X - this.Bounds.X, r.Y - this.Bounds.Y, r.Width, r.Height); + NativeMethods.DrawImageList(g, il, selectorAsInt, r2.X, r2.Y, this.IsItemSelected, !this.ListItem.Enabled); + return il.ImageSize.Width; + } + + // For some reason, printing from an image list doesn't work onto a printer context + // So get the image from the list and FALL THROUGH to the "print an image" case + imageSelector = il.Images[selectorAsInt]; + } + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image == null) + return 0; // no, give up + + if (image.Size.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, image.Size)); + + if (this.ListItem.Enabled) + g.DrawImageUnscaled(image, r.X, r.Y); + else + ControlPaint.DrawImageDisabled(g, image, r.X, r.Y, GetBackgroundColor()); + + return image.Width; + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawImageAndText(Graphics g, Rectangle r) { + int offset = 0; + if (this.ListView.CheckBoxes && this.ColumnIsPrimary) { + offset = this.DrawCheckBox(g, r) + 6; + r.X += offset; + r.Width -= offset; + } + + offset = this.DrawImage(g, r, this.GetImageSelector()); + r.X += offset; + r.Width -= offset; + + this.DrawText(g, r, this.GetText()); + } + + /// + /// Draw the given collection of image selectors + /// + /// + /// + /// + protected virtual int DrawImages(Graphics g, Rectangle r, ICollection imageSelectors) { + // Collect the non-null images + List images = new List(); + foreach (Object selector in imageSelectors) { + Image image = this.GetImage(selector); + if (image != null) + images.Add(image); + } + + // Figure out how much space they will occupy + int width = 0; + int height = 0; + foreach (Image image in images) { + width += (image.Width + this.Spacing); + height = Math.Max(height, image.Height); + } + + // Align the collection of images within the cell + Rectangle r2 = this.AlignRectangle(r, new Rectangle(0, 0, width, height)); + + // Finally, draw all the images in their correct location + Color backgroundColor = GetBackgroundColor(); + Point pt = r2.Location; + foreach (Image image in images) { + if (this.ListItem.Enabled) + g.DrawImage(image, pt); + else + ControlPaint.DrawImageDisabled(g, image, pt.X, pt.Y, backgroundColor); + pt.X += (image.Width + this.Spacing); + } + + // Return the width that the images occupy + return width; + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The string to be drawn + public virtual void DrawText(Graphics g, Rectangle r, String txt) { + if (String.IsNullOrEmpty(txt)) + return; + + if (this.UseGdiTextRendering) + this.DrawTextGdi(g, r, txt); + else + this.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Print the given text in the given rectangle using only GDI routines + /// + /// + /// + /// + /// + /// The native list control uses GDI routines to do its drawing, so using them + /// here makes the owner drawn mode looks more natural. + /// This method doesn't honour the CanWrap setting on the renderer. All + /// text is single line + /// + protected virtual void DrawTextGdi(Graphics g, Rectangle r, String txt) { + Color backColor = Color.Transparent; + if (this.IsDrawBackground && this.IsItemSelected && ColumnIsPrimary && !this.ListView.FullRowSelect) + backColor = this.GetSelectedBackgroundColor(); + + TextFormatFlags flags = NormalTextFormatFlags | this.CellVerticalAlignmentAsTextFormatFlag; + + // I think there is a bug in the TextRenderer. Setting or not setting SingleLine doesn't make + // any difference -- it is always single line. + if (!this.CanWrapOrDefault) + flags |= TextFormatFlags.SingleLine; + TextRenderer.DrawText(g, txt, this.Font, r, this.GetForegroundColor(), backColor, flags); + } + + private bool ColumnIsPrimary { + get { return this.Column != null && this.Column.Index == 0; } + } + + /// + /// Gets the cell's vertical alignment as a TextFormatFlag + /// + /// + protected TextFormatFlags CellVerticalAlignmentAsTextFormatFlag { + get { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return TextFormatFlags.Top; + case StringAlignment.Center: + return TextFormatFlags.VerticalCenter; + case StringAlignment.Far: + return TextFormatFlags.Bottom; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + /// + /// Gets the StringFormat needed when drawing text using GDI+ + /// + protected virtual StringFormat StringFormatForGdiPlus { + get { + StringFormat fmt = new StringFormat(); + fmt.LineAlignment = this.EffectiveCellVerticalAlignment; + fmt.Trimming = StringTrimming.EllipsisCharacter; + fmt.Alignment = this.Column == null ? StringAlignment.Near : this.Column.TextStringAlign; + if (!this.CanWrapOrDefault) + fmt.FormatFlags = StringFormatFlags.NoWrap; + return fmt; + } + } + + /// + /// Print the given text in the given rectangle using normal GDI+ .NET methods + /// + /// Printing to a printer dc has to be done using this method. + protected virtual void DrawTextGdiPlus(Graphics g, Rectangle r, String txt) { + using (StringFormat fmt = this.StringFormatForGdiPlus) { + // Draw the background of the text as selected, if it's the primary column + // and it's selected and it's not in FullRowSelect mode. + Font f = this.Font; + if (this.IsDrawBackground && this.IsItemSelected && this.ColumnIsPrimary && !this.ListView.FullRowSelect) { + SizeF size = g.MeasureString(txt, f, r.Width, fmt); + Rectangle r2 = r; + r2.Width = (int) size.Width + 1; + using (Brush brush = new SolidBrush(this.GetSelectedBackgroundColor())) { + g.FillRectangle(brush, r2); + } + } + RectangleF rf = r; + g.DrawString(txt, f, this.TextBrush, rf, fmt); + } + + // We should put a focus rectangle around the column 0 text if it's selected -- + // but we don't because: + // - I really dislike this UI convention + // - we are using buffered graphics, so the DrawFocusRecatangle method of the event doesn't work + + //if (this.ColumnIsPrimary) { + // Size size = TextRenderer.MeasureText(this.SubItem.Text, this.ListView.ListFont); + // if (r.Width > size.Width) + // r.Width = size.Width; + // this.Event.DrawFocusRectangle(r); + //} + } + + #endregion + } + + /// + /// This renderer highlights substrings that match a given text filter. + /// + /// + /// Implementation note: + /// This renderer uses the functionality of BaseRenderer to draw the text, and + /// then draws a translucent frame over the top of the already rendered text glyphs. + /// There's no way to draw the matching text in a different font or color in this + /// implementation. + /// + public class HighlightTextRenderer : BaseRenderer, IFilterAwareRenderer { + #region Life and death + + /// + /// Create a HighlightTextRenderer + /// + public HighlightTextRenderer() { + this.FramePen = Pens.DarkGreen; + this.FillBrush = Brushes.Yellow; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + public HighlightTextRenderer(ITextMatchFilter filter) + : this() { + this.Filter = filter; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + [Obsolete("Use HighlightTextRenderer(TextMatchFilter) instead", true)] + public HighlightTextRenderer(string text) {} + + #endregion + + #region Configuration properties + + /// + /// Gets or set how rounded will be the corners of the text match frame + /// + [Category("Appearance"), + DefaultValue(3.0f), + Description("How rounded will be the corners of the text match frame?")] + public float CornerRoundness { + get { return cornerRoundness; } + set { cornerRoundness = value; } + } + + private float cornerRoundness = 3.0f; + + /// + /// Gets or set the brush will be used to paint behind the matched substrings. + /// Set this to null to not fill the frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush FillBrush { + get { return fillBrush; } + set { fillBrush = value; } + } + + private Brush fillBrush; + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter { + get { return filter; } + set { filter = value; } + } + private ITextMatchFilter filter; + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter + { + get { return filter; } + set { RegisterNewFilter(value); } + } + + internal void RegisterNewFilter(IModelFilter newFilter) { + TextMatchFilter textFilter = newFilter as TextMatchFilter; + if (textFilter != null) + { + Filter = textFilter; + return; + } + CompositeFilter composite = newFilter as CompositeFilter; + if (composite != null) + { + foreach (TextMatchFilter textSubFilter in composite.TextFilters) + { + Filter = textSubFilter; + return; + } + } + Filter = null; + } + + /// + /// Gets or set the pen will be used to frame the matched substrings. + /// Set this to null to not draw a frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen FramePen { + get { return framePen; } + set { framePen = value; } + } + + private Pen framePen; + + /// + /// Gets or sets whether the frame around a text match will have rounded corners + /// + [Category("Appearance"), + DefaultValue(true), + Description("Will the frame around a text match will have rounded corners?")] + public bool UseRoundedRectangle { + get { return useRoundedRectangle; } + set { useRoundedRectangle = value; } + } + + private bool useRoundedRectangle = true; + + #endregion + + #region Compatibility properties + + /// + /// Gets or set the text that will be highlighted + /// + [Obsolete("Set the Filter directly rather than just the text", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string TextToHighlight { + get { return String.Empty; } + set { } + } + + /// + /// Gets or sets the manner in which substring will be compared. + /// + /// + /// Use this to control if substring matches are case sensitive or insensitive. + [Obsolete("Set the Filter directly rather than just this setting", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public StringComparison StringComparison { + get { return StringComparison.CurrentCultureIgnoreCase; } + set { } + } + + #endregion + + #region IRenderer interface overrides + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + + #endregion + + #region Rendering + + // This class has two implement two highlighting schemes: one for GDI, another for GDI+. + // Naturally, GDI+ makes the task easier, but we have to provide something for GDI + // since that it is what is normally used. + + /// + /// Draw text using GDI + /// + /// + /// + /// + protected override void DrawTextGdi(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiTextHighlighting(g, r, txt); + + base.DrawTextGdi(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI + /// + /// + /// + /// + protected virtual void DrawGdiTextHighlighting(Graphics g, Rectangle r, string txt) { + + // TextRenderer puts horizontal padding around the strings, so we need to take + // that into account when measuring strings + const int paddingAdjustment = 6; + + // Cache the font + Font f = this.Font; + + foreach (CharacterRange range in this.Filter.FindAllMatchedRanges(txt)) { + // Measure the text that comes before our substring + Size precedingTextSize = Size.Empty; + if (range.First > 0) { + string precedingText = txt.Substring(0, range.First); + precedingTextSize = TextRenderer.MeasureText(g, precedingText, f, r.Size, NormalTextFormatFlags); + precedingTextSize.Width -= paddingAdjustment; + } + + // Measure the length of our substring (may be different each time due to case differences) + string highlightText = txt.Substring(range.First, range.Length); + Size textToHighlightSize = TextRenderer.MeasureText(g, highlightText, f, r.Size, NormalTextFormatFlags); + textToHighlightSize.Width -= paddingAdjustment; + + float textToHighlightLeft = r.X + precedingTextSize.Width + 1; + float textToHighlightTop = this.AlignVertically(r, textToHighlightSize.Height); + + // Draw a filled frame around our substring + this.DrawSubstringFrame(g, textToHighlightLeft, textToHighlightTop, textToHighlightSize.Width, textToHighlightSize.Height); + } + } + + /// + /// Draw an indication around the given frame that shows a text match + /// + /// + /// + /// + /// + /// + protected virtual void DrawSubstringFrame(Graphics g, float x, float y, float width, float height) { + if (this.UseRoundedRectangle) { + using (GraphicsPath path = this.GetRoundedRect(x, y, width, height, 3.0f)) { + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.FramePen != null) + g.DrawPath(this.FramePen, path); + } + } else { + if (this.FillBrush != null) + g.FillRectangle(this.FillBrush, x, y, width, height); + if (this.FramePen != null) + g.DrawRectangle(this.FramePen, x, y, width, height); + } + } + + /// + /// Draw the text using GDI+ + /// + /// + /// + /// + protected override void DrawTextGdiPlus(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiPlusTextHighlighting(g, r, txt); + + base.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI+ + /// + /// + /// + /// + protected virtual void DrawGdiPlusTextHighlighting(Graphics g, Rectangle r, string txt) { + // Find the substrings we want to highlight + List ranges = new List(this.Filter.FindAllMatchedRanges(txt)); + + if (ranges.Count == 0) + return; + + using (StringFormat fmt = this.StringFormatForGdiPlus) { + RectangleF rf = r; + fmt.SetMeasurableCharacterRanges(ranges.ToArray()); + Region[] stringRegions = g.MeasureCharacterRanges(txt, this.Font, rf, fmt); + + foreach (Region region in stringRegions) { + RectangleF bounds = region.GetBounds(g); + this.DrawSubstringFrame(g, bounds.X - 1, bounds.Y - 1, bounds.Width + 2, bounds.Height); + } + } + } + + #endregion + + #region Utilities + + /// + /// Gets whether the renderer should actually draw highlighting + /// + protected bool ShouldDrawHighlighting { + get { return this.Column == null || (this.Column.Searchable && this.Filter != null); } + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + /// + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(float x, float y, float width, float height, float diameter) { + return GetRoundedRect(new RectangleF(x, y, width, height), diameter); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + } + + /// + /// This class maps a data value to an image that should be drawn for that value. + /// + /// It is useful for drawing data that is represented as an enum or boolean. + public class MappedImageRenderer : BaseRenderer { + /// + /// Return a renderer that draw boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// A Renderer + public static MappedImageRenderer Boolean(Object trueImage, Object falseImage) { + return new MappedImageRenderer(true, trueImage, false, falseImage); + } + + /// + /// Return a renderer that draw tristate boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// Draw this when our data value is null + /// A Renderer + public static MappedImageRenderer TriState(Object trueImage, Object falseImage, Object nullImage) { + return new MappedImageRenderer(new Object[] {true, trueImage, false, falseImage, null, nullImage}); + } + + /// + /// Make a new empty renderer + /// + public MappedImageRenderer() { + map = new System.Collections.Hashtable(); + } + + /// + /// Make a new renderer that will show the given image when the given key is the aspect value + /// + /// The data value to be matched + /// The image to be shown when the key is matched + public MappedImageRenderer(Object key, Object image) + : this() { + this.Add(key, image); + } + + /// + /// Make a new renderer that will show the given images when it receives the given keys + /// + /// + /// + /// + /// + public MappedImageRenderer(Object key1, Object image1, Object key2, Object image2) + : this() { + this.Add(key1, image1); + this.Add(key2, image2); + } + + /// + /// Build a renderer from the given array of keys and their matching images + /// + /// An array of key/image pairs + public MappedImageRenderer(Object[] keysAndImages) + : this() { + if ((keysAndImages.GetLength(0) % 2) != 0) + throw new ArgumentException("Array must have key/image pairs"); + + for (int i = 0; i < keysAndImages.GetLength(0); i += 2) + this.Add(keysAndImages[i], keysAndImages[i + 1]); + } + + /// + /// Register the image that should be drawn when our Aspect has the data value. + /// + /// Value that the Aspect must match + /// An ImageSelector -- an int, string or image + public void Add(Object value, Object image) { + if (value == null) + this.nullImage = image; + else + map[value] = image; + } + + /// + /// Render our value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + ICollection aspectAsCollection = this.Aspect as ICollection; + if (aspectAsCollection == null) + this.RenderOne(g, r, this.Aspect); + else + this.RenderCollection(g, r, aspectAsCollection); + } + + /// + /// Draw a collection of images + /// + /// + /// + /// + protected void RenderCollection(Graphics g, Rectangle r, ICollection imageSelectors) { + ArrayList images = new ArrayList(); + Image image = null; + foreach (Object selector in imageSelectors) { + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + else + image = null; + + if (image != null) + images.Add(image); + } + + this.DrawImages(g, r, images); + } + + /// + /// Draw one image + /// + /// + /// + /// + protected void RenderOne(Graphics g, Rectangle r, Object selector) { + Image image = null; + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + + if (image != null) + this.DrawAlignedImage(g, r, image); + } + + #region Private variables + + private Hashtable map; // Track the association between values and images + private Object nullImage; // image to be drawn for null values (since null can't be a key) + + #endregion + } + + /// + /// This renderer draws just a checkbox to match the check state of our model object. + /// + public class CheckStateRenderer : BaseRenderer { + /// + /// Draw our cell + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + if (this.Column == null) + return; + r = this.ApplyCellPadding(r); + CheckState state = this.Column.GetCheckState(this.RowObject); + if (this.IsPrinting) { + // Renderers don't work onto printer DCs, so we have to draw the image ourselves + string key = ObjectListView.CHECKED_KEY; + if (state == CheckState.Unchecked) + key = ObjectListView.UNCHECKED_KEY; + if (state == CheckState.Indeterminate) + key = ObjectListView.INDETERMINATE_KEY; + this.DrawAlignedImage(g, r, this.ImageListOrDefault.Images[key]); + } else { + r = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, r.Location, this.GetCheckBoxState(state)); + } + } + + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateCheckBoxBounds(g, this.Bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.CheckBox; + } + } + + /// + /// Render an image that comes from our data source. + /// + /// The image can be sourced from: + /// + /// a byte-array (normally when the image to be shown is + /// stored as a value in a database) + /// an int, which is treated as an index into the image list + /// a string, which is treated first as a file name, and failing that as an index into the image list + /// an ICollection of ints or strings, which will be drawn as consecutive images + /// + /// If an image is an animated GIF, it's state is stored in the SubItem object. + /// By default, the image renderer does not render animations (it begins life with animations paused). + /// To enable animations, you must call Unpause(). + /// In the current implementation (2009-09), each column showing animated gifs must have a + /// different instance of ImageRenderer assigned to it. You cannot share the same instance of + /// an image renderer between two animated gif columns. If you do, only the last column will be + /// animated. + /// + public class ImageRenderer : BaseRenderer { + /// + /// Make an empty image renderer + /// + public ImageRenderer() { + this.stopwatch = new Stopwatch(); + } + + /// + /// Make an empty image renderer that begins life ready for animations + /// + public ImageRenderer(bool startAnimations) + : this() { + this.Paused = !startAnimations; + } + + /// + /// Finalizer + /// + protected override void Dispose(bool disposing) { + Paused = true; + base.Dispose(disposing); + } + + #region Properties + + /// + /// Should the animations in this renderer be paused? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool Paused { + get { return isPaused; } + set { + if (this.isPaused == value) + return; + + this.isPaused = value; + if (this.isPaused) { + this.StopTickler(); + this.stopwatch.Stop(); + } else { + this.Tickler.Change(1, Timeout.Infinite); + this.stopwatch.Start(); + } + } + } + + private bool isPaused = true; + + private void StopTickler() { + if (this.tickler == null) + return; + + this.tickler.Dispose(); + this.tickler = null; + } + + /// + /// Gets a timer that can be used to trigger redraws on animations + /// + protected Timer Tickler { + get { + if (this.tickler == null) + this.tickler = new System.Threading.Timer(new TimerCallback(this.OnTimer), null, Timeout.Infinite, Timeout.Infinite); + return this.tickler; + } + } + + #endregion + + #region Commands + + /// + /// Pause any animations + /// + public void Pause() { + this.Paused = true; + } + + /// + /// Unpause any animations + /// + public void Unpause() { + this.Paused = false; + } + + #endregion + + #region Drawing + + /// + /// Draw our image + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + if (this.Aspect == null || this.Aspect == System.DBNull.Value) + return; + r = this.ApplyCellPadding(r); + + if (this.Aspect is System.Byte[]) { + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + } else { + ICollection imageSelectors = this.Aspect as ICollection; + if (imageSelectors == null) + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + else + this.DrawImages(g, r, imageSelectors); + } + } + + /// + /// Translate our Aspect into an image. + /// + /// The strategy is: + /// If its a byte array, we treat it as an in-memory image + /// If it's an int, we use that as an index into our image list + /// If it's a string, we try to load a file by that name. If we can't, + /// we use the string as an index into our image list. + /// + /// An image + protected Image GetImageFromAspect() { + // If we've already figured out the image, don't do it again + if (this.OLVSubItem != null && this.OLVSubItem.ImageSelector is Image) { + if (this.OLVSubItem.AnimationState == null) + return (Image) this.OLVSubItem.ImageSelector; + else + return this.OLVSubItem.AnimationState.image; + } + + // Try to convert our Aspect into an Image + // If its a byte array, we treat it as an in-memory image + // If it's an int, we use that as an index into our image list + // If it's a string, we try to find a file by that name. + // If we can't, we use the string as an index into our image list. + Image image = this.Aspect as Image; + if (image != null) { + // Don't do anything else + } else if (this.Aspect is System.Byte[]) { + using (MemoryStream stream = new MemoryStream((System.Byte[]) this.Aspect)) { + try { + image = Image.FromStream(stream); + } + catch (ArgumentException) { + // ignore + } + } + } else if (this.Aspect is Int32) { + image = this.GetImage(this.Aspect); + } else { + String str = this.Aspect as String; + if (!String.IsNullOrEmpty(str)) { + try { + image = Image.FromFile(str); + } + catch (FileNotFoundException) { + image = this.GetImage(this.Aspect); + } + catch (OutOfMemoryException) { + image = this.GetImage(this.Aspect); + } + } + } + + // If this image is an animation, initialize the animation process + if (this.OLVSubItem != null && AnimationState.IsAnimation(image)) { + this.OLVSubItem.AnimationState = new AnimationState(image); + } + + // Cache the image so we don't repeat this dreary process + if (this.OLVSubItem != null) + this.OLVSubItem.ImageSelector = image; + + return image; + } + + #endregion + + #region Events + + /// + /// This is the method that is invoked by the timer. It basically switches control to the listview thread. + /// + /// not used + public void OnTimer(Object state) { + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + if (this.ListView.InvokeRequired) + this.ListView.Invoke((MethodInvoker) delegate { this.OnTimer(state); }); + else + this.OnTimerInThread(); + } + + private bool IsListViewDead { + get { + // Apply a whole heap of sanity checks, which basically ensure that the ListView is still alive + return this.ListView == null || + this.ListView.Disposing || + this.ListView.IsDisposed || + !this.ListView.IsHandleCreated; + } + } + + /// + /// This is the OnTimer callback, but invoked in the same thread as the creator of the ListView. + /// This method can use all of ListViews methods without creating a CrossThread exception. + /// + protected void OnTimerInThread() { + // MAINTAINER NOTE: This method must renew the tickler. If it doesn't the animations will stop. + + // If this listview has been destroyed, we can't do anything, so we return without + // renewing the tickler, effectively killing all animations on this renderer + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + // If we're not in Detail view or our column has been removed from the list, + // we can't do anything at the moment, but we still renew the tickler because the view may change later. + if (this.ListView.View != System.Windows.Forms.View.Details || this.Column == null || this.Column.Index < 0) { + this.Tickler.Change(1000, Timeout.Infinite); + return; + } + + long elapsedMilliseconds = this.stopwatch.ElapsedMilliseconds; + int subItemIndex = this.Column.Index; + long nextCheckAt = elapsedMilliseconds + 1000; // wait at most one second before checking again + Rectangle updateRect = new Rectangle(); // what part of the view must be updated to draw the changed gifs? + + // Run through all the subitems in the view for our column, and for each one that + // has an animation attached to it, see if the frame needs updating. + + for (int i = 0; i < this.ListView.GetItemCount(); i++) { + OLVListItem lvi = this.ListView.GetItem(i); + + // Get the animation state from the subitem. If there isn't an animation state, skip this row. + OLVListSubItem lvsi = lvi.GetSubItem(subItemIndex); + AnimationState state = lvsi.AnimationState; + if (state == null || !state.IsValid) + continue; + + // Has this frame of the animation expired? + if (elapsedMilliseconds >= state.currentFrameExpiresAt) { + state.AdvanceFrame(elapsedMilliseconds); + + // Track the area of the view that needs to be redrawn to show the changed images + if (updateRect.IsEmpty) + updateRect = lvsi.Bounds; + else + updateRect = Rectangle.Union(updateRect, lvsi.Bounds); + } + + // Remember the minimum time at which a frame is next due to change + nextCheckAt = Math.Min(nextCheckAt, state.currentFrameExpiresAt); + } + + // Update the part of the listview where frames have changed + if (!updateRect.IsEmpty) + this.ListView.Invalidate(updateRect); + + // Renew the tickler in time for the next frame change + this.Tickler.Change(nextCheckAt - elapsedMilliseconds, Timeout.Infinite); + } + + #endregion + + /// + /// Instances of this class kept track of the animation state of a single image. + /// + internal class AnimationState { + private const int PropertyTagTypeShort = 3; + private const int PropertyTagTypeLong = 4; + private const int PropertyTagFrameDelay = 0x5100; + private const int PropertyTagLoopCount = 0x5101; + + /// + /// Is the given image an animation + /// + /// The image to be tested + /// Is the image an animation? + public static bool IsAnimation(Image image) { + if (image == null) + return false; + else + return (new List(image.FrameDimensionsList)).Contains(FrameDimension.Time.Guid); + } + + /// + /// Create an AnimationState in a quiet state + /// + public AnimationState() { + this.imageDuration = new List(); + } + + /// + /// Create an animation state for the given image, which may or may not + /// be an animation + /// + /// The image to be rendered + public AnimationState(Image image) + : this() { + if (!AnimationState.IsAnimation(image)) + return; + + // How many frames in the animation? + this.image = image; + this.frameCount = this.image.GetFrameCount(FrameDimension.Time); + + // Find the delay between each frame. + // The delays are stored an array of 4-byte ints. Each int is the + // number of 1/100th of a second that should elapsed before the frame expires + foreach (PropertyItem pi in this.image.PropertyItems) { + if (pi.Id == PropertyTagFrameDelay) { + for (int i = 0; i < pi.Len; i += 4) { + //TODO: There must be a better way to convert 4-bytes to an int + int delay = (pi.Value[i + 3] << 24) + (pi.Value[i + 2] << 16) + (pi.Value[i + 1] << 8) + pi.Value[i]; + this.imageDuration.Add(delay * 10); // store delays as milliseconds + } + break; + } + } + + // There should be as many frame durations as frames + Debug.Assert(this.imageDuration.Count == this.frameCount, "There should be as many frame durations as there are frames."); + } + + /// + /// Does this state represent a valid animation + /// + public bool IsValid { + get { return (this.image != null && this.frameCount > 0); } + } + + /// + /// Advance our images current frame and calculate when it will expire + /// + public void AdvanceFrame(long millisecondsNow) { + this.currentFrame = (this.currentFrame + 1) % this.frameCount; + this.currentFrameExpiresAt = millisecondsNow + this.imageDuration[this.currentFrame]; + this.image.SelectActiveFrame(FrameDimension.Time, this.currentFrame); + } + + internal int currentFrame; + internal long currentFrameExpiresAt; + internal Image image; + internal List imageDuration; + internal int frameCount; + } + + #region Private variables + + private System.Threading.Timer tickler; // timer used to tickle the animations + private Stopwatch stopwatch; // clock used to time the animation frame changes + + #endregion + } + + /// + /// Render our Aspect as a progress bar + /// + public class BarRenderer : BaseRenderer { + #region Constructors + + /// + /// Make a BarRenderer + /// + public BarRenderer() + : base() {} + + /// + /// Make a BarRenderer for the given range of data values + /// + public BarRenderer(int minimum, int maximum) + : this() { + this.MinimumValue = minimum; + this.MaximumValue = maximum; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(Pen pen, Brush brush) + : this() { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(int minimum, int maximum, Pen pen, Brush brush) + : this(minimum, maximum) { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(Pen pen, Color start, Color end) + : this() { + this.Pen = pen; + this.SetGradient(start, end); + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(int minimum, int maximum, Pen pen, Color start, Color end) + : this(minimum, maximum) { + this.Pen = pen; + this.SetGradient(start, end); + } + + #endregion + + #region Configuration Properties + + /// + /// Should this bar be drawn in the system style? + /// + [Category("ObjectListView"), + Description("Should this bar be drawn in the system style?"), + DefaultValue(true)] + public bool UseStandardBar { + get { return useStandardBar; } + set { useStandardBar = value; } + } + + private bool useStandardBar = true; + + /// + /// How many pixels in from our cell border will this bar be drawn + /// + [Category("ObjectListView"), + Description("How many pixels in from our cell border will this bar be drawn"), + DefaultValue(2)] + public int Padding { + get { return padding; } + set { padding = value; } + } + + private int padding = 2; + + /// + /// What color will be used to fill the interior of the control before the + /// progress bar is drawn? + /// + [Category("ObjectListView"), + Description("The color of the interior of the bar"), + DefaultValue(typeof (Color), "AliceBlue")] + public Color BackgroundColor { + get { return backgroundColor; } + set { backgroundColor = value; } + } + + private Color backgroundColor = Color.AliceBlue; + + /// + /// What color should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("What color should the frame of the progress bar be"), + DefaultValue(typeof (Color), "Black")] + public Color FrameColor { + get { return frameColor; } + set { frameColor = value; } + } + + private Color frameColor = Color.Black; + + /// + /// How many pixels wide should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("How many pixels wide should the frame of the progress bar be"), + DefaultValue(1.0f)] + public float FrameWidth { + get { return frameWidth; } + set { frameWidth = value; } + } + + private float frameWidth = 1.0f; + + /// + /// What color should the 'filled in' part of the progress bar be? + /// + /// This is only used if GradientStartColor is Color.Empty + [Category("ObjectListView"), + Description("What color should the 'filled in' part of the progress bar be"), + DefaultValue(typeof (Color), "BlueViolet")] + public Color FillColor { + get { return fillColor; } + set { fillColor = value; } + } + + private Color fillColor = Color.BlueViolet; + + /// + /// Use a gradient to fill the progress bar starting with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar starting with this color"), + DefaultValue(typeof (Color), "CornflowerBlue")] + public Color GradientStartColor { + get { return startColor; } + set { startColor = value; } + } + + private Color startColor = Color.CornflowerBlue; + + /// + /// Use a gradient to fill the progress bar ending with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar ending with this color"), + DefaultValue(typeof (Color), "DarkBlue")] + public Color GradientEndColor { + get { return endColor; } + set { endColor = value; } + } + + private Color endColor = Color.DarkBlue; + + /// + /// Regardless of how wide the column become the progress bar will never be wider than this + /// + [Category("Behavior"), + Description("The progress bar will never be wider than this"), + DefaultValue(100)] + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + + private int maximumWidth = 100; + + /// + /// Regardless of how high the cell is the progress bar will never be taller than this + /// + [Category("Behavior"), + Description("The progress bar will never be taller than this"), + DefaultValue(16)] + public int MaximumHeight { + get { return maximumHeight; } + set { maximumHeight = value; } + } + + private int maximumHeight = 16; + + /// + /// The minimum data value expected. Values less than this will given an empty bar + /// + [Category("Behavior"), + Description("The minimum data value expected. Values less than this will given an empty bar"), + DefaultValue(0.0)] + public double MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private double minimumValue = 0.0; + + /// + /// The maximum value for the range. Values greater than this will give a full bar + /// + [Category("Behavior"), + Description("The maximum value for the range. Values greater than this will give a full bar"), + DefaultValue(100.0)] + public double MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private double maximumValue = 100.0; + + #endregion + + #region Public Properties (non-IDE) + + /// + /// The Pen that will draw the frame surrounding this bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen Pen { + get { + if (this.pen == null && !this.FrameColor.IsEmpty) + return new Pen(this.FrameColor, this.FrameWidth); + else + return this.pen; + } + set { this.pen = value; } + } + + private Pen pen; + + /// + /// The brush that will be used to fill the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush Brush { + get { + if (this.brush == null && !this.FillColor.IsEmpty) + return new SolidBrush(this.FillColor); + else + return this.brush; + } + set { this.brush = value; } + } + + private Brush brush; + + /// + /// The brush that will be used to fill the background of the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush BackgroundBrush { + get { + if (this.backgroundBrush == null && !this.BackgroundColor.IsEmpty) + return new SolidBrush(this.BackgroundColor); + else + return this.backgroundBrush; + } + set { this.backgroundBrush = value; } + } + + private Brush backgroundBrush; + + #endregion + + /// + /// Draw this progress bar using a gradient + /// + /// + /// + public void SetGradient(Color start, Color end) { + this.GradientStartColor = start; + this.GradientEndColor = end; + } + + /// + /// Draw our aspect + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + r = this.ApplyCellPadding(r); + + Rectangle frameRect = Rectangle.Inflate(r, 0 - this.Padding, 0 - this.Padding); + frameRect.Width = Math.Min(frameRect.Width, this.MaximumWidth); + frameRect.Height = Math.Min(frameRect.Height, this.MaximumHeight); + frameRect = this.AlignRectangle(r, frameRect); + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + Rectangle fillRect = Rectangle.Inflate(frameRect, -1, -1); + if (aspectValue <= this.MinimumValue) + fillRect.Width = 0; + else if (aspectValue < this.MaximumValue) + fillRect.Width = (int) (fillRect.Width * (aspectValue - this.MinimumValue) / this.MaximumValue); + + // MS-themed progress bars don't work when printing + if (this.UseStandardBar && ProgressBarRenderer.IsSupported && !this.IsPrinting) { + ProgressBarRenderer.DrawHorizontalBar(g, frameRect); + ProgressBarRenderer.DrawHorizontalChunks(g, fillRect); + } else { + g.FillRectangle(this.BackgroundBrush, frameRect); + if (fillRect.Width > 0) { + // FillRectangle fills inside the given rectangle, so expand it a little + fillRect.Width++; + fillRect.Height++; + if (this.GradientStartColor == Color.Empty) + g.FillRectangle(this.Brush, fillRect); + else { + using (LinearGradientBrush gradient = new LinearGradientBrush(frameRect, this.GradientStartColor, this.GradientEndColor, LinearGradientMode.Horizontal)) { + g.FillRectangle(gradient, fillRect); + } + } + } + g.DrawRectangle(this.Pen, frameRect); + } + } + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + } + + + /// + /// An ImagesRenderer draws zero or more images depending on the data returned by its Aspect. + /// + /// This renderer's Aspect must return a ICollection of ints, strings or Images, + /// each of which will be drawn horizontally one after the other. + /// As of v2.1, this functionality has been absorbed into ImageRenderer and this is now an + /// empty shell, solely for backwards compatibility. + /// + [ToolboxItem(false)] + public class ImagesRenderer : ImageRenderer {} + + /// + /// A MultiImageRenderer draws the same image a number of times based on our data value + /// + /// The stars in the Rating column of iTunes is a good example of this type of renderer. + public class MultiImageRenderer : BaseRenderer { + /// + /// Make a quiet renderer + /// + public MultiImageRenderer() + : base() {} + + /// + /// Make an image renderer that will draw the indicated image, at most maxImages times. + /// + /// + /// + /// + /// + public MultiImageRenderer(Object imageSelector, int maxImages, int minValue, int maxValue) + : this() { + this.ImageSelector = imageSelector; + this.MaxNumberImages = maxImages; + this.MinimumValue = minValue; + this.MaximumValue = maxValue; + } + + #region Configuration Properties + + /// + /// The index of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(-1)] + public int ImageIndex { + get { + if (imageSelector is Int32) + return (Int32) imageSelector; + else + return -1; + } + set { imageSelector = value; } + } + + /// + /// The name of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(null)] + public string ImageName { + get { return imageSelector as String; } + set { imageSelector = value; } + } + + /// + /// The image selector that will give the image to be drawn + /// + /// Like all image selectors, this can be an int, string or Image + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + + private Object imageSelector; + + /// + /// What is the maximum number of images that this renderer should draw? + /// + [Category("Behavior"), + Description("The maximum number of images that this renderer should draw"), + DefaultValue(10)] + public int MaxNumberImages { + get { return maxNumberImages; } + set { maxNumberImages = value; } + } + + private int maxNumberImages = 10; + + /// + /// Values less than or equal to this will have 0 images drawn + /// + [Category("Behavior"), + Description("Values less than or equal to this will have 0 images drawn"), + DefaultValue(0)] + public int MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private int minimumValue = 0; + + /// + /// Values greater than or equal to this will have MaxNumberImages images drawn + /// + [Category("Behavior"), + Description("Values greater than or equal to this will have MaxNumberImages images drawn"), + DefaultValue(100)] + public int MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private int maximumValue = 100; + + #endregion + + /// + /// Draw our data value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + Image image = this.GetImage(this.ImageSelector); + if (image == null) + return; + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + // Calculate how many images we need to draw to represent our aspect value + int numberOfImages; + if (aspectValue <= this.MinimumValue) + numberOfImages = 0; + else if (aspectValue < this.MaximumValue) + numberOfImages = 1 + (int) (this.MaxNumberImages * (aspectValue - this.MinimumValue) / this.MaximumValue); + else + numberOfImages = this.MaxNumberImages; + + // If we need to shrink the image, what will its on-screen dimensions be? + int imageScaledWidth = image.Width; + int imageScaledHeight = image.Height; + if (r.Height < image.Height) { + imageScaledWidth = (int) ((float) image.Width * (float) r.Height / (float) image.Height); + imageScaledHeight = r.Height; + } + // Calculate where the images should be drawn + Rectangle imageBounds = r; + imageBounds.Width = (this.MaxNumberImages * (imageScaledWidth + this.Spacing)) - this.Spacing; + imageBounds.Height = imageScaledHeight; + imageBounds = this.AlignRectangle(r, imageBounds); + + // Finally, draw the images + Rectangle singleImageRect = new Rectangle(imageBounds.X, imageBounds.Y, imageScaledWidth, imageScaledHeight); + Color backgroundColor = GetBackgroundColor(); + for (int i = 0; i < numberOfImages; i++) { + if (this.ListItem.Enabled) { + this.DrawImage(g, singleImageRect, this.ImageSelector); + } else + ControlPaint.DrawImageDisabled(g, image, singleImageRect.X, singleImageRect.Y, backgroundColor); + singleImageRect.X += (imageScaledWidth + this.Spacing); + } + } + } + + + /// + /// A class to render a value that contains a bitwise-OR'ed collection of values. + /// + public class FlagRenderer : BaseRenderer { + /// + /// Register the given image to the given value + /// + /// When this flag is present... + /// ...draw this image + public void Add(Object key, Object imageSelector) { + Int32 k2 = ((IConvertible) key).ToInt32(NumberFormatInfo.InvariantInfo); + + this.imageMap[k2] = imageSelector; + this.keysInOrder.Remove(k2); + this.keysInOrder.Add(k2); + } + + /// + /// Draw the flags + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + r = this.ApplyCellPadding(r); + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + ArrayList images = new ArrayList(); + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) + images.Add(image); + } + } + if (images.Count > 0) + this.DrawImages(g, r, images); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + + Point pt = this.Bounds.Location; + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) { + Rectangle imageRect = new Rectangle(pt, image.Size); + if (imageRect.Contains(x, y)) { + hti.UserData = key; + return; + } + pt.X += (image.Width + this.Spacing); + } + } + } + } + + private List keysInOrder = new List(); + private Dictionary imageMap = new Dictionary(); + } + + /// + /// This renderer draws an image, a single line title, and then multi-line description + /// under the title. + /// + /// + /// This class works best with FullRowSelect = true. + /// It's not designed to work with cell editing -- it will work but will look odd. + /// + /// It's not RightToLeft friendly. + /// + /// + public class DescribedTaskRenderer : BaseRenderer, IFilterAwareRenderer + { + private readonly StringFormat noWrapStringFormat; + private readonly HighlightTextRenderer highlightTextRenderer = new HighlightTextRenderer(); + + /// + /// Create a DescribedTaskRenderer + /// + public DescribedTaskRenderer() { + this.noWrapStringFormat = new StringFormat(StringFormatFlags.NoWrap); + this.noWrapStringFormat.Trimming = StringTrimming.EllipsisCharacter; + this.noWrapStringFormat.Alignment = StringAlignment.Near; + this.noWrapStringFormat.LineAlignment = StringAlignment.Near; + this.highlightTextRenderer.CellVerticalAlignment = StringAlignment.Near; + } + + #region Configuration properties + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + public override bool UseGdiTextRendering + { + get { return base.UseGdiTextRendering; } + set + { + base.UseGdiTextRendering = value; + this.highlightTextRenderer.UseGdiTextRendering = value; + } + } + + /// + /// Gets or set the font that will be used to draw the title of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the title of the task"), + DefaultValue(null)] + public Font TitleFont { + get { return titleFont; } + set { titleFont = value; } + } + + private Font titleFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font TitleFontOrDefault { + get { return this.TitleFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the title of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the title"), + DefaultValue(typeof (Color), "")] + public Color TitleColor { + get { return titleColor; } + set { titleColor = value; } + } + + private Color titleColor; + + /// + /// Return the color of the title of the task or a reasonable default + /// + [Browsable(false)] + public Color TitleColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected || this.TitleColor.IsEmpty) + return this.GetForegroundColor(); + + return this.TitleColor; + } + } + + /// + /// Gets or set the font that will be used to draw the description of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the description of the task"), + DefaultValue(null)] + public Font DescriptionFont { + get { return descriptionFont; } + set { descriptionFont = value; } + } + + private Font descriptionFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font DescriptionFontOrDefault { + get { return this.DescriptionFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the description of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the description"), + DefaultValue(typeof (Color), "")] + public Color DescriptionColor { + get { return descriptionColor; } + set { descriptionColor = value; } + } + private Color descriptionColor = Color.Empty; + + /// + /// Return the color of the description of the task or a reasonable default + /// + [Browsable(false)] + public Color DescriptionColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection) + return this.GetForegroundColor(); + return this.DescriptionColor.IsEmpty ? defaultDescriptionColor : this.DescriptionColor; + } + } + private static Color defaultDescriptionColor = Color.FromArgb(45, 46, 49); + + /// + /// Gets or sets the number of pixels that will be left between the image and the text + /// + [Category("ObjectListView"), + Description("The number of pixels that will be left between the image and the text"), + DefaultValue(4)] + public int ImageTextSpace + { + get { return imageTextSpace; } + set { imageTextSpace = value; } + } + private int imageTextSpace = 4; + + /// + /// Gets or sets the number of pixels that will be left between the title and the description + /// + [Category("ObjectListView"), + Description("The number of pixels that that will be left between the title and the description"), + DefaultValue(2)] + public int TitleDescriptionSpace + { + get { return titleDescriptionSpace; } + set { titleDescriptionSpace = value; } + } + private int titleDescriptionSpace = 2; + + /// + /// Gets or sets the name of the aspect of the model object that contains the task description + /// + [Category("ObjectListView"), + Description("The name of the aspect of the model object that contains the task description"), + DefaultValue(null)] + public string DescriptionAspectName { + get { return descriptionAspectName; } + set { descriptionAspectName = value; } + } + private string descriptionAspectName; + + #endregion + + #region Text highlighting + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter + { + get { return this.highlightTextRenderer.Filter; } + set { this.highlightTextRenderer.Filter = value; } + } + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter { + get { return this.Filter; } + set { this.highlightTextRenderer.RegisterNewFilter(value); } + } + + #endregion + + #region Calculating + + /// + /// Fetch the description from the model class + /// + /// + /// + public virtual string GetDescription(object model) { + if (String.IsNullOrEmpty(this.DescriptionAspectName)) + return String.Empty; + + if (this.descriptionGetter == null) + this.descriptionGetter = new Munger(this.DescriptionAspectName); + + return this.descriptionGetter.GetValue(model) as string; + } + private Munger descriptionGetter; + + #endregion + + #region Rendering + + /// + /// + /// + /// + /// + /// + public override void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + base.ConfigureSubItem(e, cellBounds, model); + this.highlightTextRenderer.ConfigureSubItem(e, cellBounds, model); + } + + /// + /// Draw our item + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + this.DrawDescribedTask(g, r, this.GetText(), this.GetDescription(this.RowObject), this.GetImageSelector()); + } + + /// + /// Draw the task + /// + /// + /// + /// + /// + /// + protected virtual void DrawDescribedTask(Graphics g, Rectangle r, string title, string description, object imageSelector) { + + //Debug.WriteLine(String.Format("DrawDescribedTask({0}, {1}, {2}, {3})", r, title, description, imageSelector)); + + // Draw the image if one's been given + Rectangle textBounds = r; + if (imageSelector != null) { + int imageWidth = this.DrawImage(g, r, imageSelector); + int gapToText = imageWidth + this.ImageTextSpace; + textBounds.X += gapToText; + textBounds.Width -= gapToText; + } + + // Draw the title + if (!String.IsNullOrEmpty(title)) { + using (SolidBrush b = new SolidBrush(this.TitleColorOrDefault)) { + this.highlightTextRenderer.CanWrap = false; + this.highlightTextRenderer.Font = this.TitleFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, title); + } + + // How tall was the title? + SizeF size = g.MeasureString(title, this.TitleFontOrDefault, textBounds.Width, this.noWrapStringFormat); + int pixelsToDescription = this.TitleDescriptionSpace + (int)size.Height; + textBounds.Y += pixelsToDescription; + textBounds.Height -= pixelsToDescription; + } + + // Draw the description + if (!String.IsNullOrEmpty(description)) { + using (SolidBrush b = new SolidBrush(this.DescriptionColorOrDefault)) { + this.highlightTextRenderer.CanWrap = true; + this.highlightTextRenderer.Font = this.DescriptionFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, description); + } + } + + //g.DrawRectangle(Pens.OrangeRed, r); + } + + #endregion + + #region Hit Testing + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + if (this.Bounds.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Text; + } + + #endregion + } + + /// + /// This renderer draws a functioning button in its cell + /// + public class ColumnButtonRenderer : BaseRenderer { + + #region Properties + + /// + /// Gets or sets how each button will be sized + /// + [Category("ObjectListView"), + Description("How each button will be sized"), + DefaultValue(OLVColumn.ButtonSizingMode.TextBounds)] + public OLVColumn.ButtonSizingMode SizingMode + { + get { return this.sizingMode; } + set { this.sizingMode = value; } + } + private OLVColumn.ButtonSizingMode sizingMode = OLVColumn.ButtonSizingMode.TextBounds; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize + { + get { return this.buttonSize; } + set { this.buttonSize = value; } + } + private Size? buttonSize; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds")] + public Size? ButtonPadding + { + get { return this.buttonPadding; } + set { this.buttonPadding = value; } + } + private Size? buttonPadding = new Size(10, 10); + + private Size ButtonPaddingOrDefault { + get { return this.ButtonPadding ?? new Size(10, 10); } + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MaxButtonWidth + { + get { return this.maxButtonWidth; } + set { this.maxButtonWidth = value; } + } + private int maxButtonWidth = -1; + + /// + /// Gets or sets the minimum width that a button can occupy. + /// -1 means there is no minimum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The minimum width that a button can be when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MinButtonWidth { + get { return this.minButtonWidth; } + set { this.minButtonWidth = value; } + } + private int minButtonWidth = -1; + + #endregion + + #region Rendering + + /// + /// Calculate the size of the contents + /// + /// + /// + /// + protected override Size CalculateContentSize(Graphics g, Rectangle r) { + if (this.SizingMode == OLVColumn.ButtonSizingMode.CellBounds) + return r.Size; + + if (this.SizingMode == OLVColumn.ButtonSizingMode.FixedBounds) + return this.ButtonSize ?? r.Size; + + // Ok, SizingMode must be TextBounds. So figure out the size of the text + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width); + + // Allow for padding and max width + textSize.Height += this.ButtonPaddingOrDefault.Height * 2; + textSize.Width += this.ButtonPaddingOrDefault.Width * 2; + if (this.MaxButtonWidth != -1 && textSize.Width > this.MaxButtonWidth) + textSize.Width = this.MaxButtonWidth; + if (textSize.Width < this.MinButtonWidth) + textSize.Width = this.MinButtonWidth; + + return textSize; + } + + /// + /// Draw the button + /// + /// + /// + protected override void DrawImageAndText(Graphics g, Rectangle r) { + TextFormatFlags textFormatFlags = TextFormatFlags.HorizontalCenter | + TextFormatFlags.VerticalCenter | + TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPadding | + TextFormatFlags.SingleLine | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.ListView.RightToLeftLayout) + textFormatFlags |= TextFormatFlags.RightToLeft; + + string buttonText = GetText(); + if (!String.IsNullOrEmpty(buttonText)) + ButtonRenderer.DrawButton(g, r, buttonText, this.Font, textFormatFlags, false, CalculatePushButtonState()); + } + + /// + /// What part of the control is under the given point? + /// + /// + /// + /// + /// + /// + protected override void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle bounds, int x, int y) { + Rectangle r = ApplyCellPadding(bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Button; + } + + /// + /// What is the state of the button? + /// + /// + protected PushButtonState CalculatePushButtonState() { + if (!this.ListItem.Enabled && !this.Column.EnableButtonWhenItemIsDisabled) + return PushButtonState.Disabled; + + if (this.IsButtonHot) + return ObjectListView.IsLeftMouseDown ? PushButtonState.Pressed : PushButtonState.Hot; + + return PushButtonState.Normal; + } + + /// + /// Is the mouse over the button? + /// + protected bool IsButtonHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.Button; + } + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Styles.cs b/ObjectListView/Rendering/Styles.cs new file mode 100644 index 0000000..bc1daa2 --- /dev/null +++ b/ObjectListView/Rendering/Styles.cs @@ -0,0 +1,400 @@ +/* + * Styles - A style is a group of formatting attributes that can be applied to a row or a cell + * + * Author: Phillip Piper + * Date: 29/07/2009 23:09 + * + * Change log: + * v2.4 + * 2010-03-23 JPP - Added HeaderFormatStyle and support + * v2.3 + * 2009-08-15 JPP - Added Decoration and Overlay properties to HotItemStyle + * 2009-07-29 JPP - Initial version + * + * To do: + * - These should be more generally available. It should be possible to do something like this: + * this.olv.GetItem(i).Style = new ItemStyle(); + * this.olv.GetItem(i).GetSubItem(j).Style = new CellStyle(); + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// The common interface supported by all style objects + /// + public interface IItemStyle + { + /// + /// Gets or set the font that will be used by this style + /// + Font Font { get; set; } + + /// + /// Gets or set the font style + /// + FontStyle FontStyle { get; set; } + + /// + /// Gets or sets the ForeColor + /// + Color ForeColor { get; set; } + + /// + /// Gets or sets the BackColor + /// + Color BackColor { get; set; } + } + + /// + /// Basic implementation of IItemStyle + /// + public class SimpleItemStyle : System.ComponentModel.Component, IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font + { + get { return this.font; } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle + { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color ForeColor + { + get { return this.foreColor; } + set { this.foreColor = value; } + } + + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color BackColor + { + get { return this.backColor; } + set { this.backColor = value; } + } + + private Color backColor; + } + + + /// + /// Instances of this class specify how should "hot items" (non-selected + /// rows under the cursor) be rendered. + /// + public class HotItemStyle : SimpleItemStyle + { + /// + /// Gets or sets the overlay that should be drawn as part of the hot item + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IOverlay Overlay { + get { return this.overlay; } + set { this.overlay = value; } + } + private IOverlay overlay; + + /// + /// Gets or sets the decoration that should be drawn as part of the hot item + /// + /// A decoration is different from an overlay in that an decoration + /// scrolls with the listview contents, whilst an overlay does not. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDecoration Decoration { + get { return this.decoration; } + set { this.decoration = value; } + } + private IDecoration decoration; + } + + /// + /// This class defines how a cell should be formatted + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class CellStyle : IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + } + + /// + /// Instances of this class describe how hyperlinks will appear + /// + public class HyperlinkStyle : System.ComponentModel.Component + { + /// + /// Create a HyperlinkStyle + /// + public HyperlinkStyle() { + this.Normal = new CellStyle(); + this.Normal.ForeColor = Color.Blue; + this.Over = new CellStyle(); + this.Over.FontStyle = FontStyle.Underline; + this.Visited = new CellStyle(); + this.Visited.ForeColor = Color.Purple; + this.OverCursor = Cursors.Hand; + } + + /// + /// What sort of formatting should be applied to hyperlinks in their normal state? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn")] + public CellStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private CellStyle normalStyle; + + /// + /// What sort of formatting should be applied to hyperlinks when the mouse is over them? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn when the mouse is over them?")] + public CellStyle Over { + get { return this.overStyle; } + set { this.overStyle = value; } + } + private CellStyle overStyle; + + /// + /// What sort of formatting should be applied to hyperlinks after they have been clicked? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn after they have been clicked")] + public CellStyle Visited { + get { return this.visitedStyle; } + set { this.visitedStyle = value; } + } + private CellStyle visitedStyle; + + /// + /// Gets or sets the cursor that should be shown when the mouse is over a hyperlink. + /// + [Category("Appearance"), + Description("What cursor should be shown when the mouse is over a link?")] + public Cursor OverCursor { + get { return this.overCursor; } + set { this.overCursor = value; } + } + private Cursor overCursor; + } + + /// + /// Instances of this class control one the styling of one particular state + /// (normal, hot, pressed) of a header control + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class HeaderStateStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + + /// + /// Gets or sets the color in which a frame will be drawn around the header for this column + /// + [DefaultValue(typeof(Color), "")] + public Color FrameColor { + get { return this.frameColor; } + set { this.frameColor = value; } + } + private Color frameColor; + + /// + /// Gets or sets the width of the frame that will be drawn around the header for this column + /// + [DefaultValue(0.0f)] + public float FrameWidth { + get { return this.frameWidth; } + set { this.frameWidth = value; } + } + private float frameWidth; + } + + /// + /// This class defines how a header should be formatted in its various states. + /// + public class HeaderFormatStyle : System.ComponentModel.Component + { + /// + /// Create a new HeaderFormatStyle + /// + public HeaderFormatStyle() { + this.Hot = new HeaderStateStyle(); + this.Normal = new HeaderStateStyle(); + this.Pressed = new HeaderStateStyle(); + } + + /// + /// What sort of formatting should be applied to a column header when the mouse is over it? + /// + [Category("Appearance"), + Description("How should the header be drawn when the mouse is over it?")] + public HeaderStateStyle Hot { + get { return this.hotStyle; } + set { this.hotStyle = value; } + } + private HeaderStateStyle hotStyle; + + /// + /// What sort of formatting should be applied to a column header in its normal state? + /// + [Category("Appearance"), + Description("How should a column header normally be drawn")] + public HeaderStateStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private HeaderStateStyle normalStyle; + + /// + /// What sort of formatting should be applied to a column header when pressed? + /// + [Category("Appearance"), + Description("How should a column header be drawn when it is pressed")] + public HeaderStateStyle Pressed { + get { return this.pressedStyle; } + set { this.pressedStyle = value; } + } + private HeaderStateStyle pressedStyle; + + /// + /// Set the font for all three states + /// + /// + public void SetFont(Font font) { + this.Normal.Font = font; + this.Hot.Font = font; + this.Pressed.Font = font; + } + + /// + /// Set the fore color for all three states + /// + /// + public void SetForeColor(Color color) { + this.Normal.ForeColor = color; + this.Hot.ForeColor = color; + this.Pressed.ForeColor = color; + } + + /// + /// Set the back color for all three states + /// + /// + public void SetBackColor(Color color) { + this.Normal.BackColor = color; + this.Hot.BackColor = color; + this.Pressed.BackColor = color; + } + } +} diff --git a/ObjectListView/Rendering/TreeRenderer.cs b/ObjectListView/Rendering/TreeRenderer.cs new file mode 100644 index 0000000..a3bef8a --- /dev/null +++ b/ObjectListView/Rendering/TreeRenderer.cs @@ -0,0 +1,309 @@ +/* + * TreeRenderer - Draw the major column in a TreeListView + * + * Author: Phillip Piper + * Date: 27/06/2015 + * + * Change log: + * 2016-07-17 JPP - Added TreeRenderer.UseTriangles and IsShowGlyphs + * 2015-06-27 JPP - Split out from TreeListView.cs + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware { + + public partial class TreeListView { + /// + /// This class handles drawing the tree structure of the primary column. + /// + public class TreeRenderer : HighlightTextRenderer { + /// + /// Create a TreeRenderer + /// + public TreeRenderer() { + this.LinePen = new Pen(Color.Blue, 1.0f); + this.LinePen.DashStyle = DashStyle.Dot; + } + + #region Configuration properties + + /// + /// Should the renderer draw glyphs at the expansion points? + /// + /// The expansion points will still function to expand/collapse even if this is false. + public bool IsShowGlyphs + { + get { return isShowGlyphs; } + set { isShowGlyphs = value; } + } + private bool isShowGlyphs = true; + + /// + /// Should the renderer draw lines connecting siblings? + /// + public bool IsShowLines + { + get { return isShowLines; } + set { isShowLines = value; } + } + private bool isShowLines = true; + + /// + /// Return the pen that will be used to draw the lines between branches + /// + public Pen LinePen + { + get { return linePen; } + set { linePen = value; } + } + private Pen linePen; + + /// + /// Should the renderer draw triangles as the expansion glyphs? + /// + /// + /// This looks best with ShowLines = false + /// + public bool UseTriangles + { + get { return useTriangles; } + set { useTriangles = value; } + } + private bool useTriangles = false; + + #endregion + + /// + /// Return the branch that the renderer is currently drawing. + /// + private Branch Branch { + get { + return this.TreeListView.TreeModel.GetBranch(this.RowObject); + } + } + + /// + /// Return the TreeListView for which the renderer is being used. + /// + public TreeListView TreeListView { + get { + return (TreeListView)this.ListView; + } + } + + /// + /// How many pixels will be reserved for each level of indentation? + /// + public static int PIXELS_PER_LEVEL = 16 + 1; + + /// + /// The real work of drawing the tree is done in this method + /// + /// + /// + public override void Render(System.Drawing.Graphics g, System.Drawing.Rectangle r) { + this.DrawBackground(g, r); + + Branch br = this.Branch; + + Rectangle paddedRectangle = this.ApplyCellPadding(r); + + Rectangle expandGlyphRectangle = paddedRectangle; + expandGlyphRectangle.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + expandGlyphRectangle.Width = PIXELS_PER_LEVEL; + expandGlyphRectangle.Height = PIXELS_PER_LEVEL; + expandGlyphRectangle.Y = this.AlignVertically(paddedRectangle, expandGlyphRectangle); + int expandGlyphRectangleMidVertical = expandGlyphRectangle.Y + (expandGlyphRectangle.Height/2); + + if (this.IsShowLines) + this.DrawLines(g, r, this.LinePen, br, expandGlyphRectangleMidVertical); + + if (br.CanExpand && this.IsShowGlyphs) + this.DrawExpansionGlyph(g, expandGlyphRectangle, br.IsExpanded); + + int indent = br.Level * PIXELS_PER_LEVEL; + paddedRectangle.Offset(indent, 0); + paddedRectangle.Width -= indent; + + this.DrawImageAndText(g, paddedRectangle); + } + + /// + /// Draw the expansion indicator + /// + /// + /// + /// + protected virtual void DrawExpansionGlyph(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseStyles) { + this.DrawExpansionGlyphStyled(g, r, isExpanded); + } else { + this.DrawExpansionGlyphManual(g, r, isExpanded); + } + } + + /// + /// Gets whether or not we should render using styles + /// + protected virtual bool UseStyles { + get { + return !this.IsPrinting && Application.RenderWithVisualStyles; + } + } + + /// + /// Draw the expansion indicator using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphStyled(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseTriangles && this.IsShowLines) { + using (SolidBrush b = new SolidBrush(GetBackgroundColor())) { + Rectangle r2 = r; + r2.Inflate(-2, -2); + g.FillRectangle(b, r2); + } + } + + VisualStyleRenderer renderer = new VisualStyleRenderer(DecideVisualElement(isExpanded)); + renderer.DrawBackground(g, r); + } + + private VisualStyleElement DecideVisualElement(bool isExpanded) { + string klass = this.UseTriangles ? "Explorer::TreeView" : "TREEVIEW"; + int part = this.UseTriangles && this.IsExpansionHot ? 4 : 2; + int state = isExpanded ? 2 : 1; + return VisualStyleElement.CreateElement(klass, part, state); + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsExpansionHot { + get { return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.ExpandButton; } + } + + /// + /// Draw the expansion indicator without using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphManual(Graphics g, Rectangle r, bool isExpanded) { + int h = 8; + int w = 8; + int x = r.X + 4; + int y = r.Y + (r.Height / 2) - 4; + + g.DrawRectangle(new Pen(SystemBrushes.ControlDark), x, y, w, h); + g.FillRectangle(Brushes.White, x + 1, y + 1, w - 1, h - 1); + g.DrawLine(Pens.Black, x + 2, y + 4, x + w - 2, y + 4); + + if (!isExpanded) + g.DrawLine(Pens.Black, x + 4, y + 2, x + 4, y + h - 2); + } + + /// + /// Draw the lines of the tree + /// + /// + /// + /// + /// + /// + protected virtual void DrawLines(Graphics g, Rectangle r, Pen p, Branch br, int glyphMidVertical) { + Rectangle r2 = r; + r2.Width = PIXELS_PER_LEVEL; + + // Vertical lines have to start on even points, otherwise the dotted line looks wrong. + // This is only needed if pen is dotted. + int top = r2.Top; + //if (p.DashStyle == DashStyle.Dot && (top & 1) == 0) + // top += 1; + + // Draw lines for ancestors + int midX; + IList ancestors = br.Ancestors; + foreach (Branch ancestor in ancestors) { + if (!ancestor.IsLastChild && !ancestor.IsOnlyBranch) { + midX = r2.Left + r2.Width / 2; + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + r2.Offset(PIXELS_PER_LEVEL, 0); + } + + // Draw lines for this branch + midX = r2.Left + r2.Width / 2; + + // Horizontal line first + g.DrawLine(p, midX, glyphMidVertical, r2.Right, glyphMidVertical); + + // Vertical line second + if (br.IsFirstBranch) { + if (!br.IsLastChild && !br.IsOnlyBranch) + g.DrawLine(p, midX, glyphMidVertical, midX, r2.Bottom); + } else { + if (br.IsLastChild) + g.DrawLine(p, midX, top, midX, glyphMidVertical); + else + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + } + + /// + /// Do the hit test + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Branch br = this.Branch; + + Rectangle r = this.ApplyCellPadding(this.Bounds); + if (br.CanExpand) { + r.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + r.Width = PIXELS_PER_LEVEL; + if (r.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.ExpandButton; + return; + } + } + + r = this.Bounds; + int indent = br.Level * PIXELS_PER_LEVEL; + r.X += indent; + r.Width -= indent; + + // Ignore events in the indent zone + if (x < r.Left) { + hti.HitTestLocation = HitTestLocation.Nothing; + } else { + this.StandardHitTest(g, hti, r, x, y); + } + } + + /// + /// Calculate the edit rect + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + } + } +} \ No newline at end of file diff --git a/ObjectListView/Resources/clear-filter.png b/ObjectListView/Resources/clear-filter.png new file mode 100644 index 0000000000000000000000000000000000000000..2ddf7073b0c3de5791448e7a8effdf05f2c25e77 GIT binary patch literal 1381 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu3$w13IYNSK;YpJ;1K`>2|$pMP*6~?L4aXGMZtoMfCCZ?4-^DGXfXWOVECXR@E?dQ z1pYfH{P$4!A7F4Hz~MoF!-oim{|OHNGaUXG1pKcE_)wAXABY+fK6DiP? zKrmy%f&~jUtk?hoJ2qU{vEjpnh7U6u{?BN50A#ON@L|J(4?8v-*m2;)feiRR|N(hXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr_kFdQ zoeld1Cq2lBJ3DomuG-I@|6fF&{HffzJymf>EyJTdrCUYrF&?;bSL@WRXdYXZ8L_8& z<{G4lv8T+tYq*RrCy!C_(dAdCziTk7Os_f-vdCUx*~%@3S$j_~ZHe|x2$B30aO11n q@yq4if(I79Qcsd^-jTfMt#}vzTCZ0dwIzWLW$<+Mb6Mw<&;$TKY4H>Q literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/coffee.jpg b/ObjectListView/Resources/coffee.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6032d83fc7a5e1db6b76067d8de98e2bce6619c4 GIT binary patch literal 73464 zcmeFY1yG#Lwl@0W7TkinTX2T}!G;Wk!96&GyGsN@u;A|Q5Zoa_gS!R@5+Jy{-O0Dl z+50=E&i~(g{#$jcZk;sD@O1a;?zNs?Q>=G&&*R+V3V;KWQA? z3AF$KFc@G3000$$4~7DWFa!sy@a&KSD6qdzV0A{=3n1Tty`la_f65;Q{xI-|fjD!z zOIcVl0~SdbyoB02z~caboxQ6wL|&R&TSu1~Wds&`paIALHvkx$x;TQ>T1GD`l^A9Zf8=KkLo55t%VA#>j&g?htg5i(uZsstI zpajDo+@a>zXewZed{|Y6Wu-TXR=ej#tK}Hpb3o z)G`isj>h(0z&}j>JqW=2O)WKyV*zeq0RavkP8j?DEdSfie@gxD!SAj8hs3GsUt0!8 zH1w~we~tZDn?nu&2*GGUi27HXNiqO51OdR)g@3itX8{0qAOO^l{>>hu-|k}N>gp)M z#pU7Q!3i}t<^0X(Kg<8Ez&|Db*WhpKasFQKpWIQuFt;#vvvsBZO{%Gbt%I90wTq*% zsW~;rfA-=3u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/filter-icons3.png b/ObjectListView/Resources/filter-icons3.png new file mode 100644 index 0000000000000000000000000000000000000000..80178919d5b63ab83df2b7c669ab0779a49aa2aa GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^+(695!3-or^+GlRDVB6cUq=Rpjs4tz5?L7-m>B|m zLR>-OY^*$7-1heN&W=uQZf+hP9-f|_-hqLkp`l@6VHp`2`FT0T#l=NMCB?<1B}K(e zO)YJ0ZTkrW0Q7{?;10DkVe@>jlz`)2*666>Be`EuO;P33J zzzE?i@Q5sCVBk9h!i=ICUJXD&$r9IylHmNblJdl&REB`W%)AmkKi3e2GGjecJqvT| zhFG8?MUW!rqSVBa%=|oskj&gv1|tJQLn{LlD?>vCBSR}gBP(MQ&19DgK*fQcE{-7* z;jU-hg&GtXm>qO(2x@=3_wWB9j=m(lnN#F*)B0@kMOI+Vn;qXQmn}9~_T~=D z+XX%QB%0i|8O%7kPm;e@o7oiiks3xCpOkgD9y%{jLaR6H_xy85}S Ib4q9e03rsV#sB~S literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-ascending.png b/ObjectListView/Resources/sort-ascending.png new file mode 100644 index 0000000000000000000000000000000000000000..a21be93fa9f9415cfb652bd3f1fea9f14d09338c GIT binary patch literal 1364 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1E30yA9S={>)b#X{vND5!2?h}ptRkldbB_{`{(WMnzDc9vUQs_&0BM1<bo1Nd^W+hLRw^;Qu2VFa&>RR|SSK zXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr=C^PE^0&oV$SnRjJ>Se)@el9KzgPb(xGQ0`HCE5kgy}D{ z`~Ouz>UtNs#CGW&tXB%1p1&yert|7m7J~gd`a(DPrKwMx!92N9ht=$^ar1VS;Aj5% zj}5qGI!+k)v>%we)P+^=ZeLFF8>M517RUD-ikl)^c|iKt?Ty_hV~;%rx{JZn)z4*} HQ$iB}j@iab literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-descending.png b/ObjectListView/Resources/sort-descending.png new file mode 100644 index 0000000000000000000000000000000000000000..92dbe63f20afc6c51cf837b3aa6b0de64bfd126d GIT binary patch literal 1371 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1D=Pzs0xPd_tHAPdYaI_y&(!qvlCm-bj|PW`1wjezAz8Cy3uk*KEb+`(5>mJ_ zzIa_`?dFp19SsHwZPq$dt*v|9EvGtJPjGOU;1Mu2FmhH_{erCc1!=j<%W^iBl`XC9 zUtQhMFk$`t#fzse-MhMN`o{iwySt|BpSf(^rcI02A6d8a^twH#_Z~dB@6@g1%a)zk zwD#DAn

dzjor>jk9NOoV#%O_LIwZpWS`@{PE+*Po6w|`R*Oi*`r`I1Sk&yjoeww z7#J8CN`m}?|Br0I5d5886&RwN1s;*b3=DjSK$uZf!>a)(C|TkfQ4*Y=R#Ki=l*$m0 zn3-3i=jR%tP-d)Ws%K$t-4F{@qzF>vT$Gwvl9`{U5R#dj%3x$*XlP|%Vr6KgU|?xw zWMXAtBrKh33{*VX)5S4FBRIB?o$rtVkE^f7?kRgUb8oi9nmze<{a1>@M6*p#p1k~N z-Eu`SL2~V)lb*#tCz*=Q4?JJNw&&=s+HH*Mod1ib@bvsXa8~LjPfF4c_V0OmAFLZw zPrO#0*_f`&8uipQN%z&d#SVpjdlp=i+dJcJioJkf_=1P$=Bx_(H07fFXSt;FNoxyO jXDxlJeOk+k^#@aL!J4$pI`)r1=P`J?`njxgN@xNAhOF7) literal 0 HcmV?d00001 diff --git a/ObjectListView/SubControls/GlassPanelForm.cs b/ObjectListView/SubControls/GlassPanelForm.cs new file mode 100644 index 0000000..bcaba67 --- /dev/null +++ b/ObjectListView/SubControls/GlassPanelForm.cs @@ -0,0 +1,459 @@ +/* + * GlassPanelForm - A transparent form that is placed over an ObjectListView + * to allow flicker-free overlay images during scrolling. + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * 2010-08-18 JPP - Added WS_EX_TOOLWINDOW style so that the form won't appear in Alt-Tab list. + * v2.4 + * 2010-03-11 JPP - Work correctly in MDI applications -- more or less. Actually, less than more. + * They don't crash but they don't correctly handle overlapping MDI children. + * Overlays from one control are shown on top of the other windows. + * 2010-03-09 JPP - Correctly Unbind() when the related ObjectListView is disposed. + * 2009-10-28 JPP - Use FindForm() rather than TopMostControl, since the latter doesn't work + * as I expected when the OLV is part of an MDI child window. Thanks to + * wvd_vegt who tracked this down. + * v2.3 + * 2009-08-19 JPP - Only hide the glass pane on resize, not on move + * - Each glass panel now only draws one overlays + * v2.2 + * 2009-06-05 JPP - Handle when owning window is a topmost window + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + ///

+ /// A GlassPanelForm sits transparently over an ObjectListView to show overlays. + /// + internal partial class GlassPanelForm : Form + { + public GlassPanelForm() { + this.Name = "GlassPanelForm"; + this.Text = "GlassPanelForm"; + + ClientSize = new System.Drawing.Size(0, 0); + ControlBox = false; + FormBorderStyle = FormBorderStyle.None; + SizeGripStyle = SizeGripStyle.Hide; + StartPosition = FormStartPosition.Manual; + MaximizeBox = false; + MinimizeBox = false; + ShowIcon = false; + ShowInTaskbar = false; + FormBorderStyle = FormBorderStyle.None; + + SetStyle(ControlStyles.Selectable, false); + + this.Opacity = 0.5f; + this.BackColor = Color.FromArgb(255, 254, 254, 254); + this.TransparencyKey = this.BackColor; + this.HideGlass(); + NativeMethods.ShowWithoutActivate(this); + } + + protected override void Dispose(bool disposing) { + if (disposing) + this.Unbind(); + + base.Dispose(disposing); + } + + #region Properties + + /// + /// Get the low-level windows flag that will be given to CreateWindow. + /// + protected override CreateParams CreateParams { + get { + CreateParams cp = base.CreateParams; + cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT + cp.ExStyle |= 0x80; // WS_EX_TOOLWINDOW + return cp; + } + } + + #endregion + + #region Commands + + /// + /// Attach this form to the given ObjectListView + /// + public void Bind(ObjectListView olv, IOverlay overlay) { + if (this.objectListView != null) + this.Unbind(); + + this.objectListView = olv; + this.Overlay = overlay; + this.mdiClient = null; + this.mdiOwner = null; + + if (this.objectListView == null) + return; + + // NOTE: If you listen to any events here, you *must* stop listening in Unbind() + + this.objectListView.Disposed += new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged += new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged += new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged += new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged += new EventHandler(objectListView_ParentChanged); + + // Collect our ancestors in the widget hierarchy + if (this.ancestors == null) + this.ancestors = new List(); + Control parent = this.objectListView.Parent; + while (parent != null) { + this.ancestors.Add(parent); + parent = parent.Parent; + } + + // Listen for changes in the hierarchy + foreach (Control ancestor in this.ancestors) { + ancestor.ParentChanged += new EventHandler(objectListView_ParentChanged); + TabControl tabControl = ancestor as TabControl; + if (tabControl != null) { + tabControl.Selected += new TabControlEventHandler(tabControl_Selected); + } + } + + // Listen for changes in our owning form + this.Owner = this.objectListView.FindForm(); + this.myOwner = this.Owner; + if (this.Owner != null) { + this.Owner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.Owner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.Owner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.Owner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + if (this.Owner.TopMost) { + // We can't do this.TopMost = true; since that will activate the panel, + // taking focus away from the owner of the listview + NativeMethods.MakeTopMost(this); + } + + // We need special code to handle MDI + this.mdiOwner = this.Owner.MdiParent; + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + + // Find the MDIClient control, which houses all MDI children + foreach (Control c in this.mdiOwner.Controls) { + this.mdiClient = c as MdiClient; + if (this.mdiClient != null) { + break; + } + } + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged += new EventHandler(myMdiClient_ClientSizeChanged); + } + } + } + + this.UpdateTransparency(); + } + + void myMdiClient_ClientSizeChanged(object sender, EventArgs e) { + this.RecalculateBounds(); + this.Invalidate(); + } + + /// + /// Made the overlay panel invisible + /// + public void HideGlass() { + if (!this.isGlassShown) + return; + this.isGlassShown = false; + this.Bounds = new Rectangle(-10000, -10000, 1, 1); + } + + /// + /// Show the overlay panel in its correctly location + /// + /// + /// If the panel is always shown, this method does nothing. + /// If the panel is being resized, this method also does nothing. + /// + public void ShowGlass() { + if (this.isGlassShown || this.isDuringResizeSequence) + return; + + this.isGlassShown = true; + this.RecalculateBounds(); + } + + /// + /// Detach this glass panel from its previous ObjectListView + /// + /// + /// You should unbind the overlay panel before making any changes to the + /// widget hierarchy. + /// + public void Unbind() { + if (this.objectListView != null) { + this.objectListView.Disposed -= new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged -= new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged -= new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged -= new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged -= new EventHandler(objectListView_ParentChanged); + this.objectListView = null; + } + + if (this.ancestors != null) { + foreach (Control parent in this.ancestors) { + parent.ParentChanged -= new EventHandler(objectListView_ParentChanged); + TabControl tabControl = parent as TabControl; + if (tabControl != null) { + tabControl.Selected -= new TabControlEventHandler(tabControl_Selected); + } + } + this.ancestors = null; + } + + if (this.myOwner != null) { + this.myOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.myOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.myOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.myOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.myOwner = null; + } + + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.mdiOwner = null; + } + + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged -= new EventHandler(myMdiClient_ClientSizeChanged); + this.mdiClient = null; + } + } + + #endregion + + #region Event Handlers + + void objectListView_Disposed(object sender, EventArgs e) { + this.Unbind(); + } + + /// + /// Handle when the form that owns the ObjectListView begins to be resized + /// + /// + /// + void Owner_ResizeBegin(object sender, EventArgs e) { + // When the top level window is being resized, we just want to hide + // the overlay window. When the resizing finishes, we want to show + // the overlay window, if it was shown before the resize started. + this.isDuringResizeSequence = true; + this.wasGlassShownBeforeResize = this.isGlassShown; + } + + /// + /// Handle when the form that owns the ObjectListView finished to be resized + /// + /// + /// + void Owner_ResizeEnd(object sender, EventArgs e) { + this.isDuringResizeSequence = false; + if (this.wasGlassShownBeforeResize) + this.ShowGlass(); + } + + /// + /// The owning form has moved. Move the overlay panel too. + /// + /// + /// + void Owner_LocationChanged(object sender, EventArgs e) { + if (this.mdiOwner != null) + this.HideGlass(); + else + this.RecalculateBounds(); + } + + /// + /// The owning form is resizing. Hide our overlay panel until the resizing stops + /// + /// + /// + void Owner_SizeChanged(object sender, EventArgs e) { + this.HideGlass(); + } + + + /// + /// Handle when the bound OLV changes its location. The overlay panel must + /// be moved too, IFF it is currently visible. + /// + /// + /// + void objectListView_LocationChanged(object sender, EventArgs e) { + if (this.isGlassShown) { + this.RecalculateBounds(); + } + } + + /// + /// Handle when the bound OLV changes size. The overlay panel must + /// resize too, IFF it is currently visible. + /// + /// + /// + void objectListView_SizeChanged(object sender, EventArgs e) { + // This event is triggered in all sorts of places, and not always when the size changes. + //if (this.isGlassShown) { + // this.Size = this.objectListView.ClientSize; + //} + } + + /// + /// Handle when the bound OLV is part of a TabControl and that + /// TabControl changes tabs. The overlay panel is hidden. The + /// first time the bound OLV is redrawn, the overlay panel will + /// be shown again. + /// + /// + /// + void tabControl_Selected(object sender, TabControlEventArgs e) { + this.HideGlass(); + } + + /// + /// Somewhere the parent of the bound OLV has changed. Update + /// our events. + /// + /// + /// + void objectListView_ParentChanged(object sender, EventArgs e) { + ObjectListView olv = this.objectListView; + IOverlay overlay = this.Overlay; + this.Unbind(); + this.Bind(olv, overlay); + } + + /// + /// Handle when the bound OLV changes its visibility. + /// The overlay panel should match the OLV's visibility. + /// + /// + /// + void objectListView_VisibleChanged(object sender, EventArgs e) { + if (this.objectListView.Visible) + this.ShowGlass(); + else + this.HideGlass(); + } + + #endregion + + #region Implementation + + protected override void OnPaint(PaintEventArgs e) { + if (this.objectListView == null || this.Overlay == null) + return; + + Graphics g = e.Graphics; + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + //g.DrawRectangle(new Pen(Color.Green, 4.0f), this.ClientRectangle); + + // If we are part of an MDI app, make sure we don't draw outside the bounds + if (this.mdiClient != null) { + Rectangle r = mdiClient.RectangleToScreen(mdiClient.ClientRectangle); + Rectangle r2 = this.objectListView.RectangleToClient(r); + g.SetClip(r2, System.Drawing.Drawing2D.CombineMode.Intersect); + } + + this.Overlay.Draw(this.objectListView, g, this.objectListView.ClientRectangle); + } + + protected void RecalculateBounds() { + if (!this.isGlassShown) + return; + + Rectangle rect = this.objectListView.ClientRectangle; + rect.X = 0; + rect.Y = 0; + this.Bounds = this.objectListView.RectangleToScreen(rect); + } + + internal void UpdateTransparency() { + ITransparentOverlay transparentOverlay = this.Overlay as ITransparentOverlay; + if (transparentOverlay == null) + this.Opacity = this.objectListView.OverlayTransparency / 255.0f; + else + this.Opacity = transparentOverlay.Transparency / 255.0f; + } + + protected override void WndProc(ref Message m) { + const int WM_NCHITTEST = 132; + const int HTTRANSPARENT = -1; + switch (m.Msg) { + // Ignore all mouse interactions + case WM_NCHITTEST: + m.Result = (IntPtr)HTTRANSPARENT; + break; + } + base.WndProc(ref m); + } + + #endregion + + #region Implementation variables + + internal IOverlay Overlay; + + #endregion + + #region Private variables + + private ObjectListView objectListView; + private bool isDuringResizeSequence; + private bool isGlassShown; + private bool wasGlassShownBeforeResize; + + // Cache these so we can unsubscribe from events even when the OLV has been disposed. + private Form myOwner; + private Form mdiOwner; + private List ancestors; + MdiClient mdiClient; + + #endregion + + } +} diff --git a/ObjectListView/SubControls/HeaderControl.cs b/ObjectListView/SubControls/HeaderControl.cs new file mode 100644 index 0000000..298680b --- /dev/null +++ b/ObjectListView/SubControls/HeaderControl.cs @@ -0,0 +1,1230 @@ +/* + * HeaderControl - A limited implementation of HeaderControl + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * 2015-06-12 JPP - Use HeaderTextAlignOrDefault instead of HeaderTextAlign + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-11 JPP - Fixed bug that prevented columns from being resized in IDE Designer + * by dragging the column divider + * 2011-04-12 JPP - Added ability to draw filter indicator in a column's header + * v2.4.1 + * 2010-08-23 JPP - Added ability to draw header vertically (thanks to Mark Fenwick) + * - Uses OLVColumn.HeaderTextAlign to decide how to align the column's header + * 2010-08-08 JPP - Added ability to have image in header + * v2.4 + * 2010-03-22 JPP - Draw header using header styles + * 2009-10-30 JPP - Plugged GDI resource leak, where font handles were created during custom + * drawing, but never destroyed + * v2.3 + * 2009-10-03 JPP - Handle when ListView.HeaderFormatStyle is None + * 2009-08-24 JPP - Handle the header being destroyed + * v2.2.1 + * 2009-08-16 JPP - Correctly handle header themes + * 2009-08-15 JPP - Added formatting capabilities: font, color, word wrap + * v2.2 + * 2009-06-01 JPP - Use ToolTipControl + * 2009-05-10 JPP - Removed all unsafe code + * 2008-11-25 JPP - Initial version + * + * TO DO: + * - Put drawing code into header style object, so that it can be easily customized. + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.Remoting; +using System.Windows.Forms; +using System.Runtime.InteropServices; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; +using BrightIdeasSoftware.Properties; +using System.Security.Permissions; + +namespace BrightIdeasSoftware { + + /// + /// Class used to capture window messages for the header of the list view + /// control. + /// + public class HeaderControl : NativeWindow { + /// + /// Create a header control for the given ObjectListView. + /// + /// + public HeaderControl(ObjectListView olv) { + this.ListView = olv; + this.AssignHandle(NativeMethods.GetHeaderControl(olv)); + } + + #region Properties + + /// + /// Return the index of the column under the current cursor position, + /// or -1 if the cursor is not over a column + /// + /// Index of the column under the cursor, or -1 + public int ColumnIndexUnderCursor { + get { + Point pt = this.ScrolledCursorPosition; + return NativeMethods.GetColumnUnderPoint(this.Handle, pt); + } + } + + /// + /// Return the Windows handle behind this control + /// + /// + /// When an ObjectListView is initialized as part of a UserControl, the + /// GetHeaderControl() method returns 0 until the UserControl is + /// completely initialized. So the AssignHandle() call in the constructor + /// doesn't work. So we override the Handle property so value is always + /// current. + /// + public new IntPtr Handle { + get { return NativeMethods.GetHeaderControl(this.ListView); } + } + + //TODO: The Handle property may no longer be necessary. CHECK! 2008/11/28 + + /// + /// Gets or sets a style that should be applied to the font of the + /// column's header text when the mouse is over that column + /// + /// THIS IS EXPERIMENTAL. USE AT OWN RISK. August 2009 + [Obsolete("Use HeaderStyle.Hot.FontStyle instead")] + public FontStyle HotFontStyle { + get { return FontStyle.Regular; } + set { } + } + + /// + /// Gets the index of the column under the cursor if the cursor is over it's checkbox + /// + protected int GetColumnCheckBoxUnderCursor() { + Point pt = this.ScrolledCursorPosition; + + int columnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + return this.IsPointOverHeaderCheckBox(columnIndex, pt) ? columnIndex : -1; + } + + /// + /// Gets the client rectangle for the header + /// + public Rectangle ClientRectangle { + get { + Rectangle r = new Rectangle(); + NativeMethods.GetClientRect(this.Handle, ref r); + return r; + } + } + + /// + /// Return true if the given point is over the checkbox for the given column. + /// + /// + /// + /// + protected bool IsPointOverHeaderCheckBox(int columnIndex, Point pt) { + if (columnIndex < 0 || columnIndex >= this.ListView.Columns.Count) + return false; + + OLVColumn column = this.ListView.GetColumn(columnIndex); + if (!this.HasCheckBox(column)) + return false; + + Rectangle r = this.GetCheckBoxBounds(column); + r.Inflate(1, 1); // make the target slightly bigger + return r.Contains(pt); + } + + /// + /// Gets whether the cursor is over a "locked" divider, i.e. + /// one that cannot be dragged by the user. + /// + protected bool IsCursorOverLockedDivider { + get { + Point pt = this.ScrolledCursorPosition; + int dividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + if (dividerIndex >= 0 && dividerIndex < this.ListView.Columns.Count) { + OLVColumn column = this.ListView.GetColumn(dividerIndex); + return column.IsFixedWidth || column.FillsFreeSpace; + } else + return false; + } + } + + private Point ScrolledCursorPosition { + get { + Point pt = this.ListView.PointToClient(Cursor.Position); + pt.X += this.ListView.LowLevelScrollPosition.X; + return pt; + } + } + + /// + /// Gets or sets the listview that this header belongs to + /// + protected ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the maximum height of the header. -1 means no maximum. + /// + public int MaximumHeight + { + get { return this.ListView.HeaderMaximumHeight; } + } + + /// + /// Gets the minimum height of the header. -1 means no minimum. + /// + public int MinimumHeight + { + get { return this.ListView.HeaderMinimumHeight; } + } + + /// + /// Get or set the ToolTip that shows tips for the header + /// + public ToolTipControl ToolTip { + get { + if (this.toolTip == null) { + this.CreateToolTip(); + } + return this.toolTip; + } + protected set { this.toolTip = value; } + } + + private ToolTipControl toolTip; + + /// + /// Gets or sets whether the text in column headers should be word + /// wrapped when it is too long to fit within the column + /// + public bool WordWrap { + get { return this.wordWrap; } + set { this.wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Commands + + /// + /// Calculate how height the header needs to be + /// + /// Height in pixels + protected int CalculateHeight(Graphics g) { + TextFormatFlags flags = this.TextFormatFlags; + int columnUnderCursor = this.ColumnIndexUnderCursor; + float height = this.MinimumHeight; + for (int i = 0; i < this.ListView.Columns.Count; i++) { + OLVColumn column = this.ListView.GetColumn(i); + height = Math.Max(height, CalculateColumnHeight(g, column, flags, columnUnderCursor == i, i)); + } + return this.MaximumHeight == -1 ? (int) height : Math.Min(this.MaximumHeight, (int) height); + } + + private float CalculateColumnHeight(Graphics g, OLVColumn column, TextFormatFlags flags, bool isHot, int i) { + Font f = this.CalculateFont(column, isHot, false); + if (column.IsHeaderVertical) + return TextRenderer.MeasureText(g, column.Text, f, new Size(10000, 10000), flags).Width; + + const int fudge = 9; // 9 is a magic constant that makes it perfectly match XP behavior + if (!this.WordWrap) + return f.Height + fudge; + + Rectangle r = this.GetHeaderDrawRect(i); + if (this.HasNonThemedSortIndicator(column)) + r.Width -= 16; + if (column.HasHeaderImage) + r.Width -= column.ImageList.ImageSize.Width + 3; + if (this.HasFilterIndicator(column)) + r.Width -= this.CalculateFilterIndicatorWidth(r); + if (this.HasCheckBox(column)) + r.Width -= this.CalculateCheckBoxBounds(g, r).Width; + SizeF size = TextRenderer.MeasureText(g, column.Text, f, new Size(r.Width, 100), flags); + return size.Height + fudge; + } + + /// + /// Get the bounds of the checkbox against the given column + /// + /// + /// + public Rectangle GetCheckBoxBounds(OLVColumn column) { + Rectangle r = this.GetHeaderDrawRect(column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) + return this.CalculateCheckBoxBounds(g, r); + } + + /// + /// Should the given column be drawn with a checkbox against it? + /// + /// + /// + public bool HasCheckBox(OLVColumn column) { + return column.HeaderCheckBox || column.HeaderTriStateCheckBox; + } + + /// + /// Should the given column show a sort indicator? + /// + /// + /// + protected bool HasSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + return column == this.ListView.LastSortColumn && this.ListView.LastSortOrder != SortOrder.None; + } + + /// + /// Should the given column be drawn with a filter indicator against it? + /// + /// + /// + protected bool HasFilterIndicator(OLVColumn column) { + return (this.ListView.UseFiltering && this.ListView.UseFilterIndicator && column.HasFilterIndicator); + } + + /// + /// Should the given column show a non-themed sort indicator? + /// + /// + /// + protected bool HasNonThemedSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + if (VisualStyleRenderer.IsSupported) + return !VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp) && + this.HasSortIndicator(column); + else + return this.HasSortIndicator(column); + } + + /// + /// Return the bounds of the item with the given index + /// + /// + /// + public Rectangle GetItemRect(int itemIndex) { + const int HDM_FIRST = 0x1200; + const int HDM_GETITEMRECT = HDM_FIRST + 7; + NativeMethods.RECT r = new NativeMethods.RECT(); + NativeMethods.SendMessageRECT(this.Handle, HDM_GETITEMRECT, itemIndex, ref r); + return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); + } + + /// + /// Return the bounds within which the given column will be drawn + /// + /// + /// + public Rectangle GetHeaderDrawRect(int itemIndex) { + Rectangle r = this.GetItemRect(itemIndex); + + // Tweak the text rectangle a little to improve aesthetics + r.Inflate(-3, 0); + r.Y -= 2; + + return r; + } + + /// + /// Force the header to redraw by invalidating it + /// + public void Invalidate() { + NativeMethods.InvalidateRect(this.Handle, 0, true); + } + + /// + /// Force the header to redraw a single column by invalidating it + /// + public void Invalidate(OLVColumn column) { + NativeMethods.InvalidateRect(this.Handle, 0, true); // todo + } + + #endregion + + #region Tooltip + + /// + /// Create a native tool tip control for this listview + /// + protected virtual void CreateToolTip() { + this.ToolTip = new ToolTipControl(); + this.ToolTip.Create(this.Handle); + this.ToolTip.AddTool(this); + this.ToolTip.Showing += new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + + #endregion + + #region Windows messaging + + /// + /// Override the basic message pump + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + protected override void WndProc(ref Message m) { + const int WM_DESTROY = 2; + const int WM_SETCURSOR = 0x20; + const int WM_NOTIFY = 0x4E; + const int WM_MOUSEMOVE = 0x200; + const int WM_LBUTTONDOWN = 0x201; + const int WM_LBUTTONUP = 0x202; + const int WM_MOUSELEAVE = 675; + const int HDM_FIRST = 0x1200; + const int HDM_LAYOUT = (HDM_FIRST + 5); + + // System.Diagnostics.Debug.WriteLine(String.Format("WndProc: {0}", m.Msg)); + + switch (m.Msg) { + case WM_SETCURSOR: + if (!this.HandleSetCursor(ref m)) + return; + break; + + case WM_NOTIFY: + if (!this.HandleNotify(ref m)) + return; + break; + + case WM_MOUSEMOVE: + if (!this.HandleMouseMove(ref m)) + return; + break; + + case WM_MOUSELEAVE: + if (!this.HandleMouseLeave(ref m)) + return; + break; + + case HDM_LAYOUT: + if (!this.HandleLayout(ref m)) + return; + break; + + case WM_DESTROY: + if (!this.HandleDestroy(ref m)) + return; + break; + + case WM_LBUTTONDOWN: + if (!this.HandleLButtonDown(ref m)) + return; + break; + + case WM_LBUTTONUP: + if (!this.HandleLButtonUp(ref m)) + return; + break; + } + + base.WndProc(ref m); + } + + private bool HandleReflectNotify(ref Message m) + { + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + // System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr.code)); + return true; + } + + /// + /// Handle the LButtonDown windows message + /// + /// + /// + protected bool HandleLButtonDown(ref Message m) + { + // Was there a header checkbox under the cursor? + this.columnIndexCheckBoxMouseDown = this.GetColumnCheckBoxUnderCursor(); + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Redraw the header so the checkbox redraws + this.Invalidate(); + + // Force the owning control to ignore this mouse click + // We don't want to sort the listview when they click the checkbox + m.Result = (IntPtr)1; + return false; + } + + private int columnIndexCheckBoxMouseDown = -1; + + /// + /// Handle the LButtonUp windows message + /// + /// + /// + protected bool HandleLButtonUp(ref Message m) { + //System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + + // Was the mouse released over a header checkbox? + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Was the mouse released over the same checkbox on which it was pressed? + if (this.columnIndexCheckBoxMouseDown != this.GetColumnCheckBoxUnderCursor()) + return true; + + // Toggle the header's checkbox + OLVColumn column = this.ListView.GetColumn(this.columnIndexCheckBoxMouseDown); + this.ListView.ToggleHeaderCheckBox(column); + + return true; + } + + /// + /// Handle the SetCursor windows message + /// + /// + /// + protected bool HandleSetCursor(ref Message m) { + if (this.IsCursorOverLockedDivider) { + m.Result = (IntPtr) 1; // Don't change the cursor + return false; + } + return true; + } + + /// + /// Handle the MouseMove windows message + /// + /// + /// + protected bool HandleMouseMove(ref Message m) { + + // Forward the mouse move event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) { + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + this.ListView.HandleMouseMove(new Point(x, y)); + } + + int columnIndex = this.ColumnIndexUnderCursor; + + // If the mouse has moved to a different header, pop the current tip (if any) + // For some reason, references this.ToolTip when in design mode, causes the + // columns to not be resizable by dragging the divider in the Designer. No idea why. + if (columnIndex != this.columnShowingTip && !this.ListView.IsDesignMode) { + this.ToolTip.PopToolTip(this); + this.columnShowingTip = columnIndex; + } + + // If the mouse has moved onto or away from a checkbox, we need to draw + int checkBoxUnderCursor = this.GetColumnCheckBoxUnderCursor(); + if (checkBoxUnderCursor != this.lastCheckBoxUnderCursor) { + this.Invalidate(); + this.lastCheckBoxUnderCursor = checkBoxUnderCursor; + } + + return true; + } + + private int columnShowingTip = -1; + private int lastCheckBoxUnderCursor = -1; + + /// + /// Handle the MouseLeave windows message + /// + /// + /// + protected bool HandleMouseLeave(ref Message m) { + // Forward the mouse leave event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) + this.ListView.HandleMouseMove(new Point(-1, -1)); + + return true; + } + + /// + /// Handle the Notify windows message + /// + /// + /// + protected bool HandleNotify(ref Message m) { + // Can this ever happen? JPP 2009-05-22 + if (m.LParam == IntPtr.Zero) + return false; + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (nmhdr.code) + { + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("hdr TTN_SHOW"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleShow(ref m); + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("hdr TTN_POP"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandlePop(ref m); + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("hdr TTN_GETDISPINFO"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleGetDispInfo(ref m); + } + + return false; + } + + /// + /// Handle the CustomDraw windows message + /// + /// + /// + internal virtual bool HandleHeaderCustomDraw(ref Message m) { + const int CDRF_NEWFONT = 2; + const int CDRF_SKIPDEFAULT = 4; + const int CDRF_NOTIFYPOSTPAINT = 0x10; + const int CDRF_NOTIFYITEMDRAW = 0x20; + + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_ITEM = 0x00010000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + + NativeMethods.NMCUSTOMDRAW nmcustomdraw = (NativeMethods.NMCUSTOMDRAW) m.GetLParam(typeof (NativeMethods.NMCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("header cd: {0:x}, {1}, {2:x}", nmcustomdraw.dwDrawStage, nmcustomdraw.dwItemSpec, nmcustomdraw.uItemState)); + switch (nmcustomdraw.dwDrawStage) { + case CDDS_PREPAINT: + this.cachedNeedsCustomDraw = this.NeedsCustomDraw(); + m.Result = (IntPtr) CDRF_NOTIFYITEMDRAW; + return true; + + case CDDS_ITEMPREPAINT: + int columnIndex = nmcustomdraw.dwItemSpec.ToInt32(); + OLVColumn column = this.ListView.GetColumn(columnIndex); + + // These don't work when visual styles are enabled + //NativeMethods.SetBkColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Red)); + //NativeMethods.SetTextColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Blue)); + //m.Result = IntPtr.Zero; + + if (this.cachedNeedsCustomDraw) { + using (Graphics g = Graphics.FromHdc(nmcustomdraw.hdc)) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + this.CustomDrawHeaderCell(g, columnIndex, nmcustomdraw.uItemState); + } + m.Result = (IntPtr) CDRF_SKIPDEFAULT; + } else { + const int CDIS_SELECTED = 1; + bool isPressed = ((nmcustomdraw.uItemState & CDIS_SELECTED) == CDIS_SELECTED); + + // We don't need to modify this based on checkboxes, since there can't be checkboxes if we are here + bool isHot = columnIndex == this.ColumnIndexUnderCursor; + + Font f = this.CalculateFont(column, isHot, isPressed); + + this.fontHandle = f.ToHfont(); + NativeMethods.SelectObject(nmcustomdraw.hdc, this.fontHandle); + + m.Result = (IntPtr) (CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT); + } + + return true; + + case CDDS_ITEMPOSTPAINT: + if (this.fontHandle != IntPtr.Zero) { + NativeMethods.DeleteObject(this.fontHandle); + this.fontHandle = IntPtr.Zero; + } + break; + } + + return false; + } + + private bool cachedNeedsCustomDraw; + private IntPtr fontHandle; + + /// + /// The message divides a ListView's space between the header and the rows of the listview. + /// The WINDOWPOS structure controls the headers bounds, the RECT controls the listview bounds. + /// + /// + /// + protected bool HandleLayout(ref Message m) { + if (this.ListView.HeaderStyle == ColumnHeaderStyle.None) + return true; + + NativeMethods.HDLAYOUT hdlayout = (NativeMethods.HDLAYOUT) m.GetLParam(typeof (NativeMethods.HDLAYOUT)); + NativeMethods.RECT rect = (NativeMethods.RECT) Marshal.PtrToStructure(hdlayout.prc, typeof (NativeMethods.RECT)); + NativeMethods.WINDOWPOS wpos = (NativeMethods.WINDOWPOS) Marshal.PtrToStructure(hdlayout.pwpos, typeof (NativeMethods.WINDOWPOS)); + + using (Graphics g = this.ListView.CreateGraphics()) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + int height = this.CalculateHeight(g); + wpos.hwnd = this.Handle; + wpos.hwndInsertAfter = IntPtr.Zero; + wpos.flags = NativeMethods.SWP_FRAMECHANGED; + wpos.x = rect.left; + wpos.y = rect.top; + wpos.cx = rect.right - rect.left; + wpos.cy = height; + + rect.top = height; + + Marshal.StructureToPtr(rect, hdlayout.prc, false); + Marshal.StructureToPtr(wpos, hdlayout.pwpos, false); + } + + this.ListView.BeginInvoke((MethodInvoker) delegate { + this.Invalidate(); + this.ListView.Invalidate(); + }); + return false; + } + + /// + /// Handle when the underlying header control is destroyed + /// + /// + /// + protected bool HandleDestroy(ref Message m) { + if (this.toolTip != null) { + this.toolTip.Showing -= new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + return false; + } + + #endregion + + #region Rendering + + /// + /// Does this header need to be custom drawn? + /// + /// Word wrapping and colored text require custom drawing. Funnily enough, we + /// can change the font natively. + protected bool NeedsCustomDraw() { + if (this.WordWrap) + return true; + + if (this.ListView.HeaderUsesThemes) + return false; + + if (this.NeedsCustomDraw(this.ListView.HeaderFormatStyle)) + return true; + + foreach (OLVColumn column in this.ListView.Columns) { + if (column.HasHeaderImage || + !column.ShowTextInHeader || + column.IsHeaderVertical || + this.HasFilterIndicator(column) || + this.HasCheckBox(column) || + column.TextAlign != column.HeaderTextAlignOrDefault || + (column.Index == 0 && column.HeaderTextAlignOrDefault != HorizontalAlignment.Left) || + this.NeedsCustomDraw(column.HeaderFormatStyle)) + return true; + } + + return false; + } + + private bool NeedsCustomDraw(HeaderFormatStyle style) { + if (style == null) + return false; + + return (this.NeedsCustomDraw(style.Normal) || + this.NeedsCustomDraw(style.Hot) || + this.NeedsCustomDraw(style.Pressed)); + } + + private bool NeedsCustomDraw(HeaderStateStyle style) { + if (style == null) + return false; + + // If we want fancy colors or frames, we have to custom draw. Oddly enough, we + // can handle font changes without custom drawing. + if (!style.BackColor.IsEmpty) + return true; + + if (style.FrameWidth > 0f && !style.FrameColor.IsEmpty) + return true; + + return (!style.ForeColor.IsEmpty && style.ForeColor != Color.Black); + } + + /// + /// Draw one cell of the header + /// + /// + /// + /// + protected void CustomDrawHeaderCell(Graphics g, int columnIndex, int itemState) { + OLVColumn column = this.ListView.GetColumn(columnIndex); + + bool hasCheckBox = this.HasCheckBox(column); + bool isMouseOverCheckBox = columnIndex == this.lastCheckBoxUnderCursor; + bool isMouseDownOnCheckBox = isMouseOverCheckBox && Control.MouseButtons == MouseButtons.Left; + bool isHot = (columnIndex == this.ColumnIndexUnderCursor) && (!(hasCheckBox && isMouseOverCheckBox)); + + const int CDIS_SELECTED = 1; + bool isPressed = ((itemState & CDIS_SELECTED) == CDIS_SELECTED); + + // System.Diagnostics.Debug.WriteLine(String.Format("{2:hh:mm:ss.ff} - HeaderCustomDraw: {0}, {1}", columnIndex, itemState, DateTime.Now)); + + // Calculate which style should be used for the header + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + + // If there is an owner drawn delegate installed, give it a chance to draw the header + Rectangle fullCellBounds = this.GetItemRect(columnIndex); + if (column.HeaderDrawing != null) + { + if (!column.HeaderDrawing(g, fullCellBounds, columnIndex, column, isPressed, stateStyle)) + return; + } + + // Draw the background + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot); + else + this.DrawUnthemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot, stateStyle); + + Rectangle r = this.GetHeaderDrawRect(columnIndex); + + // Draw the sort indicator if this column has one + if (this.HasSortIndicator(column)) { + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp)) + this.DrawThemedSortIndicator(g, r); + else + r = this.DrawUnthemedSortIndicator(g, r); + } + + if (this.HasFilterIndicator(column)) + r = this.DrawFilterIndicator(g, r); + + if (hasCheckBox) + r = this.DrawCheckBox(g, r, column.HeaderCheckState, column.HeaderCheckBoxDisabled, isMouseOverCheckBox, isMouseDownOnCheckBox); + + // Debugging - Where is the text going to be drawn + // g.DrawRectangle(Pens.Blue, r); + + // Finally draw the text + this.DrawHeaderImageAndText(g, r, column, stateStyle); + } + + private Rectangle DrawCheckBox(Graphics g, Rectangle r, CheckState checkState, bool isDisabled, bool isHot, + bool isPressed) { + CheckBoxState checkBoxState = this.GetCheckBoxState(checkState, isDisabled, isHot, isPressed); + Rectangle checkBoxBounds = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, checkBoxBounds.Location, checkBoxState); + + // Move the left edge without changing the right edge + int newX = checkBoxBounds.Right + 3; + r.Width -= (newX - r.X); + r.X = newX; + + return r; + } + + private Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.CheckedNormal); + + // Vertically center the checkbox + int topOffset = (cellBounds.Height - checkBoxSize.Height)/2; + return new Rectangle(cellBounds.X + 3, cellBounds.Y + topOffset, checkBoxSize.Width, checkBoxSize.Height); + } + + private CheckBoxState GetCheckBoxState(CheckState checkState, bool isDisabled, bool isHot, bool isPressed) { + // Should the checkbox be drawn as disabled? + if (isDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the mouse button currently down? + if (isPressed) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedPressed; + case CheckState.Unchecked: + return CheckBoxState.UncheckedPressed; + default: + return CheckBoxState.MixedPressed; + } + } + + // Is the cursor currently over this checkbox? + if (isHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + } + + /// + /// Draw a background for the header, without using Themes. + /// + /// + /// + /// + /// + /// + /// + protected void DrawUnthemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot, HeaderStateStyle stateStyle) { + if (stateStyle.BackColor.IsEmpty) + // I know we're supposed to be drawing the unthemed background, but let's just see if we + // can draw something more interesting than the dull raised block + if (VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, r, columnIndex, isPressed, isHot); + else + ControlPaint.DrawBorder3D(g, r, Border3DStyle.RaisedInner); + else { + using (Brush b = new SolidBrush(stateStyle.BackColor)) + g.FillRectangle(b, r); + } + + // Draw the frame if the style asks for one + if (!stateStyle.FrameColor.IsEmpty && stateStyle.FrameWidth > 0f) { + RectangleF r2 = r; + r2.Inflate(-stateStyle.FrameWidth, -stateStyle.FrameWidth); + using (Pen pen = new Pen(stateStyle.FrameColor, stateStyle.FrameWidth)) + g.DrawRectangle(pen, r2.X, r2.Y, r2.Width, r2.Height); + } + } + + /// + /// Draw a more-or-less pure themed header background. + /// + /// + /// + /// + /// + /// + protected void DrawThemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot) { + int part = 1; // normal item + if (columnIndex == 0 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemLeft.Normal)) + part = 2; // left item + if (columnIndex == this.ListView.Columns.Count - 1 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemRight.Normal)) + part = 3; // right item + + int state = 1; // normal state + if (isPressed) + state = 3; // pressed + else if (isHot) + state = 2; // hot + + VisualStyleRenderer renderer = new VisualStyleRenderer("HEADER", part, state); + renderer.DrawBackground(g, r); + } + + /// + /// Draw a sort indicator using themes + /// + /// + /// + protected void DrawThemedSortIndicator(Graphics g, Rectangle r) { + VisualStyleRenderer renderer2 = null; + if (this.ListView.LastSortOrder == SortOrder.Ascending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedUp); + if (this.ListView.LastSortOrder == SortOrder.Descending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedDown); + if (renderer2 != null) { + Size sz = renderer2.GetPartSize(g, ThemeSizeType.True); + Point pt = renderer2.GetPoint(PointProperty.Offset); + // GetPoint() should work, but if it doesn't, put the arrow in the top middle + if (pt.X == 0 && pt.Y == 0) + pt = new Point(r.X + (r.Width/2) - (sz.Width/2), r.Y); + renderer2.DrawBackground(g, new Rectangle(pt, sz)); + } + } + + /// + /// Draw a sort indicator without using themes + /// + /// + /// + /// + protected Rectangle DrawUnthemedSortIndicator(Graphics g, Rectangle r) { + // No theme support for sort indicators. So, we draw a triangle at the right edge + // of the column header. + const int triangleHeight = 16; + const int triangleWidth = 16; + const int midX = triangleWidth/2; + const int midY = (triangleHeight/2) - 1; + const int deltaX = midX - 2; + const int deltaY = deltaX/2; + + Point triangleLocation = new Point(r.Right - triangleWidth - 2, r.Top + (r.Height - triangleHeight)/2); + Point[] pts = new Point[] {triangleLocation, triangleLocation, triangleLocation}; + + if (this.ListView.LastSortOrder == SortOrder.Ascending) { + pts[0].Offset(midX - deltaX, midY + deltaY); + pts[1].Offset(midX, midY - deltaY - 1); + pts[2].Offset(midX + deltaX, midY + deltaY); + } else { + pts[0].Offset(midX - deltaX, midY - deltaY); + pts[1].Offset(midX, midY + deltaY); + pts[2].Offset(midX + deltaX, midY - deltaY); + } + + g.FillPolygon(Brushes.SlateGray, pts); + r.Width = r.Width - triangleWidth; + return r; + } + + /// + /// Draw an indication that this column has a filter applied to it + /// + /// + /// + /// + protected Rectangle DrawFilterIndicator(Graphics g, Rectangle r) { + int width = this.CalculateFilterIndicatorWidth(r); + if (width <= 0) + return r; + + Image indicator = Resources.ColumnFilterIndicator; + int x = r.Right - width; + int y = r.Top + (r.Height - indicator.Height)/2; + g.DrawImageUnscaled(indicator, x, y); + + r.Width -= width; + return r; + } + + private int CalculateFilterIndicatorWidth(Rectangle r) { + if (Resources.ColumnFilterIndicator == null || r.Width < 48) + return 0; + return Resources.ColumnFilterIndicator.Width + 1; + } + + /// + /// Draw the header's image and text + /// + /// + /// + /// + /// + protected void DrawHeaderImageAndText(Graphics g, Rectangle r, OLVColumn column, HeaderStateStyle stateStyle) { + + TextFormatFlags flags = this.TextFormatFlags; + flags |= TextFormatFlags.VerticalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + flags |= TextFormatFlags.HorizontalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + flags |= TextFormatFlags.Right; + + Font f = this.ListView.HeaderUsesThemes ? this.ListView.Font : stateStyle.Font ?? this.ListView.Font; + Color color = this.ListView.HeaderUsesThemes ? Color.Black : stateStyle.ForeColor; + if (color.IsEmpty) + color = Color.Black; + + const int imageTextGap = 3; + + if (column.IsHeaderVertical) { + DrawVerticalText(g, r, column, f, color); + } else { + // Does the column have a header image and is there space for it? + if (column.HasHeaderImage && r.Width > column.ImageList.ImageSize.Width*2) + DrawImageAndText(g, r, column, flags, f, color, imageTextGap); + else + DrawText(g, r, column, flags, f, color); + } + } + + private void DrawText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, Color color) { + if (column.ShowTextInHeader) + TextRenderer.DrawText(g, column.Text, f, r, color, Color.Transparent, flags); + } + + private void DrawImageAndText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, + Color color, int imageTextGap) { + Rectangle textRect = r; + textRect.X += (column.ImageList.ImageSize.Width + imageTextGap); + textRect.Width -= (column.ImageList.ImageSize.Width + imageTextGap); + + Size textSize = Size.Empty; + if (column.ShowTextInHeader) + textSize = TextRenderer.MeasureText(g, column.Text, f, textRect.Size, flags); + + int imageY = r.Top + ((r.Height - column.ImageList.ImageSize.Height)/2); + int imageX = textRect.Left; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + imageX = textRect.Left + ((textRect.Width - textSize.Width)/2); + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + imageX = textRect.Right - textSize.Width; + imageX -= (column.ImageList.ImageSize.Width + imageTextGap); + + column.ImageList.Draw(g, imageX, imageY, column.ImageList.Images.IndexOfKey(column.HeaderImageKey)); + + this.DrawText(g, textRect, column, flags, f, color); + } + + private static void DrawVerticalText(Graphics g, Rectangle r, OLVColumn column, Font f, Color color) { + try { + // Create a matrix transformation that will rotate the text 90 degrees vertically + // AND place the text in the middle of where it was previously. [Think of tipping + // a box over by its bottom left edge -- you have to move it back a bit so it's + // in the same place as it started] + Matrix m = new Matrix(); + m.RotateAt(-90, new Point(r.X, r.Bottom)); + m.Translate(0, r.Height); + g.Transform = m; + StringFormat fmt = new StringFormat(StringFormatFlags.NoWrap); + fmt.Alignment = StringAlignment.Near; + fmt.LineAlignment = column.HeaderTextAlignAsStringAlignment; + //fmt.Trimming = StringTrimming.EllipsisCharacter; + + // The drawing is rotated 90 degrees, so switch our text boundaries + Rectangle textRect = r; + textRect.Width = r.Height; + textRect.Height = r.Width; + using (Brush b = new SolidBrush(color)) + g.DrawString(column.Text, f, b, textRect, fmt); + } + finally { + g.ResetTransform(); + } + } + + /// + /// Return the header format that should be used for the given column + /// + /// + /// + protected HeaderFormatStyle CalculateHeaderStyle(OLVColumn column) { + return column.HeaderFormatStyle ?? this.ListView.HeaderFormatStyle ?? new HeaderFormatStyle(); + } + + /// + /// What style should be applied to the header? + /// + /// + /// + /// + /// + protected HeaderStateStyle CalculateStateStyle(OLVColumn column, bool isHot, bool isPressed) { + HeaderFormatStyle headerStyle = this.CalculateHeaderStyle(column); + if (this.ListView.IsDesignMode) + return headerStyle.Normal; + if (isPressed) + return headerStyle.Pressed; + if (isHot) + return headerStyle.Hot; + return headerStyle.Normal; + } + + /// + /// What font should be used to draw the header text? + /// + /// + /// + /// + /// + protected Font CalculateFont(OLVColumn column, bool isHot, bool isPressed) { + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + return stateStyle.Font ?? this.ListView.Font; + } + + /// + /// What flags will be used when drawing text + /// + protected TextFormatFlags TextFormatFlags { + get { + TextFormatFlags flags = TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPrefix | + TextFormatFlags.WordEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.WordWrap) + flags |= TextFormatFlags.WordBreak; + else + flags |= TextFormatFlags.SingleLine; + if (this.ListView.RightToLeft == RightToLeft.Yes) + flags |= TextFormatFlags.RightToLeft; + + return flags; + } + } + + /// + /// Perform a HitTest for the header control + /// + /// + /// + /// Null if the given point isn't over the header + internal OlvListViewHitTestInfo.HeaderHitTestInfo HitTest(int x, int y) + { + Rectangle r = this.ClientRectangle; + if (!r.Contains(x, y)) + return null; + + Point pt = new Point(x + this.ListView.LowLevelScrollPosition.X, y); + + OlvListViewHitTestInfo.HeaderHitTestInfo hti = new OlvListViewHitTestInfo.HeaderHitTestInfo(); + hti.ColumnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + hti.IsOverCheckBox = this.IsPointOverHeaderCheckBox(hti.ColumnIndex, pt); + hti.OverDividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + + return hti; + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolStripCheckedListBox.cs b/ObjectListView/SubControls/ToolStripCheckedListBox.cs new file mode 100644 index 0000000..e8eab01 --- /dev/null +++ b/ObjectListView/SubControls/ToolStripCheckedListBox.cs @@ -0,0 +1,189 @@ +/* + * ToolStripCheckedListBox - Puts a CheckedListBox into a tool strip menu item + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class put a CheckedListBox into a tool strip menu item. + /// + public class ToolStripCheckedListBox : ToolStripControlHost { + + /// + /// Create a ToolStripCheckedListBox + /// + public ToolStripCheckedListBox() + : base(new CheckedListBox()) { + this.CheckedListBoxControl.MaximumSize = new Size(400, 700); + this.CheckedListBoxControl.ThreeDCheckBoxes = true; + this.CheckedListBoxControl.CheckOnClick = true; + this.CheckedListBoxControl.SelectionMode = SelectionMode.One; + } + + /// + /// Gets the control embedded in the menu + /// + public CheckedListBox CheckedListBoxControl { + get { + return Control as CheckedListBox; + } + } + + /// + /// Gets the items shown in the checkedlistbox + /// + public CheckedListBox.ObjectCollection Items { + get { + return this.CheckedListBoxControl.Items; + } + } + + /// + /// Gets or sets whether an item should be checked when it is clicked + /// + public bool CheckedOnClick { + get { + return this.CheckedListBoxControl.CheckOnClick; + } + set { + this.CheckedListBoxControl.CheckOnClick = value; + } + } + + /// + /// Gets a collection of the checked items + /// + public CheckedListBox.CheckedItemCollection CheckedItems { + get { + return this.CheckedListBoxControl.CheckedItems; + } + } + + /// + /// Add a possibly checked item to the control + /// + /// + /// + public void AddItem(object item, bool isChecked) { + this.Items.Add(item); + if (isChecked) + this.CheckedListBoxControl.SetItemChecked(this.Items.Count - 1, true); + } + + /// + /// Add an item with the given state to the control + /// + /// + /// + public void AddItem(object item, CheckState state) { + this.Items.Add(item); + this.CheckedListBoxControl.SetItemCheckState(this.Items.Count - 1, state); + } + + /// + /// Gets the checkedness of the i'th item + /// + /// + /// + public CheckState GetItemCheckState(int i) { + return this.CheckedListBoxControl.GetItemCheckState(i); + } + + /// + /// Set the checkedness of the i'th item + /// + /// + /// + public void SetItemState(int i, CheckState checkState) { + if (i >= 0 && i < this.Items.Count) + this.CheckedListBoxControl.SetItemCheckState(i, checkState); + } + + /// + /// Check all the items in the control + /// + public void CheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, true); + } + + /// + /// Unchecked all the items in the control + /// + public void UncheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, false); + } + + #region Events + + /// + /// Listen for events on the underlying control + /// + /// + protected override void OnSubscribeControlEvents(Control c) { + base.OnSubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck += new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Stop listening for events on the underlying control + /// + /// + protected override void OnUnsubscribeControlEvents(Control c) { + base.OnUnsubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck -= new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Tell the world that an item was checked + /// + public event ItemCheckEventHandler ItemCheck; + + /// + /// Trigger the ItemCheck event + /// + /// + /// + private void OnItemCheck(object sender, ItemCheckEventArgs e) { + if (ItemCheck != null) { + ItemCheck(this, e); + } + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolTipControl.cs b/ObjectListView/SubControls/ToolTipControl.cs new file mode 100644 index 0000000..22c1f63 --- /dev/null +++ b/ObjectListView/SubControls/ToolTipControl.cs @@ -0,0 +1,699 @@ +/* + * ToolTipControl - A limited wrapper around a Windows tooltip control + * + * For some reason, the ToolTip class in the .NET framework is implemented in a significantly + * different manner to other controls. For our purposes, the worst of these problems + * is that we cannot get the Handle, so we cannot send Windows level messages to the control. + * + * Author: Phillip Piper + * Date: 2009-05-17 7:22PM + * + * Change log: + * v2.3 + * 2009-06-13 JPP - Moved ToolTipShowingEventArgs to Events.cs + * v2.2 + * 2009-06-06 JPP - Fixed some Vista specific problems + * 2009-05-17 JPP - Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using System.Security.Permissions; + +namespace BrightIdeasSoftware +{ + /// + /// A limited wrapper around a Windows tooltip window. + /// + public class ToolTipControl : NativeWindow + { + #region Constants + + /// + /// These are the standard icons that a tooltip can display. + /// + public enum StandardIcons + { + /// + /// No icon + /// + None = 0, + + /// + /// Info + /// + Info = 1, + + /// + /// Warning + /// + Warning = 2, + + /// + /// Error + /// + Error = 3, + + /// + /// Large info (Vista and later only) + /// + InfoLarge = 4, + + /// + /// Large warning (Vista and later only) + /// + WarningLarge = 5, + + /// + /// Large error (Vista and later only) + /// + ErrorLarge = 6 + } + + const int GWL_STYLE = -16; + const int WM_GETFONT = 0x31; + const int WM_SETFONT = 0x30; + const int WS_BORDER = 0x800000; + const int WS_EX_TOPMOST = 8; + + const int TTM_ADDTOOL = 0x432; + const int TTM_ADJUSTRECT = 0x400 + 31; + const int TTM_DELTOOL = 0x433; + const int TTM_GETBUBBLESIZE = 0x400 + 30; + const int TTM_GETCURRENTTOOL = 0x400 + 59; + const int TTM_GETTIPBKCOLOR = 0x400 + 22; + const int TTM_GETTIPTEXTCOLOR = 0x400 + 23; + const int TTM_GETDELAYTIME = 0x400 + 21; + const int TTM_NEWTOOLRECT = 0x400 + 52; + const int TTM_POP = 0x41c; + const int TTM_SETDELAYTIME = 0x400 + 3; + const int TTM_SETMAXTIPWIDTH = 0x400 + 24; + const int TTM_SETTIPBKCOLOR = 0x400 + 19; + const int TTM_SETTIPTEXTCOLOR = 0x400 + 20; + const int TTM_SETTITLE = 0x400 + 33; + const int TTM_SETTOOLINFO = 0x400 + 54; + + const int TTF_IDISHWND = 1; + //const int TTF_ABSOLUTE = 0x80; + const int TTF_CENTERTIP = 2; + const int TTF_RTLREADING = 4; + const int TTF_SUBCLASS = 0x10; + //const int TTF_TRACK = 0x20; + //const int TTF_TRANSPARENT = 0x100; + const int TTF_PARSELINKS = 0x1000; + + const int TTS_NOPREFIX = 2; + const int TTS_BALLOON = 0x40; + const int TTS_USEVISUALSTYLE = 0x100; + + const int TTN_FIRST = -520; + + /// + /// + /// + public const int TTN_SHOW = (TTN_FIRST - 1); + + /// + /// + /// + public const int TTN_POP = (TTN_FIRST - 2); + + /// + /// + /// + public const int TTN_LINKCLICK = (TTN_FIRST - 3); + + /// + /// + /// + public const int TTN_GETDISPINFO = (TTN_FIRST - 10); + + const int TTDT_AUTOMATIC = 0; + const int TTDT_RESHOW = 1; + const int TTDT_AUTOPOP = 2; + const int TTDT_INITIAL = 3; + + #endregion + + #region Properties + + /// + /// Get or set if the style of the tooltip control + /// + internal int WindowStyle { + get { + return (int)NativeMethods.GetWindowLong(this.Handle, GWL_STYLE); + } + set { + NativeMethods.SetWindowLong(this.Handle, GWL_STYLE, value); + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool IsBalloon { + get { + return (this.WindowStyle & TTS_BALLOON) == TTS_BALLOON; + } + set { + if (this.IsBalloon == value) + return; + + int windowStyle = this.WindowStyle; + if (value) { + windowStyle |= (TTS_BALLOON | TTS_USEVISUALSTYLE); + // On XP, a border makes the balloon look wrong + if (!ObjectListView.IsVistaOrLater) + windowStyle &= ~WS_BORDER; + } else { + windowStyle &= ~(TTS_BALLOON | TTS_USEVISUALSTYLE); + if (!ObjectListView.IsVistaOrLater) { + if (this.hasBorder) + windowStyle |= WS_BORDER; + else + windowStyle &= ~WS_BORDER; + } + } + this.WindowStyle = windowStyle; + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool HasBorder { + get { + return this.hasBorder; + } + set { + if (this.hasBorder == value) + return; + + if (value) { + this.WindowStyle |= WS_BORDER; + } else { + this.WindowStyle &= ~WS_BORDER; + } + } + } + private bool hasBorder = true; + + /// + /// Get or set the background color of the tooltip + /// + public Color BackColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPBKCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPBKCOLOR, color, 0); + //int x2 = Marshal.GetLastWin32Error(); + } + } + } + + /// + /// Get or set the color of the text and border on the tooltip. + /// + public Color ForeColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPTEXTCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPTEXTCOLOR, color, 0); + } + } + } + + /// + /// Get or set the title that will be shown on the tooltip. + /// + public string Title { + get { + return this.title; + } + set { + if (String.IsNullOrEmpty(value)) + this.title = String.Empty; + else + if (value.Length >= 100) + this.title = value.Substring(0, 99); + else + this.title = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private string title; + + /// + /// Get or set the icon that will be shown on the tooltip. + /// + public StandardIcons StandardIcon { + get { + return this.standardIcon; + } + set { + this.standardIcon = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private StandardIcons standardIcon; + + /// + /// Gets or sets the font that will be used to draw this control. + /// is still. + /// + /// Setting this to null reverts to the default font. + public Font Font { + get { + IntPtr hfont = NativeMethods.SendMessage(this.Handle, WM_GETFONT, 0, 0); + if (hfont == IntPtr.Zero) + return Control.DefaultFont; + else + return Font.FromHfont(hfont); + } + set { + Font newFont = value ?? Control.DefaultFont; + if (newFont == this.font) + return; + + this.font = newFont; + IntPtr hfont = this.font.ToHfont(); // THINK: When should we delete this hfont? + NativeMethods.SendMessage(this.Handle, WM_SETFONT, hfont, 0); + } + } + private Font font; + + /// + /// Gets or sets how many milliseconds the tooltip will remain visible while the mouse + /// is still. + /// + public int AutoPopDelay { + get { return this.GetDelayTime(TTDT_AUTOPOP); } + set { this.SetDelayTime(TTDT_AUTOPOP, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown. + /// + public int InitialDelay { + get { return this.GetDelayTime(TTDT_INITIAL); } + set { this.SetDelayTime(TTDT_INITIAL, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown again. + /// + public int ReshowDelay { + get { return this.GetDelayTime(TTDT_RESHOW); } + set { this.SetDelayTime(TTDT_RESHOW, value); } + } + + private int GetDelayTime(int which) { + return (int)NativeMethods.SendMessage(this.Handle, TTM_GETDELAYTIME, which, 0); + } + + private void SetDelayTime(int which, int value) { + NativeMethods.SendMessage(this.Handle, TTM_SETDELAYTIME, which, value); + } + + #endregion + + #region Commands + + /// + /// Create the underlying control. + /// + /// The parent of the tooltip + /// This does nothing if the control has already been created + public void Create(IntPtr parentHandle) { + if (this.Handle != IntPtr.Zero) + return; + + CreateParams cp = new CreateParams(); + cp.ClassName = "tooltips_class32"; + cp.Style = TTS_NOPREFIX; + cp.ExStyle = WS_EX_TOPMOST; + cp.Parent = parentHandle; + this.CreateHandle(cp); + + // Ensure that multiline tooltips work correctly + this.SetMaxWidth(); + } + + /// + /// Take a copy of the current settings and restore them when the + /// tooltip is popped. + /// + /// + /// This call cannot be nested. Subsequent calls to this method will be ignored + /// until PopSettings() is called. + /// + public void PushSettings() { + // Ignore any nested calls + if (this.settings != null) + return; + this.settings = new Hashtable(); + this.settings["IsBalloon"] = this.IsBalloon; + this.settings["HasBorder"] = this.HasBorder; + this.settings["BackColor"] = this.BackColor; + this.settings["ForeColor"] = this.ForeColor; + this.settings["Title"] = this.Title; + this.settings["StandardIcon"] = this.StandardIcon; + this.settings["AutoPopDelay"] = this.AutoPopDelay; + this.settings["InitialDelay"] = this.InitialDelay; + this.settings["ReshowDelay"] = this.ReshowDelay; + this.settings["Font"] = this.Font; + } + private Hashtable settings; + + /// + /// Restore the settings of the tooltip as they were when PushSettings() + /// was last called. + /// + public void PopSettings() { + if (this.settings == null) + return; + + this.IsBalloon = (bool)this.settings["IsBalloon"]; + this.HasBorder = (bool)this.settings["HasBorder"]; + this.BackColor = (Color)this.settings["BackColor"]; + this.ForeColor = (Color)this.settings["ForeColor"]; + this.Title = (string)this.settings["Title"]; + this.StandardIcon = (StandardIcons)this.settings["StandardIcon"]; + this.AutoPopDelay = (int)this.settings["AutoPopDelay"]; + this.InitialDelay = (int)this.settings["InitialDelay"]; + this.ReshowDelay = (int)this.settings["ReshowDelay"]; + this.Font = (Font)this.settings["Font"]; + + this.settings = null; + } + + /// + /// Add the given window to those for whom this tooltip will show tips + /// + /// The window + public void AddTool(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_ADDTOOL, 0, lParam); + } + + /// + /// Hide any currently visible tooltip + /// + /// + public void PopToolTip(IWin32Window window) { + NativeMethods.SendMessage(this.Handle, TTM_POP, 0, 0); + } + + //public void Munge() { + // NativeMethods.TOOLINFO tool = new NativeMethods.TOOLINFO(); + // IntPtr result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETCURRENTTOOL, 0, tool); + // System.Diagnostics.Trace.WriteLine("-"); + // System.Diagnostics.Trace.WriteLine(result); + // result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETBUBBLESIZE, 0, tool); + // System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", result.ToInt32() >> 16, result.ToInt32() & 0xFFFF)); + // NativeMethods.ChangeSize(this, result.ToInt32() & 0xFFFF, result.ToInt32() >> 16); + // //NativeMethods.RECT r = new NativeMethods.RECT(); + // //r.right + // //IntPtr x = NativeMethods.SendMessageRECT(this.Handle, TTM_ADJUSTRECT, true, ref r); + + // //System.Diagnostics.Trace.WriteLine(String.Format("{0} {1} {2} {3}", r.left, r.top, r.right, r.bottom)); + //} + + /// + /// Remove the given window from those managed by this tooltip + /// + /// + public void RemoveToolTip(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_DELTOOL, 0, lParam); + } + + /// + /// Set the maximum width of a tooltip string. + /// + public void SetMaxWidth() { + this.SetMaxWidth(SystemInformation.MaxWindowTrackSize.Width); + } + + /// + /// Set the maximum width of a tooltip string. + /// + /// Setting this ensures that line breaks in the tooltip are honoured. + public void SetMaxWidth(int maxWidth) { + NativeMethods.SendMessage(this.Handle, TTM_SETMAXTIPWIDTH, 0, maxWidth); + } + + #endregion + + #region Implementation + + /// + /// Make a TOOLINFO structure for the given window + /// + /// + /// A filled in TOOLINFO + private NativeMethods.TOOLINFO MakeToolInfoStruct(IWin32Window window) { + + NativeMethods.TOOLINFO toolinfo_tooltip = new NativeMethods.TOOLINFO(); + toolinfo_tooltip.hwnd = window.Handle; + toolinfo_tooltip.uFlags = TTF_IDISHWND | TTF_SUBCLASS; + toolinfo_tooltip.uId = window.Handle; + toolinfo_tooltip.lpszText = (IntPtr)(-1); // LPSTR_TEXTCALLBACK + + return toolinfo_tooltip; + } + + /// + /// Handle a WmNotify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleNotify(ref Message msg) { + + //THINK: What do we have to do here? Nothing it seems :) + + //NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Trace.WriteLine("HandleNotify"); + //System.Diagnostics.Trace.WriteLine(nmheader.nhdr.code); + + //switch (nmheader.nhdr.code) { + //} + + return false; + } + + /// + /// Handle a get display info message + /// + /// The msg + /// True if the message has been handled + public virtual bool HandleGetDispInfo(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleGetDispInfo"); + this.SetMaxWidth(); + ToolTipShowingEventArgs args = new ToolTipShowingEventArgs(); + args.ToolTipControl = this; + this.OnShowing(args); + if (String.IsNullOrEmpty(args.Text)) + return false; + + this.ApplyEventFormatting(args); + + NativeMethods.NMTTDISPINFO dispInfo = (NativeMethods.NMTTDISPINFO)msg.GetLParam(typeof(NativeMethods.NMTTDISPINFO)); + dispInfo.lpszText = args.Text; + dispInfo.hinst = IntPtr.Zero; + if (args.RightToLeft == RightToLeft.Yes) + dispInfo.uFlags |= TTF_RTLREADING; + Marshal.StructureToPtr(dispInfo, msg.LParam, false); + + return true; + } + + private void ApplyEventFormatting(ToolTipShowingEventArgs args) { + if (!args.IsBalloon.HasValue && + !args.BackColor.HasValue && + !args.ForeColor.HasValue && + args.Title == null && + !args.StandardIcon.HasValue && + !args.AutoPopDelay.HasValue && + args.Font == null) + return; + + this.PushSettings(); + if (args.IsBalloon.HasValue) + this.IsBalloon = args.IsBalloon.Value; + if (args.BackColor.HasValue) + this.BackColor = args.BackColor.Value; + if (args.ForeColor.HasValue) + this.ForeColor = args.ForeColor.Value; + if (args.StandardIcon.HasValue) + this.StandardIcon = args.StandardIcon.Value; + if (args.AutoPopDelay.HasValue) + this.AutoPopDelay = args.AutoPopDelay.Value; + if (args.Font != null) + this.Font = args.Font; + if (args.Title != null) + this.Title = args.Title; + } + + /// + /// Handle a TTN_LINKCLICK message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleLinkClick(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleLinkClick"); + return false; + } + + /// + /// Handle a TTN_POP message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandlePop(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandlePop"); + this.PopSettings(); + return true; + } + + /// + /// Handle a TTN_SHOW message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleShow(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleShow"); + return false; + } + + /// + /// Handle a reflected notify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleReflectNotify(ref Message msg) { + + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + switch (nmheader.nhdr.code) { + case TTN_SHOW: + //System.Diagnostics.Trace.WriteLine("reflect TTN_SHOW"); + if (this.HandleShow(ref msg)) + return true; + break; + case TTN_POP: + //System.Diagnostics.Trace.WriteLine("reflect TTN_POP"); + if (this.HandlePop(ref msg)) + return true; + break; + case TTN_LINKCLICK: + //System.Diagnostics.Trace.WriteLine("reflect TTN_LINKCLICK"); + if (this.HandleLinkClick(ref msg)) + return true; + break; + case TTN_GETDISPINFO: + //System.Diagnostics.Trace.WriteLine("reflect TTN_GETDISPINFO"); + if (this.HandleGetDispInfo(ref msg)) + return true; + break; + } + + return false; + } + + /// + /// Mess with the basic message pump of the tooltip + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + override protected void WndProc(ref Message msg) { + //System.Diagnostics.Trace.WriteLine(String.Format("xx {0:x}", msg.Msg)); + switch (msg.Msg) { + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref msg)) + return; + break; + + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref msg)) + return; + break; + } + + base.WndProc(ref msg); + } + + #endregion + + #region Events + + /// + /// Tell the world that a tooltip is about to show + /// + public event EventHandler Showing; + + /// + /// Tell the world that a tooltip is about to disappear + /// + public event EventHandler Pop; + + /// + /// + /// + /// + protected virtual void OnShowing(ToolTipShowingEventArgs e) { + if (this.Showing != null) + this.Showing(this, e); + } + + /// + /// + /// + /// + protected virtual void OnPop(EventArgs e) { + if (this.Pop != null) + this.Pop(this, e); + } + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/TreeListView.cs b/ObjectListView/TreeListView.cs new file mode 100644 index 0000000..0b52c63 --- /dev/null +++ b/ObjectListView/TreeListView.cs @@ -0,0 +1,2269 @@ +/* + * TreeListView - A listview that can show a tree of objects in a column + * + * Author: Phillip Piper + * Date: 23/09/2008 11:15 AM + * + * Change log: + * 2018-05-03 JPP - Added ITreeModel to allow models to provide the required information to TreeListView. + * 2018-04-30 JPP - Fix small visual glitch where connecting lines were not correctly drawn when filters changed + * v2.9.2 + * 2016-06-02 JPP - Added bounds check to GetNthObject(). + * v2.9 + * 2015-08-02 JPP - Fixed buy with hierarchical checkboxes where setting the checkedness of a deeply + * nested object would sometimes not correctly calculate the changes in the hierarchy. SF #150. + * 2015-06-27 JPP - Corrected small UI glitch when focus was lost and HideSelection was false. SF #135. + * v2.8.1 + * 2014-11-28 JPP - Fixed issue in RefreshObject() where a model with less children than previous that could not + * longer be expanded would cause an exception. + * 2014-11-23 JPP - Fixed an issue where collapsing a branch could leave the internal object->index map out of date. + * v2.8 + * 2014-10-08 JPP - Fixed an issue where pre-expanded branches would not initially expand properly + * 2014-09-29 JPP - Fixed issue where RefreshObject() on a root object could cause exceptions + * - Fixed issue where CollapseAll() while filtering could cause exception + * 2014-03-09 JPP - Fixed issue where removing a branches only child and then calling RefreshObject() + * could throw an exception. + * v2.7 + * 2014-02-23 JPP - Added Reveal() method to show a deeply nested models. + * 2014-02-05 JPP - Fix issue where refreshing a non-root item would collapse all expanded children of that item + * 2014-02-01 JPP - ClearObjects() now actually, you know, clears objects :) + * - Corrected issue where Expanded event was being raised twice. + * - RebuildChildren() no longer checks if CanExpand is true before rebuilding. + * 2014-01-16 JPP - Corrected an off-by-1 error in hit detection, which meant that clicking in the last 16 pixels + * of an items label was being ignored. + * 2013-11-20 JPP - Moved event triggers into Collapse() and Expand() so that the events are always triggered. + * - CheckedObjects now includes objects that are in a branch that is currently collapsed + * - CollapseAll() and ExpandAll() now trigger cancellable events + * 2013-09-29 JPP - Added TreeFactory to allow the underlying Tree to be replaced by another implementation. + * 2013-09-23 JPP - Fixed long standing issue where RefreshObject() would not work on root objects + * which overrode Equals()/GetHashCode(). + * 2013-02-23 JPP - Added HierarchicalCheckboxes. When this is true, the checkedness of a parent + * is an synopsis of the checkedness of its children. When all children are checked, + * the parent is checked. When all children are unchecked, the parent is unchecked. + * If some children are checked and some are not, the parent is indeterminate. + * v2.6 + * 2012-10-25 JPP - Circumvent annoying issue in ListView control where changing + * selection would leave artefacts on the control. + * 2012-08-10 JPP - Don't trigger selection changed events during expands + * + * v2.5.1 + * 2012-04-30 JPP - Fixed issue where CheckedObjects would return model objects that had been filtered out. + * - Allow any column to render the tree, not just column 0 (still not sure about this one) + * v2.5.0 + * 2011-04-20 JPP - Added ExpandedObjects property and RebuildAll() method. + * 2011-04-09 JPP - Added Expanding, Collapsing, Expanded and Collapsed events. + * The ..ing events are cancellable. These are only fired in response + * to user actions. + * v2.4.1 + * 2010-06-15 JPP - Fixed issue in Tree.RemoveObjects() which resulted in removed objects + * being reported as still existing. + * v2.3 + * 2009-09-01 JPP - Fixed off-by-one error that was messing up hit detection + * 2009-08-27 JPP - Fixed issue when dragging a node from one place to another in the tree + * v2.2.1 + * 2009-07-14 JPP - Clicks to the left of the expander in tree cells are now ignored. + * v2.2 + * 2009-05-12 JPP - Added tree traverse operations: GetParent and GetChildren. + * - Added DiscardAllState() to completely reset the TreeListView. + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-09 JPP - Fixed issue where any command (Expand/Collapse/Refresh) on a model + * object that was once visible but that is currently in a collapsed branch + * would cause the control to crash. + * 2009-05-07 JPP - Fixed issue where RefreshObjects() would fail when none of the given + * objects were present/visible. + * 2009-04-20 JPP - Fixed issue where calling Expand() on an already expanded branch confused + * the display of the children (SF#2499313) + * 2009-03-06 JPP - Calculate edit rectangle on column 0 more accurately + * v2.1 + * 2009-02-24 JPP - All commands now work when the list is empty (SF #2631054) + * - TreeListViews can now be printed with ListViewPrinter + * 2009-01-27 JPP - Changed to use new Renderer and HitTest scheme + * 2009-01-22 JPP - Added RevealAfterExpand property. If this is true (the default), + * after expanding a branch, the control scrolls to reveal as much of the + * expanded branch as possible. + * 2009-01-13 JPP - Changed TreeRenderer to work with visual styles are disabled + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * - Changed some classes from 'internal' to 'protected' so that they + * can be accessed by subclasses of TreeListView. + * 2008-12-22 JPP - Added UseWaitCursorWhenExpanding property + * - Made TreeRenderer public so that it can be subclassed + * - Added LinePen property to TreeRenderer to allow the connection drawing + * pen to be changed + * - Fixed some rendering issues where the text highlight rect was miscalculated + * - Fixed connection line problem when there is only a single root + * v2.0 + * 2008-12-10 JPP - Expand/collapse with mouse now works when there is no SmallImageList. + * 2008-12-01 JPP - Search-by-typing now works. + * 2008-11-26 JPP - Corrected calculation of expand/collapse icon (SF#2338819) + * - Fixed ugliness with dotted lines in renderer (SF#2332889) + * - Fixed problem with custom selection colors (SF#2338805) + * 2008-11-19 JPP - Expand/collapse now preserve the selection -- more or less :) + * - Overrode RefreshObjects() to rebuild the given objects and their children + * 2008-11-05 JPP - Added ExpandAll() and CollapseAll() commands + * - CanExpand is no longer cached + * - Renamed InitialBranches to RootModels since it deals with model objects + * 2008-09-23 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeListView combines an expandable tree structure with list view columns. + /// + /// + /// To support tree operations, two delegates must be provided: + /// + /// + /// + /// CanExpandGetter + /// + /// + /// This delegate must accept a model object and return a boolean indicating + /// if that model should be expandable. + /// + /// + /// + /// + /// ChildrenGetter + /// + /// + /// This delegate must accept a model object and return an IEnumerable of model + /// objects that will be displayed as children of the parent model. This delegate will only be called + /// for a model object if the CanExpandGetter has already returned true for that model. + /// + /// + /// + /// + /// ParentGetter + /// + /// + /// This delegate must accept a model object and return the parent model. + /// This delegate will only be called when HierarchicalCheckboxes is true OR when Reveal() is called. + /// + /// + /// + /// + /// The top level branches of the tree are set via the Roots property. SetObjects(), AddObjects() + /// and RemoveObjects() are interpreted as operations on this collection of roots. + /// + /// + /// To add new children to an existing branch, make changes to your model objects and then + /// call RefreshObject() on the parent. + /// + /// The tree must be a directed acyclic graph -- no cycles are allowed. Put more mundanely, + /// each model object must appear only once in the tree. If the same model object appears in two + /// places in the tree, the control will become confused. + /// + public partial class TreeListView : VirtualObjectListView + { + /// + /// Make a default TreeListView + /// + public TreeListView() { + this.OwnerDraw = true; + this.View = View.Details; + this.CheckedObjectsMustStillExistInList = false; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.RegenerateTree(); + this.TreeColumnRenderer = new TreeRenderer(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + + // This improves hit detection even if we don't have any state image + this.SmallImageList = new ImageList(); + // this.StateImageList.ImageSize = new Size(6, 6); + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + /// + /// + /// This is called *often* -- on every mouse move when required. It must be fast. + /// Don't do database lookups, linear searches, or pi calculations. Just return the + /// value of a property. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't make + /// calls back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CanExpandGetterDelegate CanExpandGetter { + get { return this.TreeModel.CanExpandGetter; } + set { this.TreeModel.CanExpandGetter = value; } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + return false; + } + } + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't do anything + /// that will result in calls being made back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ChildrenGetterDelegate ChildrenGetter { + get { return this.TreeModel.ChildrenGetter; } + set { this.TreeModel.ChildrenGetter = value; } + } + + /// + /// This is the delegate that will be used to fetch the parent of a model object + /// + /// The parent of the given model, or null if the model doesn't exist or + /// if the model is a root + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ParentGetterDelegate ParentGetter { + get { return parentGetter ?? Tree.DefaultParentGetter; } + set { parentGetter = value; } + } + private ParentGetterDelegate parentGetter; + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + public override IList CheckedObjects { + get { + return base.CheckedObjects; + } + set { + ArrayList objectsToRecalculate = new ArrayList(this.CheckedObjects); + if (value != null) + objectsToRecalculate.AddRange(value); + + base.CheckedObjects = value; + + if (this.HierarchicalCheckboxes) + RecalculateHierarchicalCheckBoxGraph(objectsToRecalculate); + } + } + + /// + /// Gets or sets the model objects that are expanded. + /// + /// + /// This can be used to expand model objects before they are seen. + /// + /// Setting this does *not* force the control to rebuild + /// its display. You need to call RebuildAll(true). + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable ExpandedObjects { + get { + return this.TreeModel.mapObjectToExpanded.Keys; + } + set { + this.TreeModel.mapObjectToExpanded.Clear(); + if (value != null) { + foreach (object x in value) + this.TreeModel.SetModelExpanded(x, true); + } + } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// TreeListViews do not currently support whole list filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IListFilter ListFilter { + get { return null; } + set { + System.Diagnostics.Debug.Assert(value == null, "TreeListView do not support ListFilters"); + } + } + + /// + /// Gets or sets whether this tree list view will display hierarchical checkboxes. + /// Hierarchical checkboxes is when a parent's "checkedness" is calculated from + /// the "checkedness" of its children. If all children are checked, the parent + /// will be checked. If all children are unchecked, the parent will also be unchecked. + /// If some children are checked and others are not, the parent will be indeterminate. + /// + /// + /// Hierarchical checkboxes don't work with either CheckStateGetters or CheckedAspectName + /// (which is basically the same thing). This is because it is too expensive to build the + /// initial state of the control if these are installed, since the control would have to walk + /// *every* branch recursively since a single bottom level leaf could change the checkedness + /// of the top root. + /// + [Category("ObjectListView"), + Description("Show hierarchical checkboxes be enabled?"), + DefaultValue(false)] + public virtual bool HierarchicalCheckboxes { + get { return this.hierarchicalCheckboxes; } + set { + if (this.hierarchicalCheckboxes == value) + return; + + this.hierarchicalCheckboxes = value; + this.CheckBoxes = value; + if (value) + this.TriStateCheckBoxes = false; + } + } + private bool hierarchicalCheckboxes; + + /// + /// Gets or sets the collection of root objects of the tree + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { return this.Roots; } + set { this.Roots = value; } + } + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable ObjectsForClustering { + get { + for (int i = 0; i < this.TreeModel.GetObjectCount(); i++) + yield return this.TreeModel.GetNthObject(i); + } + } + + /// + /// After expanding a branch, should the TreeListView attempts to show as much of the + /// revealed descendants as possible. + /// + [Category("ObjectListView"), + Description("Should the parent of an expand subtree be scrolled to the top revealing the children?"), + DefaultValue(true)] + public bool RevealAfterExpand { + get { return revealAfterExpand; } + set { revealAfterExpand = value; } + } + private bool revealAfterExpand = true; + + /// + /// The model objects that form the top level branches of the tree. + /// + /// Setting this does NOT reset the state of the control. + /// In particular, it does not collapse branches. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Roots { + get { return this.TreeModel.RootObjects; } + set { + this.TreeColumnRenderer = this.TreeColumnRenderer; + this.TreeModel.RootObjects = value ?? new ArrayList(); + this.UpdateVirtualListSize(); + } + } + + /// + /// Make sure that at least one column is displaying a tree. + /// If no columns is showing the tree, make column 0 do it. + /// + protected virtual void EnsureTreeRendererPresent(TreeRenderer renderer) { + if (this.Columns.Count == 0) + return; + + foreach (OLVColumn col in this.Columns) { + if (col.Renderer is TreeRenderer) { + col.Renderer = renderer; + return; + } + } + + // No column held a tree renderer, so give column 0 one + OLVColumn columnZero = this.GetColumn(0); + columnZero.Renderer = renderer; + columnZero.WordWrap = columnZero.WordWrap; + } + + /// + /// Gets or sets the renderer that will be used to draw the tree structure. + /// Setting this to null resets the renderer to default. + /// + /// If a column is currently rendering the tree, the renderer + /// for that column will be replaced. If no column is rendering the tree, + /// column 0 will be given this renderer. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual TreeRenderer TreeColumnRenderer { + get { return treeRenderer ?? (treeRenderer = new TreeRenderer()); } + set { + treeRenderer = value ?? new TreeRenderer(); + EnsureTreeRendererPresent(treeRenderer); + } + } + private TreeRenderer treeRenderer; + + /// + /// This is the delegate that will be used to create the underlying Tree structure + /// that the TreeListView uses to manage the information about the tree. + /// + /// + /// The factory must not return null. + /// + /// Most users of TreeListView will never have to use this delegate. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public TreeFactoryDelegate TreeFactory { + get { return treeFactory; } + set { treeFactory = value; } + } + private TreeFactoryDelegate treeFactory; + + /// + /// Should a wait cursor be shown when a branch is being expanded? + /// + /// When this is true, the wait cursor will be shown whilst the children of the + /// branch are being fetched. If the children of the branch have already been cached, + /// the cursor will not change. + [Category("ObjectListView"), + Description("Should a wait cursor be shown when a branch is being expanded?"), + DefaultValue(true)] + public virtual bool UseWaitCursorWhenExpanding { + get { return useWaitCursorWhenExpanding; } + set { useWaitCursorWhenExpanding = value; } + } + private bool useWaitCursorWhenExpanding = true; + + /// + /// Gets the model that is used to manage the tree structure + /// + /// + /// Don't mess with this property unless you really know what you are doing. + /// If you don't already know what it's for, you don't need it. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Tree TreeModel { + get { return this.treeModel; } + protected set { this.treeModel = value; } + } + private Tree treeModel; + + //------------------------------------------------------------------------------------------ + // Accessing + + /// + /// Return true if the branch at the given model is expanded + /// + /// + /// + public virtual bool IsExpanded(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.IsExpanded); + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// + public virtual void Collapse(Object model) { + if (this.GetItemCount() == 0) + return; + + OLVListItem item = this.ModelToItem(model); + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(model, item); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.Collapse(model); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(model, item)); + } + } + + /// + /// Collapse all subtrees within this control + /// + public virtual void CollapseAll() { + if (this.GetItemCount() == 0) + return; + + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(null, null); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.CollapseAll(); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(null, null)); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.Roots = null; + this.DiscardAllState(); + } + } + + /// + /// Collapse all roots and forget everything we know about all models + /// + public virtual void DiscardAllState() { + this.CheckStateMap.Clear(); + this.RebuildAll(false); + } + + /// + /// Expand the subtree underneath the given model object + /// + /// + public virtual void Expand(Object model) { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + OLVListItem item = this.ModelToItem(model); + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(model, item); + this.OnExpanding(args); + if (args.Canceled) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // Expand the model first + int index = this.TreeModel.Expand(model); + if (index < 0) + return; + + // Update the size of the list and restore the selection + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + + // Redraw the items that were changed by the expand operation + this.RedrawItems(index, this.GetItemCount() - 1, true); + + this.OnExpanded(new TreeBranchExpandedEventArgs(model, item)); + + if (this.RevealAfterExpand && index > 0) { + // TODO: This should be a separate method + this.BeginUpdate(); + try { + int countPerPage = NativeMethods.GetCountPerPage(this); + int descedentCount = this.TreeModel.GetVisibleDescendentCount(model); + // If all of the descendants can be shown in the window, make sure that last one is visible. + // If all the descendants can't fit into the window, move the model to the top of the window + // (which will show as many of the descendants as possible) + if (descedentCount < countPerPage) { + this.EnsureVisible(index + descedentCount); + } else { + this.TopItemIndex = index; + } + } + finally { + this.EndUpdate(); + } + } + } + + /// + /// Expand all the branches within this tree recursively. + /// + /// Be careful: this method could take a long time for large trees. + public virtual void ExpandAll() { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(null, null); + this.OnExpanding(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.ExpandAll(); + if (index < 0) + return; + + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnExpanded(new TreeBranchExpandedEventArgs(null, null)); + } + + /// + /// Completely rebuild the tree structure + /// + /// If true, the control will try to preserve selection and expansion + public virtual void RebuildAll(bool preserveState) { + int previousTopItemIndex = preserveState ? this.TopItemIndex : -1; + + this.RebuildAll( + preserveState ? this.SelectedObjects : null, + preserveState ? this.ExpandedObjects : null, + preserveState ? this.CheckedObjects : null); + + if (preserveState) + this.TopItemIndex = previousTopItemIndex; + } + + /// + /// Completely rebuild the tree structure + /// + /// If not null, this list of objects will be selected after the tree is rebuilt + /// If not null, this collection of objects will be expanded after the tree is rebuilt + /// If not null, this collection of objects will be checked after the tree is rebuilt + protected virtual void RebuildAll(IList selected, IEnumerable expanded, IList checkedObjects) { + // Remember the bits of info we don't want to forget (anyone ever see Memento?) + IEnumerable roots = this.Roots; + CanExpandGetterDelegate canExpand = this.CanExpandGetter; + ChildrenGetterDelegate childrenGetter = this.ChildrenGetter; + + try { + this.BeginUpdate(); + + // Give ourselves a new data structure + this.RegenerateTree(); + + // Put back the bits we didn't want to forget + this.CanExpandGetter = canExpand; + this.ChildrenGetter = childrenGetter; + if (expanded != null) + this.ExpandedObjects = expanded; + this.Roots = roots; + if (selected != null) + this.SelectedObjects = selected; + if (checkedObjects != null) + this.CheckedObjects = checkedObjects; + } + finally { + this.EndUpdate(); + } + } + + /// + /// Unroll all the ancestors of the given model and make sure it is then visible. + /// + /// This works best when a ParentGetter is installed. + /// The object to be revealed + /// If true, the model will be selected and focused after being revealed + /// True if the object was found and revealed. False if it was not found. + public virtual void Reveal(object modelToReveal, bool selectAfterReveal) { + // Collect all the ancestors of the model + ArrayList ancestors = new ArrayList(); + foreach (object ancestor in this.GetAncestors(modelToReveal)) + ancestors.Add(ancestor); + + // Arrange them from root down to the model's immediate parent + ancestors.Reverse(); + try { + this.BeginUpdate(); + foreach (object ancestor in ancestors) + this.Expand(ancestor); + this.EnsureModelVisible(modelToReveal); + if (selectAfterReveal) + this.SelectObject(modelToReveal, true); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker) delegate { this.RefreshObjects(modelObjects); }); + return; + } + // There is no point in refreshing anything if the list is empty + if (this.GetItemCount() == 0) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // We actually need to refresh the parents. + // Refreshes on root objects have to be handled differently + ArrayList updatedRoots = new ArrayList(); + Hashtable modelsAndParents = new Hashtable(); + foreach (Object model in modelObjects) { + if (model == null) + continue; + modelsAndParents[model] = true; + object parent = GetParent(model); + if (parent == null) { + updatedRoots.Add(model); + } else { + modelsAndParents[parent] = true; + } + } + + // Update any changed roots + if (updatedRoots.Count > 0) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.Roots, false); + bool changed = false; + foreach (Object model in updatedRoots) { + int index = newRoots.IndexOf(model); + if (index >= 0 && !ReferenceEquals(newRoots[index], model)) { + newRoots[index] = model; + changed = true; + } + } + if (changed) + this.Roots = newRoots; + } + + // Refresh each object, remembering where the first update occurred + int firstChange = Int32.MaxValue; + foreach (Object model in modelsAndParents.Keys) { + if (model != null) { + int index = this.TreeModel.RebuildChildren(model); + if (index >= 0) + firstChange = Math.Min(firstChange, index); + } + } + + // If we didn't refresh any objects, don't do anything else + if (firstChange >= this.GetItemCount()) + return; + + this.ClearCachedInfo(); + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + + // Redraw everything from the first update to the end of the list + this.RedrawItems(firstChange, this.GetItemCount() - 1, true); + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected override bool SetObjectCheckedness(object modelObject, CheckState state) { + // If the checkedness of the given model changes AND this tree has + // hierarchical checkboxes, then we need to update the checkedness of + // its children, and recalculate the checkedness of the parent (recursively) + if (!base.SetObjectCheckedness(modelObject, state)) + return false; + + if (!this.HierarchicalCheckboxes) + return true; + + // Give each child the same checkedness as the model + + CheckState? checkedness = this.GetCheckState(modelObject); + if (!checkedness.HasValue || checkedness.Value == CheckState.Indeterminate) + return true; + + foreach (object child in this.GetChildrenWithoutExpanding(modelObject)) { + this.SetObjectCheckedness(child, checkedness.Value); + } + + ArrayList args = new ArrayList(); + args.Add(modelObject); + this.RecalculateHierarchicalCheckBoxGraph(args); + + return true; + } + + + private IEnumerable GetChildrenWithoutExpanding(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + return br.Children; + } + + /// + /// Toggle the expanded state of the branch at the given model object + /// + /// + public virtual void ToggleExpansion(Object model) { + if (this.IsExpanded(model)) + this.Collapse(model); + else + this.Expand(model); + } + + //------------------------------------------------------------------------------------------ + // Commands - Tree traversal + + /// + /// Return whether or not the given model can expand. + /// + /// + /// The given model must have already been seen in the tree + public virtual bool CanExpand(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.CanExpand); + } + + /// + /// Return the model object that is the parent of the given model object. + /// + /// + /// + /// The given model must have already been seen in the tree. + public virtual Object GetParent(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return br == null || br.ParentBranch == null ? null : br.ParentBranch.Model; + } + + /// + /// Return the collection of model objects that are the children of the + /// given model as they exist in the tree at the moment. + /// + /// + /// + /// + /// This method returns the collection of children as the tree knows them. If the given + /// model has never been presented to the user (e.g. it belongs to a parent that has + /// never been expanded), then this method will return an empty collection. + /// + /// Because of this, if you want to traverse the whole tree, this is not the method to use. + /// It's better to traverse the your data model directly. + /// + /// + /// If the given model has not already been seen in the tree or + /// if it is not expandable, an empty collection will be returned. + /// + /// + public virtual IEnumerable GetChildren(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + br.FetchChildren(); + + return br.Children; + } + + //------------------------------------------------------------------------------------------ + // Delegates + + /// + /// Delegates of this type are use to decide if the given model object can be expanded + /// + /// The model under consideration + /// Can the given model be expanded? + public delegate bool CanExpandGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the children of the given model object + /// + /// The parent whose children should be fetched + /// An enumerable over the children + public delegate IEnumerable ChildrenGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the parent of the given model object. + /// + /// The child whose parent should be fetched + /// The parent of the child or null if the child is a root + public delegate Object ParentGetterDelegate(Object model); + + /// + /// Delegates of this type are used to create a new underlying Tree structure. + /// + /// The view for which the Tree is being created + /// A subclass of Tree + public delegate Tree TreeFactoryDelegate(TreeListView view); + + //------------------------------------------------------------------------------------------ + #region Implementation + + /// + /// Handle a left button down event + /// + /// + /// + protected override bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + // Did they click in the expander? + if (hti.HitTestLocation == HitTestLocation.ExpandButton) { + this.PossibleFinishCellEditing(); + this.ToggleExpansion(hti.RowObject); + return true; + } + + return base.ProcessLButtonDown(hti); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + /// This differs from the base method by also setting up the IndentCount property. + public override OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvItem = base.MakeListViewItem(itemIndex); + Branch br = this.TreeModel.GetBranch(olvItem.RowObject); + if (br != null) + olvItem.IndentCount = br.Level; + return olvItem; + } + + /// + /// Reinitialise the Tree structure + /// + protected virtual void RegenerateTree() { + this.TreeModel = this.TreeFactory == null ? new Tree(this) : this.TreeFactory(this); + Trace.Assert(this.TreeModel != null); + this.VirtualListDataSource = this.TreeModel; + } + + /// + /// Recalculate the state of the checkboxes of all the items in the given list + /// and their ancestors. + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateHierarchicalCheckBoxGraph(IList toCheck) { + if (toCheck == null || toCheck.Count == 0) + return; + + // Avoid recursive calculations + if (isRecalculatingHierarchicalCheckBox) + return; + + try { + isRecalculatingHierarchicalCheckBox = true; + foreach (object ancestor in CalculateDistinctAncestors(toCheck)) + this.RecalculateSingleHierarchicalCheckBox(ancestor); + } + finally { + isRecalculatingHierarchicalCheckBox = false; + } + + } + private bool isRecalculatingHierarchicalCheckBox; + + /// + /// Recalculate the hierarchy state of the given item and its ancestors + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateSingleHierarchicalCheckBox(object modelObject) { + + if (modelObject == null) + return; + + // Only branches have calculated check states. Leaf node checkedness is not calculated + if (!this.CanExpandUncached(modelObject)) + return; + + // Set the checkedness of the given model based on the state of its children. + CheckState? aggregate = null; + foreach (object child in this.GetChildrenUncached(modelObject)) { + CheckState? checkedness = this.GetCheckState(child); + if (!checkedness.HasValue) + continue; + + if (aggregate.HasValue) { + if (aggregate.Value != checkedness.Value) { + aggregate = CheckState.Indeterminate; + break; + } + } else + aggregate = checkedness; + } + + base.SetObjectCheckedness(modelObject, aggregate ?? CheckState.Indeterminate); + } + + private bool CanExpandUncached(object model) { + return this.CanExpandGetter != null && model != null && this.CanExpandGetter(model); + } + + private IEnumerable GetChildrenUncached(object model) { + return this.ChildrenGetter != null && model != null ? this.ChildrenGetter(model) : new ArrayList(); + } + + /// + /// Yield the unique ancestors of the given collection of objects. + /// The order of the ancestors is guaranteed to be deeper objects first. + /// Roots will always be last. + /// + /// + /// Unique ancestors of the given objects + protected virtual IEnumerable CalculateDistinctAncestors(IList toCheck) { + + if (toCheck.Count == 1) { + foreach (object ancestor in this.GetAncestors(toCheck[0])) { + yield return ancestor; + } + } else { + // WARNING - Clever code + + // Example: Root --> GP +--> P +--> A + // | +--> B + // | + // +--> Q +--> X + // +--> Y + // + // Calculate ancestors of A, B, X and Y + + // Build a list of all ancestors of all objects we need to check + ArrayList allAncestors = new ArrayList(); + foreach (object child in toCheck) { + foreach (object ancestor in this.GetAncestors(child)) { + allAncestors.Add(ancestor); + } + } + + // allAncestors = { P, GP, Root, P, GP, Root, Q, GP, Root, Q, GP, Root } + + // Reverse them so "higher" ancestors come first + allAncestors.Reverse(); + + // allAncestors = { Root, GP, Q, Root, GP, Q, Root, GP, P, Root, GP, P } + + ArrayList uniqueAncestors = new ArrayList(); + Dictionary alreadySeen = new Dictionary(); + foreach (object ancestor in allAncestors) { + if (!alreadySeen.ContainsKey(ancestor)) { + alreadySeen[ancestor] = true; + uniqueAncestors.Add(ancestor); + } + } + + // uniqueAncestors = { Root, GP, Q, P } + + uniqueAncestors.Reverse(); + foreach (object x in uniqueAncestors) + yield return x; + } + } + + /// + /// Return all the ancestors of the given model + /// + /// + /// + /// This uses ParentGetter if possible. + /// + /// If the given model is a root OR if the model doesn't exist, the collection will be empty + /// + /// The model whose ancestors should be calculated + /// Return a collection of ancestors of the given model. + protected virtual IEnumerable GetAncestors(object model) { + ParentGetterDelegate parentGetterDelegate = this.ParentGetter ?? this.GetParent; + + object parent = parentGetterDelegate(model); + while (parent != null) { + yield return parent; + parent = parentGetterDelegate(parent); + } + } + + #endregion + + //------------------------------------------------------------------------------------------ + #region Event handlers + + /// + /// The application is idle and a SelectionChanged event has been scheduled + /// + /// + /// + protected override void HandleApplicationIdle(object sender, EventArgs e) { + base.HandleApplicationIdle(sender, e); + + // There is an annoying redraw issue on ListViews that use indentation and + // that have full row select enabled. When the selection reduces to a subset + // of previously selected rows, or when the selection is extended using + // shift-pageup/down, then the space occupied by the indentation is not + // invalidated, and hence remains highlighted. + // Ideally we'd want to know exactly which rows were selected or deselected + // and then invalidate just the indentation region of those rows, + // but that's too much work. So just redraw the control. + // Actually... the selection issues show just slightly for non-full row select + // controls as well. So, always redraw the control after the selection + // changes. + this.Invalidate(); + } + + /// + /// Decide if the given key event should be handled as a normal key input to the control? + /// + /// + /// + protected override bool IsInputKey(Keys keyData) { + // We want to handle Left and Right keys within the control + Keys key = keyData & Keys.KeyCode; + if (key == Keys.Left || key == Keys.Right) + return true; + + return base.IsInputKey(keyData); + } + + /// + /// Handle focus being lost, including making sure that the whole control is redrawn. + /// + /// + protected override void OnLostFocus(EventArgs e) + { + // When this focus is lost, the normal invalidation logic doesn't invalid the region + // of the control created by the IndentLevel on each row. This makes the control + // look wrong when HideSelection is false, since part of the selected row's background + // correctly changes colour to the "inactive" colour, but the left part of the row + // created by IndentLevel doesn't change colour. + // SF #135. + + this.Invalidate(); + } + + /// + /// Handle the keyboard input to mimic a TreeView. + /// + /// + /// Was the key press handled? + protected override void OnKeyDown(KeyEventArgs e) { + OLVListItem focused = this.FocusedItem as OLVListItem; + if (focused == null) { + base.OnKeyDown(e); + return; + } + + Object modelObject = focused.RowObject; + Branch br = this.TreeModel.GetBranch(modelObject); + + switch (e.KeyCode) { + case Keys.Left: + // If the branch is expanded, collapse it. If it's collapsed, + // select the parent of the branch. + if (br.IsExpanded) + this.Collapse(modelObject); + else { + if (br.ParentBranch != null && br.ParentBranch.Model != null) + this.SelectObject(br.ParentBranch.Model, true); + } + e.Handled = true; + break; + + case Keys.Right: + // If the branch is expanded, select the first child. + // If it isn't expanded and can be, expand it. + if (br.IsExpanded) { + List filtered = br.FilteredChildBranches; + if (filtered.Count > 0) + this.SelectObject(filtered[0].Model, true); + } else { + if (br.CanExpand) + this.Expand(modelObject); + } + e.Handled = true; + break; + } + + base.OnKeyDown(e); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Support classes + + /// + /// A Tree object represents a tree structure data model that supports both + /// tree and flat list operations as well as fast access to branches. + /// + /// If you create a subclass of Tree, you must install it in the TreeListView + /// via the TreeFactory delegate. + public class Tree : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Create a Tree + /// + /// + public Tree(TreeListView treeView) { + this.treeView = treeView; + this.trunk = new Branch(null, this, null); + this.trunk.IsExpanded = true; + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + public CanExpandGetterDelegate CanExpandGetter { + get { return canExpandGetter ?? DefaultCanExpandGetter; } + set { canExpandGetter = value; } + } + private CanExpandGetterDelegate canExpandGetter; + + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + public ChildrenGetterDelegate ChildrenGetter { + get { return childrenGetter ?? DefaultChildrenGetter; } + set { childrenGetter = value; } + } + private ChildrenGetterDelegate childrenGetter; + + /// + /// Get or return the top level model objects in the tree + /// + public IEnumerable RootObjects { + get { return this.trunk.Children; } + set { + this.trunk.Children = value; + foreach (Branch br in this.trunk.ChildBranches) + br.RefreshChildren(); + this.RebuildList(); + } + } + + /// + /// What tree view is this Tree the model for? + /// + public TreeListView TreeView { + get { return this.treeView; } + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// The model to be collapsed. If the model isn't in the tree, + /// or if it is already collapsed, the command does nothing. + /// The index of the model in flat list version of the tree + public virtual int Collapse(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.IsExpanded) + return -1; + + // Remember that the branch is collapsed, even if it's currently not visible + if (!br.Visible) { + br.Collapse(); + return -1; + } + + int count = br.NumberVisibleDescendents; + br.Collapse(); + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + this.objectList.RemoveRange(index + 1, count); + this.RebuildObjectMap(0); + return index; + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual int CollapseAll() { + this.trunk.CollapseAll(); + this.RebuildList(); + return 0; + } + + /// + /// Expand the subtree underneath the given model object + /// + /// The model to be expanded. + /// The index of the model in flat list version of the tree + /// + /// If the model isn't in the tree, + /// if it cannot be expanded or if it is already expanded, the command does nothing. + /// + public virtual int Expand(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.CanExpand || br.IsExpanded) + return -1; + + // Remember that the branch is expanded, even if it's currently not visible + br.Expand(); + if (!br.Visible) + { + return -1; + } + + int index = this.GetObjectIndex(model); + this.InsertChildren(br, index + 1); + return index; + } + + /// + /// Expand all branches in this tree + /// + /// Return the index of the first branch that was expanded + public virtual int ExpandAll() { + this.trunk.ExpandAll(); + this.Sort(this.lastSortColumn, this.lastSortOrder); + return 0; + } + + /// + /// Return the Branch object that represents the given model in the tree + /// + /// The model whose branches is to be returned + /// The branch that represents the given model, or null if the model + /// isn't in the tree. + public virtual Branch GetBranch(object model) { + if (model == null) + return null; + + Branch br; + this.mapObjectToBranch.TryGetValue(model, out br); + return br; + } + + /// + /// Return the number of visible descendants that are below the given model. + /// + /// The model whose descendent count is to be returned + /// The number of visible descendants. 0 if the model doesn't exist or is collapsed + public virtual int GetVisibleDescendentCount(object model) + { + Branch br = this.GetBranch(model); + return br == null || !br.IsExpanded ? 0 : br.NumberVisibleDescendents; + } + + /// + /// Rebuild the children of the given model, refreshing any cached information held about the given object + /// + /// + /// The index of the model in flat list version of the tree + public virtual int RebuildChildren(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.Visible) + return -1; + + int count = br.NumberVisibleDescendents; + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + if (count > 0) + this.objectList.RemoveRange(index + 1, count); + + // Refresh our knowledge of our children (do this even if CanExpand is false, because + // the branch have already collected some children and that information could be stale) + br.RefreshChildren(); + + // Insert the refreshed children if the branch can expand and is expanded + if (br.CanExpand && br.IsExpanded) + this.InsertChildren(br, index + 1); + else + this.RebuildObjectMap(index); + + return index; + } + + //------------------------------------------------------------------------------------------ + // Implementation + + private static bool DefaultCanExpandGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel != null && treeModel.TreeCanExpand; + } + + private static IEnumerable DefaultChildrenGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel == null ? new ArrayList() : treeModel.TreeChildren; + } + + internal static object DefaultParentGetter(object model) { + ITreeModelWithParent treeModel = model as ITreeModelWithParent; + return treeModel == null ? null : treeModel.TreeParent; + } + + /// + /// Is the given model expanded? + /// + /// + /// + internal bool IsModelExpanded(object model) { + // Special case: model == null is the container for the roots. This is always expanded + if (model == null) + return true; + bool isExpanded; + this.mapObjectToExpanded.TryGetValue(model, out isExpanded); + return isExpanded; + } + + /// + /// Remember whether or not the given model was expanded + /// + /// + /// + internal void SetModelExpanded(object model, bool isExpanded) { + if (model == null) return; + + if (isExpanded) + this.mapObjectToExpanded[model] = true; + else + this.mapObjectToExpanded.Remove(model); + } + + /// + /// Insert the children of the given branch into the given position + /// + /// The branch whose children should be inserted + /// The index where the children should be inserted + protected virtual void InsertChildren(Branch br, int index) { + // Expand the branch + br.Expand(); + br.Sort(this.GetBranchComparer()); + + // Insert the branch's visible descendants after the branch itself + this.objectList.InsertRange(index, br.Flatten()); + this.RebuildObjectMap(index); + } + + /// + /// Rebuild our flat internal list of objects. + /// + protected virtual void RebuildList() { + this.objectList = ArrayList.Adapter(this.trunk.Flatten()); + List filtered = this.trunk.FilteredChildBranches; + if (filtered.Count > 0) { + filtered[0].IsFirstBranch = true; + filtered[0].IsOnlyBranch = (filtered.Count == 1); + } + this.RebuildObjectMap(0); + } + + /// + /// Rebuild our reverse index that maps an object to its location + /// in the filteredObjectList array. + /// + /// + protected virtual void RebuildObjectMap(int startIndex) { + if (startIndex == 0) + this.mapObjectToIndex.Clear(); + for (int i = startIndex; i < this.objectList.Count; i++) + this.mapObjectToIndex[this.objectList[i]] = i; + } + + /// + /// Create a new branch within this tree + /// + /// + /// + /// + internal Branch MakeBranch(Branch parent, object model) { + Branch br = new Branch(parent, this, model); + + // Remember that the given branch is part of this tree. + this.mapObjectToBranch[model] = br; + return br; + } + + //------------------------------------------------------------------------------------------ + + #region IVirtualListDataSource Members + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + if (n >= 0 && n < this.objectList.Count) + return this.objectList[n]; + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return this.trunk.NumberVisibleDescendents; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) + { + int index; + if (model != null && this.mapObjectToIndex.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int first, int last) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return AbstractVirtualListDataSource.DefaultSearchText(value, first, last, column, this); + } + + /// + /// Sort the tree on the given column and in the given order + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + this.lastSortColumn = column; + this.lastSortOrder = order; + + // TODO: Need to raise an AboutToSortEvent here + + // Sorting is going to change the order of the branches so clear + // the "first branch" flag + foreach (Branch b in this.trunk.ChildBranches) + b.IsFirstBranch = false; + + this.trunk.Sort(this.GetBranchComparer()); + this.RebuildList(); + } + + /// + /// + /// + /// + protected virtual BranchComparer GetBranchComparer() { + if (this.lastSortColumn == null) + return null; + + return new BranchComparer(new ModelObjectComparer( + this.lastSortColumn, + this.lastSortOrder, + this.treeView.SecondarySortColumn ?? this.treeView.GetColumn(0), + this.treeView.SecondarySortColumn == null ? this.lastSortOrder : this.treeView.SecondarySortOrder)); + } + + /// + /// Add the given collection of objects to the roots of this tree + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, true); + foreach (Object x in modelObjects) + newRoots.Add(x); + this.SetObjects(newRoots); + } + + /// + /// + /// + /// + /// + public void InsertObjects(int index, ICollection modelObjects) { + throw new NotImplementedException(); + } + + /// + /// Remove all of the given objects from the roots of the tree. + /// Any objects that is not already in the roots collection is ignored. + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + ArrayList newRoots = new ArrayList(); + foreach (Object x in this.treeView.Roots) + newRoots.Add(x); + foreach (Object x in modelObjects) { + newRoots.Remove(x); + this.mapObjectToIndex.Remove(x); + } + this.SetObjects(newRoots); + } + + /// + /// Set the roots of this tree to be the given collection + /// + /// + public virtual void SetObjects(IEnumerable collection) { + // We interpret a SetObjects() call as setting the roots of the tree + this.treeView.Roots = collection; + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public void UpdateObject(int index, object modelObject) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, false); + if (index < newRoots.Count) + newRoots[index] = modelObject; + SetObjects(newRoots); + } + + #endregion + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + public void ApplyFilters(IModelFilter mFilter, IListFilter lFilter) { + this.modelFilter = mFilter; + this.listFilter = lFilter; + this.RebuildList(); + } + + /// + /// Is this list currently being filtered? + /// + internal bool IsFiltering { + get { + return this.treeView.UseFiltering && (this.modelFilter != null || this.listFilter != null); + } + } + + /// + /// Should the given model be included in this control? + /// + /// The model to consider + /// True if it will be included + internal bool IncludeModel(object model) { + if (!this.treeView.UseFiltering) + return true; + + if (this.modelFilter == null) + return true; + + return this.modelFilter.Filter(model); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private OLVColumn lastSortColumn; + private SortOrder lastSortOrder; + private readonly Dictionary mapObjectToBranch = new Dictionary(); +// ReSharper disable once InconsistentNaming + internal Dictionary mapObjectToExpanded = new Dictionary(); + private readonly Dictionary mapObjectToIndex = new Dictionary(); + private ArrayList objectList = new ArrayList(); + private readonly TreeListView treeView; + private readonly Branch trunk; + + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IModelFilter modelFilter; + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IListFilter listFilter; + } + + /// + /// A Branch represents a sub-tree within a tree + /// + public class Branch + { + /// + /// Indicators for branches + /// + [Flags] + public enum BranchFlags + { + /// + /// FirstBranch of tree + /// + FirstBranch = 1, + + /// + /// LastChild of parent + /// + LastChild = 2, + + /// + /// OnlyBranch of tree + /// + OnlyBranch = 4 + } + + #region Life and death + + /// + /// Create a Branch + /// + /// + /// + /// + public Branch(Branch parent, Tree tree, Object model) { + this.ParentBranch = parent; + this.Tree = tree; + this.Model = model; + } + + #endregion + + #region Public properties + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// Get the ancestor branches of this branch, with the 'oldest' ancestor first. + /// + public virtual IList Ancestors { + get { + List ancestors = new List(); + if (this.ParentBranch != null) + this.ParentBranch.PushAncestors(ancestors); + return ancestors; + } + } + + private void PushAncestors(IList list) { + // This is designed to ignore the trunk (which has no parent) + if (this.ParentBranch != null) { + this.ParentBranch.PushAncestors(list); + list.Add(this); + } + } + + /// + /// Can this branch be expanded? + /// + public virtual bool CanExpand { + get { + if (this.Tree.CanExpandGetter == null || this.Model == null) + return false; + + return this.Tree.CanExpandGetter(this.Model); + } + } + + /// + /// Gets or sets our children + /// + public List ChildBranches { + get { return this.childBranches; } + set { this.childBranches = value; } + } + private List childBranches = new List(); + + /// + /// Get/set the model objects that are beneath this branch + /// + public virtual IEnumerable Children { + get { + ArrayList children = new ArrayList(); + foreach (Branch x in this.ChildBranches) + children.Add(x.Model); + return children; + } + set { + this.ChildBranches.Clear(); + + TreeListView treeListView = this.Tree.TreeView; + CheckState? checkedness = null; + if (treeListView != null && treeListView.HierarchicalCheckboxes) + checkedness = treeListView.GetCheckState(this.Model); + foreach (Object x in value) { + this.AddChild(x); + + // If the tree view is showing hierarchical checkboxes, then + // when a child object is first added, it has the same checkedness as this branch + if (checkedness.HasValue && checkedness.Value == CheckState.Checked) + treeListView.SetObjectCheckedness(x, checkedness.Value); + } + } + } + + private void AddChild(object childModel) { + Branch br = this.Tree.GetBranch(childModel); + if (br == null) + br = this.Tree.MakeBranch(this, childModel); + else { + br.ParentBranch = this; + br.Model = childModel; + br.ClearCachedInfo(); + } + this.ChildBranches.Add(br); + } + + /// + /// Gets a list of all the branches that survive filtering + /// + public List FilteredChildBranches { + get { + if (!this.IsExpanded) + return new List(); + + if (!this.Tree.IsFiltering) + return this.ChildBranches; + + List filtered = new List(); + foreach (Branch b in this.ChildBranches) { + if (this.Tree.IncludeModel(b.Model)) + filtered.Add(b); + else { + // Also include this branch if it has any filtered branches (yes, its recursive) + if (b.FilteredChildBranches.Count > 0) + filtered.Add(b); + } + } + return filtered; + } + } + + /// + /// Gets or set whether this branch is expanded + /// + public bool IsExpanded { + get { return this.Tree.IsModelExpanded(this.Model); } + set { this.Tree.SetModelExpanded(this.Model, value); } + } + + /// + /// Return true if this branch is the first branch of the entire tree + /// + public virtual bool IsFirstBranch { + get { + return ((this.flags & Branch.BranchFlags.FirstBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.FirstBranch; + else + this.flags &= ~Branch.BranchFlags.FirstBranch; + } + } + + /// + /// Return true if this branch is the last child of its parent + /// + public virtual bool IsLastChild { + get { + return ((this.flags & Branch.BranchFlags.LastChild) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.LastChild; + else + this.flags &= ~Branch.BranchFlags.LastChild; + } + } + + /// + /// Return true if this branch is the only top level branch + /// + public virtual bool IsOnlyBranch { + get { + return ((this.flags & Branch.BranchFlags.OnlyBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.OnlyBranch; + else + this.flags &= ~Branch.BranchFlags.OnlyBranch; + } + } + + /// + /// Gets the depth level of this branch + /// + public int Level { + get { + if (this.ParentBranch == null) + return 0; + + return this.ParentBranch.Level + 1; + } + } + + /// + /// Gets or sets which model is represented by this branch + /// + public Object Model { + get { return model; } + set { model = value; } + } + private Object model; + + /// + /// Return the number of descendants of this branch that are currently visible + /// + /// + public virtual int NumberVisibleDescendents { + get { + if (!this.IsExpanded) + return 0; + + List filtered = this.FilteredChildBranches; + int count = filtered.Count; + foreach (Branch br in filtered) + count += br.NumberVisibleDescendents; + return count; + } + } + + /// + /// Gets or sets our parent branch + /// + public Branch ParentBranch { + get { return parentBranch; } + set { parentBranch = value; } + } + private Branch parentBranch; + + /// + /// Gets or sets our overall tree + /// + public Tree Tree { + get { return tree; } + set { tree = value; } + } + private Tree tree; + + /// + /// Is this branch currently visible? A branch is visible + /// if it has no parent (i.e. it's a root), or its parent + /// is visible and expanded. + /// + public virtual bool Visible { + get { + if (this.ParentBranch == null) + return true; + + return this.ParentBranch.IsExpanded && this.ParentBranch.Visible; + } + } + + #endregion + + #region Commands + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Clear any cached information that this branch is holding + /// + public virtual void ClearCachedInfo() { + this.Children = new ArrayList(); + this.alreadyHasChildren = false; + } + + /// + /// Collapse this branch + /// + public virtual void Collapse() { + this.IsExpanded = false; + } + + /// + /// Expand this branch + /// + public virtual void Expand() { + if (this.CanExpand) { + this.IsExpanded = true; + this.FetchChildren(); + } + } + + /// + /// Expand this branch recursively + /// + public virtual void ExpandAll() { + this.Expand(); + foreach (Branch br in this.ChildBranches) { + if (br.CanExpand) + br.ExpandAll(); + } + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual void CollapseAll() + { + this.Collapse(); + foreach (Branch br in this.ChildBranches) { + if (br.IsExpanded) + br.CollapseAll(); + } + } + + /// + /// Fetch the children of this branch. + /// + /// This should only be called when CanExpand is true. + public virtual void FetchChildren() { + if (this.alreadyHasChildren) + return; + + this.alreadyHasChildren = true; + + if (this.Tree.ChildrenGetter == null) + return; + + Cursor previous = Cursor.Current; + try { + if (this.Tree.TreeView.UseWaitCursorWhenExpanding) + Cursor.Current = Cursors.WaitCursor; + this.Children = this.Tree.ChildrenGetter(this.Model); + } + finally { + Cursor.Current = previous; + } + } + + /// + /// Collapse the visible descendants of this branch into list of model objects + /// + /// + public virtual IList Flatten() { + ArrayList flatList = new ArrayList(); + if (this.IsExpanded) + this.FlattenOnto(flatList); + return flatList; + } + + /// + /// Flatten this branch's visible descendants onto the given list. + /// + /// + /// The branch itself is not included in the list. + public virtual void FlattenOnto(IList flatList) { + Branch lastBranch = null; + foreach (Branch br in this.FilteredChildBranches) { + lastBranch = br; + br.IsFirstBranch = br.IsOnlyBranch = br.IsLastChild = false; + flatList.Add(br.Model); + if (br.IsExpanded) { + br.FetchChildren(); // make sure we have the branches children + br.FlattenOnto(flatList); + } + } + if (lastBranch != null) + lastBranch.IsLastChild = true; + } + + /// + /// Force a refresh of all children recursively + /// + public virtual void RefreshChildren() { + + // Forget any previous children. We always do this so that if + // IsExpanded or CanExpand have changed, we aren't left with stale information. + this.ClearCachedInfo(); + + if (!this.IsExpanded || !this.CanExpand) + return; + + this.FetchChildren(); + foreach (Branch br in this.ChildBranches) + br.RefreshChildren(); + } + + /// + /// Sort the sub-branches and their descendants so they are ordered according + /// to the given comparer. + /// + /// The comparer that orders the branches + public virtual void Sort(BranchComparer comparer) { + if (this.ChildBranches.Count == 0) + return; + + if (comparer != null) + this.ChildBranches.Sort(comparer); + + foreach (Branch br in this.ChildBranches) + br.Sort(comparer); + } + + #endregion + + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private bool alreadyHasChildren; + private BranchFlags flags; + } + + /// + /// This class sorts branches according to how their respective model objects are sorted + /// + public class BranchComparer : IComparer + { + /// + /// Create a BranchComparer + /// + /// + public BranchComparer(IComparer actualComparer) { + this.actualComparer = actualComparer; + } + + /// + /// Order the two branches + /// + /// + /// + /// + public int Compare(Branch x, Branch y) { + return this.actualComparer.Compare(x.Model, y.Model); + } + + private readonly IComparer actualComparer; + } + + } + + /// + /// This interface should be implemented by model objects that can provide children, + /// but that don't have a parent. This is either because the model objects are always + /// root level, or because they are used in TreeListView that never uses parent + /// calculations. Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithChildren { + /// + /// Get whether this this model can be expanded? If true, an expand glyph will be drawn next to it. + /// + /// This is called often! It must be fast. Dont do a database lookup, calculate pi, or do linear searches just return a property value. + bool TreeCanExpand { get; } + + /// + /// Get the models that will be shown under this model when it is expanded. + /// + /// This is only called when CanExpand returns true. + IEnumerable TreeChildren { get; } + } + + /// + /// This interface should be implemented by model objects that can never have children, + /// but that are used in a TreeListView that uses parent calculations. + /// Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithParent { + + /// + /// Get the hierarchical parent of this model. + /// + object TreeParent { get; } + } + + /// + /// ITreeModel allows model objects to provide the required information to TreeListView + /// without using the normal Getter delegates. + /// + public interface ITreeModel: ITreeModelWithChildren, ITreeModelWithParent { + + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs new file mode 100644 index 0000000..e8e520e --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs @@ -0,0 +1,190 @@ +namespace BrightIdeasSoftware +{ + partial class ColumnSelectionForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonMoveUp = new System.Windows.Forms.Button(); + this.buttonMoveDown = new System.Windows.Forms.Button(); + this.buttonShow = new System.Windows.Forms.Button(); + this.buttonHide = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.buttonOK = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.objectListView1 = new BrightIdeasSoftware.ObjectListView(); + this.olvColumn1 = new BrightIdeasSoftware.OLVColumn(); + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit(); + this.SuspendLayout(); + // + // buttonMoveUp + // + this.buttonMoveUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveUp.Location = new System.Drawing.Point(295, 31); + this.buttonMoveUp.Name = "buttonMoveUp"; + this.buttonMoveUp.Size = new System.Drawing.Size(87, 23); + this.buttonMoveUp.TabIndex = 1; + this.buttonMoveUp.Text = "Move &Up"; + this.buttonMoveUp.UseVisualStyleBackColor = true; + this.buttonMoveUp.Click += new System.EventHandler(this.buttonMoveUp_Click); + // + // buttonMoveDown + // + this.buttonMoveDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveDown.Location = new System.Drawing.Point(295, 60); + this.buttonMoveDown.Name = "buttonMoveDown"; + this.buttonMoveDown.Size = new System.Drawing.Size(87, 23); + this.buttonMoveDown.TabIndex = 2; + this.buttonMoveDown.Text = "Move &Down"; + this.buttonMoveDown.UseVisualStyleBackColor = true; + this.buttonMoveDown.Click += new System.EventHandler(this.buttonMoveDown_Click); + // + // buttonShow + // + this.buttonShow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonShow.Location = new System.Drawing.Point(295, 89); + this.buttonShow.Name = "buttonShow"; + this.buttonShow.Size = new System.Drawing.Size(87, 23); + this.buttonShow.TabIndex = 3; + this.buttonShow.Text = "&Show"; + this.buttonShow.UseVisualStyleBackColor = true; + this.buttonShow.Click += new System.EventHandler(this.buttonShow_Click); + // + // buttonHide + // + this.buttonHide.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonHide.Location = new System.Drawing.Point(295, 118); + this.buttonHide.Name = "buttonHide"; + this.buttonHide.Size = new System.Drawing.Size(87, 23); + this.buttonHide.TabIndex = 4; + this.buttonHide.Text = "&Hide"; + this.buttonHide.UseVisualStyleBackColor = true; + this.buttonHide.Click += new System.EventHandler(this.buttonHide_Click); + // + // label1 + // + this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.label1.BackColor = System.Drawing.SystemColors.Control; + this.label1.Location = new System.Drawing.Point(13, 9); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(366, 19); + this.label1.TabIndex = 5; + this.label1.Text = "Choose the columns you want to see in this list. "; + // + // buttonOK + // + this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOK.Location = new System.Drawing.Point(198, 304); + this.buttonOK.Name = "buttonOK"; + this.buttonOK.Size = new System.Drawing.Size(87, 23); + this.buttonOK.TabIndex = 6; + this.buttonOK.Text = "&OK"; + this.buttonOK.UseVisualStyleBackColor = true; + this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(295, 304); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(87, 23); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "&Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // objectListView1 + // + this.objectListView1.AllColumns.Add(this.olvColumn1); + this.objectListView1.AlternateRowBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); + this.objectListView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick; + this.objectListView1.CheckBoxes = true; + this.objectListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.olvColumn1}); + this.objectListView1.FullRowSelect = true; + this.objectListView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; + this.objectListView1.HideSelection = false; + this.objectListView1.Location = new System.Drawing.Point(12, 31); + this.objectListView1.MultiSelect = false; + this.objectListView1.Name = "objectListView1"; + this.objectListView1.ShowGroups = false; + this.objectListView1.ShowSortIndicators = false; + this.objectListView1.Size = new System.Drawing.Size(273, 259); + this.objectListView1.TabIndex = 0; + this.objectListView1.UseCompatibleStateImageBehavior = false; + this.objectListView1.View = System.Windows.Forms.View.Details; + this.objectListView1.SelectionChanged += new System.EventHandler(this.objectListView1_SelectionChanged); + // + // olvColumn1 + // + this.olvColumn1.AspectName = "Text"; + this.olvColumn1.IsVisible = true; + this.olvColumn1.Text = "Column"; + this.olvColumn1.Width = 267; + // + // ColumnSelectionForm + // + this.AcceptButton = this.buttonOK; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(391, 339); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOK); + this.Controls.Add(this.label1); + this.Controls.Add(this.buttonHide); + this.Controls.Add(this.buttonShow); + this.Controls.Add(this.buttonMoveDown); + this.Controls.Add(this.buttonMoveUp); + this.Controls.Add(this.objectListView1); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ColumnSelectionForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.Text = "Column Selection"; + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private BrightIdeasSoftware.ObjectListView objectListView1; + private System.Windows.Forms.Button buttonMoveUp; + private System.Windows.Forms.Button buttonMoveDown; + private System.Windows.Forms.Button buttonShow; + private System.Windows.Forms.Button buttonHide; + private BrightIdeasSoftware.OLVColumn olvColumn1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button buttonOK; + private System.Windows.Forms.Button buttonCancel; + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/ColumnSelectionForm.cs b/ObjectListView/Utilities/ColumnSelectionForm.cs new file mode 100644 index 0000000..6b8e7e0 --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.cs @@ -0,0 +1,263 @@ +/* + * ColumnSelectionForm - A utility form that allows columns to be rearranged and/or hidden + * + * Author: Phillip Piper + * Date: 1/04/2011 11:15 AM + * + * Change log: + * 2013-04-21 JPP - Fixed obscure bug in column re-ordered. Thanks to Edwin Chen. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This form is an example of how an application could allows the user to select which columns + /// an ObjectListView will display, as well as select which order the columns are displayed in. + /// + /// + /// In Tile view, ColumnHeader.DisplayIndex does nothing. To reorder the columns you have + /// to change the order of objects in the Columns property. + /// Remember that the first column is special! + /// It has to remain the first column. + /// + public partial class ColumnSelectionForm : Form + { + /// + /// Make a new ColumnSelectionForm + /// + public ColumnSelectionForm() + { + InitializeComponent(); + } + + /// + /// Open this form so it will edit the columns that are available in the listview's current view + /// + /// The ObjectListView whose columns are to be altered + public void OpenOn(ObjectListView olv) + { + this.OpenOn(olv, olv.View); + } + + /// + /// Open this form so it will edit the columns that are available in the given listview + /// when the listview is showing the given type of view. + /// + /// The ObjectListView whose columns are to be altered + /// The view that is to be altered. Must be View.Details or View.Tile + public void OpenOn(ObjectListView olv, View view) + { + if (view != View.Details && view != View.Tile) + return; + + this.InitializeForm(olv, view); + if (this.ShowDialog() == DialogResult.OK) + this.Apply(olv, view); + } + + /// + /// Initialize the form to show the columns of the given view + /// + /// + /// + protected void InitializeForm(ObjectListView olv, View view) + { + this.AllColumns = olv.AllColumns; + this.RearrangableColumns = new List(this.AllColumns); + foreach (OLVColumn col in this.RearrangableColumns) { + if (view == View.Details) + this.MapColumnToVisible[col] = col.IsVisible; + else + this.MapColumnToVisible[col] = col.IsTileViewColumn; + } + this.RearrangableColumns.Sort(new SortByDisplayOrder(this)); + + this.objectListView1.BooleanCheckStateGetter = delegate(Object rowObject) { + return this.MapColumnToVisible[(OLVColumn)rowObject]; + }; + + this.objectListView1.BooleanCheckStatePutter = delegate(Object rowObject, bool newValue) { + // Some columns should always be shown, so ignore attempts to hide them + OLVColumn column = (OLVColumn)rowObject; + if (!column.CanBeHidden) + return true; + + this.MapColumnToVisible[column] = newValue; + EnableControls(); + return newValue; + }; + + this.objectListView1.SetObjects(this.RearrangableColumns); + this.EnableControls(); + } + private List AllColumns = null; + private List RearrangableColumns = new List(); + private Dictionary MapColumnToVisible = new Dictionary(); + + /// + /// The user has pressed OK. Do what's required. + /// + /// + /// + protected void Apply(ObjectListView olv, View view) + { + olv.Freeze(); + + // Update the column definitions to reflect whether they have been hidden + if (view == View.Details) { + foreach (OLVColumn col in olv.AllColumns) + col.IsVisible = this.MapColumnToVisible[col]; + } else { + foreach (OLVColumn col in olv.AllColumns) + col.IsTileViewColumn = this.MapColumnToVisible[col]; + } + + // Collect the columns are still visible + List visibleColumns = this.RearrangableColumns.FindAll( + delegate(OLVColumn x) { return this.MapColumnToVisible[x]; }); + + // Detail view and Tile view have to be handled in different ways. + if (view == View.Details) { + // Of the still visible columns, change DisplayIndex to reflect their position in the rearranged list + olv.ChangeToFilteredColumns(view); + foreach (OLVColumn col in visibleColumns) { + col.DisplayIndex = visibleColumns.IndexOf((OLVColumn)col); + col.LastDisplayIndex = col.DisplayIndex; + } + } else { + // In Tile view, DisplayOrder does nothing. So to change the display order, we have to change the + // order of the columns in the Columns property. + // Remember, the primary column is special and has to remain first! + OLVColumn primaryColumn = this.AllColumns[0]; + visibleColumns.Remove(primaryColumn); + + olv.Columns.Clear(); + olv.Columns.Add(primaryColumn); + olv.Columns.AddRange(visibleColumns.ToArray()); + olv.CalculateReasonableTileSize(); + } + + olv.Unfreeze(); + } + + #region Event handlers + + private void buttonMoveUp_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex-1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonMoveDown_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex + 1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonShow_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = true; + } + + private void buttonHide_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = false; + } + + private void buttonOK_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.OK; + this.Close(); + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.Cancel; + this.Close(); + } + + private void objectListView1_SelectionChanged(object sender, EventArgs e) + { + EnableControls(); + } + + #endregion + + #region Control enabling + + /// + /// Enable the controls on the dialog to match the current state + /// + protected void EnableControls() + { + if (this.objectListView1.SelectedIndices.Count == 0) { + this.buttonMoveUp.Enabled = false; + this.buttonMoveDown.Enabled = false; + this.buttonShow.Enabled = false; + this.buttonHide.Enabled = false; + } else { + // Can't move the first row up or the last row down + this.buttonMoveUp.Enabled = (this.objectListView1.SelectedIndices[0] != 0); + this.buttonMoveDown.Enabled = (this.objectListView1.SelectedIndices[0] < (this.objectListView1.GetItemCount() - 1)); + + OLVColumn selectedColumn = (OLVColumn)this.objectListView1.SelectedObject; + + // Some columns cannot be hidden (and hence cannot be Shown) + this.buttonShow.Enabled = !this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + this.buttonHide.Enabled = this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + } + } + #endregion + + /// + /// A Comparer that will sort a list of columns so that visible ones come before hidden ones, + /// and that are ordered by their display order. + /// + private class SortByDisplayOrder : IComparer + { + public SortByDisplayOrder(ColumnSelectionForm form) + { + this.Form = form; + } + private ColumnSelectionForm Form; + + #region IComparer Members + + int IComparer.Compare(OLVColumn x, OLVColumn y) + { + if (this.Form.MapColumnToVisible[x] && !this.Form.MapColumnToVisible[y]) + return -1; + + if (!this.Form.MapColumnToVisible[x] && this.Form.MapColumnToVisible[y]) + return 1; + + if (x.DisplayIndex == y.DisplayIndex) + return x.Text.CompareTo(y.Text); + else + return x.DisplayIndex - y.DisplayIndex; + } + + #endregion + } + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.resx b/ObjectListView/Utilities/ColumnSelectionForm.resx new file mode 100644 index 0000000..19dc0dd --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ObjectListView/Utilities/Generator.cs b/ObjectListView/Utilities/Generator.cs new file mode 100644 index 0000000..705ed30 --- /dev/null +++ b/ObjectListView/Utilities/Generator.cs @@ -0,0 +1,563 @@ +/* + * Generator - Utility methods that generate columns or methods + * + * Author: Phillip Piper + * Date: 15/08/2009 22:37 + * + * Change log: + * 2015-06-17 JPP - Columns without [OLVColumn] now auto size + * 2012-08-16 JPP - Generator now considers [OLVChildren] and [OLVIgnore] attributes. + * 2012-06-14 JPP - Allow columns to be generated even if they are not marked with [OLVColumn] + * - Converted class from static to instance to allow it to be subclassed. + * Also, added IGenerator to allow it to be completely reimplemented. + * v2.5.1 + * 2010-11-01 JPP - DisplayIndex is now set correctly for columns that lack that attribute + * v2.4.1 + * 2010-08-25 JPP - Generator now also resets sort columns + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * - Don't double set the Text property + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; +using System.Reflection.Emit; +using System.Text.RegularExpressions; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An object that implements the IGenerator interface provides the ability + /// to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + public interface IGenerator { + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties); + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + IList GenerateColumns(Type type, bool allProperties); + } + + /// + /// The Generator class provides methods to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + /// + /// For a given type, a Generator can create columns to match the public properties + /// of that type. The generator can consider all public properties or only those public properties marked with + /// [OLVColumn] attribute. + /// + public class Generator : IGenerator { + #region Static convenience methods + + /// + /// Gets or sets the actual generator used by the static convenience methods. + /// + /// If you subclass the standard generator or implement IGenerator yourself, + /// you should install an instance of your subclass/implementation here. + public static IGenerator Instance { + get { return Generator.instance ?? (Generator.instance = new Generator()); } + set { Generator.instance = value; } + } + private static IGenerator instance; + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable) { + Generator.GenerateColumns(olv, enumerable, false); + } + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable, bool allProperties) { + // Generate columns based on the type of the first model in the collection and then quit + if (enumerable != null) { + foreach (object model in enumerable) { + Generator.Instance.GenerateAndReplaceColumns(olv, model.GetType(), allProperties); + return; + } + } + + // If we reach here, the collection was empty, so we clear the list + Generator.Instance.GenerateAndReplaceColumns(olv, null, allProperties); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + static public void GenerateColumns(ObjectListView olv, Type type) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, false); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, Type type, bool allProperties) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, allProperties); + } + + /// + /// Generate a list of OLVColumns based on the public properties of the given type + /// that have a OLVColumn attribute. + /// + /// + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + static public IList GenerateColumns(Type type) { + return Generator.Instance.GenerateColumns(type, false); + } + + #endregion + + #region Public interface + + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + public virtual void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties) { + IList columns = this.GenerateColumns(type, allProperties); + TreeListView tlv = olv as TreeListView; + if (tlv != null) + this.TryGenerateChildrenDelegates(tlv, type); + this.ReplaceColumns(olv, columns); + } + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + public virtual IList GenerateColumns(Type type, bool allProperties) { + List columns = new List(); + + // Sanity + if (type == null) + return columns; + + // Iterate all public properties in the class and build columns from those that have + // an OLVColumn attribute and that are not ignored. + foreach (PropertyInfo pinfo in type.GetProperties()) { + if (Attribute.GetCustomAttribute(pinfo, typeof(OLVIgnoreAttribute)) != null) + continue; + + OLVColumnAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVColumnAttribute)) as OLVColumnAttribute; + if (attr == null) { + if (allProperties) + columns.Add(this.MakeColumnFromPropertyInfo(pinfo)); + } else { + columns.Add(this.MakeColumnFromAttribute(pinfo, attr)); + } + } + + // How many columns have DisplayIndex specifically set? + int countPositiveDisplayIndex = 0; + foreach (OLVColumn col in columns) { + if (col.DisplayIndex >= 0) + countPositiveDisplayIndex += 1; + } + + // Give columns that don't have a DisplayIndex an incremental index + int columnIndex = countPositiveDisplayIndex; + foreach (OLVColumn col in columns) + if (col.DisplayIndex < 0) + col.DisplayIndex = (columnIndex++); + + columns.Sort(delegate(OLVColumn x, OLVColumn y) { + return x.DisplayIndex.CompareTo(y.DisplayIndex); + }); + + return columns; + } + + #endregion + + #region Implementation + + /// + /// Replace all the columns in the given listview with the given list of columns. + /// + /// + /// + protected virtual void ReplaceColumns(ObjectListView olv, IList columns) { + olv.Reset(); + + // Are there new columns to add? + if (columns == null || columns.Count == 0) + return; + + // Setup the columns + olv.AllColumns.AddRange(columns); + this.PostCreateColumns(olv); + } + + /// + /// Post process columns after creating them and adding them to the AllColumns collection. + /// + /// + public virtual void PostCreateColumns(ObjectListView olv) { + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.CheckBoxes; })) + olv.UseSubItemCheckBoxes = true; + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.Index > 0 && (x.ImageGetter != null || !String.IsNullOrEmpty(x.ImageAspectName)); })) + olv.ShowImagesOnSubItems = true; + olv.RebuildColumns(); + olv.AutoSizeColumns(); + } + + /// + /// Create a column from the given PropertyInfo and OLVColumn attribute + /// + /// + /// + /// + protected virtual OLVColumn MakeColumnFromAttribute(PropertyInfo pinfo, OLVColumnAttribute attr) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, attr); + } + + /// + /// Make a column from the given PropertyInfo + /// + /// + /// + protected virtual OLVColumn MakeColumnFromPropertyInfo(PropertyInfo pinfo) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, null); + } + + /// + /// Make a column from the given PropertyDescriptor + /// + /// + /// + public virtual OLVColumn MakeColumnFromPropertyDescriptor(PropertyDescriptor pd) { + OLVColumnAttribute attr = pd.Attributes[typeof(OLVColumnAttribute)] as OLVColumnAttribute; + return MakeColumn(pd.Name, DisplayNameToColumnTitle(pd.DisplayName), !pd.IsReadOnly, pd.PropertyType, attr); + } + + /// + /// Create a column with all the given information + /// + /// + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, bool editable, Type propertyType, OLVColumnAttribute attr) { + + OLVColumn column = this.MakeColumn(aspectName, title, attr); + column.Name = (attr == null || String.IsNullOrEmpty(attr.Name)) ? aspectName : attr.Name; + this.ConfigurePossibleBooleanColumn(column, propertyType); + + if (attr == null) { + column.IsEditable = editable; + column.Width = -1; // Auto size + return column; + } + + column.AspectToStringFormat = attr.AspectToStringFormat; + if (attr.IsCheckBoxesSet) + column.CheckBoxes = attr.CheckBoxes; + column.DisplayIndex = attr.DisplayIndex; + column.FillsFreeSpace = attr.FillsFreeSpace; + if (attr.IsFreeSpaceProportionSet) + column.FreeSpaceProportion = attr.FreeSpaceProportion; + column.GroupWithItemCountFormat = attr.GroupWithItemCountFormat; + column.GroupWithItemCountSingularFormat = attr.GroupWithItemCountSingularFormat; + column.Hyperlink = attr.Hyperlink; + column.ImageAspectName = attr.ImageAspectName; + column.IsEditable = attr.IsEditableSet ? attr.IsEditable : editable; + column.IsTileViewColumn = attr.IsTileViewColumn; + column.IsVisible = attr.IsVisible; + column.MaximumWidth = attr.MaximumWidth; + column.MinimumWidth = attr.MinimumWidth; + column.Tag = attr.Tag; + if (attr.IsTextAlignSet) + column.TextAlign = attr.TextAlign; + column.ToolTipText = attr.ToolTipText; + if (attr.IsTriStateCheckBoxesSet) + column.TriStateCheckBoxes = attr.TriStateCheckBoxes; + column.UseInitialLetterForGroup = attr.UseInitialLetterForGroup; + column.Width = attr.Width; + if (attr.GroupCutoffs != null && attr.GroupDescriptions != null) + column.MakeGroupies(attr.GroupCutoffs, attr.GroupDescriptions); + return column; + } + + /// + /// Create a column. + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, OLVColumnAttribute attr) { + string columnTitle = (attr == null || String.IsNullOrEmpty(attr.Title)) ? title : attr.Title; + return new OLVColumn(columnTitle, aspectName); + } + + /// + /// Convert a property name to a displayable title. + /// + /// + /// + protected virtual string DisplayNameToColumnTitle(string displayName) { + string title = displayName.Replace("_", " "); + // Put a space between a lower-case letter that is followed immediately by an upper case letter + title = Regex.Replace(title, @"(\p{Ll})(\p{Lu})", @"$1 $2"); + return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title); + } + + /// + /// Configure the given column to show a checkbox if appropriate + /// + /// + /// + protected virtual void ConfigurePossibleBooleanColumn(OLVColumn column, Type propertyType) { + if (propertyType != typeof(bool) && propertyType != typeof(bool?) && propertyType != typeof(CheckState)) + return; + + column.CheckBoxes = true; + column.TextAlign = HorizontalAlignment.Center; + column.Width = 32; + column.TriStateCheckBoxes = (propertyType == typeof(bool?) || propertyType == typeof(CheckState)); + } + + /// + /// If this given type has an property marked with [OLVChildren], make delegates that will + /// traverse that property as the children of an instance of the model + /// + /// + /// + protected virtual void TryGenerateChildrenDelegates(TreeListView tlv, Type type) { + foreach (PropertyInfo pinfo in type.GetProperties()) { + OLVChildrenAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVChildrenAttribute)) as OLVChildrenAttribute; + if (attr != null) { + this.GenerateChildrenDelegates(tlv, pinfo); + return; + } + } + } + + /// + /// Generate CanExpand and ChildrenGetter delegates from the given property. + /// + /// + /// + protected virtual void GenerateChildrenDelegates(TreeListView tlv, PropertyInfo pinfo) { + Munger childrenGetter = new Munger(pinfo.Name); + tlv.CanExpandGetter = delegate(object x) { + try { + IEnumerable result = childrenGetter.GetValueEx(x) as IEnumerable; + return !ObjectListView.IsEnumerableEmpty(result); + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return false; + } + }; + tlv.ChildrenGetter = delegate(object x) { + try { + return childrenGetter.GetValueEx(x) as IEnumerable; + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return null; + } + }; + } + #endregion + + /* + #region Dynamic methods + + /// + /// Generate methods so that reflection is not needed. + /// + /// + /// + public static void GenerateMethods(ObjectListView olv, Type type) { + foreach (OLVColumn column in olv.Columns) { + GenerateColumnMethods(column, type); + } + } + + public static void GenerateColumnMethods(OLVColumn column, Type type) { + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) + column.AspectGetter = Generator.GenerateAspectGetter(type, column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + private static AspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, typeof(Object), new Type[] { type }, type, true); + Generator.GenerateIL(type, path, getter.GetILGenerator()); + return (AspectGetterDelegate)getter.CreateDelegate(typeof(AspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private static void GenerateIL(Type modelType, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + OpCodes.Castclass + // Generate the IL to access each part of the dotted chain + Type type = modelType; + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = Generator.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !modelType.IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private static Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + */ + } +} diff --git a/ObjectListView/Utilities/OLVExporter.cs b/ObjectListView/Utilities/OLVExporter.cs new file mode 100644 index 0000000..1400ba1 --- /dev/null +++ b/ObjectListView/Utilities/OLVExporter.cs @@ -0,0 +1,277 @@ +/* + * OLVExporter - Export the contents of an ObjectListView into various text-based formats + * + * Author: Phillip Piper + * Date: 7 August 2012, 10:35pm + * + * Change log: + * 2012-08-07 JPP Initial code + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace BrightIdeasSoftware { + /// + /// An OLVExporter converts a collection of rows from an ObjectListView + /// into a variety of textual formats. + /// + public class OLVExporter { + + /// + /// What format will be used for exporting + /// + public enum ExportFormat { + + /// + /// Tab separated values, according to http://www.iana.org/assignments/media-types/text/tab-separated-values + /// + TabSeparated = 1, + + /// + /// Alias for TabSeparated + /// + TSV = 1, + + /// + /// Comma separated values, according to http://www.ietf.org/rfc/rfc4180.txt + /// + CSV, + + /// + /// HTML table, according to me + /// + HTML + } + + #region Life and death + + /// + /// Create an empty exporter + /// + public OLVExporter() {} + + /// + /// Create an exporter that will export all the rows of the given ObjectListView + /// + /// + public OLVExporter(ObjectListView olv) : this(olv, olv.Objects) {} + + /// + /// Create an exporter that will export all the given rows from the given ObjectListView + /// + /// + /// + public OLVExporter(ObjectListView olv, IEnumerable objectsToExport) { + if (olv == null) throw new ArgumentNullException("olv"); + if (objectsToExport == null) throw new ArgumentNullException("objectsToExport"); + + this.ListView = olv; + this.ModelObjects = ObjectListView.EnumerableToArray(objectsToExport, true); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the textual + /// representation. If this is false (the default), only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + set { includeHiddenColumns = value; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. Default is true. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + set { includeColumnHeaders = value; } + } + private bool includeColumnHeaders = true; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// to be exported + /// + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + set { modelObjects = value; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + #region Commands + + /// + /// Export the nominated rows from the nominated ObjectListView. + /// Returns the result in the expected format. + /// + /// + /// + /// This will perform only one conversion, even if called multiple times with different formats. + public string ExportTo(ExportFormat format) { + if (results == null) + this.Convert(); + + return results[format]; + } + + /// + /// Convert + /// + public void Convert() { + + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + StringBuilder sbText = new StringBuilder(); + StringBuilder sbCsv = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (this.IncludeColumnHeaders) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.Text); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + + foreach (object modelObject in this.ModelObjects) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.GetStringValue(modelObject)); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + sbHtml.AppendLine("
", "", "
", "", "
"); + + results = new Dictionary(); + results[ExportFormat.TabSeparated] = sbText.ToString(); + results[ExportFormat.CSV] = sbCsv.ToString(); + results[ExportFormat.HTML] = sbHtml.ToString(); + } + + private delegate string StringToString(string str); + + private void WriteOneRow(StringBuilder sb, IEnumerable strings, string startRow, string betweenCells, string endRow, StringToString encoder) { + sb.Append(startRow); + bool first = true; + foreach (string s in strings) { + if (!first) + sb.Append(betweenCells); + sb.Append(encoder == null ? s : encoder(s)); + first = false; + } + sb.AppendLine(endRow); + } + + private Dictionary results; + + #endregion + + #region Encoding + + /// + /// Encode a string such that it can be used as a value in a CSV file. + /// This basically means replacing any quote mark with two quote marks, + /// and enclosing the whole string in quotes. + /// + /// + /// + private static string CsvEncode(string text) { + if (text == null) + return null; + + const string DOUBLEQUOTE = @""""; // one double quote + const string TWODOUBEQUOTES = @""""""; // two double quotes + + StringBuilder sb = new StringBuilder(DOUBLEQUOTE); + sb.Append(text.Replace(DOUBLEQUOTE, TWODOUBEQUOTES)); + sb.Append(DOUBLEQUOTE); + + return sb.ToString(); + } + + /// + /// HTML-encodes a string and returns the encoded string. + /// + /// The text string to encode. + /// The HTML-encoded text. + /// Taken from http://www.west-wind.com/weblog/posts/2009/Feb/05/Html-and-Uri-String-Encoding-without-SystemWeb + private static string HtmlEncode(string text) { + if (text == null) + return null; + + StringBuilder sb = new StringBuilder(text.Length); + + int len = text.Length; + for (int i = 0; i < len; i++) { + switch (text[i]) { + case '<': + sb.Append("<"); + break; + case '>': + sb.Append(">"); + break; + case '"': + sb.Append("""); + break; + case '&': + sb.Append("&"); + break; + default: + if (text[i] > 159) { + // decimal numeric entity + sb.Append("&#"); + sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture)); + sb.Append(";"); + } else + sb.Append(text[i]); + break; + } + } + return sb.ToString(); + } + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/TypedObjectListView.cs b/ObjectListView/Utilities/TypedObjectListView.cs new file mode 100644 index 0000000..8eb6bd0 --- /dev/null +++ b/ObjectListView/Utilities/TypedObjectListView.cs @@ -0,0 +1,561 @@ +/* + * TypedObjectListView - A wrapper around an ObjectListView that provides type-safe delegates. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * v2.6 + * 2012-10-26 JPP - Handle rare case where a null model object was passed into aspect getters. + * v2.3 + * 2009-03-31 JPP - Added Objects property + * 2008-11-26 JPP - Added tool tip getting methods + * 2008-11-05 JPP - Added CheckState handling methods + * 2008-10-24 JPP - Generate dynamic methods MkII. This one handles value types + * 2008-10-21 JPP - Generate dynamic methods + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; +using System.Reflection.Emit; + +namespace BrightIdeasSoftware +{ + /// + /// A TypedObjectListView is a type-safe wrapper around an ObjectListView. + /// + /// + /// VCS does not support generics on controls. It can be faked to some degree, but it + /// cannot be completely overcome. In our case in particular, there is no way to create + /// the custom OLVColumn's that we need to truly be generic. So this wrapper is an + /// experiment in providing some type-safe access in a way that is useful and available today. + /// A TypedObjectListView is not more efficient than a normal ObjectListView. + /// Underneath, the same name of casts are performed. But it is easier to use since you + /// do not have to write the casts yourself. + /// + /// + /// The class of model object that the list will manage + /// + /// To use a TypedObjectListView, you write code like this: + /// + /// TypedObjectListView<Person> tlist = new TypedObjectListView<Person>(this.listView1); + /// tlist.CheckStateGetter = delegate(Person x) { return x.IsActive; }; + /// tlist.GetColumn(0).AspectGetter = delegate(Person x) { return x.Name; }; + /// ... + /// + /// To iterate over the selected objects, you can write something elegant like this: + /// + /// foreach (Person x in tlist.SelectedObjects) { + /// x.GrantSalaryIncrease(); + /// } + /// + /// + public class TypedObjectListView where T : class + { + /// + /// Create a typed wrapper around the given list. + /// + /// The listview to be wrapped + public TypedObjectListView(ObjectListView olv) { + this.olv = olv; + } + + //-------------------------------------------------------------------------------------- + // Properties + + /// + /// Return the model object that is checked, if only one row is checked. + /// If zero rows are checked, or more than one row, null is returned. + /// + public virtual T CheckedObject { + get { return (T)this.olv.CheckedObject; } + } + + /// + /// Return the list of all the checked model objects + /// + public virtual IList CheckedObjects { + get { + IList checkedObjects = this.olv.CheckedObjects; + List objects = new List(checkedObjects.Count); + foreach (object x in checkedObjects) + objects.Add((T)x); + + return objects; + } + set { this.olv.CheckedObjects = (IList)value; } + } + + /// + /// The ObjectListView that is being wrapped + /// + public virtual ObjectListView ListView { + get { return olv; } + set { olv = value; } + } + private ObjectListView olv; + + /// + /// Get or set the list of all model objects + /// + public virtual IList Objects { + get { + List objects = new List(this.olv.GetItemCount()); + for (int i = 0; i < this.olv.GetItemCount(); i++) + objects.Add(this.GetModelObject(i)); + + return objects; + } + set { this.olv.SetObjects(value); } + } + + /// + /// Return the model object that is selected, if only one row is selected. + /// If zero rows are selected, or more than one row, null is returned. + /// + public virtual T SelectedObject { + get { return (T)this.olv.SelectedObject; } + set { this.olv.SelectedObject = value; } + } + + /// + /// The list of model objects that are selected. + /// + public virtual IList SelectedObjects { + get { + List objects = new List(this.olv.SelectedIndices.Count); + foreach (int index in this.olv.SelectedIndices) + objects.Add((T)this.olv.GetModelObject(index)); + + return objects; + } + set { this.olv.SelectedObjects = (IList)value; } + } + + //-------------------------------------------------------------------------------------- + // Accessors + + /// + /// Return a typed wrapper around the column at the given index + /// + /// The index of the column + /// A typed column or null + public virtual TypedColumn GetColumn(int i) { + return new TypedColumn(this.olv.GetColumn(i)); + } + + /// + /// Return a typed wrapper around the column with the given name + /// + /// The name of the column + /// A typed column or null + public virtual TypedColumn GetColumn(string name) { + return new TypedColumn(this.olv.GetColumn(name)); + } + + /// + /// Return the model object at the given index + /// + /// The index of the model object + /// The model object or null + public virtual T GetModelObject(int index) { + return (T)this.olv.GetModelObject(index); + } + + //-------------------------------------------------------------------------------------- + // Delegates + + /// + /// CheckStateGetter + /// + /// + /// + public delegate CheckState TypedCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the check state getter + /// + public virtual TypedCheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { + this.checkStateGetter = value; + if (value == null) + this.olv.CheckStateGetter = null; + else + this.olv.CheckStateGetter = delegate(object x) { + return this.checkStateGetter((T)x); + }; + } + } + private TypedCheckStateGetterDelegate checkStateGetter; + + /// + /// BooleanCheckStateGetter + /// + /// + /// + public delegate bool TypedBooleanCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the boolean check state getter + /// + public virtual TypedBooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.olv.BooleanCheckStateGetter = null; + else + this.olv.BooleanCheckStateGetter = delegate(object x) { + return value((T)x); + }; + } + } + + /// + /// CheckStatePutter + /// + /// + /// + /// + public delegate CheckState TypedCheckStatePutterDelegate(T rowObject, CheckState newValue); + + /// + /// Gets or sets the check state putter delegate + /// + public virtual TypedCheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { + this.checkStatePutter = value; + if (value == null) + this.olv.CheckStatePutter = null; + else + this.olv.CheckStatePutter = delegate(object x, CheckState newValue) { + return this.checkStatePutter((T)x, newValue); + }; + } + } + private TypedCheckStatePutterDelegate checkStatePutter; + + /// + /// BooleanCheckStatePutter + /// + /// + /// + /// + public delegate bool TypedBooleanCheckStatePutterDelegate(T rowObject, bool newValue); + + /// + /// Gets or sets the boolean check state putter + /// + public virtual TypedBooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.olv.BooleanCheckStatePutter = null; + else + this.olv.BooleanCheckStatePutter = delegate(object x, bool newValue) { + return value((T)x, newValue); + }; + } + } + + /// + /// ToolTipGetter + /// + /// + /// + /// + public delegate String TypedCellToolTipGetterDelegate(OLVColumn column, T modelObject); + + /// + /// Gets or sets the cell tooltip getter + /// + public virtual TypedCellToolTipGetterDelegate CellToolTipGetter { + set { + if (value == null) + this.olv.CellToolTipGetter = null; + else + this.olv.CellToolTipGetter = delegate(OLVColumn col, Object x) { + return value(col, (T)x); + }; + } + } + + /// + /// Gets or sets the header tool tip getter + /// + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return this.olv.HeaderToolTipGetter; } + set { this.olv.HeaderToolTipGetter = value; } + } + + //-------------------------------------------------------------------------------------- + // Commands + + /// + /// This method will generate AspectGetters for any column that has an AspectName. + /// + public virtual void GenerateAspectGetters() { + for (int i = 0; i < this.ListView.Columns.Count; i++) + this.GetColumn(i).GenerateAspectGetter(); + } + } + + /// + /// A type-safe wrapper around an OLVColumn + /// + /// + public class TypedColumn where T : class + { + /// + /// Creates a TypedColumn + /// + /// + public TypedColumn(OLVColumn column) { + this.column = column; + } + private OLVColumn column; + + /// + /// + /// + /// + /// + public delegate Object TypedAspectGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate void TypedAspectPutterDelegate(T rowObject, Object newValue); + + /// + /// + /// + /// + /// + public delegate Object TypedGroupKeyGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate Object TypedImageGetterDelegate(T rowObject); + + /// + /// + /// + public TypedAspectGetterDelegate AspectGetter { + get { return this.aspectGetter; } + set { + this.aspectGetter = value; + if (value == null) + this.column.AspectGetter = null; + else + this.column.AspectGetter = delegate(object x) { + return x == null ? null : this.aspectGetter((T)x); + }; + } + } + private TypedAspectGetterDelegate aspectGetter; + + /// + /// + /// + public TypedAspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { + this.aspectPutter = value; + if (value == null) + this.column.AspectPutter = null; + else + this.column.AspectPutter = delegate(object x, object newValue) { + this.aspectPutter((T)x, newValue); + }; + } + } + private TypedAspectPutterDelegate aspectPutter; + + /// + /// + /// + public TypedImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { + this.imageGetter = value; + if (value == null) + this.column.ImageGetter = null; + else + this.column.ImageGetter = delegate(object x) { + return this.imageGetter((T)x); + }; + } + } + private TypedImageGetterDelegate imageGetter; + + /// + /// + /// + public TypedGroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { + this.groupKeyGetter = value; + if (value == null) + this.column.GroupKeyGetter = null; + else + this.column.GroupKeyGetter = delegate(object x) { + return this.groupKeyGetter((T)x); + }; + } + } + private TypedGroupKeyGetterDelegate groupKeyGetter; + + #region Dynamic methods + + /// + /// Generate an aspect getter that does the same thing as the AspectName, + /// except without using reflection. + /// + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + /// If AspectName is empty, this method will do nothing, otherwise + /// this will replace any existing AspectGetter. + /// + /// + public void GenerateAspectGetter() { + if (!String.IsNullOrEmpty(this.column.AspectName)) + this.AspectGetter = this.GenerateAspectGetter(typeof(T), this.column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + private TypedAspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, + typeof(Object), new Type[] { type }, type, true); + this.GenerateIL(type, path, getter.GetILGenerator()); + return (TypedAspectGetterDelegate)getter.CreateDelegate(typeof(TypedAspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private void GenerateIL(Type type, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + + // Generate the IL to access each part of the dotted chain + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = this.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !typeof(T).IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + if (Munger.IgnoreMissingAspects) + il.Emit(OpCodes.Ldnull); + else + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + } +} diff --git a/ObjectListView/VirtualObjectListView.cs b/ObjectListView/VirtualObjectListView.cs new file mode 100644 index 0000000..8c3ba28 --- /dev/null +++ b/ObjectListView/VirtualObjectListView.cs @@ -0,0 +1,1255 @@ +/* + * VirtualObjectListView - A virtual listview delays fetching model objects until they are actually displayed. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-06-14 JPP - Moved handling of CheckBoxes on virtual lists into base class (ObjectListView). + * This allows the property to be set correctly, even when set via an upcast reference. + * 2015-03-25 JPP - Subscribe to change notifications when objects are added + * v2.8 + * 2014-09-26 JPP - Correct an incorrect use of checkStateMap when setting CheckedObjects + * and a CheckStateGetter is installed + * v2.6 + * 2012-06-13 JPP - Corrected several bugs related to groups on virtual lists. + * - Added EnsureNthGroupVisible() since EnsureGroupVisible() can't work on virtual lists. + * v2.5.1 + * 2012-05-04 JPP - Avoid bug/feature in ListView.VirtalListSize setter that causes flickering + * when the size of the list changes. + * 2012-04-24 JPP - Fixed bug that occurred when adding/removing item while the view was grouped. + * v2.5 + * 2011-05-31 JPP - Setting CheckedObjects is more efficient on large collections + * 2011-04-05 JPP - CheckedObjects now only returns objects that are currently in the list. + * ClearObjects() now resets all check state info. + * 2011-03-31 JPP - Filtering on grouped virtual lists no longer behaves strangely. + * 2011-03-17 JPP - Virtual lists can (finally) set CheckBoxes back to false if it has been set to true. + * (this is a little hacky and may not work reliably). + * - GetNextItem() and GetPreviousItem() now work on grouped virtual lists. + * 2011-03-08 JPP - BREAKING CHANGE: 'DataSource' was renamed to 'VirtualListDataSource'. This was necessary + * to allow FastDataListView which is both a DataListView AND a VirtualListView -- + * which both used a 'DataSource' property :( + * v2.4 + * 2010-04-01 JPP - Support filtering + * v2.3 + * 2009-08-28 JPP - BIG CHANGE. Virtual lists can now have groups! + * - Objects property now uses "yield return" -- much more efficient for big lists + * 2009-08-07 JPP - Use new scheme for formatting rows/cells + * v2.2.1 + * 2009-07-24 JPP - Added specialised version of RefreshSelectedObjects() which works efficiently with virtual lists + * (thanks to chriss85 for finding this bug) + * 2009-07-03 JPP - Standardized code format + * v2.2 + * 2009-04-06 JPP - ClearObjects() now works again + * v2.1 + * 2009-02-24 JPP - Removed redundant OnMouseDown() since checkbox + * handling is now handled in the base class + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-12-07 JPP - Trigger Before/AfterSearching events + * 2008-11-15 JPP - Fixed some caching issues + * 2008-11-05 JPP - Rewrote handling of check boxes + * 2008-10-28 JPP - Handle SetSelectedObjects(null) + * 2008-10-02 JPP - MAJOR CHANGE: Use IVirtualListDataSource + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A virtual object list view operates in virtual mode, that is, it only gets model objects for + /// a row when it is needed. This gives it the ability to handle very large numbers of rows with + /// minimal resources. + /// + /// A listview is not a great user interface for a large number of items. But if you've + /// ever wanted to have a list with 10 million items, go ahead, knock yourself out. + /// Virtual lists can never iterate their contents. That would defeat the whole purpose. + /// Animated GIFs should not be used in virtual lists. Animated GIFs require some state + /// information to be stored for each animation, but virtual lists specifically do not keep any state information. + /// In any case, you really do not want to keep state information for 10 million animations! + /// + /// Although it isn't documented, .NET virtual lists cannot have checkboxes. This class codes around this limitation, + /// but you must use the functions provided by ObjectListView: CheckedObjects, CheckObject(), UncheckObject() and their friends. + /// If you use the normal check box properties (CheckedItems or CheckedIndicies), they will throw an exception, since the + /// list is in virtual mode, and .NET "knows" it can't handle checkboxes in virtual mode. + /// + /// Due to the limits of the underlying Windows control, virtual lists do not trigger ItemCheck/ItemChecked events. + /// Use a CheckStatePutter instead. + /// To enable grouping, you must provide an implementation of IVirtualGroups interface, via the GroupingStrategy property. + /// Similarly, to enable filtering on the list, your VirtualListDataSource must also implement the IFilterableDataSource interface. + /// + public class VirtualObjectListView : ObjectListView + { + /// + /// Create a VirtualObjectListView + /// + public VirtualObjectListView() + : base() { + this.VirtualMode = true; // Virtual lists have to be virtual -- no prizes for guessing that :) + + this.CacheVirtualItems += new CacheVirtualItemsEventHandler(this.HandleCacheVirtualItems); + this.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(this.HandleRetrieveVirtualItem); + this.SearchForVirtualItem += new SearchForVirtualItemEventHandler(this.HandleSearchForVirtualItem); + + // At the moment, we don't need to handle this event. But we'll keep this comment to remind us about it. + this.VirtualItemsSelectionRangeChanged += new ListViewVirtualItemsSelectionRangeChangedEventHandler(this.HandleVirtualItemsSelectionRangeChanged); + + this.VirtualListDataSource = new VirtualListVersion1DataSource(this); + + // Virtual lists have to manage their own check state, since the normal ListView control + // doesn't even allow checkboxes on virtual lists + this.PersistentCheckBoxes = true; + } + + #region Public Properties + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + // Virtual lists need Vista and a grouping strategy to show groups + return (ObjectListView.IsVistaOrLater && this.GroupingStrategy != null); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + /// This class optimizes the management of CheckStates so that it will work efficiently even on + /// large lists of item. However, those optimizations are impossible if you install a CheckStateGetter. + /// With a CheckStateGetter installed, the performance of this method is O(n) where n is the size + /// of the list. This could be painfully slow. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IList CheckedObjects { + get { + // If we aren't should checkboxes, then no objects can be checked + if (!this.CheckBoxes) + return new ArrayList(); + + // If the data source has somehow vanished, we can't do anything + if (this.VirtualListDataSource == null) + return new ArrayList(); + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) + return base.CheckedObjects; + + // Collect items that are checked AND that still exist in the list. + ArrayList objects = new ArrayList(); + foreach (KeyValuePair kvp in this.CheckStateMap) + { + if (kvp.Value == CheckState.Checked && + (!this.CheckedObjectsMustStillExistInList || + this.VirtualListDataSource.GetObjectIndex(kvp.Key) >= 0)) + objects.Add(kvp.Key); + } + return objects; + } + set { + if (!this.CheckBoxes) + return; + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) { + base.CheckedObjects = value; + return; + } + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + + // Uncheck anything that is no longer checked + Object[] keys = new Object[this.CheckStateMap.Count]; + this.CheckStateMap.Keys.CopyTo(keys, 0); + foreach (Object key in keys) { + if (!table.Contains(key)) + this.SetObjectCheckedness(key, CheckState.Unchecked); + } + + // Check all the new checked objects + foreach (Object x in table.Keys) + this.SetObjectCheckedness(x, CheckState.Checked); + + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting virtual CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + } + + /// + /// Gets or sets whether or not an object will be included in the CheckedObjects + /// collection, even if it is not present in the control at the moment + /// + /// + /// This property is an implementation detail and should not be altered. + /// + protected internal bool CheckedObjectsMustStillExistInList { + get { return checkedObjectsMustStillExistInList; } + set { checkedObjectsMustStillExistInList = value; } + } + private bool checkedObjectsMustStillExistInList = true; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + for (int i = 0; i < this.GetItemCount(); i++) + yield return this.GetModelObject(i); + } + } + + /// + /// Gets or sets the strategy that will be used to create groups + /// + /// + /// This must be provided for a virtual list to show groups. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IVirtualGroups GroupingStrategy { + get { return this.groupingStrategy; } + set { this.groupingStrategy = value; } + } + private IVirtualGroups groupingStrategy; + + /// + /// Gets whether or not the current list is filtering its contents + /// + /// + /// This is only possible if our underlying data source supports filtering. + /// + public override bool IsFiltering { + get { + return base.IsFiltering && (this.VirtualListDataSource is IFilterableDataSource); + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// Setting this property preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code -- performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists, but if you try to iterate through a list + /// of 10 million objects, it may take some time :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + try { + // If we are filtering, we have to temporarily disable filtering so we get + // the whole collection + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(null, null); + return this.FilteredObjects; + } finally { + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + } + } + set { base.Objects = value; } + } + + /// + /// This delegate is used to fetch a rowObject, given it's index within the list + /// + /// Only use this property if you are not using a VirtualListDataSource. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowGetterDelegate RowGetter { + get { return ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter; } + set { ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter = value; } + } + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + override public bool ShowGroups { + get { + // Pre-Vista, virtual lists cannot show groups + return ObjectListView.IsVistaOrLater && this.showGroups; + } + set { + this.showGroups = value; + if (this.Created && !value) + this.DisableVirtualGroups(); + } + } + private bool showGroups; + + + /// + /// Get/set the data source that is behind this virtual list + /// + /// Setting this will cause the list to redraw. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IVirtualListDataSource VirtualListDataSource { + get { + return this.virtualListDataSource; + } + set { + this.virtualListDataSource = value; + this.CustomSorter = delegate(OLVColumn column, SortOrder sortOrder) { + this.ClearCachedInfo(); + this.virtualListDataSource.Sort(column, sortOrder); + }; + this.BuildList(false); + } + } + private IVirtualListDataSource virtualListDataSource; + + /// + /// Gets or sets the number of rows in this virtual list. + /// + /// + /// There is an annoying feature/bug in the .NET ListView class. + /// When you change the VirtualListSize property, it always scrolls so + /// that the focused item is the top item. This is annoying since it makes + /// the virtual list seem to flicker as the control scrolls to show the focused + /// item and then scrolls back to where ObjectListView wants it to be. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected new virtual int VirtualListSize { + get { return base.VirtualListSize; } + set { + if (value == this.VirtualListSize || value < 0) + return; + + // Get around the 'private' marker on 'virtualListSize' field using reflection + if (virtualListSizeFieldInfo == null) { + virtualListSizeFieldInfo = typeof(ListView).GetField("virtualListSize", BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(virtualListSizeFieldInfo != null); + } + + // Set the base class private field so that it keeps on working + virtualListSizeFieldInfo.SetValue(this, value); + + // Send a raw message to change the virtual list size *without* changing the scroll position + if (this.IsHandleCreated && !this.DesignMode) + NativeMethods.SetItemCount(this, value); + } + } + static private FieldInfo virtualListSizeFieldInfo; + + #endregion + + #region OLV accessing + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + public override int GetItemCount() { + return this.VirtualListSize; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public override object GetModelObject(int index) { + if (this.VirtualListDataSource != null && index >= 0 && index < this.GetItemCount()) + return this.VirtualListDataSource.GetNthObject(index); + else + return null; + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public override int IndexOf(Object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return -1; + + return this.VirtualListDataSource.GetObjectIndex(modelObject); + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public override OLVListItem ModelToItem(object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return null; + + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + return index >= 0 ? this.GetItem(index) : null; + } + + #endregion + + #region Object manipulation + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void AddObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.AddObjects(args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.CheckStateMap.Clear(); + this.SetObjects(new ArrayList()); + } + } + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The index of the group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// + public virtual void EnsureNthGroupVisible(int groupIndex) { + if (!this.ShowGroups) + return; + + if (groupIndex <= 0 || groupIndex >= this.OLVGroups.Count) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + int lastItemInGroup = this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1); + Rectangle r = this.GetItemRect(lastItemInGroup); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Inserts the given collection of model objects to this control at hte given location + /// + /// The index where the new objects will be inserted + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the given position of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void InsertObjects(int index, ICollection modelObjects) + { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(index, modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.InsertObjects(index, args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + /// This method does not resort the items. + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + try { + this.BeginUpdate(); + this.ClearCachedInfo(); + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0) { + this.VirtualListDataSource.UpdateObject(index, modelObject); + this.RedrawItems(index, index, true); + } + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public override void RefreshSelectedObjects() { + foreach (int index in this.SelectedIndices) + this.RedrawItems(index, index, true); + } + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// Due to problems in the underlying ListView, if you remove all the objects from + /// the control using this method and the list scroll vertically when you do so, + /// then when you subsequently add more objects to the control, + /// the vertical scroll bar will become confused and the control will draw one or more + /// blank lines at the top of the list. + /// + public override void RemoveObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the removed objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + + try { + this.BeginUpdate(); + this.VirtualListDataSource.RemoveObjects(args.ObjectsToRemove); + this.BuildList(); + this.UnsubscribeNotifications(args.ObjectsToRemove); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Select the row that is displaying the given model object. All other rows are deselected. + /// + /// Model object to select + /// Should the object be focused as well? + public override void SelectObject(object modelObject, bool setFocus) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + // Check that the object is in the list (plus not all data sources can locate objects) + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index < 0 || index >= this.VirtualListSize) + return; + + // If the given model is already selected, don't do anything else (prevents an flicker) + if (this.SelectedIndices.Count == 1 && this.SelectedIndices[0] == index) + return; + + // Finally, select the row + this.SelectedIndices.Clear(); + this.SelectedIndices.Add(index); + if (setFocus && this.SelectedItem != null) + this.SelectedItem.Focused = true; + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + /// This method has O(n) performance where n is the number of model objects passed. + /// Do not use this to select all the rows in the list -- use SelectAll() for that. + public override void SelectObjects(IList modelObjects) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0 && index < this.VirtualListSize) + this.SelectedIndices.Add(index); + } + } + + /// + /// Set the collection of objects that this control will show. + /// + /// + /// Should the state of the list be preserved as far as is possible. + public override void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(null, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + + this.BeginUpdate(); + try { + this.VirtualListDataSource.SetObjects(args.NewObjects); + this.BuildList(); + this.UpdateNotificationSubscriptions(args.NewObjects); + } + finally { + this.EndUpdate(); + } + } + + #endregion + + #region Check boxes +// +// /// +// /// Check all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void CheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Checked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - CheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// +// } +// +// /// +// /// Uncheck all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void UncheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Unchecked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - UncheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does know and the value from the control will be used. + /// + /// + /// + protected override CheckState? GetCheckState(object modelObject) + { + if (this.CheckStateGetter != null) + return base.GetCheckState(modelObject); + + CheckState state; + if (modelObject != null && this.CheckStateMap.TryGetValue(modelObject, out state)) + return state; + return CheckState.Unchecked; + } + + #endregion + + #region Implementation + + /// + /// Rebuild the list with its current contents. + /// + /// + /// Invalidate any cached information when we rebuild the list. + /// + public override void BuildList(bool shouldPreserveSelection) { + this.UpdateVirtualListSize(); + this.ClearCachedInfo(); + if (this.ShowGroups) + this.BuildGroups(); + else + this.Sort(); + this.Invalidate(); + } + + /// + /// Clear any cached info this list may have been using + /// + public override void ClearCachedInfo() { + this.lastRetrieveVirtualItemIndex = -1; + } + + /// + /// Do the work of creating groups for this control + /// + /// + protected override void CreateGroups(IEnumerable groups) { + + // In a virtual list, we cannot touch the Groups property. + // It was obviously not written for virtual list and often throws exceptions. + + NativeMethods.ClearGroups(this); + + this.EnableVirtualGroups(); + + foreach (OLVGroup group in groups) { + System.Diagnostics.Debug.Assert(group.Items.Count == 0, "Groups in virtual lists cannot set Items. Use VirtualItemCount instead."); + System.Diagnostics.Debug.Assert(group.VirtualItemCount > 0, "VirtualItemCount must be greater than 0."); + + group.InsertGroupNewStyle(this); + } + } + + /// + /// Do the plumbing to disable groups on a virtual list + /// + protected void DisableVirtualGroups() { + NativeMethods.ClearGroups(this); + //System.Diagnostics.Debug.WriteLine(err); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 0, 0); + //System.Diagnostics.Debug.WriteLine(x); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr x2 = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, 0, 0); + //System.Diagnostics.Debug.WriteLine(x2); + } + + /// + /// Do the plumbing to enable groups on a virtual list + /// + protected void EnableVirtualGroups() { + + // We need to implement the IOwnerDataCallback interface + if (this.ownerDataCallbackImpl == null) + this.ownerDataCallbackImpl = new OwnerDataCallbackImpl(this); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr ptr = Marshal.GetComInterfaceForObject(ownerDataCallbackImpl, typeof(IOwnerDataCallback)); + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, ptr, 0); + //System.Diagnostics.Debug.WriteLine(x); + Marshal.Release(ptr); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 1, 0); + //System.Diagnostics.Debug.WriteLine(x); + } + private OwnerDataCallbackImpl ownerDataCallbackImpl; + + /// + /// Return the position of the given itemIndex in the list as it currently shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups) + return itemIndex; + + int groupIndex = this.GroupingStrategy.GetGroup(itemIndex); + int displayIndex = 0; + for (int i = 0; i < groupIndex - 1; i++) + displayIndex += this.OLVGroups[i].VirtualItemCount; + displayIndex += this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemIndex); + + return displayIndex; + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public override OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return base.GetLastItemInDisplayOrder(); + + if (this.OLVGroups.Count > 0) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + if (lastGroup.VirtualItemCount > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.OLVGroups == null || this.OLVGroups.Count == 0) + return this.GetItem(n); + + foreach (OLVGroup group in this.OLVGroups) { + if (n < group.VirtualItemCount) + return this.GetItem(this.GroupingStrategy.GetGroupMember(group, n)); + + n -= group.VirtualItemCount; + } + + return null; + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A OLVListItem + public override OLVListItem GetNextItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetNextItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given item is null, return the first member of the first group + if (itemToFind == null) { + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[0], 0)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the last member, just return the next member + if (indexWithinGroup < this.OLVGroups[groupIndex].VirtualItemCount - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup + 1)); + + // The item is the last member of its group. Return the first member of the next group + // (unless there isn't a next group) + if (groupIndex < this.OLVGroups.Count - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex + 1], 0)); + + return null; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public override OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetPreviousItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given items is null, return the last member of the last group + if (itemToFind == null) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the first member of the group, just return the previous member + if (indexWithinGroup > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup - 1)); + + // The item is the first member of its group. Return the last member of the previous group + // (if there is one) + if (groupIndex > 0) { + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// + protected override IList MakeGroups(GroupingParameters parms) { + if (this.GroupingStrategy == null) + return new List(); + else + return this.GroupingStrategy.GetGroups(parms); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + public virtual OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvi = new OLVListItem(this.GetModelObject(itemIndex)); + this.FillInValues(olvi, olvi.RowObject); + + this.PostProcessOneRow(itemIndex, this.GetDisplayOrderOfItemIndex(itemIndex), olvi); + + if (this.HotRowIndex == itemIndex) + this.UpdateHotRow(olvi); + + return olvi; + } + + /// + /// On virtual lists, this cannot work. + /// + protected override void PostProcessRows() { + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected override CheckState PutCheckState(object modelObject, CheckState state) { + state = base.PutCheckState(modelObject, state); + this.CheckStateMap[modelObject] = state; + return state; + } + + /// + /// Refresh the given item in the list + /// + /// The item to refresh + public override void RefreshItem(OLVListItem olvi) { + this.ClearCachedInfo(); + this.RedrawItems(olvi.Index, olvi.Index, true); + } + + /// + /// Change the size of the list + /// + /// + protected virtual void SetVirtualListSize(int newSize) { + if (newSize < 0 || this.VirtualListSize == newSize) + return; + + int oldSize = this.VirtualListSize; + + this.ClearCachedInfo(); + + // There is a bug in .NET when a virtual ListView is cleared + // (i.e. VirtuaListSize set to 0) AND it is scrolled vertically: the scroll position + // is wrong when the list is next populated. To avoid this, before + // clearing a virtual list, we make sure the list is scrolled to the top. + // [6 weeks later] Damn this is a pain! There are cases where this can also throw exceptions! + try { + if (newSize == 0 && this.TopItemIndex > 0) + this.TopItemIndex = 0; + } + catch (Exception) { + // Ignore any failures + } + + // In strange cases, this can throw the exceptions too. The best we can do is ignore them :( + try { + this.VirtualListSize = newSize; + } + catch (ArgumentOutOfRangeException) { + // pass + } + catch (NullReferenceException) { + // pass + } + + // Tell the world that the size of the list has changed + this.OnItemsChanged(new ItemsChangedEventArgs(oldSize, this.VirtualListSize)); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// VirtualObjectListViews always own their collections, so this is a no-op. + /// + /// + protected override void TakeOwnershipOfObjects() { + } + + /// + /// Change the state of the control to reflect changes in filtering + /// + protected override void UpdateFiltering() { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + if (filterable == null) + return; + + this.BeginUpdate(); + try { + int originalSize = this.VirtualListSize; + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + this.BuildList(); + + //// If the filtering actually did something, rebuild the groups if they are being shown + //if (originalSize != this.VirtualListSize && this.ShowGroups) + // this.BuildGroups(); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change the size of the virtual list so that it matches its data source + /// + public virtual void UpdateVirtualListSize() { + if (this.VirtualListDataSource != null) + this.SetVirtualListSize(this.VirtualListDataSource.GetObjectCount()); + } + + #endregion + + #region Event handlers + + /// + /// Handle the CacheVirtualItems event + /// + /// + /// + protected virtual void HandleCacheVirtualItems(object sender, CacheVirtualItemsEventArgs e) { + if (this.VirtualListDataSource != null) + this.VirtualListDataSource.PrepareCache(e.StartIndex, e.EndIndex); + } + + /// + /// Handle a RetrieveVirtualItem + /// + /// + /// + protected virtual void HandleRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { + // .NET 2.0 seems to generate a lot of these events. Before drawing *each* sub-item, + // this event is triggered 4-8 times for the same index. So we save lots of CPU time + // by caching the last result. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleRetrieveVirtualItem({0})", e.ItemIndex)); + + if (this.lastRetrieveVirtualItemIndex != e.ItemIndex) { + this.lastRetrieveVirtualItemIndex = e.ItemIndex; + this.lastRetrieveVirtualItem = this.MakeListViewItem(e.ItemIndex); + } + e.Item = this.lastRetrieveVirtualItem; + } + + /// + /// Handle the SearchForVirtualList event, which is called when the user types into a virtual list + /// + /// + /// + protected virtual void HandleSearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e) { + // The event has e.IsPrefixSearch, but as far as I can tell, this is always false (maybe that's different under Vista) + // So we ignore IsPrefixSearch and IsTextSearch and always to a case insensitive prefix match. + + // We can't do anything if we don't have a data source + if (this.VirtualListDataSource == null) + return; + + // Where should we start searching? If the last row is focused, the SearchForVirtualItemEvent starts searching + // from the next row, which is actually an invalidate index -- so we make sure we never go past the last object. + int start = Math.Min(e.StartIndex, this.VirtualListDataSource.GetObjectCount() - 1); + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(e.Text, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return; + + // Do the search + int i = this.FindMatchingRow(args.StringToFind, args.StartSearchFrom, e.Direction); + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(args.StringToFind, i); + this.OnAfterSearching(args2); + + // If we found a match, tell the event + if (i != -1) + e.Index = i; + } + + /// + /// Handle the VirtualItemsSelectionRangeChanged event, which is called "when the selection state of a range of items has changed" + /// + /// + /// + /// This method is not called whenever the selection changes on a virtual list. It only seems to be triggered when + /// the user uses Shift-Ctrl-Click to change the selection + protected virtual void HandleVirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e) { + // System.Diagnostics.Debug.WriteLine(string.Format("HandleVirtualItemsSelectionRangeChanged: {0}->{1}, selected: {2}", e.StartIndex, e.EndIndex, e.IsSelected)); + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected override int FindMatchInRange(string text, int first, int last, OLVColumn column) { + return this.VirtualListDataSource.SearchText(text, first, last, column); + } + + #endregion + + #region Variable declarations + + private OLVListItem lastRetrieveVirtualItem; + private int lastRetrieveVirtualItemIndex = -1; + + #endregion + } +} diff --git a/ObjectListView/olv-keyfile.snk b/ObjectListView/olv-keyfile.snk new file mode 100644 index 0000000000000000000000000000000000000000..2658a0adcf122aaa2a591535b53464d516af3378 GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa500986W$cIN!~W%bg8iKqt=v+03$~e~mJs!s zjxU8c(azlkAM^?lBdSg#@Xo86g5b(px(_u*|NRInNPMa(oZ7FOGX3y+S9*R?1vg*78kM6LjIK||X zWAU4blpG9GP}*;3w5@>NY`@4N-#_U$uE!7hH-#IbZu}s16Lpq{mQ;i43=-|@nVZDs zG|+jdK4Cm@V#c*g=H%5QNh=MIIeg0)t4qN7H3-6RuS70^Bde3q0o`&}OfWbuURm=Y zn5*%bskV-f%^ClA~ zN7~lW00)-QecLE7reqRZ{s)OjgHOfCAWI2#-kPm(z2TWw^;P~&q24T=-IOLtj~kL+ zUJ}~BbjP&wIAX literal 0 HcmV?d00001 diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 8e4ae4a..7eb1350 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,10 +128,10 @@ Error Exporting MIDI - GBA Files + Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.* - MIDI Files + MIDI Files (*.mid, *.midi)|*.mid;*.midi Data @@ -202,7 +202,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.* End Current Playlist @@ -338,7 +338,7 @@ Error Exporting WAV - WAV Files + WAV Files (*.wav)|*.wav Export Song as WAV @@ -351,7 +351,7 @@ Error Exporting SF2 - SF2 Files + SF2 Files (*.sf2)|*.sf2 Export VoiceTable as SF2 @@ -364,7 +364,7 @@ Error Exporting DLS - DLS Files + DLS Files (*.dls)|*.dls Export VoiceTable as DLS diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index e5af0e5..a60696a 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -12,8 +12,6 @@ - - diff --git a/VG Music Studio - WinForms/MainForm.cs b/VG Music Studio - WinForms/MainForm.cs index eb1b18b..43c381d 100644 --- a/VG Music Studio - WinForms/MainForm.cs +++ b/VG Music Studio - WinForms/MainForm.cs @@ -7,8 +7,6 @@ using Kermalis.VGMusicStudio.Core.Util; using Kermalis.VGMusicStudio.WinForms.Properties; using Kermalis.VGMusicStudio.WinForms.Util; -using Microsoft.WindowsAPICodePack.Dialogs; -using Microsoft.WindowsAPICodePack.Taskbar; using System; using System.Collections.Generic; using System.ComponentModel; @@ -53,7 +51,6 @@ internal sealed class MainForm : ThemedForm private readonly ColorSlider _volumeBar, _positionBar; private readonly SongInfoControl _songInfo; private readonly ImageComboBox _songsComboBox; - private readonly ThumbnailToolBarButton _prevTButton, _toggleTButton, _nextTButton; #endregion @@ -154,19 +151,6 @@ private MainForm() Resize += OnResize; Text = ConfigUtils.PROGRAM_NAME; - // Taskbar Buttons - if (TaskbarManager.IsPlatformSupported) - { - _prevTButton = new ThumbnailToolBarButton(Resources.IconPrevious, Strings.PlayerPreviousSong); - _prevTButton.Click += PlayPreviousSong; - _toggleTButton = new ThumbnailToolBarButton(Resources.IconPlay, Strings.PlayerPlay); - _toggleTButton.Click += TogglePlayback; - _nextTButton = new ThumbnailToolBarButton(Resources.IconNext, Strings.PlayerNextSong); - _nextTButton.Click += PlayNextSong; - _prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = false; - TaskbarManager.Instance.ThumbnailToolBars.AddButtons(Handle, _prevTButton, _toggleTButton, _nextTButton); - } - OnResize(null, null); } @@ -322,12 +306,12 @@ private void EndCurrentPlaylist(object? sender, EventArgs? e) private void OpenDSE(object? sender, EventArgs? e) { - var d = new CommonOpenFileDialog + var d = new FolderBrowserDialog { - Title = Strings.MenuOpenDSE, - IsFolderPicker = true, + Description = Strings.MenuOpenDSE, + UseDescriptionForTitle = true, }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -335,7 +319,7 @@ private void OpenDSE(object? sender, EventArgs? e) DisposeEngine(); try { - _ = new DSEEngine(d.FileName); + _ = new DSEEngine(d.SelectedPath); } catch (Exception ex) { @@ -352,12 +336,14 @@ private void OpenDSE(object? sender, EventArgs? e) } private void OpenAlphaDream(object? sender, EventArgs? e) { - var d = new CommonOpenFileDialog + var d = new OpenFileDialog { Title = Strings.MenuOpenAlphaDream, - Filters = { new CommonFileDialogFilter(Strings.FilterOpenGBA, ".gba") } + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -382,12 +368,14 @@ private void OpenAlphaDream(object? sender, EventArgs? e) } private void OpenMP2K(object? sender, EventArgs? e) { - var d = new CommonOpenFileDialog + var d = new OpenFileDialog { Title = Strings.MenuOpenMP2K, - Filters = { new CommonFileDialogFilter(Strings.FilterOpenGBA, ".gba") } + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -412,12 +400,14 @@ private void OpenMP2K(object? sender, EventArgs? e) } private void OpenSDAT(object? sender, EventArgs? e) { - var d = new CommonOpenFileDialog + var d = new OpenFileDialog { Title = Strings.MenuOpenSDAT, - Filters = { new CommonFileDialogFilter(Strings.FilterOpenSDAT, ".sdat") }, + Filter = Strings.FilterOpenSDAT, + FilterIndex = 1, + DefaultExt = ".sdat", }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -445,15 +435,15 @@ private void ExportDLS(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = cfg.GetGameName(), - DefaultExtension = ".dls", - EnsureValidNames = true, + FileName = cfg.GetGameName(), + DefaultExt = ".dls", + ValidateNames = true, Title = Strings.MenuSaveDLS, - Filters = { new CommonFileDialogFilter(Strings.FilterSaveDLS, ".dls") }, + Filter = Strings.FilterSaveDLS, }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -470,15 +460,15 @@ private void ExportDLS(object? sender, EventArgs? e) } private void ExportMIDI(object? sender, EventArgs? e) { - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), - DefaultExtension = ".mid", - EnsureValidNames = true, + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".mid", + ValidateNames = true, Title = Strings.MenuSaveMIDI, - Filters = { new CommonFileDialogFilter(Strings.FilterSaveMIDI, ".mid;.midi") }, + Filter = Strings.FilterSaveMIDI, }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -508,15 +498,15 @@ private void ExportSF2(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = cfg.GetGameName(), - DefaultExtension = ".sf2", - EnsureValidNames = true, + FileName = cfg.GetGameName(), + DefaultExt = ".sf2", + ValidateNames = true, Title = Strings.MenuSaveSF2, - Filters = { new CommonFileDialogFilter(Strings.FilterSaveSF2, ".sf2") } + Filter = Strings.FilterSaveSF2, }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -533,15 +523,15 @@ private void ExportSF2(object? sender, EventArgs? e) } private void ExportWAV(object? sender, EventArgs? e) { - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), - DefaultExtension = ".wav", - EnsureValidNames = true, + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".wav", + ValidateNames = true, Title = Strings.MenuSaveWAV, - Filters = { new CommonFileDialogFilter(Strings.FilterSaveWAV, ".wav") }, + Filter = Strings.FilterSaveWAV, }; - if (d.ShowDialog() != CommonFileDialogResult.Ok) + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -580,8 +570,6 @@ public void LetUIKnowPlayerIsPlaying() _pauseButton.Text = Strings.PlayerPause; _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); _timer.Start(); - UpdateTaskbarState(); - UpdateTaskbarButtons(); } private void Play() { @@ -601,8 +589,6 @@ private void Pause() _pauseButton.Text = Strings.PlayerPause; _timer.Start(); } - UpdateTaskbarState(); - UpdateTaskbarButtons(); } private void Stop() { @@ -613,8 +599,6 @@ private void Stop() _songInfo.Reset(); _piano.UpdateKeys(_songInfo.Info.Tracks, PianoTracks); UpdatePositionIndicators(0L); - UpdateTaskbarState(); - UpdateTaskbarButtons(); } private void TogglePlayback(object? sender, EventArgs? e) { @@ -669,7 +653,6 @@ private void FinishLoading(long numSongs) _autoplay = false; SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = true; - UpdateTaskbarButtons(); } private void DisposeEngine() { @@ -680,13 +663,11 @@ private void DisposeEngine() } _trackViewer?.UpdateTracks(); - _prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = _positionBar.Enabled = false; Text = ConfigUtils.PROGRAM_NAME; _songInfo.SetNumTracks(0); _songInfo.ResetMutes(); ResetPlaylistStuff(false); UpdatePositionIndicators(0L); - UpdateTaskbarState(); _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged -= SongNumerical_ValueChanged; _songNumerical.Visible = false; @@ -733,51 +714,6 @@ private void UpdatePositionIndicators(long ticks) { _positionBar.Value = ticks; } - if (GlobalConfig.Instance.TaskbarProgress && TaskbarManager.IsPlatformSupported) - { - TaskbarManager.Instance.SetProgressValue((int)ticks, (int)_positionBar.Maximum); - } - } - private static void UpdateTaskbarState() - { - if (!GlobalConfig.Instance.TaskbarProgress || !TaskbarManager.IsPlatformSupported) - { - return; - } - - TaskbarProgressBarState state; - switch (Engine.Instance?.Player.State) - { - case PlayerState.Playing: state = TaskbarProgressBarState.Normal; break; - case PlayerState.Paused: state = TaskbarProgressBarState.Paused; break; - default: state = TaskbarProgressBarState.NoProgress; break; - } - TaskbarManager.Instance.SetProgressState(state); - } - private void UpdateTaskbarButtons() - { - if (!TaskbarManager.IsPlatformSupported) - { - return; - } - - if (_playlistPlaying) - { - _prevTButton.Enabled = _playedSongs.Count > 0; - _nextTButton.Enabled = true; - } - else - { - _prevTButton.Enabled = _curSong > 0; - _nextTButton.Enabled = _curSong < _songNumerical.Maximum; - } - switch (Engine.Instance.Player.State) - { - case PlayerState.Stopped: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerPlay; break; - case PlayerState.Playing: _toggleTButton.Icon = Resources.IconPause; _toggleTButton.Tooltip = Strings.PlayerPause; break; - case PlayerState.Paused: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerUnpause; break; - } - _toggleTButton.Enabled = true; } private void OpenTrackViewer(object? sender, EventArgs? e) diff --git a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj index e960f0d..bf42797 100644 --- a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj +++ b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj @@ -19,8 +19,8 @@ - - + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 0f1fbff..228d43f 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "V EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - MIDI", "VG Music Studio - MIDI\VG Music Studio - MIDI.csproj", "{6756ED81-71F6-457D-AD23-9C03B6C934E4}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{A171BF23-4281-46CD-AE0B-ED6CD118744E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,6 +29,10 @@ Global {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.Build.0 = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From ccdf3a9c3aa05d41bd1f86622b09632e09106555 Mon Sep 17 00:00:00 2001 From: Davin Date: Sun, 4 Sep 2022 21:31:57 +1000 Subject: [PATCH 02/20] Added GTK3 project --- VG Music Studio - GTK3/MainWindow.cs | 25 +++++++++++++++++++ VG Music Studio - GTK3/Program.cs | 23 +++++++++++++++++ .../VG Music Studio - GTK3.csproj | 12 +++++++++ 3 files changed, 60 insertions(+) create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..89fbb13 --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,25 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.UI +{ + internal class MainWindow : Window + { + public MainWindow() : this(new Builder("MainWindow.glade")) { } + + private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("MainWindow")) + { + + } + + private void Window_DeleteEvent(object sender, DeleteEventArgs a) + { + Application.Quit(); + } + + private void Button1_Clicked(object sender, EventArgs a) + { + + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..4ce1752 --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.UI +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.UI", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..4509a0a --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,12 @@ + + + + WinExe + net6.0 + + + + + + + From 7d54bf9afa6cdb83661637189d128d19f60831c0 Mon Sep 17 00:00:00 2001 From: Davin Date: Sat, 10 Sep 2022 01:42:03 +1000 Subject: [PATCH 03/20] Added MenuBar and methods --- .../Properties/Strings.Designer.cs | 77 ++ .../Properties/Strings.resx | 21 + VG Music Studio - GTK3/MainWindow.cs | 702 +++++++++++++++++- VG Music Studio - GTK3/Program.cs | 4 +- .../VG Music Studio - GTK3.csproj | 4 + VG Music Studio.sln | 6 + 6 files changed, 805 insertions(+), 9 deletions(-) diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index 8a481f3..5cada93 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -743,5 +743,82 @@ public static string TrackViewerTrackX { return ResourceManager.GetString("TrackViewerTrackX", resourceCulture); } } + + /// + /// Looks up a localized string similar to GBA Files. + /// + public static string GTKFilterOpenGBA + { + get + { + return ResourceManager.GetString("GTKFilterOpenGBA", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SDAT Files. + /// + public static string GTKFilterOpenSDAT + { + get + { + return ResourceManager.GetString("GTKFilterOpenSDAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DLS Files. + /// + public static string GTKFilterSaveDLS + { + get + { + return ResourceManager.GetString("GTKFilterSaveDLS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MIDI Files. + /// + public static string GTKFilterSaveMIDI + { + get + { + return ResourceManager.GetString("GTKFilterSaveMIDI", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SF2 Files. + /// + public static string GTKFilterSaveSF2 + { + get + { + return ResourceManager.GetString("GTKFilterSaveSF2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKFilterSaveWAV + { + get + { + return ResourceManager.GetString("GTKFilterSaveWAV", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKAllFiles + { + get + { + return ResourceManager.GetString("GTKAllFiles", resourceCulture); + } + } } } diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 7eb1350..79ccfce 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -373,4 +373,25 @@ VoiceTable saved to {0}. {0} is the file name. + + Game Boy Advance binary + + + Nitro Soundmaker Sound Data + + + DLS Files + + + MIDI Files + + + SF2 Files + + + WAV Files + + + All files + \ No newline at end of file diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs index 89fbb13..c270b05 100644 --- a/VG Music Studio - GTK3/MainWindow.cs +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -1,25 +1,713 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; using Gtk; using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; -namespace Kermalis.VGMusicStudio.UI +namespace Kermalis.VGMusicStudio.GTK3 { - internal class MainWindow : Window + internal sealed class MainWindow : Window { - public MainWindow() : this(new Builder("MainWindow.glade")) { } + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedTracks; + private readonly List _remainingTracks; - private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("MainWindow")) + private bool _stopUI = false; + + #region Widgets + + // For viewing sequenced tracks + private Box _trackViewer; + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _soundNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem; + + // Main Box + private Box _mainBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _soundNumberAdjustment; + + #endregion + + public MainWindow() : base("Main Window") + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedTracks and _remainingTracks with a List() function to be ready for use + //_playedTracks = new List(); + //_remainingTracks = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + //Mixer.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Buttons + + // Spin Button + + // Timer + + // Volume Scale + + // Position Scale + + // Main display + _mainBox = new Box(Orientation.Vertical, 2); + _mainBox.PackStart(_mainMenu, false, false, 0); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Value / _volumeAdjustment.Value)); + } + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; } - private void Window_DeleteEvent(object sender, DeleteEventArgs a) + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) { - Application.Quit(); + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); + _positionScaleFree = true; + } + } + private void PositionScale_MouseButtonRelease(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } } - private void Button1_Clicked(object sender, EventArgs a) + private bool _autoplay = false; + private void SoundNumberSpinButton_ValueChanged(object? sender, EventArgs? e) { + //_songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; + + long index = (long)_soundNumberAdjustment.Value; + Stop(); + Parent.Name = ConfigUtils.PROGRAM_NAME; + //_songsComboBox.SelectedIndex = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + Parent.Name = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_songsComboBox.SelectedIndex = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + } + + private void SetAndLoadTrack(long index) + { + _curSong = index; + if (_soundNumberSpinButton.Value == index) + { + SoundNumberSpinButton_ValueChanged(null, null); + } + else + { + _soundNumberSpinButton.Value = index; + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _soundNumberSpinButton.Visible = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _soundNumberSpinButton.Visible = true; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _soundNumberSpinButton.Visible = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _soundNumberSpinButton.Visible = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, d.FileName), Text); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_soundNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, d.FileName), Text); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, d.FileName), Text); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_soundNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, d.FileName), Text); + } + catch (Exception ex) + { + //FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + timerValue = _timer.Equals(_positionAdjustment); + timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + + } + _soundNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + //SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _soundNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + //ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; + _soundNumberAdjustment.ValueChanged -= SoundNumberSpinButton_ValueChanged; + _soundNumberSpinButton.Visible = false; + _soundNumberSpinButton.Value = _soundNumberAdjustment.Upper = 0; + //_songsComboBox.SelectedItem = null; + //_songsComboBox.Items.Clear(); + //_songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; + _soundNumberSpinButton.ValueChanged += SoundNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedTracks.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } } } } diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs index 4ce1752..0f13fcc 100644 --- a/VG Music Studio - GTK3/Program.cs +++ b/VG Music Studio - GTK3/Program.cs @@ -1,7 +1,7 @@ using Gtk; using System; -namespace Kermalis.VGMusicStudio.UI +namespace Kermalis.VGMusicStudio.GTK3 { internal class Program { @@ -10,7 +10,7 @@ public static void Main(string[] args) { Application.Init(); - var app = new Application("org.Kermalis.VGMusicStudio.UI", GLib.ApplicationFlags.None); + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); app.Register(GLib.Cancellable.Current); var win = new MainWindow(); diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj index 4509a0a..7352a8a 100644 --- a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -9,4 +9,8 @@ + + + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 228d43f..9737985 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -11,6 +11,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - MIDI", "V EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{A171BF23-4281-46CD-AE0B-ED6CD118744E}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +35,10 @@ Global {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.Build.0 = Debug|Any CPU {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.ActiveCfg = Release|Any CPU {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 566ac664cf6ab4cad3330bb6f3dddf4240114b66 Mon Sep 17 00:00:00 2001 From: Davin Date: Sun, 11 Sep 2022 20:09:05 +1000 Subject: [PATCH 04/20] Added Buttons, SpinButton and Scales --- VG Music Studio - GTK3/MainWindow.cs | 65 ++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 17 deletions(-) diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs index c270b05..aaa51c4 100644 --- a/VG Music Studio - GTK3/MainWindow.cs +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -53,7 +53,7 @@ internal sealed class MainWindow : Window _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem; // Main Box - private Box _mainBox; + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; // Volume Button to indicate volume status private readonly VolumeButton _volumeButton; @@ -66,7 +66,7 @@ internal sealed class MainWindow : Window #endregion - public MainWindow() : base("Main Window") + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) { // Main Window // Sets the default size of the Window @@ -74,11 +74,11 @@ public MainWindow() : base("Main Window") // Sets the _playedTracks and _remainingTracks with a List() function to be ready for use - //_playedTracks = new List(); - //_remainingTracks = new List(); + _playedTracks = new List(); + _remainingTracks = new List(); // Configures SetVolumeScale method with the MixerVolumeChanged Event action - //Mixer.MixerVolumeChanged += SetVolumeScale; + Mixer.MixerVolumeChanged += SetVolumeScale; // Main Menu _mainMenu = new MenuBar(); @@ -113,7 +113,7 @@ public MainWindow() : base("Main Window") _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; _dataItem.Submenu = _dataMenu; - _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false _exportDLSItem.Activated += ExportDLS; _dataMenu.Append(_exportDLSItem); @@ -132,18 +132,50 @@ public MainWindow() : base("Main Window") _mainMenu.Append(_dataItem); // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); // Spin Button + _soundNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _soundNumberSpinButton = new SpinButton(_soundNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = false, Visible = false }; + _soundNumberSpinButton.ValueChanged += SoundNumberSpinButton_ValueChanged; // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; // Main display - _mainBox = new Box(Orientation.Vertical, 2); + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + _configSpinButtonBox.PackStart(_soundNumberSpinButton, false, false, 0); + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); Add(_mainBox); @@ -168,15 +200,16 @@ public void SetVolumeScale(float volume) } private bool _positionScaleFree = true; - private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) { if (args.Event.Button == 1) // Number 1 is Left Mouse Button { - Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); - _positionScaleFree = true; + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track } } - private void PositionScale_MouseButtonRelease(object? sender, ButtonPressEventArgs args) + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) { if (args.Event.Button == 1) // Number 1 is Left Mouse Button { @@ -277,6 +310,7 @@ private void OpenDSE(object? sender, EventArgs? e) DSEConfig config = DSEEngine.DSEInstance!.Config; FinishLoading(config.BGMFiles.Length); _soundNumberSpinButton.Visible = false; + _soundNumberSpinButton.NoShowAll = true; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; @@ -296,13 +330,11 @@ private void OpenAlphaDream(object? sender, EventArgs? e) }; filterGBA.AddPattern("*.gba"); filterGBA.AddPattern("*.srl"); - FileFilter allFiles = new FileFilter() { Name = Strings.GTKAllFiles }; allFiles.AddPattern("*.*"); - d.AddFilter(filterGBA); d.AddFilter(allFiles); @@ -326,6 +358,7 @@ private void OpenAlphaDream(object? sender, EventArgs? e) AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; FinishLoading(config.SongTableSizes[0]); _soundNumberSpinButton.Visible = true; + _soundNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = true; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = true; @@ -345,13 +378,11 @@ private void OpenMP2K(object? sender, EventArgs? e) }; filterGBA.AddPattern("*.gba"); filterGBA.AddPattern("*.srl"); - FileFilter allFiles = new FileFilter() { Name = Strings.GTKAllFiles }; allFiles.AddPattern("*.*"); - d.AddFilter(filterGBA); d.AddFilter(allFiles); @@ -375,6 +406,7 @@ private void OpenMP2K(object? sender, EventArgs? e) MP2KConfig config = MP2KEngine.MP2KInstance!.Config; FinishLoading(config.SongTableSizes[0]); _soundNumberSpinButton.Visible = true; + _soundNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = true; _exportSF2Item.Visible = false; @@ -393,13 +425,11 @@ private void OpenSDAT(object? sender, EventArgs? e) Name = Strings.GTKFilterOpenSDAT }; filterSDAT.AddPattern("*.sdat"); - FileFilter allFiles = new FileFilter() { Name = Strings.GTKAllFiles }; allFiles.AddPattern("*.*"); - d.AddFilter(filterSDAT); d.AddFilter(allFiles); @@ -423,6 +453,7 @@ private void OpenSDAT(object? sender, EventArgs? e) SDATConfig config = SDATEngine.SDATInstance!.Config; FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); _soundNumberSpinButton.Visible = true; + _soundNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; From 6a5c7b73a1c1509ef6e5830ac250d3468f89e4d3 Mon Sep 17 00:00:00 2001 From: Davin Date: Mon, 12 Sep 2022 12:38:00 +1000 Subject: [PATCH 05/20] Added TreeListView, sequences kinda working, but still needs more work --- VG Music Studio - GTK3/MainWindow.cs | 265 ++++++++++++++++++++------- 1 file changed, 197 insertions(+), 68 deletions(-) diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs index aaa51c4..e5ba058 100644 --- a/VG Music Studio - GTK3/MainWindow.cs +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -20,16 +20,13 @@ internal sealed class MainWindow : Window private bool _playlistPlaying; private Config.Playlist _curPlaylist; private long _curSong = -1; - private readonly List _playedTracks; - private readonly List _remainingTracks; + private readonly List _playedSequences; + private readonly List _remainingSequences; private bool _stopUI = false; #region Widgets - // For viewing sequenced tracks - private Box _trackViewer; - // Buttons private readonly Button _buttonPlay, _buttonPause, _buttonStop; @@ -37,7 +34,7 @@ internal sealed class MainWindow : Window private readonly Box _splitContainerBox; // Spin Button for the numbered tracks - private readonly SpinButton _soundNumberSpinButton; + private readonly SpinButton _sequenceNumberSpinButton; // Timer private readonly Timer _timer; @@ -46,11 +43,11 @@ internal sealed class MainWindow : Window private readonly MenuBar _mainMenu; // Menus - private readonly Menu _fileMenu, _dataMenu; + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; // Menu Items private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, - _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem; + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; // Main Box private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; @@ -62,7 +59,14 @@ internal sealed class MainWindow : Window private readonly Scale _volumeScale, _positionScale; // Adjustments are for indicating the numbers and the position of the scale - private Adjustment _volumeAdjustment, _positionAdjustment, _soundNumberAdjustment; + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; #endregion @@ -73,9 +77,9 @@ public MainWindow() : base(ConfigUtils.PROGRAM_NAME) SetDefaultSize(500, 300); - // Sets the _playedTracks and _remainingTracks with a List() function to be ready for use - _playedTracks = new List(); - _remainingTracks = new List(); + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); // Configures SetVolumeScale method with the MixerVolumeChanged Event action Mixer.MixerVolumeChanged += SetVolumeScale; @@ -131,6 +135,18 @@ public MainWindow() : base(ConfigUtils.PROGRAM_NAME) _mainMenu.Append(_dataItem); + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + // Buttons _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; _buttonPlay.Clicked += (o, e) => Play(); @@ -140,9 +156,9 @@ public MainWindow() : base(ConfigUtils.PROGRAM_NAME) _buttonStop.Clicked += (o, e) => Stop(); // Spin Button - _soundNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); - _soundNumberSpinButton = new SpinButton(_soundNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = false, Visible = false }; - _soundNumberSpinButton.ValueChanged += SoundNumberSpinButton_ValueChanged; + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; // Timer _timer = new Timer(); @@ -159,21 +175,35 @@ public MainWindow() : base(ConfigUtils.PROGRAM_NAME) _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + // Main display _mainBox = new Box(Orientation.Vertical, 4); _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _mainBox.PackStart(_mainMenu, false, false, 0); _mainBox.PackStart(_configButtonBox, false, false, 0); _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); - _configSpinButtonBox.PackStart(_soundNumberSpinButton, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + _configScaleBox.PackStart(_volumeScale, false, false, 20); _configScaleBox.PackStart(_positionScale, false, false, 20); @@ -218,14 +248,14 @@ private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs } private bool _autoplay = false; - private void SoundNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) { - //_songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; - long index = (long)_soundNumberAdjustment.Value; + long index = (long)_sequenceNumberAdjustment.Value; Stop(); - Parent.Name = ConfigUtils.PROGRAM_NAME; - //_songsComboBox.SelectedIndex = 0; + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; //_songInfo.Reset(); bool success; try @@ -235,7 +265,7 @@ private void SoundNumberSpinButton_ValueChanged(object? sender, EventArgs? e) } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); success = false; } @@ -247,8 +277,8 @@ private void SoundNumberSpinButton_ValueChanged(object? sender, EventArgs? e) Config.Song? song = songs.SingleOrDefault(s => s.Index == index); if (song is not null) { - Parent.Name = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func - //_songsComboBox.SelectedIndex = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; _positionAdjustment.Value = _positionAdjustment.Upper / 10; @@ -268,18 +298,77 @@ private void SoundNumberSpinButton_ValueChanged(object? sender, EventArgs? e) _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; } - - private void SetAndLoadTrack(long index) + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) { _curSong = index; - if (_soundNumberSpinButton.Value == index) + if (_sequenceNumberSpinButton.Value == index) { - SoundNumberSpinButton_ValueChanged(null, null); + SequenceNumberSpinButton_ValueChanged(null, null); } else { - _soundNumberSpinButton.Value = index; + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); } } @@ -303,14 +392,14 @@ private void OpenDSE(object? sender, EventArgs? e) } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); return; } DSEConfig config = DSEEngine.DSEInstance!.Config; FinishLoading(config.BGMFiles.Length); - _soundNumberSpinButton.Visible = false; - _soundNumberSpinButton.NoShowAll = true; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; @@ -351,14 +440,14 @@ private void OpenAlphaDream(object? sender, EventArgs? e) } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); return; } AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; FinishLoading(config.SongTableSizes[0]); - _soundNumberSpinButton.Visible = true; - _soundNumberSpinButton.NoShowAll = false; + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = true; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = true; @@ -399,14 +488,14 @@ private void OpenMP2K(object? sender, EventArgs? e) } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); return; } MP2KConfig config = MP2KEngine.MP2KInstance!.Config; FinishLoading(config.SongTableSizes[0]); - _soundNumberSpinButton.Visible = true; - _soundNumberSpinButton.NoShowAll = false; + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = true; _exportSF2Item.Visible = false; @@ -446,14 +535,14 @@ private void OpenSDAT(object? sender, EventArgs? e) } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); return; } SDATConfig config = SDATEngine.SDATInstance!.Config; FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); - _soundNumberSpinButton.Visible = true; - _soundNumberSpinButton.NoShowAll = false; + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; _exportDLSItem.Visible = false; _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; @@ -487,11 +576,11 @@ private void ExportDLS(object? sender, EventArgs? e) try { AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); - //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, d.FileName), Text); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); } d.Destroy(); @@ -502,7 +591,7 @@ private void ExportMIDI(object? sender, EventArgs? e) Strings.MenuSaveMIDI, this, FileChooserAction.Save, "Save", "Cancel"); - d.SetFilename(Engine.Instance!.Config.GetSongName((long)_soundNumberSpinButton.Value)); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); FileFilter ff = new FileFilter() { @@ -524,19 +613,19 @@ private void ExportMIDI(object? sender, EventArgs? e) SaveCommandsBeforeTranspose = true, ReverseVolume = false, TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> - { - (0, (4, 4)), - }, + { + (0, (4, 4)), + }, }; try { p.SaveAsMIDI(d.Filename, args); - //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, d.FileName), Text); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); } } private void ExportSF2(object? sender, EventArgs? e) @@ -566,11 +655,11 @@ private void ExportSF2(object? sender, EventArgs? e) try { AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); - //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, d.FileName), Text); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); } } private void ExportWAV(object? sender, EventArgs? e) @@ -580,7 +669,7 @@ private void ExportWAV(object? sender, EventArgs? e) this, FileChooserAction.Save, "Save", "Cancel"); - d.SetFilename(Engine.Instance!.Config.GetSongName((long)_soundNumberSpinButton.Value)); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); FileFilter ff = new FileFilter() { @@ -606,11 +695,11 @@ private void ExportWAV(object? sender, EventArgs? e) try { player.Record(d.Filename); - //FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, d.FileName), Text); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); } catch (Exception ex) { - //FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); } player.ShouldFadeOut = oldFade; @@ -667,21 +756,61 @@ private void Stop() _timer.Stop(); UpdatePositionIndicators(0L); } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } private void FinishLoading(long numSongs) { Engine.Instance!.Player.SongEnded += SongEnded; foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) { - + int i = 0; + _sequencesListStore.AppendValues(i++, playlist); + playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray(); } - _soundNumberAdjustment.Upper = numSongs - 1; + _sequenceNumberAdjustment.Upper = numSongs - 1; #if DEBUG // [Debug methods specific to this UI will go in here] #endif _autoplay = false; - //SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); - _soundNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); } private void DisposeEngine() { @@ -695,16 +824,16 @@ private void DisposeEngine() Name = ConfigUtils.PROGRAM_NAME; //_songInfo.SetNumTracks(0); //_songInfo.ResetMutes(); - //ResetPlaylistStuff(false); + ResetPlaylistStuff(false); UpdatePositionIndicators(0L); - //_songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; - _soundNumberAdjustment.ValueChanged -= SoundNumberSpinButton_ValueChanged; - _soundNumberSpinButton.Visible = false; - _soundNumberSpinButton.Value = _soundNumberAdjustment.Upper = 0; - //_songsComboBox.SelectedItem = null; - //_songsComboBox.Items.Clear(); - //_songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; - _soundNumberSpinButton.ValueChanged += SoundNumberSpinButton_ValueChanged; + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; } private void UpdateUI(object? sender, EventArgs? e) @@ -714,7 +843,7 @@ private void UpdateUI(object? sender, EventArgs? e) _stopUI = false; if (_playlistPlaying) { - _playedTracks.Add(_curSong); + _playedSequences.Add(_curSong); } else { From b6b7b07f101ac7ed676c34baea836f8700296ba5 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Wed, 5 Jul 2023 00:06:37 +1000 Subject: [PATCH 06/20] Using Gir.Core to make a GTK4 UI --- .vscode/launch.json | 26 + .vscode/tasks.json | 41 + README.md | 127 ++ SDL2-CS | 1 + .../GBA/MP2K/MP2KMixer_NAudio.cs | 276 +++ VG Music Studio - Core/Mixer.cs | 4 +- VG Music Studio - Core/Mixer_NAudio.cs | 96 ++ .../Properties/Strings.resx | 18 +- .../VG Music Studio - Core.csproj | 4 +- VG Music Studio - GTK4/ExtraLibBindingsGtk.cs | 442 +++++ .../ExtraLibBindingsGtkInternal.cs | 425 +++++ VG Music Studio - GTK4/MainWindow.cs | 1518 +++++++++++++++++ VG Music Studio - GTK4/Program.cs | 107 ++ VG Music Studio - GTK4/Theme.cs | 224 +++ .../Util/FlexibleMessageBox.cs | 763 +++++++++ .../VG Music Studio - GTK4.csproj | 282 +++ VG Music Studio.sln | 12 + portaudio2-sharp/Configuration.cs | 105 ++ portaudio2-sharp/Makefile | 16 + portaudio2-sharp/PaErrorCode.cs | 13 + portaudio2-sharp/PaHostTypeId.cs | 9 + portaudio2-sharp/PaSampleFormat.cs | 14 + portaudio2-sharp/PaStreamCallbackFlags.cs | 11 + portaudio2-sharp/PaStreamCallbackResult.cs | 9 + portaudio2-sharp/PaStreamFlags.cs | 12 + portaudio2-sharp/PortAudioException.cs | 27 + portaudio2-sharp/PortAudioInterop.cs | 342 ++++ portaudio2-sharp/PortAudioStream.cs | 289 ++++ portaudio2-sharp/README | 3 + portaudio2-sharp/libs/README | 2 + portaudio2-sharp/libs/portaudio.dll | Bin 0 -> 306077 bytes portaudio2-sharp/portaudio-sharp.csproj | 13 + portaudio2-sharp/portaudio-sharp.sln | 20 + 33 files changed, 5239 insertions(+), 12 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json create mode 160000 SDL2-CS create mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs create mode 100644 VG Music Studio - Core/Mixer_NAudio.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindingsGtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj create mode 100644 portaudio2-sharp/Configuration.cs create mode 100644 portaudio2-sharp/Makefile create mode 100644 portaudio2-sharp/PaErrorCode.cs create mode 100644 portaudio2-sharp/PaHostTypeId.cs create mode 100644 portaudio2-sharp/PaSampleFormat.cs create mode 100644 portaudio2-sharp/PaStreamCallbackFlags.cs create mode 100644 portaudio2-sharp/PaStreamCallbackResult.cs create mode 100644 portaudio2-sharp/PaStreamFlags.cs create mode 100644 portaudio2-sharp/PortAudioException.cs create mode 100644 portaudio2-sharp/PortAudioInterop.cs create mode 100644 portaudio2-sharp/PortAudioStream.cs create mode 100644 portaudio2-sharp/README create mode 100644 portaudio2-sharp/libs/README create mode 100644 portaudio2-sharp/libs/portaudio.dll create mode 100644 portaudio2-sharp/portaudio-sharp.csproj create mode 100644 portaudio2-sharp/portaudio-sharp.sln diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..23ffcc2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/VG Music Studio - GTK4/bin/Debug/net6.0/VG Music Studio - GTK4.dll", + "args": [], + "cwd": "${workspaceFolder}/VG Music Studio - GTK4", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..bf93855 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md index 90f4177..d214231 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,133 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General diff --git a/SDL2-CS b/SDL2-CS new file mode 160000 index 0000000..f8c6fc4 --- /dev/null +++ b/SDL2-CS @@ -0,0 +1 @@ +Subproject commit f8c6fc407fbb22072fdafcda918aec52b2102519 diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs new file mode 100644 index 0000000..23fca8f --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs @@ -0,0 +1,276 @@ +/* This will be used as a reference and NAudio may be used for debugging and comparing. + +using Kermalis.VGMusicStudio.Core.Util; +using NAudio.Wave; +using System; +using System.Linq; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +public sealed class MP2KMixer_NAudio : Mixer_NAudio +{ + internal readonly int SampleRate; + internal readonly int SamplesPerBuffer; + internal readonly float SampleRateReciprocal; + private readonly float _samplesReciprocal; + internal readonly float PCM8MasterVolume; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; + + internal readonly MP2KConfig Config; + private readonly WaveBuffer _audio; + private readonly float[][] _trackBuffers; + private readonly PCM8Channel[] _pcm8Channels; + private readonly SquareChannel _sq1; + private readonly SquareChannel _sq2; + private readonly PCM4Channel _pcm4; + private readonly NoiseChannel _noise; + private readonly PSGChannel[] _psgChannels; + private readonly BufferedWaveProvider _buffer; + + internal MP2KMixer_NAudio(MP2KConfig config) + { + Config = config; + (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; + + _pcm8Channels = new PCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new PCM8Channel(this); + } + _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; + + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + Init(_buffer); + } + + internal PCM8Channel AllocPCM8Channel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) + { + PCM8Channel nChn = null; + IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner == null ? 0xFF : c.Owner.Index); + foreach (PCM8Channel i in byOwner) // Find free + { + if (i.State == EnvelopeState.Dead || i.Owner == null) + { + nChn = i; + break; + } + } + if (nChn == null) // Find releasing + { + foreach (PCM8Channel i in byOwner) + { + if (i.State == EnvelopeState.Releasing) + { + nChn = i; + break; + } + } + } + if (nChn == null) // Find prioritized + { + foreach (PCM8Channel i in byOwner) + { + if (owner.Priority > i.Owner.Priority) + { + nChn = i; + break; + } + } + } + if (nChn == null) // None available + { + PCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one + if (lowest.Owner.Index >= owner.Index) + { + nChn = lowest; + } + } + if (nChn != null) // Could still be null from the above if + { + nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); + } + return nChn; + } + internal PSGChannel AllocPSGChannel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) + { + PSGChannel nChn; + switch (type) + { + case VoiceType.Square1: + { + nChn = _sq1; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) + { + return null; + } + _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.Square2: + { + nChn = _sq2; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) + { + return null; + } + _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.PCM4: + { + nChn = _pcm4; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) + { + return null; + } + _pcm4.Init(owner, note, env, instPan, (int)arg); + break; + } + case VoiceType.Noise: + { + nChn = _noise; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) + { + return null; + } + _noise.Init(owner, note, env, instPan, (NoisePattern)arg); + break; + } + default: return null; + } + nChn.SetVolume(vol, pan); + nChn.SetPitch(pitch); + return nChn; + } + + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } + + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } + internal void Process(bool output, bool recording) + { + for (int i = 0; i < _trackBuffers.Length; i++) + { + float[] buf = _trackBuffers[i]; + Array.Clear(buf, 0, buf.Length); + } + _audio.Clear(); + + for (int i = 0; i < _pcm8Channels.Length; i++) + { + PCM8Channel c = _pcm8Channels[i]; + if (c.Owner != null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } + + for (int i = 0; i < _psgChannels.Length; i++) + { + PSGChannel c = _psgChannels[i]; + if (c.Owner != null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } + + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < _trackBuffers.Length; i++) + { + if (Mutes[i]) + { + continue; + } + + float level = masterLevel; + float[] buf = _trackBuffers[i]; + for (int j = 0; j < SamplesPerBuffer; j++) + { + _audio.FloatBuffer[j * 2] += buf[j * 2] * level; + _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + level += masterStep; + } + } + if (output) + { + _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + if (recording) + { + _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + } +} + */ \ No newline at end of file diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index fb6b818..1c06132 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -1,4 +1,4 @@ -using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi; using NAudio.CoreAudioApi.Interfaces; using NAudio.Wave; using System; @@ -90,4 +90,4 @@ public virtual void Dispose() _out.Dispose(); _appVolume.Dispose(); } -} +} \ No newline at end of file diff --git a/VG Music Studio - Core/Mixer_NAudio.cs b/VG Music Studio - Core/Mixer_NAudio.cs new file mode 100644 index 0000000..2a0d18a --- /dev/null +++ b/VG Music Studio - Core/Mixer_NAudio.cs @@ -0,0 +1,96 @@ +/* This will be used as a reference and NAudio may be used for debugging and comparing. + +using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.Wave; +using System; + +namespace Kermalis.VGMusicStudio.Core; + +public abstract class Mixer_NAudio : IAudioSessionEventsHandler, IDisposable +{ + public static event Action? MixerVolumeChanged; + + public readonly bool[] Mutes; + private IWavePlayer _out; + private AudioSessionControl _appVolume; + + private bool _shouldSendVolUpdateEvent = true; + + protected Mixer_NAudio() + { + Mutes = new bool[SongState.MAX_TRACKS]; + } + + protected void Init(IWaveProvider waveProvider) + { + _out = new WasapiOut(); + _out.Init(waveProvider); + using (var en = new MMDeviceEnumerator()) + { + SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; + int id = Environment.ProcessId; + for (int i = 0; i < sessions.Count; i++) + { + AudioSessionControl session = sessions[i]; + if (session.GetProcessID == id) + { + _appVolume = session; + _appVolume.RegisterEventClient(this); + break; + } + } + } + _out.Play(); + } + + public void OnVolumeChanged(float volume, bool isMuted) + { + if (_shouldSendVolUpdateEvent) + { + MixerVolumeChanged?.Invoke(volume); + } + _shouldSendVolUpdateEvent = true; + } + public void OnDisplayNameChanged(string displayName) + { + throw new NotImplementedException(); + } + public void OnIconPathChanged(string iconPath) + { + throw new NotImplementedException(); + } + public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) + { + throw new NotImplementedException(); + } + public void OnGroupingParamChanged(ref Guid groupingId) + { + throw new NotImplementedException(); + } + // Fires on @out.Play() and @out.Stop() + public void OnStateChanged(AudioSessionState state) + { + if (state == AudioSessionState.AudioSessionStateActive) + { + OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); + } + } + public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) + { + throw new NotImplementedException(); + } + public void SetVolume(float volume) + { + _shouldSendVolUpdateEvent = false; + _appVolume.SimpleAudioVolume.Volume = volume; + } + + public virtual void Dispose() + { + _out.Stop(); + _out.Dispose(); + _appVolume.Dispose(); + } +} + */ \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 79ccfce..c88d68c 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -134,10 +134,10 @@ MIDI Files (*.mid, *.midi)|*.mid;*.midi - Data + _Data - File + _File Open GBA ROM (MP2K) @@ -374,24 +374,24 @@ {0} is the file name. - Game Boy Advance binary + Game Boy Advance binary (*.gba, *.srl) - Nitro Soundmaker Sound Data + Nitro Soundmaker Sound Data (*.sdat) - DLS Files + DLS Soundfont Files (*.dls) - MIDI Files + MIDI Sequence Files (*.mid, *.midi) - SF2 Files + SF2 Soundfont Files (*.sf2) - WAV Files + Wave Audio Data (*.wav) - All files + All files (*.*) \ No newline at end of file diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index a60696a..4662854 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -14,7 +14,9 @@ - + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs b/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs new file mode 100644 index 0000000..8626a50 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs @@ -0,0 +1,442 @@ +using System; +using System.Runtime.InteropServices; +using Gtk.Internal; + +namespace Gtk; + +public partial class AlertDialog : GObject.Object +{ + protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) + { + } + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint linux_gtk_alert_dialog_new(string format); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint macos_gtk_alert_dialog_new(string format); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint windows_gtk_alert_dialog_new(string format); + + private static IntPtr ObjPtr; + + public static AlertDialog New(string format) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + ObjPtr = linux_gtk_alert_dialog_new(format); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + ObjPtr = macos_gtk_alert_dialog_new(format); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + ObjPtr = windows_gtk_alert_dialog_new(format); + } + return new AlertDialog(ObjPtr, true); + } +} + +public partial class FileDialog : GObject.Object +{ + [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] + private static extern void LinuxUnref(nint obj); + + [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] + private static extern void MacOSUnref(nint obj); + + [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] + private static extern void WindowsUnref(nint obj); + + [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] + private static extern void LinuxReturnValue(nint task, nint result); + + [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] + private static extern void MacOSReturnValue(nint task, nint result); + + [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] + private static extern void WindowsReturnValue(nint task, nint result); + + [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] + private static extern string LinuxGetPath(nint file); + + [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] + private static extern string MacOSGetPath(nint file); + + [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] + private static extern string WindowsGetPath(nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void LinuxLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void MacOSLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void WindowsLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] + private static extern nint LinuxNew(); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] + private static extern nint MacOSNew(); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] + private static extern nint WindowsNew(); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint LinuxGetInitialFile(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint MacOSGetInitialFile(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint WindowsGetInitialFile(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint LinuxGetInitialFolder(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint MacOSGetInitialFolder(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint WindowsGetInitialFolder(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string LinuxGetInitialName(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string MacOSGetInitialName(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string WindowsGetInitialName(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void LinuxSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void MacOSSetTitle(nint dialog, string title); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void WindowsSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void LinuxSetFilters(nint dialog, nint filters); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void MacOSSetFilters(nint dialog, nint filters); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void WindowsSetFilters(nint dialog, nint filters); + + public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] + private static extern void LinuxOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] + private static extern void MacOSOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] + private static extern void WindowsOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint LinuxOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint MacOSOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint WindowsOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] + private static extern void LinuxSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] + private static extern void MacOSSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] + private static extern void WindowsSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint LinuxSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint MacOSSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint WindowsSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void LinuxSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void MacOSSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void WindowsSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint LinuxSelectFolderFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint MacOSSelectFolderFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint WindowsSelectFolderFinish(nint dialog, nint result, nint error); + + private static IntPtr ObjPtr; + private GAsyncReadyCallback callbackHandle { get; set; } + + private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) + { + } + + // GtkFileDialog* gtk_file_dialog_new (void) + public static FileDialog New() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + ObjPtr = LinuxNew(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + ObjPtr = MacOSNew(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + ObjPtr = WindowsNew(); + } + return new FileDialog(ObjPtr, true); + } + + // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); + } + } + + // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) + public nint OpenFinish(nint result, nint error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxOpenFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSOpenFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsOpenFinish(ObjPtr, result, error); + } + return OpenFinish(result, error); + } + + // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSave(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSave(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSave(ObjPtr, parent, cancellable, callback, user_data); + } + } + + // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) + public nint SaveFinish(nint result, nint error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxSaveFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSSaveFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsSaveFinish(ObjPtr, result, error); + } + return SaveFinish(result, error); + } + + // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) + { + // if (cancellable is null) + // { + // cancellable = nint.New(); + // cancellable.Handle.Equals(IntPtr.Zero); + // cancellable.Cancel(); + // user_data = IntPtr.Zero; + // } + + + // callback = (source, res) => + // { + // var data = new nint(); + // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); + // }; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSelectFolder(ObjPtr, Handle, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSelectFolder(ObjPtr, Handle, cancellable, callback, user_data); + } + } + + // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) + public nint SelectFolderFinish(nint result, nint error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxSelectFolderFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSSelectFolderFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsSelectFolderFinish(ObjPtr, result, error); + } + return SelectFolderFinish(result, error); + } + + // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) + public nint GetInitialFile() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxGetInitialFile(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSGetInitialFile(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsGetInitialFile(ObjPtr); + } + return GetInitialFile(); + } + + // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) + public nint GetInitialFolder() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxGetInitialFolder(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSGetInitialFolder(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsGetInitialFolder(ObjPtr); + } + return GetInitialFolder(); + } + + // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) + public string GetInitialName() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxGetInitialName(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSGetInitialName(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsGetInitialName(ObjPtr); + } + return GetInitialName(); + } + + // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) + public void SetTitle(string title) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSetTitle(ObjPtr, title); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSetTitle(ObjPtr, title); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSetTitle(ObjPtr, title); + } + } + + // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) + public void SetFilters(Gio.ListModel filters) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSetFilters(ObjPtr, filters.Handle); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSetFilters(ObjPtr, filters.Handle); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSetFilters(ObjPtr, filters.Handle); + } + } + + + + + + public string GetPath(nint path) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxGetPath(path); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSGetPath(path); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsGetPath(path); + } + return path.ToString(); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs new file mode 100644 index 0000000..44cdfd8 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs @@ -0,0 +1,425 @@ +using System; +using System.Runtime.InteropServices; + +namespace Gtk.Internal; + +public partial class AlertDialog : GObject.Internal.Object +{ + protected AlertDialog(IntPtr handle, bool ownedRef) : base() + { + } + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint linux_gtk_alert_dialog_new(string format); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint macos_gtk_alert_dialog_new(string format); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] + private static extern nint windows_gtk_alert_dialog_new(string format); + + private static IntPtr ObjPtr; + + public static AlertDialog New(string format) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + ObjPtr = linux_gtk_alert_dialog_new(format); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + ObjPtr = macos_gtk_alert_dialog_new(format); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + ObjPtr = windows_gtk_alert_dialog_new(format); + } + return new AlertDialog(ObjPtr, true); + } +} + +public partial class FileDialog : GObject.Internal.Object +{ + [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] + private static extern void LinuxUnref(nint obj); + + [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] + private static extern void MacOSUnref(nint obj); + + [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] + private static extern void WindowsUnref(nint obj); + + [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] + private static extern void LinuxReturnValue(nint task, nint result); + + [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] + private static extern void MacOSReturnValue(nint task, nint result); + + [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] + private static extern void WindowsReturnValue(nint task, nint result); + + [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] + private static extern string LinuxGetPath(nint file); + + [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] + private static extern string MacOSGetPath(nint file); + + [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] + private static extern string WindowsGetPath(nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void LinuxLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void MacOSLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void WindowsLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] + private static extern nint LinuxNew(); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] + private static extern nint MacOSNew(); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] + private static extern nint WindowsNew(); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint LinuxGetInitialFile(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint MacOSGetInitialFile(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint WindowsGetInitialFile(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint LinuxGetInitialFolder(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint MacOSGetInitialFolder(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint WindowsGetInitialFolder(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string LinuxGetInitialName(nint dialog); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string MacOSGetInitialName(nint dialog); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern string WindowsGetInitialName(nint dialog); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void LinuxSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void MacOSSetTitle(nint dialog, string title); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void WindowsSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + + public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] + private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] + private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] + private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] + private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] + private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] + private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + + private static IntPtr ObjPtr; + private static IntPtr UserData; + private GAsyncReadyCallback callbackHandle { get; set; } + private static IntPtr FilePath; + + private FileDialog(IntPtr handle, bool ownedRef) : base() + { + } + + // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); + } + } + + // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) + public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxOpenFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSOpenFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsOpenFinish(ObjPtr, result, error); + } + return OpenFinish(result, error); + } + + // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSave(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSave(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSave(ObjPtr, parent, cancellable, callback, user_data); + } + } + + // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) + public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSaveFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSaveFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSaveFinish(ObjPtr, result, error); + } + return SaveFinish(result, error); + } + + // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) + public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) + { + // if (cancellable is null) + // { + // cancellable = Gio.Internal.Cancellable.New(); + // cancellable.Handle.Equals(IntPtr.Zero); + // cancellable.Cancel(); + // UserData = IntPtr.Zero; + // } + + + // callback = (source, res) => + // { + // var data = new nint(); + // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); + // }; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); + } + } + + // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) + public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSelectFolderFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSelectFolderFinish(ObjPtr, result, error); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSelectFolderFinish(ObjPtr, result, error); + } + return SelectFolderFinish(result, error); + } + + // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) + public Gio.Internal.File GetInitialFile() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxGetInitialFile(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSGetInitialFile(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsGetInitialFile(ObjPtr); + } + return GetInitialFile(); + } + + // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) + public Gio.Internal.File GetInitialFolder() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxGetInitialFolder(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSGetInitialFolder(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsGetInitialFolder(ObjPtr); + } + return GetInitialFolder(); + } + + // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) + public string GetInitialName() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxGetInitialName(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return MacOSGetInitialName(ObjPtr); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return WindowsGetInitialName(ObjPtr); + } + return GetInitialName(); + } + + // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) + public void SetTitle(string title) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSetTitle(ObjPtr, title); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSetTitle(ObjPtr, title); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSetTitle(ObjPtr, title); + } + } + + // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) + public void SetFilters(Gio.Internal.ListModel filters) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + LinuxSetFilters(ObjPtr, filters); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSSetFilters(ObjPtr, filters); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsSetFilters(ObjPtr, filters); + } + } + + + + + + public string GetPath(nint path) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return LinuxGetPath(path); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + MacOSGetPath(FilePath); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + WindowsGetPath(FilePath); + } + return FilePath.ToString(); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..b76b3cf --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1518 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +using Application = Adw.Application; +using Window = Adw.Window; +using GObject; +using Kermalis.VGMusicStudio.GTK4.Util; +using System.Runtime.InteropServices; +using System.Diagnostics; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal sealed class MainWindow : Window + { + [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] + private static extern void LinuxUnref(nint obj); + + [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] + private static extern void MacOSUnref(nint obj); + + [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] + private static extern void WindowsUnref(nint obj); + + [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] + private static extern string LinuxGetPath(nint file); + + [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] + private static extern string MacOSGetPath(nint file); + + [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] + private static extern string WindowsGetPath(nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void LinuxLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void MacOSLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] + private static extern void WindowsLoadFromData(nint provider, string data, int length); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] + private static extern nint linux_gtk_file_dialog_new(); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] + private static extern nint macos_gtk_file_dialog_new(); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] + private static extern nint windows_gtk_file_dialog_new(); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint LinuxGetInitialFile(nint dialog, nint file); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint MacOSGetInitialFile(nint dialog, nint file); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] + private static extern nint WindowsGetInitialFile(nint dialog, nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint LinuxGetInitialFolder(nint dialog, nint file); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint MacOSGetInitialFolder(nint dialog, nint file); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] + private static extern nint WindowsGetInitialFolder(nint dialog, nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern nint LinuxGetInitialName(nint dialog, nint file); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern nint MacOSGetInitialName(nint dialog, nint file); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] + private static extern nint WindowsGetInitialName(nint dialog, nint file); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void LinuxSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void MacOSSetTitle(nint dialog, string title); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] + private static extern void WindowsSetTitle(nint dialog, string title); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void LinuxSetFilters(nint dialog, nint filters); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void MacOSSetFilters(nint dialog, nint filters); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] + private static extern void WindowsSetFilters(nint dialog, nint filters); + + private delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] + private static extern void LinuxOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] + private static extern void MacOSOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] + private static extern void WindowsOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint LinuxOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint MacOSOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] + private static extern nint WindowsOpenFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] + private static extern void LinuxSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] + private static extern void MacOSSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] + private static extern void WindowsSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint LinuxSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint MacOSSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] + private static extern nint WindowsSaveFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void LinuxSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void MacOSSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] + private static extern void WindowsSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + + [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint LinuxSelectFolderFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint MacOSSelectFolderFinish(nint dialog, nint result, nint error); + + [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] + private static extern nint WindowsSelectFolderFinish(nint dialog, nint result, nint error); + + + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Menu Widgets + private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget, + _sequencesScrListView, _sequencesListView; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // List Item Factory + private readonly ListItemFactory _sequencesListFactory; + + // String List + private string[] _sequencesListRowLabel; + private StringList _sequencesStringList; + + // Single Selection + private readonly SingleSelection _sequencesSingleSelection; + + // Column View + private readonly ColumnView _sequencesColumnView; + private readonly ColumnViewColumn _sequencesColumn; + + // List Item + private readonly ListItem _sequencesListItem; + + // Tree View + private readonly TreeView _sequencesTreeView; + //private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + // Signal + private Signal _signal; + + // Callback + private Gtk.FileDialog.GAsyncReadyCallback _saveCallback { get; set; } + private Gtk.FileDialog.GAsyncReadyCallback _openCallback { get; set; } + private Gtk.FileDialog.GAsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.AsyncReadyCallback _openCB { get; set; } + private Gio.AsyncReadyCallback _saveCB { get; set; } + private Gio.AsyncReadyCallback _selectFolderCB { get; set; } + private Gio.AsyncReadyCallback _exceptionCallback { get; set;} + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item, not the file menu itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + //_mainMenu.PrependItem(_dataItem); // Data menu item needs to be reserved, but remain invisible until a sound engine is initialized. + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + //_mainMenu.PrependItem(_playlistItem); // Same thing as Data menu item. + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); + _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _positionScale = Scale.New(Orientation.Horizontal, _positionAdjustment); + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionGestureClick = GestureClick.New(); + //_positionGestureClick.GetWidget().SetParent(_positionScale); + _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListRowLabel = new string[3] { "#", "Internal Name", null }; + _sequencesStringList = StringList.New(_sequencesListRowLabel); + _sequencesScrListView = ScrolledWindow.New(); + _sequencesSingleSelection = SingleSelection.New(_sequencesStringList); + _sequencesColumnView = ColumnView.New(_sequencesSingleSelection); + _sequencesColumn = ColumnViewColumn.New("Name", _sequencesListFactory); + //_sequencesColumn.GetColumnView().SetParent(_sequencesColumnView); + _sequencesListFactory = SignalListItemFactory.New(); + _sequencesGestureClick = GestureClick.New(); + _sequencesListView = ListView.New(_sequencesSingleSelection, _sequencesListFactory); + _sequencesListView.SetParent(_sequencesScrListView); + //_sequencesGestureClick.GetWidget().SetParent(_sequencesListView); + //_sequencesListView = new TreeView(); + //_sequencesListStore = new ListStore(typeof(string), typeof(string)); + //_sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + //_sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + //_sequencesListView.AppendColumn(_sequencesColumn); + //_sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + _mainBox.Append(_sequencesScrListView); + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + SetContent(_mainBox); + + Show(); + + // Ensures the entire application closes when the window is closed + //OnCloseRequest += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment.Value / _volumeAdjustment.Value)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, GestureClick.ReleasedSignalArgs args) + { + if (args.NPress == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Adjustment.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, GestureClick.PressedSignalArgs args) + { + if (args.NPress == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + _signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVWidget.Sensitive = success; + _exportMIDIWidget.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSWidget.Sensitive = _exportSF2Widget.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + _signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + private void SequencesListView_SelectionGet(object sender, EventArgs e) + { + var item = new object(); + item = _sequencesSingleSelection.SelectedItem; + if (item is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item is Config.Playlist playlist) + { + if (playlist.Songs.Count > 0 + && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endPlaylistWidget.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + //_endPlaylistWidget.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = d.SelectFolderFinish(res, IntPtr.Zero); + if (folderHandle != IntPtr.Zero) + { + var path = d.GetPath(folderHandle); + OpenDSEFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + // if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + // { + // var d = linux_gtk_file_dialog_new(); + // LinuxSetTitle(d, Strings.MenuOpenDSE); + + // _selectFolderCallback = (source, res, data) => + // { + // var folderHandle = LinuxSelectFolderFinish(d, res, IntPtr.Zero); + // if (folderHandle != IntPtr.Zero) + // { + // var path = LinuxGetPath(folderHandle); + // OpenDSEFinish(path); // GtkFileDialog also doesn't have blocking APIs. + // } + // }; + // LinuxSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + // } + // else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + // { + // var d = macos_gtk_file_dialog_new(); + // MacOSSetTitle(d, Strings.MenuOpenDSE); + + // _selectFolderCallback = (source, res, data) => + // { + // var folderHandle = MacOSSelectFolderFinish(d, res, IntPtr.Zero); + // if (folderHandle != IntPtr.Zero) + // { + // var path = MacOSGetPath(folderHandle); + // OpenDSEFinish(path); + // } + // }; + // MacOSSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + // } + // else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + // { + // var d = windows_gtk_file_dialog_new(); + // WindowsSetTitle(d, Strings.MenuOpenDSE); + + // _selectFolderCallback = (source, res, data) => + // { + // var folderHandle = WindowsSelectFolderFinish(d, res, IntPtr.Zero); + // if (folderHandle != IntPtr.Zero) + // { + // var path = WindowsGetPath(folderHandle); + // OpenDSEFinish(path); + // } + // }; + // WindowsSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + // } + // else { return; } + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = d.OpenFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = d.OpenFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = d.OpenFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + d.GetData(path); + OpenMP2KFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + DisposeEngine(); + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = d.SaveFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + ExportDLSFinish(cfg, path); + d.Unref(); + } + d.Unref(); + }; + d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = d.SaveFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + ExportMIDIFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = d.SaveFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + ExportSF2Finish(cfg, path); + d.Unref(); + } + d.Unref(); + }; + d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = Gtk.FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = d.SaveFinish(res, IntPtr.Zero); + if (fileHandle != IntPtr.Zero) + { + var path = d.GetPath(fileHandle); + ExportWAVFinish(path); + d.Unref(); + } + d.Unref(); + }; + d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + timerValue = _timer.Equals(_positionAdjustment); + timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + int i = 0; + Value v = new Value(i++); + _sequencesListStore.SetValue(null, playlist.GetHashCode(), v); + playlist.Songs.Select(s => ColumnView.New((SelectionModel)_sequencesListStore)).ToArray(); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..086cbda --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,107 @@ +using Adw; +using System; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + [DllImport("libadwaita-1.so.0", EntryPoint = "g_resource_load")] + private static extern nint LinuxResourceLoad(string path); + + [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_resource_load")] + private static extern nint MacOSResourceLoad(string path); + + [DllImport("libadwaita-1-0.dll", EntryPoint = "g_resource_load")] + private static extern nint WindowsResourceLoad(string path); + + [DllImport("libadwaita-1.so.0", EntryPoint = "g_resources_register")] + private static extern void LinuxResourcesRegister(nint file); + + [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_resources_register")] + private static extern void MacOSResourcesRegister(nint file); + + [DllImport("libadwaita-1-0.dll", EntryPoint = "g_resources_register")] + private static extern void WindowsResourcesRegister(nint file); + + [DllImport("libadwaita-1.so.0", EntryPoint = "g_file_get_path")] + private static extern string LinuxFileGetPath(nint file); + + [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_file_get_path")] + private static extern string MacOSFileGetPath(nint file); + + [DllImport("libadwaita-1-0.dll", EntryPoint = "g_file_get_path")] + private static extern string WindowsFileGetPath(nint file); + + private delegate void OpenCallback(nint application, nint[] files, int n_files, nint hint, nint data); + + [DllImport("libadwaita-1.so.0", EntryPoint = "g_signal_connect_data")] + private static extern ulong LinuxSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); + + [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_signal_connect_data")] + private static extern ulong MacOSSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); + + [DllImport("libadwaita-1-0.dll", EntryPoint = "g_signal_connect_data")] + private static extern ulong WindowsSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); + + //[DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_chooser_cell_get_type")] + //static extern nuint GetGType(); + + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + //var getType = GetGType(); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + + } + else + { + + } + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..0dc2876 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..43aa3a1 --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..8f3bbd0 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,282 @@ + + + + Exe + net6.0 + enable + true + + + + + + + + + + + + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + libadwaita-1.so.0 + + + Always + libadwaita-1.0.dylib + + + Always + libadwaita-1-0.dll + + + Always + libgtk-4.so.1 + + + Always + libgtk-4.1.dylib + + + Always + libgtk-4-1.dll + + + Always + libpangowin32-1.0-0.dll + + + Always + libpangocairo-1.0.so.0 + + + Always + libpangocairo-1.0.0.dylib + + + Always + libpangocairo-1.0-0.dll + + + Always + libpango-1.0.so.0 + + + Always + libpango-1.0.0.dylib + + + Always + libpango-1.0-0.dll + + + Always + libharfbuzz.so.0 + + + Always + libharfbuzz.0.dylib + + + Always + libharfbuzz-0.dll + + + Always + libgdk_pixbuf-2.0.so.0 + + + Always + libgdk_pixbuf-2.0.0.dylib + + + Always + libgdk_pixbuf-2.0-0.dll + + + Always + libcairo-gobject.so.2 + + + Always + libcairo-gobject.2.dylib + + + Always + libcairo-gobject-2.dll + + + Always + libcairo.so.2 + + + Always + libcairo.2.dylib + + + Always + libcairo-2.dll + + + Always + libgraphene-1.0.so.0 + + + Always + libgraphene-1.0.0.dylib + + + Always + libgraphene-1.0-0.dll + + + Always + libgio-2.0.so.0 + + + Always + libgio-2.0.0.dylib + + + Always + libgio-2.0-0.dll + + + Always + libgobject-2.0.so.0 + + + Always + libgobject-2.0.0.dylib + + + Always + libgobject-2.0-0.dll + + + Always + libglib-2.0.so.0 + + + Always + libglib-2.0.0.dylib + + + Always + libglib-2.0-0.dll + + + Always + libgmodule-2.0.so.0 + + + Always + libgmodule-2.0.0.dylib + + + Always + libgmodule-2.0-0.dll + + + Always + libgtksourceview-5.so.0 + + + Always + libgtksourceview-5.0.dylib + + + Always + libgtksourceview-5-0.dll + + + Always + libharfbuzz-gobject.so.0 + + + Always + libharfbuzz-gobject.0.dylib + + + Always + libharfbuzz-gobject-0.dll + + + Always + libgstreamer-1.0.so.0 + + + Always + libstreamer-1.0.0.dylib + + + Always + libgstreamer-1.0-0.dll + + + Always + libgstaudio-1.0.so.0 + + + Always + libgstaudio-1.0.0.dylib + + + Always + libgstaudio-1.0-0.dll + + + Always + libgstbase-1.0.so.0 + + + Always + libgstbase-1.0.0.dylib + + + Always + libgstbase-1.0-0.dll + + + Always + libgstpbutils-1.0.so.0 + + + Always + libgstpbutils-1.0.0.dylib + + + Always + libgstpbutils-1.0-0.dll + + + Always + libgstvideo-1.0.so.0 + + + Always + libgstvideo-1.0.0.dylib + + + Always + libgstvideo-1.0-0.dll + + + Always + libsoup-3.0.so.0 + + + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 9737985..06fd0ca 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -13,6 +13,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "Objec EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "portaudio-sharp", "portaudio2-sharp\portaudio-sharp.csproj", "{B9B3599A-1420-419A-A620-719E26099547}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +43,14 @@ Global {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU + {B9B3599A-1420-419A-A620-719E26099547}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9B3599A-1420-419A-A620-719E26099547}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9B3599A-1420-419A-A620-719E26099547}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9B3599A-1420-419A-A620-719E26099547}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/portaudio2-sharp/Configuration.cs b/portaudio2-sharp/Configuration.cs new file mode 100644 index 0000000..4122fb6 --- /dev/null +++ b/portaudio2-sharp/Configuration.cs @@ -0,0 +1,105 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace Commons.Media.PortAudio +{ + public class Configuration + { + public static int Version { + get { return PortAudioInterop.Pa_GetVersion (); } + } + + public static string VersionString { + get { return Marshal.PtrToStringAnsi (PortAudioInterop.Pa_GetVersionText ()); } + } + + public static string GetErrorText (PaErrorCode errorCode) + { + return Marshal.PtrToStringAuto (PortAudioInterop.Pa_GetErrorText (errorCode)); + } + + public static int HostApiCount { + get { return PortAudioInterop.Pa_GetHostApiCount (); } + } + + public static int DefaultHostApi { + get { return PortAudioInterop.Pa_GetDefaultHostApi (); } + } + + public static PaHostApiInfo GetHostApiInfo (int hostApi) + { + var ptr = PortAudioInterop.Pa_GetHostApiInfo (hostApi); + if (ptr == IntPtr.Zero) + ThrowLastError (); + using (var cppptr = new CppInstancePtr (ptr)) + return Factory.Create (cppptr); + } + + public static int HostApiTypeIdToHostApiIndex (PaHostApiTypeId type) + { + return PortAudioInterop.Pa_HostApiTypeIdToHostApiIndex (type); + } + + public static int HostApiDeviceIndexToDeviceIndex (int hostApi, int hostApiDeviceIndex) + { + return PortAudioInterop.Pa_HostApiDeviceIndexToDeviceIndex (hostApi, hostApiDeviceIndex); + } + + public static PaHostErrorInfo GetLastHostErrorInfo () + { + using (var cppptr = new CppInstancePtr (PortAudioInterop.Pa_GetLastHostErrorInfo ())) + return Factory.Create (cppptr); + } + + public static int DeviceCount { + get { return PortAudioInterop.Pa_GetDeviceCount (); } + } + + public static int DefaultInputDevice { + get { return PortAudioInterop.Pa_GetDefaultInputDevice (); } + } + + public static int DefaultOutputDevice { + get { return PortAudioInterop.Pa_GetDefaultOutputDevice (); } + } + + public static PaDeviceInfo GetDeviceInfo (int deviceIndex) + { + var ptr = PortAudioInterop.Pa_GetDeviceInfo (deviceIndex); + if (ptr == IntPtr.Zero) + ThrowLastError (); + using (var cppptr = new CppInstancePtr (ptr)) + return Factory.Create (cppptr); + } + + public static PaErrorCode CheckIfFormatSupported (PaStreamParameters inputParameters, PaStreamParameters outputParameters, double sampleRate) + { + using (var input = Factory.ToNative (inputParameters)) + using (var output = Factory.ToNative (outputParameters)) + return PortAudioInterop.Pa_IsFormatSupported (input.Native, output.Native, sampleRate); + } + + public static int GetSampleSize (PaSampleFormat format) + { + var ret = PortAudioInterop.Pa_GetSampleSize (format); + HandleError ((PaErrorCode) ret); + return ret; + } + + internal static PaErrorCode HandleError (PaErrorCode errorCode) + { + if ((int) errorCode < 0) + throw new PortAudioException (errorCode); + return errorCode; + } + + internal static void ThrowLastError () + { + var ret = PortAudioInterop.Pa_GetLastHostErrorInfo (); + var ei = Factory.Create (new CppInstancePtr (ret)); + if (ei.errorCode < 0) + throw new PortAudioException (ei); + } + } +} diff --git a/portaudio2-sharp/Makefile b/portaudio2-sharp/Makefile new file mode 100644 index 0000000..2f44729 --- /dev/null +++ b/portaudio2-sharp/Makefile @@ -0,0 +1,16 @@ + +PA_PATH=$(PORTAUDIO_PATH) + +portaudio-sharp.dll: $(CXXI_DLL) *.cs + mcs -debug -t:library -out:portaudio-sharp.dll *.cs -unsafe + +output/Libs.cs: portaudio.xml + generator portaudio.xml --lib=portaudio --ns=Commons.Media.PortAudio + +portaudio.xml: $(PA_PATH)/include/portaudio.h + gccxml $(PA_PATH)/include/portaudio.h -fxml=portaudio.xml + +clean: + rm -rf portaudio-sharp.dll portaudio-sharp.dll.mdb + rm -rf portaudio.xml + rm -rf output/*.cs diff --git a/portaudio2-sharp/PaErrorCode.cs b/portaudio2-sharp/PaErrorCode.cs new file mode 100644 index 0000000..f5ecbf2 --- /dev/null +++ b/portaudio2-sharp/PaErrorCode.cs @@ -0,0 +1,13 @@ +namespace Commons.Media.PortAudio +{ + public enum PaErrorCode { + paNoError = 0, paNotInitialized = -10000, paUnanticipatedHostError, paInvalidChannelCount, + paInvalidSampleRate, paInvalidDevice, paInvalidFlag, paSampleFormatNotSupported, + paBadIODeviceCombination, paInsufficientMemory, paBufferTooBig, paBufferTooSmall, + paNullCallback, paBadStreamPtr, paTimedOut, paInternalError, + paDeviceUnavailable, paIncompatibleHostApiSpecificStreamInfo, paStreamIsStopped, paStreamIsNotStopped, + paInputOverflowed, paOutputUnderflowed, paHostApiNotFound, paInvalidHostApi, + paCanNotReadFromACallbackStream, paCanNotWriteToACallbackStream, paCanNotReadFromAnOutputOnlyStream, paCanNotWriteToAnInputOnlyStream, + paIncompatibleStreamHostApi, paBadBufferPtr +} +} diff --git a/portaudio2-sharp/PaHostTypeId.cs b/portaudio2-sharp/PaHostTypeId.cs new file mode 100644 index 0000000..a9fccac --- /dev/null +++ b/portaudio2-sharp/PaHostTypeId.cs @@ -0,0 +1,9 @@ +namespace Commons.Media.PortAudio +{ + public enum PaHostApiTypeId { + paInDevelopment = 0, paDirectSound = 1, paMME = 2, paASIO = 3, + paSoundManager = 4, paCoreAudio = 5, paOSS = 7, paALSA = 8, + paAL = 9, paBeOS = 10, paWDMKS = 11, paJACK = 12, + paWASAPI = 13, paAudioScienceHPI = 14 +} +} diff --git a/portaudio2-sharp/PaSampleFormat.cs b/portaudio2-sharp/PaSampleFormat.cs new file mode 100644 index 0000000..8bfe575 --- /dev/null +++ b/portaudio2-sharp/PaSampleFormat.cs @@ -0,0 +1,14 @@ +namespace Commons.Media.PortAudio +{ + public enum PaSampleFormat + { + Float32 = 1, + Int32 = 2, + Int24 = 4, + Int16 = 8, + Int8 = 16, + UInt8 = 32, + Custom = 0x10000, + NonInterleaved = ~(0x0FFFFFFF) + } +} diff --git a/portaudio2-sharp/PaStreamCallbackFlags.cs b/portaudio2-sharp/PaStreamCallbackFlags.cs new file mode 100644 index 0000000..8d8bd5f --- /dev/null +++ b/portaudio2-sharp/PaStreamCallbackFlags.cs @@ -0,0 +1,11 @@ +namespace Commons.Media.PortAudio +{ + public enum PaStreamCallbackFlags + { + InputUnderflow = 1, + InputOverflow = 2, + OutputUnderflow = 4, + OutputOverflow = 8, + PrimingOutput = 16 + } +} diff --git a/portaudio2-sharp/PaStreamCallbackResult.cs b/portaudio2-sharp/PaStreamCallbackResult.cs new file mode 100644 index 0000000..61b1386 --- /dev/null +++ b/portaudio2-sharp/PaStreamCallbackResult.cs @@ -0,0 +1,9 @@ +namespace Commons.Media.PortAudio +{ + public enum PaStreamCallbackResult + { + Continue = 0, + Complete = 1, + Abort = 2 + } +} diff --git a/portaudio2-sharp/PaStreamFlags.cs b/portaudio2-sharp/PaStreamFlags.cs new file mode 100644 index 0000000..551ac90 --- /dev/null +++ b/portaudio2-sharp/PaStreamFlags.cs @@ -0,0 +1,12 @@ +namespace Commons.Media.PortAudio +{ + public enum PaStreamFlags + { + NoFlags = 0, + ClipOff = 1, + DitherOff = 2, + NeverDropInput = 4, + PrimeOutputBuffersUsingStreamCallback = 8, + PlatformSpecificFlags = ~(0x0000FFFF) + } +} diff --git a/portaudio2-sharp/PortAudioException.cs b/portaudio2-sharp/PortAudioException.cs new file mode 100644 index 0000000..82b9a68 --- /dev/null +++ b/portaudio2-sharp/PortAudioException.cs @@ -0,0 +1,27 @@ +using System; + +namespace Commons.Media.PortAudio +{ + public class PortAudioException : Exception + { + public PortAudioException () + : this ("PortAudio error") + { + } + + public PortAudioException (string message) + : base (message) + { + } + + public PortAudioException (PaErrorCode errorCode) + : this (Configuration.GetErrorText (errorCode)) + { + } + + public PortAudioException (PaHostErrorInfo info) + : this (info.errorText) + { + } + } +} diff --git a/portaudio2-sharp/PortAudioInterop.cs b/portaudio2-sharp/PortAudioInterop.cs new file mode 100644 index 0000000..76ba5b4 --- /dev/null +++ b/portaudio2-sharp/PortAudioInterop.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +#region Typedefs +using PaError = Commons.Media.PortAudio.PaErrorCode; +// typedef int PaError +using PaDeviceIndex = System.Int32; +// typedef int PaDeviceIndex +using PaHostApiIndex = System.Int32; +// typedef int PaHostApiIndex +using PaTime = System.Double; +// typedef double PaTime +//using PaSampleFormat = System.UInt64; // typedef unsigned long PaSampleFormat +//using PaStream = System.Void; // typedef void PaStream +using PaStreamFlags = System.UInt32; +// typedef unsigned long PaStreamFlags +#endregion + +namespace Commons.Media.PortAudio +{ + #region Typedefs -> delegates + [UnmanagedFunctionPointer (CallingConvention.Cdecl)] + public delegate PaStreamCallbackResult/*int*/ PaStreamCallback (/*const*/ IntPtr/*void **/input,IntPtr/**void **/output, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/IntPtr frameCount,/*const*/ IntPtr/*PaStreamCallbackTimeInfo **/timeInfo, [MarshalAs (UnmanagedType.SysUInt)] UIntPtr/*PaStreamCallbackFlags*/ statusFlags,IntPtr/*void **/userData); + + [UnmanagedFunctionPointer (CallingConvention.Cdecl)] + public delegate void PaStreamFinishedCallback (IntPtr/*void **/userData); + #endregion + + public static class PortAudioInterop + { + static PortAudioInterop () + { + Pa_Initialize (); + AppDomain.CurrentDomain.DomainUnload += (o, args) => Pa_Terminate (); + } + + #region Functions + [DllImport ("portaudio")] + public static extern + int Pa_GetVersion (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*char * */ Pa_GetVersionText (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*char * */ Pa_GetErrorText (PaError errorCode) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_Initialize (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_Terminate (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaHostApiIndex Pa_GetHostApiCount (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaHostApiIndex Pa_GetDefaultHostApi (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*PaHostApiInfo * */ Pa_GetHostApiInfo (PaHostApiIndex hostApi) + ; + + [DllImport ("portaudio")] + public static extern + PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex (PaHostApiTypeId type) + ; + + [DllImport ("portaudio")] + public static extern + PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex (PaHostApiIndex hostApi, int hostApiDeviceIndex) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*PaHostErrorInfo * */ Pa_GetLastHostErrorInfo (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaDeviceIndex Pa_GetDeviceCount (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaDeviceIndex Pa_GetDefaultInputDevice (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + PaDeviceIndex Pa_GetDefaultOutputDevice (/*void*/) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*PaDeviceInfo * */ Pa_GetDeviceInfo (PaDeviceIndex device) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_IsFormatSupported (/*const*/IntPtr/*PaStreamParameters * */inputParameters, /*const*/ + IntPtr/*PaStreamParameters * */outputParameters, double sampleRate) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_OpenStream (out IntPtr/*PaStream ** */stream, /*const*/IntPtr/*PaStreamParameters * */inputParameters, /*const*/IntPtr/*PaStreamParameters * */outputParameters, double sampleRate, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint framesPerBuffer, [MarshalAs (UnmanagedType.SysUInt)] PaStreamFlags streamFlags, PaStreamCallback streamCallback, IntPtr/*void **/userData) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_OpenDefaultStream (out IntPtr/*PaStream ** */stream, int numInputChannels, int numOutputChannels, [MarshalAs (UnmanagedType.SysUInt)] IntPtr/*PaSampleFormat*/ sampleFormat, double sampleRate, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/IntPtr framesPerBuffer, PaStreamCallback streamCallback, IntPtr/*void **/userData) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_CloseStream (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_SetStreamFinishedCallback (IntPtr/*PaStream * */stream, PaStreamFinishedCallback streamFinishedCallback) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_StartStream (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_StopStream (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_AbortStream (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_IsStreamStopped (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_IsStreamActive (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + /*const*/ IntPtr/*PaStreamInfo * */ Pa_GetStreamInfo (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaTime Pa_GetStreamTime (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + double Pa_GetStreamCpuLoad (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_ReadStream (IntPtr/*PaStream * */stream, IntPtr/*void **/buffer, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint frames) + ; + + [DllImport ("portaudio")] + public static extern + PaError Pa_WriteStream (IntPtr/*PaStream * */stream, /*const*/IntPtr/*void **/buffer, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint frames) + ; + + [DllImport ("portaudio")] + [return: MarshalAs (UnmanagedType.SysInt)] + public static extern + /*signed long*/int Pa_GetStreamReadAvailable (IntPtr/*PaStream * */stream) + ; + + [DllImport ("portaudio")] + [return: MarshalAs (UnmanagedType.SysUInt)] + public static extern + /*signed long*/int Pa_GetStreamWriteAvailable (IntPtr/*PaStream * */stream) + ; + + // Return value is originally defined as PaError but this should rather make sense. + [DllImport ("portaudio")] + public static extern + int Pa_GetSampleSize ([MarshalAs (UnmanagedType.SysUInt)] PaSampleFormat format) + ; + + [DllImport ("portaudio")] + public static extern + void Pa_Sleep ([MarshalAs (UnmanagedType.SysInt)] /*long*/int msec) + ; + #endregion + } + +#if !USE_CXXI + + public static class Factory + { + public static CppInstancePtr ToNative (T value) + { + IntPtr ret = Marshal.AllocHGlobal (Marshal.SizeOf (value)); + Marshal.StructureToPtr (value, ret, false); + return CppInstancePtr.Create (ret); + } + + public static T Create (CppInstancePtr handle) + { + return (T)Marshal.PtrToStructure (handle.Native, typeof(T)); + } + + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaHostApiInfo + { + public int structVersion; + public PaHostApiTypeId type; + [MarshalAs (UnmanagedType.LPStr)] + public string + name; + public int deviceCount; + public PaDeviceIndex defaultInputDevice; + public PaDeviceIndex defaultOutputDevice; + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaHostErrorInfo + { + public PaHostApiTypeId hostApiType; + [MarshalAs (UnmanagedType.SysInt)] + public /*long*/int errorCode; + [MarshalAs (UnmanagedType.LPStr)] + public string + errorText; + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaDeviceInfo + { + public int structVersion; + [MarshalAs (UnmanagedType.LPStr)] + public string + name; + public PaHostApiIndex hostApi; + public int maxInputChannels; + public int maxOutputChannels; + public PaTime defaultLowInputLatency; + public PaTime defaultLowOutputLatency; + public PaTime defaultHighInputLatency; + public PaTime defaultHighOutputLatency; + public double defaultSampleRate; + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaStreamParameters + { + public PaDeviceIndex device; + public int channelCount; + [MarshalAs (UnmanagedType.SysUInt)] + public PaSampleFormat sampleFormat; + public PaTime suggestedLatency; + public IntPtr hostApiSpecificStreamInfo; + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaStreamCallbackTimeInfo + { + public PaTime inputBufferAdcTime; + public PaTime currentTime; + public PaTime outputBufferDacTime; + } + + [StructLayout (LayoutKind.Sequential)] + public struct PaStreamInfo + { + public int structVersion; + public PaTime inputLatency; + public PaTime outputLatency; + public double sampleRate; + } + + public struct CppInstancePtr : IDisposable + { + IntPtr ptr; + bool delete; + Type type; + + public CppInstancePtr (IntPtr ptr) + { + this.ptr = ptr; + delete = false; + type = null; + } + + public static CppInstancePtr Create (IntPtr ptr) + { + return new CppInstancePtr (ptr, typeof(T)); + } + + CppInstancePtr (IntPtr ptr, Type type) + { + this.ptr = ptr; + this.delete = true; + this.type = type; + } + + public void Dispose () + { + if (delete) + Marshal.DestroyStructure (ptr, type); + } + + public IntPtr Native { + get { return ptr; } + } + } +#endif + +} + + + diff --git a/portaudio2-sharp/PortAudioStream.cs b/portaudio2-sharp/PortAudioStream.cs new file mode 100644 index 0000000..270b40e --- /dev/null +++ b/portaudio2-sharp/PortAudioStream.cs @@ -0,0 +1,289 @@ +using System; +using System.Runtime.InteropServices; + +namespace Commons.Media.PortAudio +{ + public class PortAudioInputStream : PortAudioStream + { + public PortAudioInputStream (PaStreamParameters inputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, IntPtr userData) + : base (inputParameters.sampleFormat, inputParameters.channelCount) + { + using (var input = Factory.ToNative (inputParameters)) + HandleError (PortAudioInterop.Pa_OpenStream ( + out handle, + input.Native, + IntPtr.Zero, + sampleRate, + framesPerBuffer, + streamFlags, + ToPaStreamCallback (streamCallback, false), + userData + )); + } + + public PortAudioInputStream (int numInputChannels, PaSampleFormat sampleFormat, double sampleRate, uint framesPerBuffer, StreamCallback streamCallback, IntPtr userData) + : base (sampleFormat, numInputChannels) + { + HandleError (PortAudioInterop.Pa_OpenDefaultStream ( + out handle, + numInputChannels, + 0, + (IntPtr) sampleFormat, + sampleRate, + (IntPtr) framesPerBuffer, + ToPaStreamCallback (streamCallback, false), + userData + )); + } + } + + public class PortAudioOutputStream : PortAudioStream + { + public PortAudioOutputStream (PaStreamParameters outputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, object userData) + : base (outputParameters.sampleFormat, outputParameters.channelCount) + { + var gch = userData == null ? default (GCHandle) : GCHandle.Alloc (userData, GCHandleType.Pinned); + try { + using (var output = Factory.ToNative (outputParameters)) + HandleError (PortAudioInterop.Pa_OpenStream ( + out handle, + IntPtr.Zero, + output.Native, + sampleRate, + framesPerBuffer, + streamFlags, + ToPaStreamCallback (streamCallback, true), + userData != null ? gch.AddrOfPinnedObject () : IntPtr.Zero)); + } finally { + if (userData != null) + gch.Free (); + } + } + + public PortAudioOutputStream (int numOutputChannels, PaSampleFormat sampleFormat, double sampleRate, uint framesPerBuffer, StreamCallback streamCallback, object userData) + : base (sampleFormat, numOutputChannels) + { + var gch = userData == null ? default (GCHandle) : GCHandle.Alloc (userData, GCHandleType.Pinned); + try { + HandleError (PortAudioInterop.Pa_OpenDefaultStream ( + out handle, + 0, + numOutputChannels, + (IntPtr) sampleFormat, + sampleRate, + (IntPtr) framesPerBuffer, + ToPaStreamCallback (streamCallback, true), + userData != null ? gch.AddrOfPinnedObject () : IntPtr.Zero)); + } finally { + if (userData != null) + gch.Free (); + } + } + } + + public abstract class PortAudioStream : IDisposable + { + internal IntPtr handle; + PaSampleFormat sample_format; + int channels; + + protected PortAudioStream (PaSampleFormat sampleFormat, int channels) + { + this.sample_format = sampleFormat; + this.channels = channels; + } + + protected PortAudioStream (IntPtr handle) + { + if (handle == IntPtr.Zero) + throw new ArgumentNullException ("handle"); + this.handle = handle; + should_dispose_handle = false; + } + + bool should_dispose_handle = true; + + public void Close () + { + if (handle != IntPtr.Zero) { + if (should_dispose_handle) + HandleError (PortAudioInterop.Pa_CloseStream (handle)); + handle = IntPtr.Zero; + } + } + + public void Dispose () + { + Close (); + } + + public delegate PaStreamCallbackResult StreamCallback (byte[] buffer, int offset, int byteCount, PaStreamCallbackTimeInfo timeInfo, PaStreamCallbackFlags statusFlags, IntPtr userData); + + public delegate void StreamFinishedCallback (IntPtr userData); + + public void SetStreamFinishedCallback (StreamFinishedCallback streamFinishedCallback) + { + HandleError (PortAudioInterop.Pa_SetStreamFinishedCallback ( + handle, + userData => streamFinishedCallback (userData) + )); + } + + public void StartStream () + { + HandleError (PortAudioInterop.Pa_StartStream (handle)); + } + + public void StopStream () + { + HandleError (PortAudioInterop.Pa_StopStream (handle)); + } + + public void AbortStream () + { + HandleError (PortAudioInterop.Pa_AbortStream (handle)); + } + + public bool IsStopped { + get { + var ret = HandleError (PortAudioInterop.Pa_IsStreamStopped (handle)); + return (int)ret != 0; + } + } + + public bool IsActive { + get { + var ret = HandleError (PortAudioInterop.Pa_IsStreamActive (handle)); + return (int)ret != 0; + } + } + + public PaStreamInfo StreamInfo { + get { + var ptr = PortAudioInterop.Pa_GetStreamInfo (handle); + if (ptr == IntPtr.Zero) + ThrowLastError (); + using (var cppptr = new CppInstancePtr (ptr)) + return Factory.Create (cppptr); + } + } + + public double StreamTime { + get { + var ret = PortAudioInterop.Pa_GetStreamTime (handle); + if (ret == 0) + ThrowLastError (); + return ret; + } + } + + public double CpuLoad { + get { + var ret = PortAudioInterop.Pa_GetStreamCpuLoad (handle); + if (ret == 0) + ThrowLastError (); + return ret; + } + } + + // "The function doesn't return until the entire buffer has been filled - this may involve waiting for the operating system to supply the data." (!) + public void Read (byte[] buffer, int offset, uint frames) + { + unsafe { + fixed (byte* buf = buffer) + HandleError (PortAudioInterop.Pa_ReadStream ( + handle, + (IntPtr) (buf + offset), + frames + )); + } + } + + // "The function doesn't return until the entire buffer has been filled - this may involve waiting for the operating system to supply the data." (!) + public void Write (byte[] buffer, int offset, uint frames) + { + unsafe { + fixed (byte* buf = buffer) + HandleError (PortAudioInterop.Pa_WriteStream ( + handle, + (IntPtr) (buf + offset), + frames + )); + } + } + + public long AvailableReadFrames { + get { + var ret = PortAudioInterop.Pa_GetStreamReadAvailable (handle); + if (ret < 0) + HandleError ((PaErrorCode)ret); + return ret; + } + } + + public long AvailableWriteFrames { + get { + var ret = PortAudioInterop.Pa_GetStreamWriteAvailable (handle); + if (ret < 0) + HandleError ((PaErrorCode)ret); + return ret; + } + } + + internal static PaErrorCode HandleError (PaErrorCode errorCode) + { + return Configuration.HandleError (errorCode); + } + + internal static void ThrowLastError () + { + Configuration.ThrowLastError (); + } + + WeakReference buffer; + + int FramesToBytes (ulong frames) + { + switch (sample_format) { + case PaSampleFormat.Int32: + case PaSampleFormat.Float32: + return (int) frames * 4 * channels; + case PaSampleFormat.Int16: + return (int) frames * 2 * channels; + case PaSampleFormat.Int24: + return (int) frames * 3 * channels; + case PaSampleFormat.NonInterleaved: + case PaSampleFormat.Int8: + default: + return (int) frames * channels; + } + } + + internal unsafe PaStreamCallback ToPaStreamCallback (StreamCallback src, bool isOutput) + { + return (input, output, frameCount, timeInfo, statusFlags, userData) => { + var ptr = timeInfo != IntPtr.Zero ? new CppInstancePtr (timeInfo) : default (CppInstancePtr); + try { + byte [] buf = buffer != null ? (byte[]) buffer.Target : null; + var byteCount = FramesToBytes ((uint) frameCount); + if (buf == null || buf.Length < byteCount) { + buf = new byte [byteCount]; + buffer = new WeakReference (buf); + } + var ret = src ( + buf, + 0, + byteCount, + timeInfo != IntPtr.Zero ? Factory.Create (ptr) : default (PaStreamCallbackTimeInfo), + (PaStreamCallbackFlags) statusFlags, + userData + ); + Marshal.Copy (buf, 0, isOutput ? output : input, byteCount); + return ret; + } finally { + ptr.Dispose (); + } + }; + } + } +} diff --git a/portaudio2-sharp/README b/portaudio2-sharp/README new file mode 100644 index 0000000..37a1be0 --- /dev/null +++ b/portaudio2-sharp/README @@ -0,0 +1,3 @@ +C# binding for portaudio r1788 (v19). + +To build the dll, run xbuild. diff --git a/portaudio2-sharp/libs/README b/portaudio2-sharp/libs/README new file mode 100644 index 0000000..2d37684 --- /dev/null +++ b/portaudio2-sharp/libs/README @@ -0,0 +1,2 @@ +portaudio.dll in this directory was built without ASIO support as I never +bothered to register to Steinberg and download ASIO SDK. diff --git a/portaudio2-sharp/libs/portaudio.dll b/portaudio2-sharp/libs/portaudio.dll new file mode 100644 index 0000000000000000000000000000000000000000..f2c8c537056f326c36270a117e7708d3af8cf13e GIT binary patch literal 306077 zcmeFaePC48wLUzPOmKw388vFOQBxZ$C@Rrd8G#xJ0|-Q;VT3BFv|>tcrRBm5pb!X7 z26EgEjzy}y)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oAKb5>U`1yw2Y)xG}*LI}sM literal 0 HcmV?d00001 diff --git a/portaudio2-sharp/portaudio-sharp.csproj b/portaudio2-sharp/portaudio-sharp.csproj new file mode 100644 index 0000000..ccefc75 --- /dev/null +++ b/portaudio2-sharp/portaudio-sharp.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + Library + latest + Commons.Media.PortAudio + enable + true + CA1069 + + + \ No newline at end of file diff --git a/portaudio2-sharp/portaudio-sharp.sln b/portaudio2-sharp/portaudio-sharp.sln new file mode 100644 index 0000000..c841244 --- /dev/null +++ b/portaudio2-sharp/portaudio-sharp.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "portaudio-sharp", "portaudio-sharp.csproj", "{46F2F4B1-6424-431F-8D30-F9D5EB465022}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Debug|Any CPU.Build.0 = Debug|Any CPU + {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Release|Any CPU.ActiveCfg = Release|Any CPU + {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal From 4bec866dc48ae8421090cc37027e544275b7ab7b Mon Sep 17 00:00:00 2001 From: Davin Date: Sat, 8 Jul 2023 16:13:51 +1000 Subject: [PATCH 07/20] Removed SDL2-CS and portaudio-sharp projects. --- .gitignore | 3 +- SDL2-CS | 1 - VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 60 +-- .../GBA/MP2K/MP2KMixer_NAudio.cs | 276 ----------- VG Music Studio - Core/Mixer.cs | 30 +- VG Music Studio - Core/Mixer_NAudio.cs | 96 ---- .../VG Music Studio - Core.csproj | 1 - .../ExtraLibBindings/Gtk.cs | 199 ++++++++ .../ExtraLibBindings/GtkInternal.cs | 425 +++++++++++++++++ VG Music Studio - GTK4/ExtraLibBindingsGtk.cs | 442 ------------------ .../ExtraLibBindingsGtkInternal.cs | 425 ----------------- VG Music Studio - GTK4/MainWindow.cs | 405 ++++------------ VG Music Studio - GTK4/Program.cs | 61 +-- .../Util/SoundSequenceList.cs | 110 +++++ .../VG Music Studio - GTK4.csproj | 127 +++-- VG Music Studio.sln | 8 +- portaudio2-sharp/Configuration.cs | 105 ----- portaudio2-sharp/Makefile | 16 - portaudio2-sharp/PaErrorCode.cs | 13 - portaudio2-sharp/PaHostTypeId.cs | 9 - portaudio2-sharp/PaSampleFormat.cs | 14 - portaudio2-sharp/PaStreamCallbackFlags.cs | 11 - portaudio2-sharp/PaStreamCallbackResult.cs | 9 - portaudio2-sharp/PaStreamFlags.cs | 12 - portaudio2-sharp/PortAudioException.cs | 27 -- portaudio2-sharp/PortAudioInterop.cs | 342 -------------- portaudio2-sharp/PortAudioStream.cs | 289 ------------ portaudio2-sharp/README | 3 - portaudio2-sharp/libs/README | 2 - portaudio2-sharp/libs/portaudio.dll | Bin 306077 -> 0 bytes portaudio2-sharp/portaudio-sharp.csproj | 13 - portaudio2-sharp/portaudio-sharp.sln | 20 - 32 files changed, 958 insertions(+), 2596 deletions(-) delete mode 160000 SDL2-CS delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs delete mode 100644 VG Music Studio - Core/Mixer_NAudio.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs delete mode 100644 VG Music Studio - GTK4/ExtraLibBindingsGtk.cs delete mode 100644 VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs delete mode 100644 portaudio2-sharp/Configuration.cs delete mode 100644 portaudio2-sharp/Makefile delete mode 100644 portaudio2-sharp/PaErrorCode.cs delete mode 100644 portaudio2-sharp/PaHostTypeId.cs delete mode 100644 portaudio2-sharp/PaSampleFormat.cs delete mode 100644 portaudio2-sharp/PaStreamCallbackFlags.cs delete mode 100644 portaudio2-sharp/PaStreamCallbackResult.cs delete mode 100644 portaudio2-sharp/PaStreamFlags.cs delete mode 100644 portaudio2-sharp/PortAudioException.cs delete mode 100644 portaudio2-sharp/PortAudioInterop.cs delete mode 100644 portaudio2-sharp/PortAudioStream.cs delete mode 100644 portaudio2-sharp/README delete mode 100644 portaudio2-sharp/libs/README delete mode 100644 portaudio2-sharp/libs/portaudio.dll delete mode 100644 portaudio2-sharp/portaudio-sharp.csproj delete mode 100644 portaudio2-sharp/portaudio-sharp.sln diff --git a/.gitignore b/.gitignore index 80921d3..1bbfb2e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,5 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ diff --git a/SDL2-CS b/SDL2-CS deleted file mode 160000 index f8c6fc4..0000000 --- a/SDL2-CS +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f8c6fc407fbb22072fdafcda918aec52b2102519 diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index b52245c..638301b 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -2,6 +2,9 @@ using NAudio.Wave; using System; using System.Linq; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.CoreAudioApi; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; @@ -9,6 +12,7 @@ public sealed class MP2KMixer : Mixer { internal readonly int SampleRate; internal readonly int SamplesPerBuffer; + public readonly int BufferLength; internal readonly float SampleRateReciprocal; private readonly float _samplesReciprocal; internal readonly float PCM8MasterVolume; @@ -30,33 +34,33 @@ public sealed class MP2KMixer : Mixer internal MP2KMixer(MP2KConfig config) { - Config = config; - (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; - SampleRateReciprocal = 1f / SampleRate; - _samplesReciprocal = 1f / SamplesPerBuffer; - PCM8MasterVolume = config.Volume / 15f; + Config = config; + (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; - _pcm8Channels = new PCM8Channel[24]; - for (int i = 0; i < _pcm8Channels.Length; i++) - { - _pcm8Channels[i] = new PCM8Channel(this); - } - _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; + _pcm8Channels = new PCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new PCM8Channel(this); + } + _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; - int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; - _trackBuffers = new float[0x10][]; - for (int i = 0; i < _trackBuffers.Length; i++) - { - _trackBuffers[i] = new float[amt]; - } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) - { - DiscardOnBufferOverflow = true, - BufferLength = SamplesPerBuffer * 64, - }; - Init(_buffer); - } + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + Init(_buffer); + } internal PCM8Channel AllocPCM8Channel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) { @@ -155,10 +159,10 @@ internal PSGChannel AllocPSGChannel(Track owner, ADSR env, NoteInfo note, byte v } nChn.SetVolume(vol, pan); nChn.SetPitch(pitch); - return nChn; - } + return nChn; + } - internal void BeginFadeIn() + internal void BeginFadeIn() { _fadePos = 0f; _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs deleted file mode 100644 index 23fca8f..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs +++ /dev/null @@ -1,276 +0,0 @@ -/* This will be used as a reference and NAudio may be used for debugging and comparing. - -using Kermalis.VGMusicStudio.Core.Util; -using NAudio.Wave; -using System; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -public sealed class MP2KMixer_NAudio : Mixer_NAudio -{ - internal readonly int SampleRate; - internal readonly int SamplesPerBuffer; - internal readonly float SampleRateReciprocal; - private readonly float _samplesReciprocal; - internal readonly float PCM8MasterVolume; - private bool _isFading; - private long _fadeMicroFramesLeft; - private float _fadePos; - private float _fadeStepPerMicroframe; - - internal readonly MP2KConfig Config; - private readonly WaveBuffer _audio; - private readonly float[][] _trackBuffers; - private readonly PCM8Channel[] _pcm8Channels; - private readonly SquareChannel _sq1; - private readonly SquareChannel _sq2; - private readonly PCM4Channel _pcm4; - private readonly NoiseChannel _noise; - private readonly PSGChannel[] _psgChannels; - private readonly BufferedWaveProvider _buffer; - - internal MP2KMixer_NAudio(MP2KConfig config) - { - Config = config; - (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; - SampleRateReciprocal = 1f / SampleRate; - _samplesReciprocal = 1f / SamplesPerBuffer; - PCM8MasterVolume = config.Volume / 15f; - - _pcm8Channels = new PCM8Channel[24]; - for (int i = 0; i < _pcm8Channels.Length; i++) - { - _pcm8Channels[i] = new PCM8Channel(this); - } - _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; - - int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; - _trackBuffers = new float[0x10][]; - for (int i = 0; i < _trackBuffers.Length; i++) - { - _trackBuffers[i] = new float[amt]; - } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) - { - DiscardOnBufferOverflow = true, - BufferLength = SamplesPerBuffer * 64, - }; - Init(_buffer); - } - - internal PCM8Channel AllocPCM8Channel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) - { - PCM8Channel nChn = null; - IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner == null ? 0xFF : c.Owner.Index); - foreach (PCM8Channel i in byOwner) // Find free - { - if (i.State == EnvelopeState.Dead || i.Owner == null) - { - nChn = i; - break; - } - } - if (nChn == null) // Find releasing - { - foreach (PCM8Channel i in byOwner) - { - if (i.State == EnvelopeState.Releasing) - { - nChn = i; - break; - } - } - } - if (nChn == null) // Find prioritized - { - foreach (PCM8Channel i in byOwner) - { - if (owner.Priority > i.Owner.Priority) - { - nChn = i; - break; - } - } - } - if (nChn == null) // None available - { - PCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one - if (lowest.Owner.Index >= owner.Index) - { - nChn = lowest; - } - } - if (nChn != null) // Could still be null from the above if - { - nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); - } - return nChn; - } - internal PSGChannel AllocPSGChannel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) - { - PSGChannel nChn; - switch (type) - { - case VoiceType.Square1: - { - nChn = _sq1; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) - { - return null; - } - _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } - case VoiceType.Square2: - { - nChn = _sq2; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) - { - return null; - } - _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } - case VoiceType.PCM4: - { - nChn = _pcm4; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) - { - return null; - } - _pcm4.Init(owner, note, env, instPan, (int)arg); - break; - } - case VoiceType.Noise: - { - nChn = _noise; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) - { - return null; - } - _noise.Init(owner, note, env, instPan, (NoisePattern)arg); - break; - } - default: return null; - } - nChn.SetVolume(vol, pan); - nChn.SetPitch(pitch); - return nChn; - } - - internal void BeginFadeIn() - { - _fadePos = 0f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); - _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; - _isFading = true; - } - internal void BeginFadeOut() - { - _fadePos = 1f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); - _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; - _isFading = true; - } - internal bool IsFading() - { - return _isFading; - } - internal bool IsFadeDone() - { - return _isFading && _fadeMicroFramesLeft == 0; - } - internal void ResetFade() - { - _isFading = false; - _fadeMicroFramesLeft = 0; - } - - private WaveFileWriter? _waveWriter; - public void CreateWaveWriter(string fileName) - { - _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); - } - public void CloseWaveWriter() - { - _waveWriter!.Dispose(); - _waveWriter = null; - } - internal void Process(bool output, bool recording) - { - for (int i = 0; i < _trackBuffers.Length; i++) - { - float[] buf = _trackBuffers[i]; - Array.Clear(buf, 0, buf.Length); - } - _audio.Clear(); - - for (int i = 0; i < _pcm8Channels.Length; i++) - { - PCM8Channel c = _pcm8Channels[i]; - if (c.Owner != null) - { - c.Process(_trackBuffers[c.Owner.Index]); - } - } - - for (int i = 0; i < _psgChannels.Length; i++) - { - PSGChannel c = _psgChannels[i]; - if (c.Owner != null) - { - c.Process(_trackBuffers[c.Owner.Index]); - } - } - - float masterStep; - float masterLevel; - if (_isFading && _fadeMicroFramesLeft == 0) - { - masterStep = 0; - masterLevel = 0; - } - else - { - float fromMaster = 1f; - float toMaster = 1f; - if (_fadeMicroFramesLeft > 0) - { - const float scale = 10f / 6f; - fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); - _fadePos += _fadeStepPerMicroframe; - toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); - _fadeMicroFramesLeft--; - } - masterStep = (toMaster - fromMaster) * _samplesReciprocal; - masterLevel = fromMaster; - } - for (int i = 0; i < _trackBuffers.Length; i++) - { - if (Mutes[i]) - { - continue; - } - - float level = masterLevel; - float[] buf = _trackBuffers[i]; - for (int j = 0; j < SamplesPerBuffer; j++) - { - _audio.FloatBuffer[j * 2] += buf[j * 2] * level; - _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; - level += masterStep; - } - } - if (output) - { - _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); - } - if (recording) - { - _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); - } - } -} - */ \ No newline at end of file diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 1c06132..a33fd80 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -2,6 +2,8 @@ using NAudio.CoreAudioApi.Interfaces; using NAudio.Wave; using System; +using System.Diagnostics; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core; @@ -12,10 +14,11 @@ public abstract class Mixer : IAudioSessionEventsHandler, IDisposable public readonly bool[] Mutes; private IWavePlayer _out; private AudioSessionControl _appVolume; + private Process _appVol; private bool _shouldSendVolUpdateEvent = true; - protected Mixer() + protected Mixer() { Mutes = new bool[SongState.MAX_TRACKS]; } @@ -42,7 +45,30 @@ protected void Init(IWaveProvider waveProvider) _out.Play(); } - public void OnVolumeChanged(float volume, bool isMuted) + // protected void Init(PortAudioOutputStream waveProvider) + // { + // _outStream = waveProvider; + //var dev = Configuration.DefaultOutputDevice; + // { + // var sessions = dev; + // int id = Environment.ProcessId; + // for (int i = 0; i < sessions; i++) + // { + // var sessionID = new int[i]; + // sessionID[i] = sessions; + // var session = Process.GetProcessById(sessionID[i]); + // if (session.SessionId == id) + // { + // _appVol = session; + // _appVolume.RegisterEventClient(this); + // break; + // } + // } + // } + // _outStream.StartStream(); + // } + + public void OnVolumeChanged(float volume, bool isMuted) { if (_shouldSendVolUpdateEvent) { diff --git a/VG Music Studio - Core/Mixer_NAudio.cs b/VG Music Studio - Core/Mixer_NAudio.cs deleted file mode 100644 index 2a0d18a..0000000 --- a/VG Music Studio - Core/Mixer_NAudio.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* This will be used as a reference and NAudio may be used for debugging and comparing. - -using NAudio.CoreAudioApi; -using NAudio.CoreAudioApi.Interfaces; -using NAudio.Wave; -using System; - -namespace Kermalis.VGMusicStudio.Core; - -public abstract class Mixer_NAudio : IAudioSessionEventsHandler, IDisposable -{ - public static event Action? MixerVolumeChanged; - - public readonly bool[] Mutes; - private IWavePlayer _out; - private AudioSessionControl _appVolume; - - private bool _shouldSendVolUpdateEvent = true; - - protected Mixer_NAudio() - { - Mutes = new bool[SongState.MAX_TRACKS]; - } - - protected void Init(IWaveProvider waveProvider) - { - _out = new WasapiOut(); - _out.Init(waveProvider); - using (var en = new MMDeviceEnumerator()) - { - SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; - int id = Environment.ProcessId; - for (int i = 0; i < sessions.Count; i++) - { - AudioSessionControl session = sessions[i]; - if (session.GetProcessID == id) - { - _appVolume = session; - _appVolume.RegisterEventClient(this); - break; - } - } - } - _out.Play(); - } - - public void OnVolumeChanged(float volume, bool isMuted) - { - if (_shouldSendVolUpdateEvent) - { - MixerVolumeChanged?.Invoke(volume); - } - _shouldSendVolUpdateEvent = true; - } - public void OnDisplayNameChanged(string displayName) - { - throw new NotImplementedException(); - } - public void OnIconPathChanged(string iconPath) - { - throw new NotImplementedException(); - } - public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) - { - throw new NotImplementedException(); - } - public void OnGroupingParamChanged(ref Guid groupingId) - { - throw new NotImplementedException(); - } - // Fires on @out.Play() and @out.Stop() - public void OnStateChanged(AudioSessionState state) - { - if (state == AudioSessionState.AudioSessionStateActive) - { - OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); - } - } - public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) - { - throw new NotImplementedException(); - } - public void SetVolume(float volume) - { - _shouldSendVolUpdateEvent = false; - _appVolume.SimpleAudioVolume.Volume = volume; - } - - public virtual void Dispose() - { - _out.Stop(); - _out.Dispose(); - _appVolume.Dispose(); - } -} - */ \ No newline at end of file diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index 4662854..c60a0f8 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -16,7 +16,6 @@ - diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs b/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs deleted file mode 100644 index 8626a50..0000000 --- a/VG Music Studio - GTK4/ExtraLibBindingsGtk.cs +++ /dev/null @@ -1,442 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using Gtk.Internal; - -namespace Gtk; - -public partial class AlertDialog : GObject.Object -{ - protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) - { - } - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint linux_gtk_alert_dialog_new(string format); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint macos_gtk_alert_dialog_new(string format); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint windows_gtk_alert_dialog_new(string format); - - private static IntPtr ObjPtr; - - public static AlertDialog New(string format) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - ObjPtr = linux_gtk_alert_dialog_new(format); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - ObjPtr = macos_gtk_alert_dialog_new(format); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - ObjPtr = windows_gtk_alert_dialog_new(format); - } - return new AlertDialog(ObjPtr, true); - } -} - -public partial class FileDialog : GObject.Object -{ - [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] - private static extern void LinuxUnref(nint obj); - - [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] - private static extern void MacOSUnref(nint obj); - - [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] - private static extern void WindowsUnref(nint obj); - - [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] - private static extern void LinuxReturnValue(nint task, nint result); - - [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] - private static extern void MacOSReturnValue(nint task, nint result); - - [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] - private static extern void WindowsReturnValue(nint task, nint result); - - [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] - private static extern string LinuxGetPath(nint file); - - [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] - private static extern string MacOSGetPath(nint file); - - [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] - private static extern string WindowsGetPath(nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void LinuxLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void MacOSLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void WindowsLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] - private static extern nint LinuxNew(); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] - private static extern nint MacOSNew(); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] - private static extern nint WindowsNew(); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint LinuxGetInitialFile(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint MacOSGetInitialFile(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint WindowsGetInitialFile(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint LinuxGetInitialFolder(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint MacOSGetInitialFolder(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint WindowsGetInitialFolder(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string LinuxGetInitialName(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string MacOSGetInitialName(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string WindowsGetInitialName(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void LinuxSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void MacOSSetTitle(nint dialog, string title); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void WindowsSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void LinuxSetFilters(nint dialog, nint filters); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void MacOSSetFilters(nint dialog, nint filters); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void WindowsSetFilters(nint dialog, nint filters); - - public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] - private static extern void LinuxOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] - private static extern void MacOSOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] - private static extern void WindowsOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint LinuxOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint MacOSOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint WindowsOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] - private static extern void LinuxSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] - private static extern void MacOSSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] - private static extern void WindowsSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint LinuxSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint MacOSSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint WindowsSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void LinuxSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void MacOSSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void WindowsSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint LinuxSelectFolderFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint MacOSSelectFolderFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint WindowsSelectFolderFinish(nint dialog, nint result, nint error); - - private static IntPtr ObjPtr; - private GAsyncReadyCallback callbackHandle { get; set; } - - private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) - { - } - - // GtkFileDialog* gtk_file_dialog_new (void) - public static FileDialog New() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - ObjPtr = LinuxNew(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - ObjPtr = MacOSNew(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - ObjPtr = WindowsNew(); - } - return new FileDialog(ObjPtr, true); - } - - // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); - } - } - - // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) - public nint OpenFinish(nint result, nint error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxOpenFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSOpenFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsOpenFinish(ObjPtr, result, error); - } - return OpenFinish(result, error); - } - - // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSave(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSave(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSave(ObjPtr, parent, cancellable, callback, user_data); - } - } - - // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) - public nint SaveFinish(nint result, nint error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxSaveFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSSaveFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsSaveFinish(ObjPtr, result, error); - } - return SaveFinish(result, error); - } - - // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) - { - // if (cancellable is null) - // { - // cancellable = nint.New(); - // cancellable.Handle.Equals(IntPtr.Zero); - // cancellable.Cancel(); - // user_data = IntPtr.Zero; - // } - - - // callback = (source, res) => - // { - // var data = new nint(); - // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); - // }; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSelectFolder(ObjPtr, Handle, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSelectFolder(ObjPtr, Handle, cancellable, callback, user_data); - } - } - - // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) - public nint SelectFolderFinish(nint result, nint error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxSelectFolderFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSSelectFolderFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsSelectFolderFinish(ObjPtr, result, error); - } - return SelectFolderFinish(result, error); - } - - // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) - public nint GetInitialFile() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxGetInitialFile(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSGetInitialFile(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsGetInitialFile(ObjPtr); - } - return GetInitialFile(); - } - - // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) - public nint GetInitialFolder() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxGetInitialFolder(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSGetInitialFolder(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsGetInitialFolder(ObjPtr); - } - return GetInitialFolder(); - } - - // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) - public string GetInitialName() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxGetInitialName(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSGetInitialName(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsGetInitialName(ObjPtr); - } - return GetInitialName(); - } - - // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) - public void SetTitle(string title) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSetTitle(ObjPtr, title); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSetTitle(ObjPtr, title); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSetTitle(ObjPtr, title); - } - } - - // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) - public void SetFilters(Gio.ListModel filters) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSetFilters(ObjPtr, filters.Handle); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSetFilters(ObjPtr, filters.Handle); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSetFilters(ObjPtr, filters.Handle); - } - } - - - - - - public string GetPath(nint path) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxGetPath(path); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSGetPath(path); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsGetPath(path); - } - return path.ToString(); - } -} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs deleted file mode 100644 index 44cdfd8..0000000 --- a/VG Music Studio - GTK4/ExtraLibBindingsGtkInternal.cs +++ /dev/null @@ -1,425 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Gtk.Internal; - -public partial class AlertDialog : GObject.Internal.Object -{ - protected AlertDialog(IntPtr handle, bool ownedRef) : base() - { - } - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint linux_gtk_alert_dialog_new(string format); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint macos_gtk_alert_dialog_new(string format); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] - private static extern nint windows_gtk_alert_dialog_new(string format); - - private static IntPtr ObjPtr; - - public static AlertDialog New(string format) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - ObjPtr = linux_gtk_alert_dialog_new(format); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - ObjPtr = macos_gtk_alert_dialog_new(format); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - ObjPtr = windows_gtk_alert_dialog_new(format); - } - return new AlertDialog(ObjPtr, true); - } -} - -public partial class FileDialog : GObject.Internal.Object -{ - [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] - private static extern void LinuxUnref(nint obj); - - [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] - private static extern void MacOSUnref(nint obj); - - [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] - private static extern void WindowsUnref(nint obj); - - [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] - private static extern void LinuxReturnValue(nint task, nint result); - - [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] - private static extern void MacOSReturnValue(nint task, nint result); - - [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] - private static extern void WindowsReturnValue(nint task, nint result); - - [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] - private static extern string LinuxGetPath(nint file); - - [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] - private static extern string MacOSGetPath(nint file); - - [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] - private static extern string WindowsGetPath(nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void LinuxLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void MacOSLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void WindowsLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] - private static extern nint LinuxNew(); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] - private static extern nint MacOSNew(); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] - private static extern nint WindowsNew(); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint LinuxGetInitialFile(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint MacOSGetInitialFile(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint WindowsGetInitialFile(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint LinuxGetInitialFolder(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint MacOSGetInitialFolder(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint WindowsGetInitialFolder(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string LinuxGetInitialName(nint dialog); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string MacOSGetInitialName(nint dialog); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern string WindowsGetInitialName(nint dialog); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void LinuxSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void MacOSSetTitle(nint dialog, string title); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void WindowsSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); - - public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] - private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] - private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] - private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] - private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] - private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] - private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); - - private static IntPtr ObjPtr; - private static IntPtr UserData; - private GAsyncReadyCallback callbackHandle { get; set; } - private static IntPtr FilePath; - - private FileDialog(IntPtr handle, bool ownedRef) : base() - { - } - - // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); - } - } - - // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) - public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxOpenFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSOpenFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsOpenFinish(ObjPtr, result, error); - } - return OpenFinish(result, error); - } - - // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSave(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSave(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSave(ObjPtr, parent, cancellable, callback, user_data); - } - } - - // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) - public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSaveFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSaveFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSaveFinish(ObjPtr, result, error); - } - return SaveFinish(result, error); - } - - // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) - public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) - { - // if (cancellable is null) - // { - // cancellable = Gio.Internal.Cancellable.New(); - // cancellable.Handle.Equals(IntPtr.Zero); - // cancellable.Cancel(); - // UserData = IntPtr.Zero; - // } - - - // callback = (source, res) => - // { - // var data = new nint(); - // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); - // }; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); - } - } - - // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) - public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSelectFolderFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSelectFolderFinish(ObjPtr, result, error); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSelectFolderFinish(ObjPtr, result, error); - } - return SelectFolderFinish(result, error); - } - - // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) - public Gio.Internal.File GetInitialFile() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxGetInitialFile(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSGetInitialFile(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsGetInitialFile(ObjPtr); - } - return GetInitialFile(); - } - - // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) - public Gio.Internal.File GetInitialFolder() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxGetInitialFolder(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSGetInitialFolder(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsGetInitialFolder(ObjPtr); - } - return GetInitialFolder(); - } - - // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) - public string GetInitialName() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxGetInitialName(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return MacOSGetInitialName(ObjPtr); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return WindowsGetInitialName(ObjPtr); - } - return GetInitialName(); - } - - // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) - public void SetTitle(string title) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSetTitle(ObjPtr, title); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSetTitle(ObjPtr, title); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSetTitle(ObjPtr, title); - } - } - - // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) - public void SetFilters(Gio.Internal.ListModel filters) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - LinuxSetFilters(ObjPtr, filters); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSSetFilters(ObjPtr, filters); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsSetFilters(ObjPtr, filters); - } - } - - - - - - public string GetPath(nint path) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return LinuxGetPath(path); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - MacOSGetPath(FilePath); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - WindowsGetPath(FilePath); - } - return FilePath.ToString(); - } -} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index b76b3cf..1726947 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -25,149 +25,12 @@ namespace Kermalis.VGMusicStudio.GTK4 { internal sealed class MainWindow : Window { - [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] - private static extern void LinuxUnref(nint obj); - - [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] - private static extern void MacOSUnref(nint obj); - - [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] - private static extern void WindowsUnref(nint obj); - - [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] - private static extern string LinuxGetPath(nint file); - - [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] - private static extern string MacOSGetPath(nint file); - - [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] - private static extern string WindowsGetPath(nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void LinuxLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void MacOSLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] - private static extern void WindowsLoadFromData(nint provider, string data, int length); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] - private static extern nint linux_gtk_file_dialog_new(); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] - private static extern nint macos_gtk_file_dialog_new(); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] - private static extern nint windows_gtk_file_dialog_new(); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint LinuxGetInitialFile(nint dialog, nint file); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint MacOSGetInitialFile(nint dialog, nint file); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] - private static extern nint WindowsGetInitialFile(nint dialog, nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint LinuxGetInitialFolder(nint dialog, nint file); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint MacOSGetInitialFolder(nint dialog, nint file); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] - private static extern nint WindowsGetInitialFolder(nint dialog, nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern nint LinuxGetInitialName(nint dialog, nint file); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern nint MacOSGetInitialName(nint dialog, nint file); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] - private static extern nint WindowsGetInitialName(nint dialog, nint file); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void LinuxSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void MacOSSetTitle(nint dialog, string title); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] - private static extern void WindowsSetTitle(nint dialog, string title); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void LinuxSetFilters(nint dialog, nint filters); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void MacOSSetFilters(nint dialog, nint filters); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] - private static extern void WindowsSetFilters(nint dialog, nint filters); - - private delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] - private static extern void LinuxOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] - private static extern void MacOSOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] - private static extern void WindowsOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint LinuxOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint MacOSOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] - private static extern nint WindowsOpenFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] - private static extern void LinuxSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] - private static extern void MacOSSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] - private static extern void WindowsSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint LinuxSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint MacOSSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] - private static extern nint WindowsSaveFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void LinuxSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void MacOSSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] - private static extern void WindowsSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); - - [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint LinuxSelectFolderFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint MacOSSelectFolderFinish(nint dialog, nint result, nint error); - - [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] - private static extern nint WindowsSelectFolderFinish(nint dialog, nint result, nint error); - - private bool _playlistPlaying; private Config.Playlist _curPlaylist; private long _curSong = -1; private readonly List _playedSequences; private readonly List _remainingSequences; + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. private bool _stopUI = false; @@ -212,15 +75,15 @@ internal sealed class MainWindow : Window // Menu Actions private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, - _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction; + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; private Signal _openDSESignal; private SignalHandler _openDSEHandler; // Menu Widgets - private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget, - _sequencesScrListView, _sequencesListView; + private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget; // Main Box private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; @@ -242,41 +105,20 @@ internal sealed class MainWindow : Window // Adjustments are for indicating the numbers and the position of the scale private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; - // List Item Factory - private readonly ListItemFactory _sequencesListFactory; - - // String List - private string[] _sequencesListRowLabel; - private StringList _sequencesStringList; + // Sound Sequence List + private SoundSequenceList _soundSequenceList; - // Single Selection - private readonly SingleSelection _sequencesSingleSelection; - - // Column View - private readonly ColumnView _sequencesColumnView; - private readonly ColumnViewColumn _sequencesColumn; - - // List Item - private readonly ListItem _sequencesListItem; - - // Tree View - private readonly TreeView _sequencesTreeView; - //private readonly TreeViewColumn _sequencesColumn; - - // List Store - private ListStore _sequencesListStore; + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); // Signal private Signal _signal; // Callback - private Gtk.FileDialog.GAsyncReadyCallback _saveCallback { get; set; } - private Gtk.FileDialog.GAsyncReadyCallback _openCallback { get; set; } - private Gtk.FileDialog.GAsyncReadyCallback _selectFolderCallback { get; set; } - private Gio.AsyncReadyCallback _openCB { get; set; } - private Gio.AsyncReadyCallback _saveCB { get; set; } - private Gio.AsyncReadyCallback _selectFolderCB { get; set; } - private Gio.AsyncReadyCallback _exceptionCallback { get; set;} + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } #endregion @@ -452,25 +294,10 @@ public MainWindow(Application app) _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; - // Sequences List View - _sequencesListRowLabel = new string[3] { "#", "Internal Name", null }; - _sequencesStringList = StringList.New(_sequencesListRowLabel); - _sequencesScrListView = ScrolledWindow.New(); - _sequencesSingleSelection = SingleSelection.New(_sequencesStringList); - _sequencesColumnView = ColumnView.New(_sequencesSingleSelection); - _sequencesColumn = ColumnViewColumn.New("Name", _sequencesListFactory); - //_sequencesColumn.GetColumnView().SetParent(_sequencesColumnView); - _sequencesListFactory = SignalListItemFactory.New(); - _sequencesGestureClick = GestureClick.New(); - _sequencesListView = ListView.New(_sequencesSingleSelection, _sequencesListFactory); - _sequencesListView.SetParent(_sequencesScrListView); - //_sequencesGestureClick.GetWidget().SetParent(_sequencesListView); - //_sequencesListView = new TreeView(); - //_sequencesListStore = new ListStore(typeof(string), typeof(string)); - //_sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); - //_sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); - //_sequencesListView.AppendColumn(_sequencesColumn); - //_sequencesListView.Model = _sequencesListStore; + // Sound Sequence List + _soundSequenceList = new SoundSequenceList { Sensitive = false }; + _soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + _soundSequenceAction.OnChangeState += SequencesListView_SelectionGet; // Main display _mainBox = Box.New(Orientation.Vertical, 4); @@ -488,7 +315,7 @@ public MainWindow(Application app) _mainBox.Append(_popoverMenuBar); _mainBox.Append(_configButtonBox); _mainBox.Append(_configScaleBox); - _mainBox.Append(_sequencesScrListView); + _mainBox.Append(_soundSequenceList); _configPlayerButtonBox.MarginStart = 40; _configPlayerButtonBox.MarginEnd = 40; @@ -554,7 +381,7 @@ private void PositionScale_MouseButtonPress(object sender, GestureClick.PressedS private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) { //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; - _signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); long index = (long)_sequenceNumberAdjustment.Value; Stop(); @@ -603,17 +430,16 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) _autoplay = true; //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; - _signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); } private void SequencesListView_SelectionGet(object sender, EventArgs e) { - var item = new object(); - item = _sequencesSingleSelection.SelectedItem; - if (item is Config.Song song) + var item = _soundSequenceList; + if (item.Item is Config.Song song) { SetAndLoadSequence(song.Index); } - else if (item is Config.Playlist playlist) + else if (item.Item is Config.Playlist playlist) { if (playlist.Songs.Count > 0 && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) @@ -666,7 +492,7 @@ private void ResetPlaylistStuff(bool enableds) _remainingSequences.Clear(); _playedSequences.Clear(); //_endPlaylistWidget.Sensitive = false; - _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + _sequenceNumberSpinButton.Sensitive = _soundSequenceList.Sensitive = enableds; } private void EndCurrentPlaylist(object sender, EventArgs e) { @@ -709,70 +535,23 @@ private void OpenDSE(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuOpenDSE); _selectFolderCallback = (source, res, data) => { - var folderHandle = d.SelectFolderFinish(res, IntPtr.Zero); + //var errorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); if (folderHandle != IntPtr.Zero) { - var path = d.GetPath(folderHandle); - OpenDSEFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); d.Unref(); } d.Unref(); }; - d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); - // if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - // { - // var d = linux_gtk_file_dialog_new(); - // LinuxSetTitle(d, Strings.MenuOpenDSE); - - // _selectFolderCallback = (source, res, data) => - // { - // var folderHandle = LinuxSelectFolderFinish(d, res, IntPtr.Zero); - // if (folderHandle != IntPtr.Zero) - // { - // var path = LinuxGetPath(folderHandle); - // OpenDSEFinish(path); // GtkFileDialog also doesn't have blocking APIs. - // } - // }; - // LinuxSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); - // } - // else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - // { - // var d = macos_gtk_file_dialog_new(); - // MacOSSetTitle(d, Strings.MenuOpenDSE); - - // _selectFolderCallback = (source, res, data) => - // { - // var folderHandle = MacOSSelectFolderFinish(d, res, IntPtr.Zero); - // if (folderHandle != IntPtr.Zero) - // { - // var path = MacOSGetPath(folderHandle); - // OpenDSEFinish(path); - // } - // }; - // MacOSSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); - // } - // else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - // { - // var d = windows_gtk_file_dialog_new(); - // WindowsSetTitle(d, Strings.MenuOpenDSE); - - // _selectFolderCallback = (source, res, data) => - // { - // var folderHandle = WindowsSelectFolderFinish(d, res, IntPtr.Zero); - // if (folderHandle != IntPtr.Zero) - // { - // var path = WindowsGetPath(folderHandle); - // OpenDSEFinish(path); - // } - // }; - // WindowsSelectFolder(d, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); - // } - // else { return; } + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); } } private void OpenDSEFinish(string path) @@ -836,25 +615,25 @@ private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuOpenSDAT); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(filterSDAT); filters.Append(allFiles); d.SetFilters(filters); _openCallback = (source, res, data) => { - var fileHandle = d.OpenFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - d.GetData(path); - OpenSDATFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); d.Unref(); } d.Unref(); }; - d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); } } private void OpenSDATFinish(string path) @@ -917,25 +696,25 @@ private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuOpenAlphaDream); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(filterGBA); filters.Append(allFiles); d.SetFilters(filters); _openCallback = (source, res, data) => { - var fileHandle = d.OpenFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - d.GetData(path); - OpenAlphaDreamFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); d.Unref(); } d.Unref(); }; - d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); } } private void OpenAlphaDreamFinish(string path) @@ -1000,41 +779,49 @@ private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuOpenMP2K); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(filterGBA); filters.Append(allFiles); d.SetFilters(filters); _openCallback = (source, res, data) => { - var fileHandle = d.OpenFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - d.GetData(path); - OpenMP2KFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); d.Unref(); } d.Unref(); }; - d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); } } private void OpenMP2KFinish(string path) { DisposeEngine(); - try + if (IsWindows()) { - _ = new MP2KEngine(File.ReadAllBytes(path)); + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } } - catch (Exception ex) + else { - //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); - DisposeEngine(); + var ex = new PlatformNotSupportedException(); ExceptionDialog(ex, Strings.ErrorOpenMP2K); - return; } MP2KConfig config = MP2KEngine.MP2KInstance!.Config; @@ -1082,23 +869,24 @@ private void ExportDLS(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuSaveDLS); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(ff); d.SetFilters(filters); _saveCallback = (source, res, data) => { - var fileHandle = d.SaveFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - ExportDLSFinish(cfg, path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); d.Unref(); } d.Unref(); }; - d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); } } private void ExportDLSFinish(AlphaDreamConfig config, string path) @@ -1147,23 +935,24 @@ private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuSaveMIDI); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(ff); d.SetFilters(filters); _saveCallback = (source, res, data) => { - var fileHandle = d.SaveFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - ExportMIDIFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); d.Unref(); } d.Unref(); }; - d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); } } private void ExportMIDIFinish(string path) @@ -1225,23 +1014,24 @@ private void ExportSF2(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuSaveSF2); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(ff); d.SetFilters(filters); _saveCallback = (source, res, data) => { - var fileHandle = d.SaveFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - ExportSF2Finish(cfg, path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(cfg, path!); d.Unref(); } d.Unref(); }; - d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); } } private void ExportSF2Finish(AlphaDreamConfig config, string path) @@ -1290,23 +1080,24 @@ private void ExportWAV(Gio.SimpleAction sender, EventArgs e) } else { - var d = Gtk.FileDialog.New(); + var d = FileDialog.New(); d.SetTitle(Strings.MenuSaveWAV); - var filters = Gio.ListStore.New(Gtk.FileFilter.GetGType()); + var filters = Gio.ListStore.New(FileFilter.GetGType()); filters.Append(ff); d.SetFilters(filters); _saveCallback = (source, res, data) => { - var fileHandle = d.SaveFinish(res, IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); if (fileHandle != IntPtr.Zero) { - var path = d.GetPath(fileHandle); - ExportWAVFinish(path); + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); d.Unref(); } d.Unref(); }; - d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); } } private void ExportWAVFinish(string path) @@ -1343,7 +1134,7 @@ public void ExceptionDialog(Exception error, string heading) md.SetResponseAppearance("ok", ResponseAppearance.Default); md.SetDefaultResponse("ok"); md.SetCloseResponse("ok"); - _exceptionCallback = (source, res) => + _exceptionCallback = (source, res, data) => { md.Destroy(); }; @@ -1443,10 +1234,8 @@ private void FinishLoading(long numSongs) Engine.Instance!.Player.SongEnded += SongEnded; foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) { - int i = 0; - Value v = new Value(i++); - _sequencesListStore.SetValue(null, playlist.GetHashCode(), v); - playlist.Songs.Select(s => ColumnView.New((SelectionModel)_sequencesListStore)).ToArray(); + _soundSequenceList.AddItem(new SoundSequenceList(playlist.Name)); + _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceList(s.Name)).ToArray()); } _sequenceNumberAdjustment.Upper = numSongs - 1; #if DEBUG diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs index 086cbda..940f1f1 100644 --- a/VG Music Studio - GTK4/Program.cs +++ b/VG Music Studio - GTK4/Program.cs @@ -1,52 +1,12 @@ using Adw; using System; +using System.Reflection; using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.GTK4 { internal class Program { - [DllImport("libadwaita-1.so.0", EntryPoint = "g_resource_load")] - private static extern nint LinuxResourceLoad(string path); - - [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_resource_load")] - private static extern nint MacOSResourceLoad(string path); - - [DllImport("libadwaita-1-0.dll", EntryPoint = "g_resource_load")] - private static extern nint WindowsResourceLoad(string path); - - [DllImport("libadwaita-1.so.0", EntryPoint = "g_resources_register")] - private static extern void LinuxResourcesRegister(nint file); - - [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_resources_register")] - private static extern void MacOSResourcesRegister(nint file); - - [DllImport("libadwaita-1-0.dll", EntryPoint = "g_resources_register")] - private static extern void WindowsResourcesRegister(nint file); - - [DllImport("libadwaita-1.so.0", EntryPoint = "g_file_get_path")] - private static extern string LinuxFileGetPath(nint file); - - [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_file_get_path")] - private static extern string MacOSFileGetPath(nint file); - - [DllImport("libadwaita-1-0.dll", EntryPoint = "g_file_get_path")] - private static extern string WindowsFileGetPath(nint file); - - private delegate void OpenCallback(nint application, nint[] files, int n_files, nint hint, nint data); - - [DllImport("libadwaita-1.so.0", EntryPoint = "g_signal_connect_data")] - private static extern ulong LinuxSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); - - [DllImport("libadwaita-1.0.dylib", EntryPoint = "g_signal_connect_data")] - private static extern ulong MacOSSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); - - [DllImport("libadwaita-1-0.dll", EntryPoint = "g_signal_connect_data")] - private static extern ulong WindowsSignalConnectData(nint instance, string signal, OpenCallback callback, nint data, nint destroy_data, int flags); - - //[DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_chooser_cell_get_type")] - //static extern nuint GetGType(); - private readonly Adw.Application app; // public Theme Theme => Theme.ThemeType; @@ -57,25 +17,6 @@ public Program() { app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); - //var getType = GetGType(); - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - - } - else - { - - } - // var theme = new ThemeType(); // // Set LibAdwaita Themes // app.StyleManager!.ColorScheme = theme switch diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..468b31e --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static Gio.ListStore Store; + internal static SortListModel Model; + internal static ColumnView View; + static SignalListItemFactory Factory; + + static long Index; + static string Name; + + internal object Item { get; } + + internal SoundSequenceList(string name) + { + // Import the variables + Name = name; + + // Allow the box to be scrollable + var sw = ScrolledWindow.New(); + sw.SetHasFrame(true); + sw.SetPolicy(PolicyType.Never, PolicyType.Automatic); + + // Create a Sort List Model + Model = CreateModel(); + Model.Unref(); + + sw.SetChild(View); + + Item = View; + + // Add the Columns + AddColumns(View); + } + internal SoundSequenceList() + { + // Allow the box to be scrollable + var sw = ScrolledWindow.New(); + sw.SetHasFrame(true); + sw.SetPolicy(PolicyType.Never, PolicyType.Automatic); + + // Create a Sort List Model + Model = CreateModel(); + Model.Unref(); + + sw.SetChild(View); + + // Create a new name + Name = new string("Name"); + + // Add the Columns + AddColumns(View); + + Item = View; + } + + static SortListModel CreateModel() + { + // Create List Store + Store = Gio.ListStore.New(SortListModel.GetGType()); + + // Create Column View with a Single Selection that reads from List Store + View = ColumnView.New(SingleSelection.New(Store)); + + // Create Sort List Model + var model = SortListModel.New(Store, View.Sorter); + + // Add data to the list store + for (int i = 0; i < Index; i++) + { + Store.Append(model); + } + + return model; + } + + //static void FixedToggled(object sender, EventArgs e) + //{ + // var model = Model; + + // var fixedBit = new bool(); + // fixedBit ^= true; + //} + + static void AddColumns(ColumnView columnView) + { + Factory = SignalListItemFactory.New(); + //var renderer = ToggleButton.New(); + //renderer.OnToggled += FixedToggled; + var colName = ColumnViewColumn.New(Name, Factory); + columnView.AppendColumn(colName); + } + + internal int AddItem(object item) + { + return AddItem(item); + } + internal int AddRange(Span item) + { + return AddRange(item); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj index 8f3bbd0..64ba658 100644 --- a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -8,8 +8,7 @@ - - + @@ -31,251 +30,251 @@ Always - libadwaita-1.so.0 + %(Filename)%(Extension) Always - libadwaita-1.0.dylib + %(Filename)%(Extension) Always - libadwaita-1-0.dll + %(Filename)%(Extension) Always - libgtk-4.so.1 + %(Filename)%(Extension) Always - libgtk-4.1.dylib + %(Filename)%(Extension) Always - libgtk-4-1.dll + %(Filename)%(Extension) Always - libpangowin32-1.0-0.dll + %(Filename)%(Extension) Always - libpangocairo-1.0.so.0 + %(Filename)%(Extension) Always - libpangocairo-1.0.0.dylib + %(Filename)%(Extension) Always - libpangocairo-1.0-0.dll + %(Filename)%(Extension) Always - libpango-1.0.so.0 + %(Filename)%(Extension) Always - libpango-1.0.0.dylib + %(Filename)%(Extension) Always - libpango-1.0-0.dll + %(Filename)%(Extension) Always - libharfbuzz.so.0 + %(Filename)%(Extension) Always - libharfbuzz.0.dylib + %(Filename)%(Extension) Always - libharfbuzz-0.dll + %(Filename)%(Extension) Always - libgdk_pixbuf-2.0.so.0 + %(Filename)%(Extension) Always - libgdk_pixbuf-2.0.0.dylib + %(Filename)%(Extension) Always - libgdk_pixbuf-2.0-0.dll + %(Filename)%(Extension) Always - libcairo-gobject.so.2 + %(Filename)%(Extension) Always - libcairo-gobject.2.dylib + %(Filename)%(Extension) Always - libcairo-gobject-2.dll + %(Filename)%(Extension) Always - libcairo.so.2 + %(Filename)%(Extension) Always - libcairo.2.dylib + %(Filename)%(Extension) Always - libcairo-2.dll + %(Filename)%(Extension) Always - libgraphene-1.0.so.0 + %(Filename)%(Extension) Always - libgraphene-1.0.0.dylib + %(Filename)%(Extension) Always - libgraphene-1.0-0.dll + %(Filename)%(Extension) Always - libgio-2.0.so.0 + %(Filename)%(Extension) Always - libgio-2.0.0.dylib + %(Filename)%(Extension) Always - libgio-2.0-0.dll + %(Filename)%(Extension) Always - libgobject-2.0.so.0 + %(Filename)%(Extension) Always - libgobject-2.0.0.dylib + %(Filename)%(Extension) Always - libgobject-2.0-0.dll + %(Filename)%(Extension) Always - libglib-2.0.so.0 + %(Filename)%(Extension) Always - libglib-2.0.0.dylib + %(Filename)%(Extension) Always - libglib-2.0-0.dll + %(Filename)%(Extension) Always - libgmodule-2.0.so.0 + %(Filename)%(Extension) Always - libgmodule-2.0.0.dylib + %(Filename)%(Extension) Always - libgmodule-2.0-0.dll + %(Filename)%(Extension) Always - libgtksourceview-5.so.0 + %(Filename)%(Extension) Always - libgtksourceview-5.0.dylib + %(Filename)%(Extension) Always - libgtksourceview-5-0.dll + %(Filename)%(Extension) Always - libharfbuzz-gobject.so.0 + %(Filename)%(Extension) Always - libharfbuzz-gobject.0.dylib + %(Filename)%(Extension) Always - libharfbuzz-gobject-0.dll + %(Filename)%(Extension) Always - libgstreamer-1.0.so.0 + %(Filename)%(Extension) Always - libstreamer-1.0.0.dylib + %(Filename)%(Extension) Always - libgstreamer-1.0-0.dll + %(Filename)%(Extension) Always - libgstaudio-1.0.so.0 + %(Filename)%(Extension) Always - libgstaudio-1.0.0.dylib + %(Filename)%(Extension) Always - libgstaudio-1.0-0.dll + %(Filename)%(Extension) Always - libgstbase-1.0.so.0 + %(Filename)%(Extension) Always - libgstbase-1.0.0.dylib + %(Filename)%(Extension) Always - libgstbase-1.0-0.dll + %(Filename)%(Extension) Always - libgstpbutils-1.0.so.0 + %(Filename)%(Extension) Always - libgstpbutils-1.0.0.dylib + %(Filename)%(Extension) Always - libgstpbutils-1.0-0.dll + %(Filename)%(Extension) Always - libgstvideo-1.0.so.0 + %(Filename)%(Extension) Always - libgstvideo-1.0.0.dylib + %(Filename)%(Extension) Always - libgstvideo-1.0-0.dll + %(Filename)%(Extension) Always - libsoup-3.0.so.0 + %(Filename)%(Extension) diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 06fd0ca..37b7672 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -13,9 +13,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "Objec EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "portaudio-sharp", "portaudio2-sharp\portaudio-sharp.csproj", "{B9B3599A-1420-419A-A620-719E26099547}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -47,10 +45,6 @@ Global {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU - {B9B3599A-1420-419A-A620-719E26099547}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B9B3599A-1420-419A-A620-719E26099547}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B9B3599A-1420-419A-A620-719E26099547}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B9B3599A-1420-419A-A620-719E26099547}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/portaudio2-sharp/Configuration.cs b/portaudio2-sharp/Configuration.cs deleted file mode 100644 index 4122fb6..0000000 --- a/portaudio2-sharp/Configuration.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; - -namespace Commons.Media.PortAudio -{ - public class Configuration - { - public static int Version { - get { return PortAudioInterop.Pa_GetVersion (); } - } - - public static string VersionString { - get { return Marshal.PtrToStringAnsi (PortAudioInterop.Pa_GetVersionText ()); } - } - - public static string GetErrorText (PaErrorCode errorCode) - { - return Marshal.PtrToStringAuto (PortAudioInterop.Pa_GetErrorText (errorCode)); - } - - public static int HostApiCount { - get { return PortAudioInterop.Pa_GetHostApiCount (); } - } - - public static int DefaultHostApi { - get { return PortAudioInterop.Pa_GetDefaultHostApi (); } - } - - public static PaHostApiInfo GetHostApiInfo (int hostApi) - { - var ptr = PortAudioInterop.Pa_GetHostApiInfo (hostApi); - if (ptr == IntPtr.Zero) - ThrowLastError (); - using (var cppptr = new CppInstancePtr (ptr)) - return Factory.Create (cppptr); - } - - public static int HostApiTypeIdToHostApiIndex (PaHostApiTypeId type) - { - return PortAudioInterop.Pa_HostApiTypeIdToHostApiIndex (type); - } - - public static int HostApiDeviceIndexToDeviceIndex (int hostApi, int hostApiDeviceIndex) - { - return PortAudioInterop.Pa_HostApiDeviceIndexToDeviceIndex (hostApi, hostApiDeviceIndex); - } - - public static PaHostErrorInfo GetLastHostErrorInfo () - { - using (var cppptr = new CppInstancePtr (PortAudioInterop.Pa_GetLastHostErrorInfo ())) - return Factory.Create (cppptr); - } - - public static int DeviceCount { - get { return PortAudioInterop.Pa_GetDeviceCount (); } - } - - public static int DefaultInputDevice { - get { return PortAudioInterop.Pa_GetDefaultInputDevice (); } - } - - public static int DefaultOutputDevice { - get { return PortAudioInterop.Pa_GetDefaultOutputDevice (); } - } - - public static PaDeviceInfo GetDeviceInfo (int deviceIndex) - { - var ptr = PortAudioInterop.Pa_GetDeviceInfo (deviceIndex); - if (ptr == IntPtr.Zero) - ThrowLastError (); - using (var cppptr = new CppInstancePtr (ptr)) - return Factory.Create (cppptr); - } - - public static PaErrorCode CheckIfFormatSupported (PaStreamParameters inputParameters, PaStreamParameters outputParameters, double sampleRate) - { - using (var input = Factory.ToNative (inputParameters)) - using (var output = Factory.ToNative (outputParameters)) - return PortAudioInterop.Pa_IsFormatSupported (input.Native, output.Native, sampleRate); - } - - public static int GetSampleSize (PaSampleFormat format) - { - var ret = PortAudioInterop.Pa_GetSampleSize (format); - HandleError ((PaErrorCode) ret); - return ret; - } - - internal static PaErrorCode HandleError (PaErrorCode errorCode) - { - if ((int) errorCode < 0) - throw new PortAudioException (errorCode); - return errorCode; - } - - internal static void ThrowLastError () - { - var ret = PortAudioInterop.Pa_GetLastHostErrorInfo (); - var ei = Factory.Create (new CppInstancePtr (ret)); - if (ei.errorCode < 0) - throw new PortAudioException (ei); - } - } -} diff --git a/portaudio2-sharp/Makefile b/portaudio2-sharp/Makefile deleted file mode 100644 index 2f44729..0000000 --- a/portaudio2-sharp/Makefile +++ /dev/null @@ -1,16 +0,0 @@ - -PA_PATH=$(PORTAUDIO_PATH) - -portaudio-sharp.dll: $(CXXI_DLL) *.cs - mcs -debug -t:library -out:portaudio-sharp.dll *.cs -unsafe - -output/Libs.cs: portaudio.xml - generator portaudio.xml --lib=portaudio --ns=Commons.Media.PortAudio - -portaudio.xml: $(PA_PATH)/include/portaudio.h - gccxml $(PA_PATH)/include/portaudio.h -fxml=portaudio.xml - -clean: - rm -rf portaudio-sharp.dll portaudio-sharp.dll.mdb - rm -rf portaudio.xml - rm -rf output/*.cs diff --git a/portaudio2-sharp/PaErrorCode.cs b/portaudio2-sharp/PaErrorCode.cs deleted file mode 100644 index f5ecbf2..0000000 --- a/portaudio2-sharp/PaErrorCode.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaErrorCode { - paNoError = 0, paNotInitialized = -10000, paUnanticipatedHostError, paInvalidChannelCount, - paInvalidSampleRate, paInvalidDevice, paInvalidFlag, paSampleFormatNotSupported, - paBadIODeviceCombination, paInsufficientMemory, paBufferTooBig, paBufferTooSmall, - paNullCallback, paBadStreamPtr, paTimedOut, paInternalError, - paDeviceUnavailable, paIncompatibleHostApiSpecificStreamInfo, paStreamIsStopped, paStreamIsNotStopped, - paInputOverflowed, paOutputUnderflowed, paHostApiNotFound, paInvalidHostApi, - paCanNotReadFromACallbackStream, paCanNotWriteToACallbackStream, paCanNotReadFromAnOutputOnlyStream, paCanNotWriteToAnInputOnlyStream, - paIncompatibleStreamHostApi, paBadBufferPtr -} -} diff --git a/portaudio2-sharp/PaHostTypeId.cs b/portaudio2-sharp/PaHostTypeId.cs deleted file mode 100644 index a9fccac..0000000 --- a/portaudio2-sharp/PaHostTypeId.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaHostApiTypeId { - paInDevelopment = 0, paDirectSound = 1, paMME = 2, paASIO = 3, - paSoundManager = 4, paCoreAudio = 5, paOSS = 7, paALSA = 8, - paAL = 9, paBeOS = 10, paWDMKS = 11, paJACK = 12, - paWASAPI = 13, paAudioScienceHPI = 14 -} -} diff --git a/portaudio2-sharp/PaSampleFormat.cs b/portaudio2-sharp/PaSampleFormat.cs deleted file mode 100644 index 8bfe575..0000000 --- a/portaudio2-sharp/PaSampleFormat.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaSampleFormat - { - Float32 = 1, - Int32 = 2, - Int24 = 4, - Int16 = 8, - Int8 = 16, - UInt8 = 32, - Custom = 0x10000, - NonInterleaved = ~(0x0FFFFFFF) - } -} diff --git a/portaudio2-sharp/PaStreamCallbackFlags.cs b/portaudio2-sharp/PaStreamCallbackFlags.cs deleted file mode 100644 index 8d8bd5f..0000000 --- a/portaudio2-sharp/PaStreamCallbackFlags.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaStreamCallbackFlags - { - InputUnderflow = 1, - InputOverflow = 2, - OutputUnderflow = 4, - OutputOverflow = 8, - PrimingOutput = 16 - } -} diff --git a/portaudio2-sharp/PaStreamCallbackResult.cs b/portaudio2-sharp/PaStreamCallbackResult.cs deleted file mode 100644 index 61b1386..0000000 --- a/portaudio2-sharp/PaStreamCallbackResult.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaStreamCallbackResult - { - Continue = 0, - Complete = 1, - Abort = 2 - } -} diff --git a/portaudio2-sharp/PaStreamFlags.cs b/portaudio2-sharp/PaStreamFlags.cs deleted file mode 100644 index 551ac90..0000000 --- a/portaudio2-sharp/PaStreamFlags.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Commons.Media.PortAudio -{ - public enum PaStreamFlags - { - NoFlags = 0, - ClipOff = 1, - DitherOff = 2, - NeverDropInput = 4, - PrimeOutputBuffersUsingStreamCallback = 8, - PlatformSpecificFlags = ~(0x0000FFFF) - } -} diff --git a/portaudio2-sharp/PortAudioException.cs b/portaudio2-sharp/PortAudioException.cs deleted file mode 100644 index 82b9a68..0000000 --- a/portaudio2-sharp/PortAudioException.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; - -namespace Commons.Media.PortAudio -{ - public class PortAudioException : Exception - { - public PortAudioException () - : this ("PortAudio error") - { - } - - public PortAudioException (string message) - : base (message) - { - } - - public PortAudioException (PaErrorCode errorCode) - : this (Configuration.GetErrorText (errorCode)) - { - } - - public PortAudioException (PaHostErrorInfo info) - : this (info.errorText) - { - } - } -} diff --git a/portaudio2-sharp/PortAudioInterop.cs b/portaudio2-sharp/PortAudioInterop.cs deleted file mode 100644 index 76ba5b4..0000000 --- a/portaudio2-sharp/PortAudioInterop.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -#region Typedefs -using PaError = Commons.Media.PortAudio.PaErrorCode; -// typedef int PaError -using PaDeviceIndex = System.Int32; -// typedef int PaDeviceIndex -using PaHostApiIndex = System.Int32; -// typedef int PaHostApiIndex -using PaTime = System.Double; -// typedef double PaTime -//using PaSampleFormat = System.UInt64; // typedef unsigned long PaSampleFormat -//using PaStream = System.Void; // typedef void PaStream -using PaStreamFlags = System.UInt32; -// typedef unsigned long PaStreamFlags -#endregion - -namespace Commons.Media.PortAudio -{ - #region Typedefs -> delegates - [UnmanagedFunctionPointer (CallingConvention.Cdecl)] - public delegate PaStreamCallbackResult/*int*/ PaStreamCallback (/*const*/ IntPtr/*void **/input,IntPtr/**void **/output, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/IntPtr frameCount,/*const*/ IntPtr/*PaStreamCallbackTimeInfo **/timeInfo, [MarshalAs (UnmanagedType.SysUInt)] UIntPtr/*PaStreamCallbackFlags*/ statusFlags,IntPtr/*void **/userData); - - [UnmanagedFunctionPointer (CallingConvention.Cdecl)] - public delegate void PaStreamFinishedCallback (IntPtr/*void **/userData); - #endregion - - public static class PortAudioInterop - { - static PortAudioInterop () - { - Pa_Initialize (); - AppDomain.CurrentDomain.DomainUnload += (o, args) => Pa_Terminate (); - } - - #region Functions - [DllImport ("portaudio")] - public static extern - int Pa_GetVersion (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*char * */ Pa_GetVersionText (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*char * */ Pa_GetErrorText (PaError errorCode) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_Initialize (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_Terminate (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaHostApiIndex Pa_GetHostApiCount (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaHostApiIndex Pa_GetDefaultHostApi (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*PaHostApiInfo * */ Pa_GetHostApiInfo (PaHostApiIndex hostApi) - ; - - [DllImport ("portaudio")] - public static extern - PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex (PaHostApiTypeId type) - ; - - [DllImport ("portaudio")] - public static extern - PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex (PaHostApiIndex hostApi, int hostApiDeviceIndex) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*PaHostErrorInfo * */ Pa_GetLastHostErrorInfo (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaDeviceIndex Pa_GetDeviceCount (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaDeviceIndex Pa_GetDefaultInputDevice (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - PaDeviceIndex Pa_GetDefaultOutputDevice (/*void*/) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*PaDeviceInfo * */ Pa_GetDeviceInfo (PaDeviceIndex device) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_IsFormatSupported (/*const*/IntPtr/*PaStreamParameters * */inputParameters, /*const*/ - IntPtr/*PaStreamParameters * */outputParameters, double sampleRate) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_OpenStream (out IntPtr/*PaStream ** */stream, /*const*/IntPtr/*PaStreamParameters * */inputParameters, /*const*/IntPtr/*PaStreamParameters * */outputParameters, double sampleRate, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint framesPerBuffer, [MarshalAs (UnmanagedType.SysUInt)] PaStreamFlags streamFlags, PaStreamCallback streamCallback, IntPtr/*void **/userData) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_OpenDefaultStream (out IntPtr/*PaStream ** */stream, int numInputChannels, int numOutputChannels, [MarshalAs (UnmanagedType.SysUInt)] IntPtr/*PaSampleFormat*/ sampleFormat, double sampleRate, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/IntPtr framesPerBuffer, PaStreamCallback streamCallback, IntPtr/*void **/userData) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_CloseStream (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_SetStreamFinishedCallback (IntPtr/*PaStream * */stream, PaStreamFinishedCallback streamFinishedCallback) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_StartStream (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_StopStream (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_AbortStream (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_IsStreamStopped (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_IsStreamActive (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - /*const*/ IntPtr/*PaStreamInfo * */ Pa_GetStreamInfo (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaTime Pa_GetStreamTime (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - double Pa_GetStreamCpuLoad (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_ReadStream (IntPtr/*PaStream * */stream, IntPtr/*void **/buffer, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint frames) - ; - - [DllImport ("portaudio")] - public static extern - PaError Pa_WriteStream (IntPtr/*PaStream * */stream, /*const*/IntPtr/*void **/buffer, [MarshalAs (UnmanagedType.SysUInt)] /*unsigned long*/uint frames) - ; - - [DllImport ("portaudio")] - [return: MarshalAs (UnmanagedType.SysInt)] - public static extern - /*signed long*/int Pa_GetStreamReadAvailable (IntPtr/*PaStream * */stream) - ; - - [DllImport ("portaudio")] - [return: MarshalAs (UnmanagedType.SysUInt)] - public static extern - /*signed long*/int Pa_GetStreamWriteAvailable (IntPtr/*PaStream * */stream) - ; - - // Return value is originally defined as PaError but this should rather make sense. - [DllImport ("portaudio")] - public static extern - int Pa_GetSampleSize ([MarshalAs (UnmanagedType.SysUInt)] PaSampleFormat format) - ; - - [DllImport ("portaudio")] - public static extern - void Pa_Sleep ([MarshalAs (UnmanagedType.SysInt)] /*long*/int msec) - ; - #endregion - } - -#if !USE_CXXI - - public static class Factory - { - public static CppInstancePtr ToNative (T value) - { - IntPtr ret = Marshal.AllocHGlobal (Marshal.SizeOf (value)); - Marshal.StructureToPtr (value, ret, false); - return CppInstancePtr.Create (ret); - } - - public static T Create (CppInstancePtr handle) - { - return (T)Marshal.PtrToStructure (handle.Native, typeof(T)); - } - - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaHostApiInfo - { - public int structVersion; - public PaHostApiTypeId type; - [MarshalAs (UnmanagedType.LPStr)] - public string - name; - public int deviceCount; - public PaDeviceIndex defaultInputDevice; - public PaDeviceIndex defaultOutputDevice; - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaHostErrorInfo - { - public PaHostApiTypeId hostApiType; - [MarshalAs (UnmanagedType.SysInt)] - public /*long*/int errorCode; - [MarshalAs (UnmanagedType.LPStr)] - public string - errorText; - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaDeviceInfo - { - public int structVersion; - [MarshalAs (UnmanagedType.LPStr)] - public string - name; - public PaHostApiIndex hostApi; - public int maxInputChannels; - public int maxOutputChannels; - public PaTime defaultLowInputLatency; - public PaTime defaultLowOutputLatency; - public PaTime defaultHighInputLatency; - public PaTime defaultHighOutputLatency; - public double defaultSampleRate; - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamParameters - { - public PaDeviceIndex device; - public int channelCount; - [MarshalAs (UnmanagedType.SysUInt)] - public PaSampleFormat sampleFormat; - public PaTime suggestedLatency; - public IntPtr hostApiSpecificStreamInfo; - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamCallbackTimeInfo - { - public PaTime inputBufferAdcTime; - public PaTime currentTime; - public PaTime outputBufferDacTime; - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamInfo - { - public int structVersion; - public PaTime inputLatency; - public PaTime outputLatency; - public double sampleRate; - } - - public struct CppInstancePtr : IDisposable - { - IntPtr ptr; - bool delete; - Type type; - - public CppInstancePtr (IntPtr ptr) - { - this.ptr = ptr; - delete = false; - type = null; - } - - public static CppInstancePtr Create (IntPtr ptr) - { - return new CppInstancePtr (ptr, typeof(T)); - } - - CppInstancePtr (IntPtr ptr, Type type) - { - this.ptr = ptr; - this.delete = true; - this.type = type; - } - - public void Dispose () - { - if (delete) - Marshal.DestroyStructure (ptr, type); - } - - public IntPtr Native { - get { return ptr; } - } - } -#endif - -} - - - diff --git a/portaudio2-sharp/PortAudioStream.cs b/portaudio2-sharp/PortAudioStream.cs deleted file mode 100644 index 270b40e..0000000 --- a/portaudio2-sharp/PortAudioStream.cs +++ /dev/null @@ -1,289 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Commons.Media.PortAudio -{ - public class PortAudioInputStream : PortAudioStream - { - public PortAudioInputStream (PaStreamParameters inputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, IntPtr userData) - : base (inputParameters.sampleFormat, inputParameters.channelCount) - { - using (var input = Factory.ToNative (inputParameters)) - HandleError (PortAudioInterop.Pa_OpenStream ( - out handle, - input.Native, - IntPtr.Zero, - sampleRate, - framesPerBuffer, - streamFlags, - ToPaStreamCallback (streamCallback, false), - userData - )); - } - - public PortAudioInputStream (int numInputChannels, PaSampleFormat sampleFormat, double sampleRate, uint framesPerBuffer, StreamCallback streamCallback, IntPtr userData) - : base (sampleFormat, numInputChannels) - { - HandleError (PortAudioInterop.Pa_OpenDefaultStream ( - out handle, - numInputChannels, - 0, - (IntPtr) sampleFormat, - sampleRate, - (IntPtr) framesPerBuffer, - ToPaStreamCallback (streamCallback, false), - userData - )); - } - } - - public class PortAudioOutputStream : PortAudioStream - { - public PortAudioOutputStream (PaStreamParameters outputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, object userData) - : base (outputParameters.sampleFormat, outputParameters.channelCount) - { - var gch = userData == null ? default (GCHandle) : GCHandle.Alloc (userData, GCHandleType.Pinned); - try { - using (var output = Factory.ToNative (outputParameters)) - HandleError (PortAudioInterop.Pa_OpenStream ( - out handle, - IntPtr.Zero, - output.Native, - sampleRate, - framesPerBuffer, - streamFlags, - ToPaStreamCallback (streamCallback, true), - userData != null ? gch.AddrOfPinnedObject () : IntPtr.Zero)); - } finally { - if (userData != null) - gch.Free (); - } - } - - public PortAudioOutputStream (int numOutputChannels, PaSampleFormat sampleFormat, double sampleRate, uint framesPerBuffer, StreamCallback streamCallback, object userData) - : base (sampleFormat, numOutputChannels) - { - var gch = userData == null ? default (GCHandle) : GCHandle.Alloc (userData, GCHandleType.Pinned); - try { - HandleError (PortAudioInterop.Pa_OpenDefaultStream ( - out handle, - 0, - numOutputChannels, - (IntPtr) sampleFormat, - sampleRate, - (IntPtr) framesPerBuffer, - ToPaStreamCallback (streamCallback, true), - userData != null ? gch.AddrOfPinnedObject () : IntPtr.Zero)); - } finally { - if (userData != null) - gch.Free (); - } - } - } - - public abstract class PortAudioStream : IDisposable - { - internal IntPtr handle; - PaSampleFormat sample_format; - int channels; - - protected PortAudioStream (PaSampleFormat sampleFormat, int channels) - { - this.sample_format = sampleFormat; - this.channels = channels; - } - - protected PortAudioStream (IntPtr handle) - { - if (handle == IntPtr.Zero) - throw new ArgumentNullException ("handle"); - this.handle = handle; - should_dispose_handle = false; - } - - bool should_dispose_handle = true; - - public void Close () - { - if (handle != IntPtr.Zero) { - if (should_dispose_handle) - HandleError (PortAudioInterop.Pa_CloseStream (handle)); - handle = IntPtr.Zero; - } - } - - public void Dispose () - { - Close (); - } - - public delegate PaStreamCallbackResult StreamCallback (byte[] buffer, int offset, int byteCount, PaStreamCallbackTimeInfo timeInfo, PaStreamCallbackFlags statusFlags, IntPtr userData); - - public delegate void StreamFinishedCallback (IntPtr userData); - - public void SetStreamFinishedCallback (StreamFinishedCallback streamFinishedCallback) - { - HandleError (PortAudioInterop.Pa_SetStreamFinishedCallback ( - handle, - userData => streamFinishedCallback (userData) - )); - } - - public void StartStream () - { - HandleError (PortAudioInterop.Pa_StartStream (handle)); - } - - public void StopStream () - { - HandleError (PortAudioInterop.Pa_StopStream (handle)); - } - - public void AbortStream () - { - HandleError (PortAudioInterop.Pa_AbortStream (handle)); - } - - public bool IsStopped { - get { - var ret = HandleError (PortAudioInterop.Pa_IsStreamStopped (handle)); - return (int)ret != 0; - } - } - - public bool IsActive { - get { - var ret = HandleError (PortAudioInterop.Pa_IsStreamActive (handle)); - return (int)ret != 0; - } - } - - public PaStreamInfo StreamInfo { - get { - var ptr = PortAudioInterop.Pa_GetStreamInfo (handle); - if (ptr == IntPtr.Zero) - ThrowLastError (); - using (var cppptr = new CppInstancePtr (ptr)) - return Factory.Create (cppptr); - } - } - - public double StreamTime { - get { - var ret = PortAudioInterop.Pa_GetStreamTime (handle); - if (ret == 0) - ThrowLastError (); - return ret; - } - } - - public double CpuLoad { - get { - var ret = PortAudioInterop.Pa_GetStreamCpuLoad (handle); - if (ret == 0) - ThrowLastError (); - return ret; - } - } - - // "The function doesn't return until the entire buffer has been filled - this may involve waiting for the operating system to supply the data." (!) - public void Read (byte[] buffer, int offset, uint frames) - { - unsafe { - fixed (byte* buf = buffer) - HandleError (PortAudioInterop.Pa_ReadStream ( - handle, - (IntPtr) (buf + offset), - frames - )); - } - } - - // "The function doesn't return until the entire buffer has been filled - this may involve waiting for the operating system to supply the data." (!) - public void Write (byte[] buffer, int offset, uint frames) - { - unsafe { - fixed (byte* buf = buffer) - HandleError (PortAudioInterop.Pa_WriteStream ( - handle, - (IntPtr) (buf + offset), - frames - )); - } - } - - public long AvailableReadFrames { - get { - var ret = PortAudioInterop.Pa_GetStreamReadAvailable (handle); - if (ret < 0) - HandleError ((PaErrorCode)ret); - return ret; - } - } - - public long AvailableWriteFrames { - get { - var ret = PortAudioInterop.Pa_GetStreamWriteAvailable (handle); - if (ret < 0) - HandleError ((PaErrorCode)ret); - return ret; - } - } - - internal static PaErrorCode HandleError (PaErrorCode errorCode) - { - return Configuration.HandleError (errorCode); - } - - internal static void ThrowLastError () - { - Configuration.ThrowLastError (); - } - - WeakReference buffer; - - int FramesToBytes (ulong frames) - { - switch (sample_format) { - case PaSampleFormat.Int32: - case PaSampleFormat.Float32: - return (int) frames * 4 * channels; - case PaSampleFormat.Int16: - return (int) frames * 2 * channels; - case PaSampleFormat.Int24: - return (int) frames * 3 * channels; - case PaSampleFormat.NonInterleaved: - case PaSampleFormat.Int8: - default: - return (int) frames * channels; - } - } - - internal unsafe PaStreamCallback ToPaStreamCallback (StreamCallback src, bool isOutput) - { - return (input, output, frameCount, timeInfo, statusFlags, userData) => { - var ptr = timeInfo != IntPtr.Zero ? new CppInstancePtr (timeInfo) : default (CppInstancePtr); - try { - byte [] buf = buffer != null ? (byte[]) buffer.Target : null; - var byteCount = FramesToBytes ((uint) frameCount); - if (buf == null || buf.Length < byteCount) { - buf = new byte [byteCount]; - buffer = new WeakReference (buf); - } - var ret = src ( - buf, - 0, - byteCount, - timeInfo != IntPtr.Zero ? Factory.Create (ptr) : default (PaStreamCallbackTimeInfo), - (PaStreamCallbackFlags) statusFlags, - userData - ); - Marshal.Copy (buf, 0, isOutput ? output : input, byteCount); - return ret; - } finally { - ptr.Dispose (); - } - }; - } - } -} diff --git a/portaudio2-sharp/README b/portaudio2-sharp/README deleted file mode 100644 index 37a1be0..0000000 --- a/portaudio2-sharp/README +++ /dev/null @@ -1,3 +0,0 @@ -C# binding for portaudio r1788 (v19). - -To build the dll, run xbuild. diff --git a/portaudio2-sharp/libs/README b/portaudio2-sharp/libs/README deleted file mode 100644 index 2d37684..0000000 --- a/portaudio2-sharp/libs/README +++ /dev/null @@ -1,2 +0,0 @@ -portaudio.dll in this directory was built without ASIO support as I never -bothered to register to Steinberg and download ASIO SDK. diff --git a/portaudio2-sharp/libs/portaudio.dll b/portaudio2-sharp/libs/portaudio.dll deleted file mode 100644 index f2c8c537056f326c36270a117e7708d3af8cf13e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 306077 zcmeFaePC48wLUzPOmKw388vFOQBxZ$C@Rrd8G#xJ0|-Q;VT3BFv|>tcrRBm5pb!X7 z26EgEjzy}y)fTRLOD!$5qDDncAY~FtH6WEl5{))jXF90iqY%-W-}9_}&SZv$BPF5%RA@e*f`L4U$j0@TJpin@;`H zSL^MQ|Mb-C&% zD+Ui9SZIPS_t|Wd?YXu(-_tkSj%M3#J;i40vJLp^AbVD>?I<#hu-j}No2>!=7}`8| zw+*{Xp0hOGj3NH=w-HYRY_{ao9BG%$R-ntV0L$Y~f*E$(S6FC{-4;DnqEGy@#%^;C zJaLl5M(wt|e~^5#q$>hfavcmxOnCXn<{RE{#dqh;V-}AaKjoR}jOSks z>%CjoE3}+}d~Cx7nfXg>!%MFCzRoAK2F-1xY2k7C8m=h4bqZk%O>2X<9PXp4~cO@stS9}e#*{(VVKdne-gUU~k?;AzTW?PyCB5C3MJAm6oDOTMXu z;~bA$Pv-zOxY?JvJZeExJl0*oE{4*Zbl4CYj>7mGf3w+Iwnm<3?UBuwF!+c0f5H5rUi-NXTceRp zUpMntg!bjCvj{W1D^RS?XDy+m!~6Dvvs8AtA#kv-RVPd2{G^dv7_S7RSPsh&NX${l zAbvAqLruANRBkm6r{gois63=9T}H511)WCq=c?Kh`ph0EH5L~-jp>CBqqs2swRI@F z&lTPqJl8_TUAq!c4PSTsw!XeTt(J;{cw%`Zl~8Uneji?pL?puWCVR2IMKX%sbni5N4Lf=z5zBaYZK1XaBKi@v_1 zhUEQG)>qV!m=9#)0n`^0WrdiTh>7YyO@9)k;PSiTyO8Tv)P6T>J`*wQwLc&-w9kp? z(-~a=ESbOL^1DFj!NX4nzAb?wL=7c~hfENcGViq}i2G9@PDMTz>1%D-TF+J|e;L)` z`_W8X#-YqD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XrrJK?Ng{p*G>w_2rRZxI z*rifWv}p*_etLiyOPfqKutIXvVmC%&7=Ys*-r>-8Tn7wx7+ky>|FpI~VXceZ1+W4ur zzBY{(<_Tj|p_+DNK>u75rW$O@$CYKCq%BD{2{n!6dVVpbAD6-sxO$DHIHy|`1v4kB z_+dEep==zDQXSLzBlO8x^VOJxF|Z jW+s+7HXWETF=`-VY3v}Z{5oAKb5>U`1yw2Y)xG}*LI}sM diff --git a/portaudio2-sharp/portaudio-sharp.csproj b/portaudio2-sharp/portaudio-sharp.csproj deleted file mode 100644 index ccefc75..0000000 --- a/portaudio2-sharp/portaudio-sharp.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net6.0 - Library - latest - Commons.Media.PortAudio - enable - true - CA1069 - - - \ No newline at end of file diff --git a/portaudio2-sharp/portaudio-sharp.sln b/portaudio2-sharp/portaudio-sharp.sln deleted file mode 100644 index c841244..0000000 --- a/portaudio2-sharp/portaudio-sharp.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "portaudio-sharp", "portaudio-sharp.csproj", "{46F2F4B1-6424-431F-8D30-F9D5EB465022}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Debug|Any CPU.Build.0 = Debug|Any CPU - {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Release|Any CPU.ActiveCfg = Release|Any CPU - {46F2F4B1-6424-431F-8D30-F9D5EB465022}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal From f90058c710bb6c78742adaff1a649595d2289440 Mon Sep 17 00:00:00 2001 From: Davin Date: Thu, 3 Aug 2023 18:47:23 +1000 Subject: [PATCH 08/20] MP2K Engine is now useable in GTK4 GUI --- VG Music Studio - GTK3/MainWindow.cs | 7 +- VG Music Studio - GTK4/MainWindow.cs | 2531 +++++++++-------- VG Music Studio - GTK4/Program.cs | 68 +- VG Music Studio - GTK4/Theme.cs | 358 +-- .../Util/FlexibleMessageBox.cs | 176 +- .../Util/SoundSequenceList.cs | 242 +- 6 files changed, 1726 insertions(+), 1656 deletions(-) diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs index e5ba058..7d593b4 100644 --- a/VG Music Studio - GTK3/MainWindow.cs +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -715,16 +715,17 @@ public void LetUIKnowPlayerIsPlaying() return; } - bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer // Configures the buttons when player is playing a sequenced track _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); // Experimental attempt for _positionAdjustment to be synchronized with _timer - timerValue = _timer.Equals(_positionAdjustment); - timerValue.CompareTo(_timer); + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); _timer.Start(); } diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index 1726947..fe17244 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -21,1287 +21,1310 @@ using System.Runtime.InteropServices; using System.Diagnostics; -namespace Kermalis.VGMusicStudio.GTK4 -{ - internal sealed class MainWindow : Window - { - private bool _playlistPlaying; - private Config.Playlist _curPlaylist; - private long _curSong = -1; - private readonly List _playedSequences; - private readonly List _remainingSequences; - private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. +namespace Kermalis.VGMusicStudio.GTK4; - private bool _stopUI = false; +internal sealed class MainWindow : Window +{ + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. - #region Widgets + private bool _stopUI = false; - // Buttons - private readonly Button _buttonPlay, _buttonPause, _buttonStop; + #region Widgets - // A Box specifically made to contain two contents inside - private readonly Box _splitContainerBox; + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; - // Spin Button for the numbered tracks - private readonly SpinButton _sequenceNumberSpinButton; + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; - // Timer - private readonly Timer _timer; + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; - // Popover Menu Bar - private readonly PopoverMenuBar _popoverMenuBar; + // Timer + private readonly Timer _timer; - // LibAdwaita Header Bar - private readonly Adw.HeaderBar _headerBar; + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; - // LibAdwaita Application - private readonly Adw.Application _app; + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; - // LibAdwaita Message Dialog - private Adw.MessageDialog _dialog; + // LibAdwaita Application + private readonly Adw.Application _app; - // Menu Model - //private readonly Gio.MenuModel _mainMenu; + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; - // Menus - private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + // Menu Model + //private readonly Gio.MenuModel _mainMenu; - // Menu Labels - private readonly Label _fileLabel, _dataLabel, _playlistLabel; + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; - // Menu Items - private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, - _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; - // Menu Actions - private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, - _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, - _soundSequenceAction; + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; - private Signal _openDSESignal; + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; - private SignalHandler _openDSEHandler; + private Signal _openDSESignal; - // Menu Widgets - private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget; + private SignalHandler _openDSEHandler; - // Main Box - private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + // Menu Widgets + private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget; - // Volume Button to indicate volume status - private readonly VolumeButton _volumeButton; + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; - // One Scale controling volume and one Scale for the sequenced track - private readonly Scale _volumeScale, _positionScale; + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; - // Mouse Click Gesture - private GestureClick _positionGestureClick, _sequencesGestureClick; + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; - // Event Controller - private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, - _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, - _sequencesEventController; + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; - // Adjustments are for indicating the numbers and the position of the scale - private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; - // Sound Sequence List - private SoundSequenceList _soundSequenceList; - - // Error Handle - private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); - - // Signal - private Signal _signal; - - // Callback - private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } - private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } - private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } - private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } - - #endregion - - public MainWindow(Application app) - { - // Main Window - SetDefaultSize(500, 300); // Sets the default size of the Window - Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" - _app = app; - - // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use - _playedSequences = new List(); - _remainingSequences = new List(); - - // Configures SetVolumeScale method with the MixerVolumeChanged Event action - Mixer.MixerVolumeChanged += SetVolumeScale; - - // LibAdwaita Header Bar - _headerBar = Adw.HeaderBar.New(); - _headerBar.SetShowEndTitleButtons(true); - - // Main Menu - _mainMenu = Gio.Menu.New(); - - // Popover Menu Bar - _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget - _popoverMenuBar.MenuModel = _mainMenu; - _popoverMenuBar.MnemonicActivate(true); - - // File Menu - _fileMenu = Gio.Menu.New(); - - _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); - _fileLabel.GetMnemonicKeyval(); - _fileLabel.SetUseUnderline(true); - _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); - _fileLabel.SetMnemonicWidget(_popoverMenuBar); - _popoverMenuBar.AddMnemonicLabel(_fileLabel); - _fileItem.SetSubmenu(_fileMenu); - - _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); - _openDSEAction = Gio.SimpleAction.New("openDSE", null); - _openDSEItem.SetActionAndTargetValue("app.openDSE", null); - _app.AddAction(_openDSEAction); - _openDSEAction.OnActivate += OpenDSE; - _fileMenu.AppendItem(_openDSEItem); - _openDSEItem.Unref(); - - _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); - _openSDATAction = Gio.SimpleAction.New("openSDAT", null); - _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); - _app.AddAction(_openSDATAction); - _openSDATAction.OnActivate += OpenSDAT; - _fileMenu.AppendItem(_openSDATItem); - _openSDATItem.Unref(); - - _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); - _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); - _app.AddAction(_openAlphaDreamAction); - _openAlphaDreamAction.OnActivate += OpenAlphaDream; - _fileMenu.AppendItem(_openAlphaDreamItem); - _openAlphaDreamItem.Unref(); - - _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); - _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); - _app.AddAction(_openMP2KAction); - _openMP2KAction.OnActivate += OpenMP2K; - _fileMenu.AppendItem(_openMP2KItem); - _openMP2KItem.Unref(); - - _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item, not the file menu itself - _fileItem.Unref(); - - // Data Menu - _dataMenu = Gio.Menu.New(); - - _dataLabel = Label.NewWithMnemonic(Strings.MenuData); - _dataLabel.GetMnemonicKeyval(); - _dataLabel.SetUseUnderline(true); - _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); - _popoverMenuBar.AddMnemonicLabel(_dataLabel); - _dataItem.SetSubmenu(_dataMenu); - - _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); - _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); - _app.AddAction(_exportDLSAction); - _exportDLSAction.OnActivate += ExportDLS; - _dataMenu.AppendItem(_exportDLSItem); - _exportDLSItem.Unref(); - - _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); - _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); - _app.AddAction(_exportSF2Action); - _exportSF2Action.OnActivate += ExportSF2; - _dataMenu.AppendItem(_exportSF2Item); - _exportSF2Item.Unref(); - - _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); - _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); - _app.AddAction(_exportMIDIAction); - _exportMIDIAction.OnActivate += ExportMIDI; - _dataMenu.AppendItem(_exportMIDIItem); - _exportMIDIItem.Unref(); - - _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); - _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); - _app.AddAction(_exportWAVAction); - _exportWAVAction.OnActivate += ExportWAV; - _dataMenu.AppendItem(_exportWAVItem); - _exportWAVItem.Unref(); - - //_mainMenu.PrependItem(_dataItem); // Data menu item needs to be reserved, but remain invisible until a sound engine is initialized. - _dataItem.Unref(); - - // Playlist Menu - _playlistMenu = Gio.Menu.New(); - - _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); - _playlistLabel.GetMnemonicKeyval(); - _playlistLabel.SetUseUnderline(true); - _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); - _popoverMenuBar.AddMnemonicLabel(_playlistLabel); - _playlistItem.SetSubmenu(_playlistMenu); - - _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); - _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); - _app.AddAction(_endPlaylistAction); - _endPlaylistAction.OnActivate += EndCurrentPlaylist; - _playlistMenu.AppendItem(_endPlaylistItem); - _endPlaylistItem.Unref(); - - //_mainMenu.PrependItem(_playlistItem); // Same thing as Data menu item. - _playlistItem.Unref(); - - // Buttons - _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; - _buttonPlay.OnClicked += (o, e) => Play(); - _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; - _buttonPause.OnClicked += (o, e) => Pause(); - _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; - _buttonStop.OnClicked += (o, e) => Stop(); - - // Spin Button - _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); - _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); - _sequenceNumberSpinButton.Sensitive = false; - _sequenceNumberSpinButton.Value = 0; - _sequenceNumberSpinButton.Visible = false; - _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; - - // Timer - _timer = new Timer(); - _timer.Elapsed += UpdateUI; - - // Volume Scale - _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); - _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); - _volumeScale.Sensitive = false; - _volumeScale.ShowFillLevel = true; - _volumeScale.DrawValue = false; - _volumeScale.WidthRequest = 250; - _volumeScale.OnValueChanged += VolumeScale_ValueChanged; - - // Position Scale - _positionAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); - _positionScale = Scale.New(Orientation.Horizontal, _positionAdjustment); - _positionScale.Sensitive = false; - _positionScale.ShowFillLevel = true; - _positionScale.DrawValue = false; - _positionScale.WidthRequest = 250; - _positionGestureClick = GestureClick.New(); - //_positionGestureClick.GetWidget().SetParent(_positionScale); - _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading - _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; - - // Sound Sequence List - _soundSequenceList = new SoundSequenceList { Sensitive = false }; - _soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); - _soundSequenceAction.OnChangeState += SequencesListView_SelectionGet; - - // Main display - _mainBox = Box.New(Orientation.Vertical, 4); - _configButtonBox = Box.New(Orientation.Horizontal, 2); - _configButtonBox.Halign = Align.Center; - _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); - _configPlayerButtonBox.Halign = Align.Center; - _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); - _configSpinButtonBox.Halign = Align.Center; - _configSpinButtonBox.WidthRequest = 100; - _configScaleBox = Box.New(Orientation.Horizontal, 2); - _configScaleBox.Halign = Align.Center; - - _mainBox.Append(_headerBar); - _mainBox.Append(_popoverMenuBar); - _mainBox.Append(_configButtonBox); - _mainBox.Append(_configScaleBox); - _mainBox.Append(_soundSequenceList); - - _configPlayerButtonBox.MarginStart = 40; - _configPlayerButtonBox.MarginEnd = 40; - _configButtonBox.Append(_configPlayerButtonBox); - _configSpinButtonBox.MarginStart = 100; - _configSpinButtonBox.MarginEnd = 100; - _configButtonBox.Append(_configSpinButtonBox); - - _configPlayerButtonBox.Append(_buttonPlay); - _configPlayerButtonBox.Append(_buttonPause); - _configPlayerButtonBox.Append(_buttonStop); - - _configSpinButtonBox.Append(_sequenceNumberSpinButton); - - _volumeScale.MarginStart = 20; - _volumeScale.MarginEnd = 20; - _configScaleBox.Append(_volumeScale); - _positionScale.MarginStart = 20; - _positionScale.MarginEnd = 20; - _configScaleBox.Append(_positionScale); - - SetContent(_mainBox); - - Show(); - - // Ensures the entire application closes when the window is closed - //OnCloseRequest += delegate { Application.Quit(); }; - } - - // When the value is changed on the volume scale - private void VolumeScale_ValueChanged(object sender, EventArgs e) - { - Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment.Value / _volumeAdjustment.Value)); - } - - // Sets the volume scale to the specified position - public void SetVolumeScale(float volume) - { - _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; - _volumeScale.Adjustment.Value = (int)(volume * _volumeAdjustment.Upper); - _volumeScale.OnValueChanged += VolumeScale_ValueChanged; - } - - private bool _positionScaleFree = true; - private void PositionScale_MouseButtonRelease(object sender, GestureClick.ReleasedSignalArgs args) - { - if (args.NPress == 1) // Number 1 is Left Mouse Button - { - Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Adjustment.Value); // Sets the value based on the position when mouse button is released - _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released - LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track - } - } - private void PositionScale_MouseButtonPress(object sender, GestureClick.PressedSignalArgs args) - { - if (args.NPress == 1) // Number 1 is Left Mouse Button - { - _positionScaleFree = false; - } - } - - private bool _autoplay = false; - private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) - { - //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; - //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); - - long index = (long)_sequenceNumberAdjustment.Value; - Stop(); - this.Title = ConfigUtils.PROGRAM_NAME; - //_sequencesListView.Margin = 0; - //_songInfo.Reset(); - bool success; - try - { - Engine.Instance!.Player.LoadSong(index); - success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); - success = false; - } - - //_trackViewer?.UpdateTracks(); - if (success) - { - Config config = Engine.Instance.Config; - List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 - Config.Song? song = songs.SingleOrDefault(s => s.Index == index); - if (song is not null) - { - this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func - //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox - } - _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; - _positionAdjustment.Value = _positionAdjustment.Upper / 10; - _positionAdjustment.Value = _positionAdjustment.Value / 4; - //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); - if (_autoplay) - { - Play(); - } - } - else - { - //_songInfo.SetNumTracks(0); - } - _positionScale.Sensitive = _exportWAVWidget.Sensitive = success; - _exportMIDIWidget.Sensitive = success && MP2KEngine.MP2KInstance is not null; - _exportDLSWidget.Sensitive = _exportSF2Widget.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; - - _autoplay = true; - //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; - //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); - } - private void SequencesListView_SelectionGet(object sender, EventArgs e) - { - var item = _soundSequenceList; - if (item.Item is Config.Song song) - { - SetAndLoadSequence(song.Index); - } - else if (item.Item is Config.Playlist playlist) - { - if (playlist.Songs.Count > 0 - && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) - { - ResetPlaylistStuff(false); - _curPlaylist = playlist; - Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; - Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; - _endPlaylistWidget.Sensitive = true; - SetAndLoadNextPlaylistSong(); - } - } - } - private void SetAndLoadSequence(long index) - { - _curSong = index; - if (_sequenceNumberSpinButton.Value == index) - { - SequenceNumberSpinButton_ValueChanged(null, null); - } - else - { - _sequenceNumberSpinButton.Value = index; - } - } - - private void SetAndLoadNextPlaylistSong() - { - if (_remainingSequences.Count == 0) - { - _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); - if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) - { - _remainingSequences.Any(); - } - } - long nextSequence = _remainingSequences[0]; - _remainingSequences.RemoveAt(0); - SetAndLoadSequence(nextSequence); - } - private void ResetPlaylistStuff(bool enableds) - { - if (Engine.Instance != null) - { - Engine.Instance.Player.ShouldFadeOut = false; - } - _playlistPlaying = false; - _curPlaylist = null; - _curSong = -1; - _remainingSequences.Clear(); - _playedSequences.Clear(); - //_endPlaylistWidget.Sensitive = false; - _sequenceNumberSpinButton.Sensitive = _soundSequenceList.Sensitive = enableds; - } - private void EndCurrentPlaylist(object sender, EventArgs e) - { - if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) - { - ResetPlaylistStuff(true); - } - } - - private void OpenDSE(Gio.SimpleAction sender, EventArgs e) - { - if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken - { - // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog - var d = FileChooserNative.New( - Strings.MenuOpenDSE, // The title shown in the folder select dialog window - this, // The parent of the dialog window, is the MainWindow itself - FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction - "Select Folder", // Followed by the accept - "Cancel"); // and cancel button names. - - d.SetModal(true); - - // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. - // Instead, it's handled by the OnResponse event function when it re-enters upon selection. - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. - { - d.Unref(); - return; - } - var path = d.GetCurrentFolder()!.GetPath() ?? ""; - d.GetData(path); - OpenDSEFinish(path); - d.Unref(); // Ensures disposal of the dialog when closed - return; - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuOpenDSE); - - _selectFolderCallback = (source, res, data) => - { - //var errorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); - var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); - if (folderHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); - OpenDSEFinish(path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. - //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); - } - } - private void OpenDSEFinish(string path) - { - DisposeEngine(); - try - { - _ = new DSEEngine(path); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); - return; - } - DSEConfig config = DSEEngine.DSEInstance!.Config; - FinishLoading(config.BGMFiles.Length); - _sequenceNumberSpinButton.Visible = false; - _sequenceNumberSpinButton.Hide(); - _mainMenu.AppendItem(_playlistItem); - _exportDLSAction.Enabled = false; - _exportMIDIAction.Enabled = false; - _exportSF2Action.Enabled = false; - } - private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) - { - var filterSDAT = FileFilter.New(); - filterSDAT.SetName(Strings.GTKFilterOpenSDAT); - filterSDAT.AddPattern("*.sdat"); - var allFiles = FileFilter.New(); - allFiles.SetName(Strings.GTKAllFiles); - allFiles.AddPattern("*.*"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuOpenSDAT, - this, - FileChooserAction.Open, - "Open", - "Cancel"); - - d.SetModal(true); - - d.AddFilter(filterSDAT); - d.AddFilter(allFiles); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - - var path = d.GetFile()!.GetPath() ?? ""; - d.GetData(path); - OpenSDATFinish(path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuOpenSDAT); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(filterSDAT); - filters.Append(allFiles); - d.SetFilters(filters); - _openCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - OpenSDATFinish(path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - } - } - private void OpenSDATFinish(string path) - { - DisposeEngine(); - try - { - _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); - return; - } - - SDATConfig config = SDATEngine.SDATInstance!.Config; - FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); - _sequenceNumberSpinButton.Visible = true; - _sequenceNumberSpinButton.Show(); - _exportDLSAction.Enabled = false; - _exportMIDIAction.Enabled = false; - _exportSF2Action.Enabled = false; - } - private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) - { - var filterGBA = FileFilter.New(); - filterGBA.SetName(Strings.GTKFilterOpenGBA); - filterGBA.AddPattern("*.gba"); - filterGBA.AddPattern("*.srl"); - var allFiles = FileFilter.New(); - allFiles.SetName(Name = Strings.GTKAllFiles); - allFiles.AddPattern("*.*"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuOpenAlphaDream, - this, - FileChooserAction.Open, - "Open", - "Cancel"); - d.SetModal(true); - - d.AddFilter(filterGBA); - d.AddFilter(allFiles); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - var path = d.GetFile()!.GetPath() ?? ""; - d.GetData(path); - OpenAlphaDreamFinish(path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuOpenAlphaDream); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(filterGBA); - filters.Append(allFiles); - d.SetFilters(filters); - _openCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - OpenAlphaDreamFinish(path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - } - } - private void OpenAlphaDreamFinish(string path) - { - DisposeEngine(); - try - { - _ = new AlphaDreamEngine(File.ReadAllBytes(path)); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); - return; - } - - AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; - FinishLoading(config.SongTableSizes[0]); - _sequenceNumberSpinButton.Visible = true; - _sequenceNumberSpinButton.Show(); - _mainMenu.AppendItem(_dataItem); - _mainMenu.AppendItem(_playlistItem); - _exportDLSAction.Enabled = true; - _exportMIDIAction.Enabled = false; - _exportSF2Action.Enabled = true; - } - private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) - { - FileFilter filterGBA = FileFilter.New(); - filterGBA.SetName(Strings.GTKFilterOpenGBA); - filterGBA.AddPattern("*.gba"); - filterGBA.AddPattern("*.srl"); - FileFilter allFiles = FileFilter.New(); - allFiles.SetName(Strings.GTKAllFiles); - allFiles.AddPattern("*.*"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuOpenMP2K, - this, - FileChooserAction.Open, - "Open", - "Cancel"); - - - d.AddFilter(filterGBA); - d.AddFilter(allFiles); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - var path = d.GetFile()!.GetPath() ?? ""; - d.GetData(path); - OpenMP2KFinish(path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuOpenMP2K); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(filterGBA); - filters.Append(allFiles); - d.SetFilters(filters); - _openCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - OpenMP2KFinish(path!); - d.Unref(); - } + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Sound Sequence List + private SignalListItemFactory _soundSequenceFactory; + private SoundSequenceList _soundSequenceList; + private SoundSequenceListItem _soundSequenceListItem; + private SortListModel _soundSequenceSortListModel; + private ListBox _soundSequenceListBox; + private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); + _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _positionScale = Scale.New(Orientation.Horizontal, _positionAdjustment); + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionGestureClick = GestureClick.New(); + //_positionGestureClick.GetWidget().SetParent(_positionScale); + _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + _soundSequenceFactory = SignalListItemFactory.New(); + _soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + _mainBox.Append(_soundSequenceListBox); + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + SetContent(_mainBox); + + Show(); + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment.Value / _volumeAdjustment.Value)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, GestureClick.ReleasedSignalArgs args) + { + if (args.NPress == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Adjustment.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, GestureClick.PressedSignalArgs args) + { + if (args.NPress == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + private void SequencesListView_SelectionGet(object sender, EventArgs e) + { + var item = _soundSequenceList.SelectedItem; + if (item is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item is Config.Playlist playlist) + { + if (playlist.Songs.Count > 0 + && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endPlaylistWidget.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + //_endPlaylistWidget.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _soundSequenceListBox.Sensitive = enableds; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); d.Unref(); - }; - Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - } - } - private void OpenMP2KFinish(string path) - { - DisposeEngine(); - if (IsWindows()) - { - try - { - _ = new MP2KEngine(File.ReadAllBytes(path)); + return; } - catch (Exception ex) - { - //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); - DisposeEngine(); - ExceptionDialog(ex, Strings.ErrorOpenMP2K); - return; - } - } - else - { - var ex = new PlatformNotSupportedException(); - ExceptionDialog(ex, Strings.ErrorOpenMP2K); - } - - MP2KConfig config = MP2KEngine.MP2KInstance!.Config; - FinishLoading(config.SongTableSizes[0]); - _sequenceNumberSpinButton.Visible = true; - _sequenceNumberSpinButton.Show(); - _mainMenu.AppendItem(_dataItem); - _mainMenu.AppendItem(_playlistItem); - _exportDLSAction.Enabled = false; - _exportMIDIAction.Enabled = true; - _exportSF2Action.Enabled = false; - } - private void ExportDLS(Gio.SimpleAction sender, EventArgs e) - { - AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - - FileFilter ff = FileFilter.New(); - ff.SetName(Strings.GTKFilterSaveDLS); - ff.AddPattern("*.dls"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuSaveDLS, - this, - FileChooserAction.Save, - "Save", - "Cancel"); - d.SetCurrentName(cfg.GetGameName()); - d.AddFilter(ff); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - - var path = d.GetFile()!.GetPath() ?? ""; - ExportDLSFinish(cfg, path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuSaveDLS); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(ff); - d.SetFilters(filters); - _saveCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - ExportDLSFinish(cfg, path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - } - } - private void ExportDLSFinish(AlphaDreamConfig config, string path) - { - try - { - AlphaDreamSoundFontSaver_DLS.Save(config, path); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); - } - } - private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) - { - FileFilter ff = FileFilter.New(); - ff.SetName(Strings.GTKFilterSaveMIDI); - ff.AddPattern("*.mid"); - ff.AddPattern("*.midi"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuSaveMIDI, - this, - FileChooserAction.Save, - "Save", - "Cancel"); - d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); - d.AddFilter(ff); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - - var path = d.GetFile()!.GetPath() ?? ""; - ExportMIDIFinish(path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuSaveMIDI); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(ff); - d.SetFilters(filters); - _saveCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - ExportMIDIFinish(path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - } - } - private void ExportMIDIFinish(string path) - { - MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; - var args = new MIDISaveArgs - { - SaveCommandsBeforeTranspose = true, - ReverseVolume = false, - TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> - { - (0, (4, 4)), - }, - }; - - try - { - p.SaveAsMIDI(path, args); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); - } - } - private void ExportSF2(Gio.SimpleAction sender, EventArgs e) - { - AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - - FileFilter ff = FileFilter.New(); - ff.SetName(Strings.GTKFilterSaveSF2); - ff.AddPattern("*.sf2"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuSaveSF2, - this, - FileChooserAction.Save, - "Save", - "Cancel"); - - d.SetCurrentName(cfg.GetGameName()); - d.AddFilter(ff); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - - var path = d.GetFile()!.GetPath() ?? ""; - ExportSF2Finish(cfg, path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuSaveSF2); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(ff); - d.SetFilters(filters); - _saveCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - ExportSF2Finish(cfg, path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - } - } - private void ExportSF2Finish(AlphaDreamConfig config, string path) - { - try - { - AlphaDreamSoundFontSaver_SF2.Save(config, path); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); - } - } - private void ExportWAV(Gio.SimpleAction sender, EventArgs e) - { - FileFilter ff = FileFilter.New(); - ff.SetName(Strings.GTKFilterSaveWAV); - ff.AddPattern("*.wav"); - - if (Gtk.Functions.GetMinorVersion() <= 8) - { - var d = FileChooserNative.New( - Strings.MenuSaveWAV, - this, - FileChooserAction.Save, - "Save", - "Cancel"); - - d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); - d.AddFilter(ff); - - d.OnResponse += (sender, e) => - { - if (e.ResponseId != (int)ResponseType.Accept) - { - d.Unref(); - return; - } - - var path = d.GetFile()!.GetPath() ?? ""; - ExportWAVFinish(path); - d.Unref(); - }; - d.Show(); - } - else - { - var d = FileDialog.New(); - d.SetTitle(Strings.MenuSaveWAV); - var filters = Gio.ListStore.New(FileFilter.GetGType()); - filters.Append(ff); - d.SetFilters(filters); - _saveCallback = (source, res, data) => - { - var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); - if (fileHandle != IntPtr.Zero) - { - var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - ExportWAVFinish(path!); - d.Unref(); - } - d.Unref(); - }; - Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); - } - } - private void ExportWAVFinish(string path) - { - Stop(); - - IPlayer player = Engine.Instance.Player; - bool oldFade = player.ShouldFadeOut; - long oldLoops = player.NumLoops; - player.ShouldFadeOut = true; - player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; - - try - { - player.Record(path); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); - } - catch (Exception ex) - { - FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); - } - - player.ShouldFadeOut = oldFade; - player.NumLoops = oldLoops; - _stopUI = false; - } - - public void ExceptionDialog(Exception error, string heading) - { - Debug.WriteLine(error.Message); - var md = Adw.MessageDialog.New(this, heading, error.Message); - md.SetModal(true); - md.AddResponse("ok", ("_OK")); - md.SetResponseAppearance("ok", ResponseAppearance.Default); - md.SetDefaultResponse("ok"); - md.SetCloseResponse("ok"); - _exceptionCallback = (source, res, data) => - { - md.Destroy(); - }; - md.Activate(); - md.Show(); - } - - public void LetUIKnowPlayerIsPlaying() - { - // Prevents method from being used if timer is already active - if (_timer.Enabled) - { - return; - } - - bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer - - // Configures the buttons when player is playing a sequenced track - _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; - _buttonPause.Label = Strings.PlayerPause; - _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); - - // Experimental attempt for _positionAdjustment to be synchronized with _timer - timerValue = _timer.Equals(_positionAdjustment); - timerValue.CompareTo(_timer); - - _timer.Start(); - } - - private void Play() - { - Engine.Instance!.Player.Play(); - LetUIKnowPlayerIsPlaying(); - } - private void Pause() - { - Engine.Instance!.Player.Pause(); - if (Engine.Instance.Player.State == PlayerState.Paused) - { - _buttonPause.Label = Strings.PlayerUnpause; - _timer.Stop(); - } - else - { - _buttonPause.Label = Strings.PlayerPause; - _timer.Start(); - } - } - private void Stop() - { - Engine.Instance!.Player.Stop(); - _buttonPause.Sensitive = _buttonStop.Sensitive = false; - _buttonPause.Label = Strings.PlayerPause; - _timer.Stop(); - UpdatePositionIndicators(0L); - } - private void TogglePlayback(object? sender, EventArgs? e) - { - switch (Engine.Instance!.Player.State) - { - case PlayerState.Stopped: Play(); break; - case PlayerState.Paused: - case PlayerState.Playing: Pause(); break; - } - } - private void PlayPreviousSequence(object? sender, EventArgs? e) - { - long prevSequence; - if (_playlistPlaying) - { - int index = _playedSequences.Count - 1; - prevSequence = _playedSequences[index]; - _playedSequences.RemoveAt(index); - _playedSequences.Insert(0, _curSong); - } - else - { - prevSequence = (long)_sequenceNumberSpinButton.Value - 1; - } - SetAndLoadSequence(prevSequence); - } - private void PlayNextSong(object? sender, EventArgs? e) - { - if (_playlistPlaying) - { - _playedSequences.Add(_curSong); - SetAndLoadNextPlaylistSong(); - } - else - { - SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); - } - } - - private void FinishLoading(long numSongs) - { - Engine.Instance!.Player.SongEnded += SongEnded; - foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) - { - _soundSequenceList.AddItem(new SoundSequenceList(playlist.Name)); - _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceList(s.Name)).ToArray()); - } - _sequenceNumberAdjustment.Upper = numSongs - 1; + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + + // Configures the buttons when player is playing a sequenced track + _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + //_soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + //_soundSequenceList.Add(new SoundSequenceListItem(playlist)); + //_soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; #if DEBUG - // [Debug methods specific to this UI will go in here] + // [Debug methods specific to this UI will go in here] #endif - _autoplay = false; - SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); - _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; - Show(); - } - private void DisposeEngine() - { - if (Engine.Instance is not null) - { - Stop(); - Engine.Instance.Dispose(); - } - - //_trackViewer?.UpdateTracks(); - Name = ConfigUtils.PROGRAM_NAME; - //_songInfo.SetNumTracks(0); - //_songInfo.ResetMutes(); - ResetPlaylistStuff(false); - UpdatePositionIndicators(0L); - //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); - _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; - _sequenceNumberSpinButton.Visible = false; - _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; - //_sequencesListView.Selection.SelectFunction = null; - //_sequencesColumnView.Unref(); - //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); - _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; - } - - private void UpdateUI(object? sender, EventArgs? e) - { - if (_stopUI) - { - _stopUI = false; - if (_playlistPlaying) - { - _playedSequences.Add(_curSong); - } - else - { - Stop(); - } - } - else - { - UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); - } - } - private void SongEnded() - { - _stopUI = true; - } - - // This updates _positionScale and _positionAdjustment to the value specified - // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead - private void UpdatePositionIndicators(long ticks) - { - if (_positionScaleFree) - { - _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues - } - } - } + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } } diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs index 940f1f1..a99da5f 100644 --- a/VG Music Studio - GTK4/Program.cs +++ b/VG Music Studio - GTK4/Program.cs @@ -5,44 +5,44 @@ namespace Kermalis.VGMusicStudio.GTK4 { - internal class Program - { - private readonly Adw.Application app; + internal class Program + { + private readonly Adw.Application app; - // public Theme Theme => Theme.ThemeType; + // public Theme Theme => Theme.ThemeType; - [STAThread] - public static int Main(string[] args) => new Program().Run(args); - public Program() - { - app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); - // var theme = new ThemeType(); - // // Set LibAdwaita Themes - // app.StyleManager!.ColorScheme = theme switch - // { - // ThemeType.System => ColorScheme.PreferDark, - // ThemeType.Light => ColorScheme.ForceLight, - // ThemeType.Dark => ColorScheme.ForceDark, - // _ => ColorScheme.PreferDark - // }; - var win = new MainWindow(app); + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); - app.OnActivate += OnActivate; + app.OnActivate += OnActivate; - void OnActivate(Gio.Application sender, EventArgs e) - { - // Add Main Window - app.AddWindow(win); - } - } + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } - public int Run(string[] args) - { - var argv = new string[args.Length + 1]; - argv[0] = "Kermalis.VGMusicStudio.GTK4"; - args.CopyTo(argv, 1); - return app.Run(args.Length + 1, argv); - } - } + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } } diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs index 0dc2876..1fd8cf1 100644 --- a/VG Music Studio - GTK4/Theme.cs +++ b/VG Music Studio - GTK4/Theme.cs @@ -15,210 +15,210 @@ namespace Kermalis.VGMusicStudio.GTK4; /// public enum ThemeType { - Light = 0, // Light Theme - Dark, // Dark Theme - System // System Default Theme + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme } internal class Theme { - public Theme ThemeType { get; set; } - - //[StructLayout(LayoutKind.Sequential)] - //public struct Color - //{ - // public float Red; - // public float Green; - // public float Blue; - // public float Alpha; - //} - - //[DllImport("libadwaita-1.so.0")] - //[return: MarshalAs(UnmanagedType.I1)] - //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); - - //[DllImport("libadwaita-1.so.0")] - //private static extern string gdk_rgba_to_string(ref Color rgba); - - //[DllImport("libadwaita-1.so.0")] - //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); - - //[DllImport("libadwaita-1.so.0")] - //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); - - //public static Color FromArgb(int r, int g, int b) - //{ - // Color color = new Color(); - // r = (int)color.Red; - // g = (int)color.Green; - // b = (int)color.Blue; - - // return color; - //} - - //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); - //public static readonly Color - // BackColor = Color.FromArgb(33, 33, 39), - // BackColorDisabled = Color.FromArgb(35, 42, 47), - // BackColorMouseOver = Color.FromArgb(32, 37, 47), - // BorderColor = Color.FromArgb(25, 120, 186), - // BorderColorDisabled = Color.FromArgb(47, 55, 60), - // ForeColor = Color.FromArgb(94, 159, 230), - // PlayerColor = Color.FromArgb(8, 8, 8), - // SelectionColor = Color.FromArgb(7, 51, 141), - // TitleBar = Color.FromArgb(16, 40, 63); - - - - //public static Color DrainColor(Color c) - //{ - // var hsl = new HSLColor(c); - // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); - //} + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} } internal sealed class ThemedButton : Button { - public ResponseType ResponseType; - public ThemedButton() - { - //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; - //FlatStyle = FlatStyle.Flat; - //Font = Theme.FontType; - //ForeColor = Theme.ForeColor; - } - protected void OnEnabledChanged(EventArgs e) - { - //base.OnEnabledChanged(e); - //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; - //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; - } - protected void OnDraw(Context c) - { - //base.OnPaint(e); - //if (!Enabled) - //{ - // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); - //} - } - //protected override bool ShowFocusCues => false; + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; } internal sealed class ThemedLabel : Label { - public ThemedLabel() - { - //Font = Theme.Font; - //ForeColor = Theme.ForeColor; - } + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } } internal class ThemedWindow : Window { - public ThemedWindow() - { - //BackColor = Theme.BackColor; - //Icon = Resources.Icon; - } + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } } internal class ThemedBox : Box { - public ThemedBox() - { - //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); - } - protected void OnDraw(Context c) - { - //base.OnPaint(e); - //using (var b = new SolidBrush(BackColor)) - //{ - // e.Graphics.FillRectangle(b, e.ClipRectangle); - //} - //using (var b = new SolidBrush(Theme.BorderColor)) - //using (var p = new Pen(b, 2)) - //{ - // e.Graphics.DrawRectangle(p, e.ClipRectangle); - //} - } - private const int WM_PAINT = 0xF; - //protected void WndProc(ref Message m) - //{ - // if (m.Msg == WM_PAINT) - // { - // Invalidate(); - // } - // base.WndProc(ref m); - //} + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} } internal class ThemedTextBox : Adw.Window { - public Box Box; - public Text Text; - public ThemedTextBox() - { - //BackColor = Theme.BackColor; - //Font = Theme.Font; - //ForeColor = Theme.ForeColor; - Box = Box.New(Orientation.Horizontal, 0); - Text = Text.New(); - Box.Append(Text); - } - //[DllImport("user32.dll")] - //private static extern IntPtr GetWindowDC(IntPtr hWnd); - //[DllImport("user32.dll")] - //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); - //[DllImport("user32.dll")] - //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); - //private const int WM_NCPAINT = 0x85; - //private const uint RDW_INVALIDATE = 0x1; - //private const uint RDW_IUPDATENOW = 0x100; - //private const uint RDW_FRAME = 0x400; - //protected override void WndProc(ref Message m) - //{ - // base.WndProc(ref m); - // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) - // { - // IntPtr hdc = GetWindowDC(Handle); - // using (var g = Graphics.FromHdcInternal(hdc)) - // using (var p = new Pen(Theme.BorderColor)) - // { - // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); - // } - // ReleaseDC(Handle, hdc); - // } - //} - protected void OnSizeChanged(EventArgs e) - { - //base.OnSizeChanged(e); - //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); - } + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } } internal sealed class ThemedRichTextBox : Adw.Window { - public Box Box; - public Text Text; - public ThemedRichTextBox() - { - //BackColor = Theme.BackColor; - //Font = Theme.Font; - //ForeColor = Theme.ForeColor; - //SelectionColor = Theme.SelectionColor; - Box = Box.New(Orientation.Horizontal, 0); - Text = Text.New(); - Box.Append(Text); - } + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } } internal sealed class ThemedNumeric : SpinButton { - public ThemedNumeric() - { - //BackColor = Theme.BackColor; - //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); - //ForeColor = Theme.ForeColor; - //TextAlign = HorizontalAlignment.Center; - } - protected void OnDraw(Context c) - { - //base.OnPaint(e); - //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); - } + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } } \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs index 43aa3a1..621175f 100644 --- a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -33,76 +33,76 @@ namespace Kermalis.VGMusicStudio.GTK4.Util; #region Original Author /* FlexibleMessageBox – A flexible replacement for the .NET MessageBox - * - * Author: Jörg Reichert (public@jreichert.de) - * Contributors: Thanks to: David Hall, Roink - * Version: 1.3 - * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox - * - ************************************************************************************************************ - * Features: - * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported - * - It is small, only one source file, which could be added easily to each solution - * - It can be resized and the content is correctly word-wrapped - * - It tries to auto-size the width to show the longest text row - * - It never exceeds the current desktop working area - * - It displays a vertical scrollbar when needed - * - It does support hyperlinks in text - * - * Because the interface is identical to MessageBox, you can add this single source file to your project - * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. - * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my - * own needs. Feel free to add additional features on your own, but please left my credits in this class. - * - ************************************************************************************************************ - * Usage examples: - * - * FlexibleMessageBox.Show("Just a text"); - * - * FlexibleMessageBox.Show("A text", - * "A caption"); - * - * FlexibleMessageBox.Show("Some text with a link: www.google.com", - * "Some caption", - * MessageBoxButtons.AbortRetryIgnore, - * MessageBoxIcon.Information, - * MessageBoxDefaultButton.Button2); - * - * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", - * "One short question", - * MessageBoxButtons.YesNo); - * - ************************************************************************************************************ - * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY - * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS - * SOFTWARE. - * - ************************************************************************************************************ - * History: - * Version 1.3 - 19.Dezember 2014 - * - Added refactoring function GetButtonText() - * - Used CurrentUICulture instead of InstalledUICulture - * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN - * - Added standard MessageBox handling for "copy to clipboard" with + and + - * - Tab handling is now corrected (only tabbing over the visible buttons) - * - Added standard MessageBox handling for ALT-Keyboard shortcuts - * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing - * - * Version 1.2 - 10.August 2013 - * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) - * - Added handling for Escape-Button - * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) - * - * Version 1.1 - 14.June 2013 - * - Some Refactoring - * - Added internal form class - * - Added missing code comments, etc. - * - * Version 1.0 - 15.April 2013 - * - Initial Version - */ + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ #endregion internal class FlexibleMessageBox @@ -202,7 +202,7 @@ private FlexibleButton() } } - internal sealed class FlexibleContentBox : Gtk.Box + internal sealed class FlexibleContentBox : Gtk.Box { public Gtk.Text Text; @@ -227,8 +227,8 @@ protected void Dispose(bool disposing) void InitializeComponent() { //components = new Container(); - richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); - button1 = (FlexibleButton)Gtk.Button.New(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); //FlexibleMessageBoxFormBindingSource = new BindingSource(components); panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); pictureBoxForIcon = Gtk.Image.New(); @@ -274,9 +274,9 @@ void InitializeComponent() //richTextBoxMessage.Size = new Size(200, 20); richTextBoxMessage.WidthRequest = 200; richTextBoxMessage.HeightRequest = 20; - //richTextBoxMessage.TabIndex = 0; - //richTextBoxMessage.TabStop = false; - richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); // // panel1 @@ -313,11 +313,11 @@ void InitializeComponent() //button2.Location = new Point(92, 67); //button2.MinimumSize = new Size(0, 24); button2.Name = "button2"; - //button2.Size = new Size(75, 24); - button2.WidthRequest = 75; - button2.HeightRequest = 24; - //button2.TabIndex = 3; - button2.Label = "OK"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; //button2.UseVisualStyleBackColor = true; button2.Visible = false; // @@ -329,11 +329,11 @@ void InitializeComponent() //button3.Location = new Point(173, 67); //button3.MinimumSize = new Size(0, 24); button3.Name = "button3"; - //button3.Size = new Size(75, 24); - button3.WidthRequest = 75; - button3.HeightRequest = 24; - //button3.TabIndex = 0; - button3.Label = "OK"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; //button3.UseVisualStyleBackColor = true; button3.Visible = false; // @@ -512,10 +512,10 @@ static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.M break; case Gtk.MessageType.Warning: flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); - break; + break; case Gtk.MessageType.Error: flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); - break; + break; case Gtk.MessageType.Question: flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); break; diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs index 468b31e..6077bf9 100644 --- a/VG Music Studio - GTK4/Util/SoundSequenceList.cs +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -4,107 +4,153 @@ using System.Text; using System.Threading.Tasks; using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; namespace Kermalis.VGMusicStudio.GTK4.Util; internal class SoundSequenceList : Widget, IDisposable { - internal static Gio.ListStore Store; - internal static SortListModel Model; - internal static ColumnView View; - static SignalListItemFactory Factory; - - static long Index; - static string Name; - - internal object Item { get; } - - internal SoundSequenceList(string name) - { - // Import the variables - Name = name; - - // Allow the box to be scrollable - var sw = ScrolledWindow.New(); - sw.SetHasFrame(true); - sw.SetPolicy(PolicyType.Never, PolicyType.Automatic); - - // Create a Sort List Model - Model = CreateModel(); - Model.Unref(); - - sw.SetChild(View); - - Item = View; - - // Add the Columns - AddColumns(View); - } - internal SoundSequenceList() - { - // Allow the box to be scrollable - var sw = ScrolledWindow.New(); - sw.SetHasFrame(true); - sw.SetPolicy(PolicyType.Never, PolicyType.Automatic); - - // Create a Sort List Model - Model = CreateModel(); - Model.Unref(); - - sw.SetChild(View); - - // Create a new name - Name = new string("Name"); - - // Add the Columns - AddColumns(View); - - Item = View; - } - - static SortListModel CreateModel() - { - // Create List Store - Store = Gio.ListStore.New(SortListModel.GetGType()); - - // Create Column View with a Single Selection that reads from List Store - View = ColumnView.New(SingleSelection.New(Store)); - - // Create Sort List Model - var model = SortListModel.New(Store, View.Sorter); - - // Add data to the list store - for (int i = 0; i < Index; i++) - { - Store.Append(model); - } - - return model; - } - - //static void FixedToggled(object sender, EventArgs e) - //{ - // var model = Model; - - // var fixedBit = new bool(); - // fixedBit ^= true; - //} - - static void AddColumns(ColumnView columnView) - { - Factory = SignalListItemFactory.New(); - //var renderer = ToggleButton.New(); - //renderer.OnToggled += FixedToggled; - var colName = ColumnViewColumn.New(Name, Factory); - columnView.AppendColumn(colName); - } - - internal int AddItem(object item) - { - return AddItem(item); - } - internal int AddRange(Span item) - { - return AddRange(item); - } + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } } From 277c1e79b57ba6c8e86941e90e266d15b1eae817 Mon Sep 17 00:00:00 2001 From: Davin Date: Sat, 5 Aug 2023 16:20:30 +1000 Subject: [PATCH 09/20] Pause and Stop buttons are now usable --- VG Music Studio - GTK4/MainWindow.cs | 98 ++++++++++++--------- VG Music Studio - GTK4/Util/ScaleControl.cs | 86 ++++++++++++++++++ 2 files changed, 144 insertions(+), 40 deletions(-) create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index fe17244..e3e3ac9 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -5,6 +5,8 @@ using Kermalis.VGMusicStudio.Core.NDS.SDAT; using Kermalis.VGMusicStudio.Core.Properties; using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; using Adw; using Gtk; using System; @@ -13,13 +15,11 @@ using System.IO; using System.Linq; using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; using Application = Adw.Application; using Window = Adw.Window; -using GObject; -using Kermalis.VGMusicStudio.GTK4.Util; -using System.Runtime.InteropServices; -using System.Diagnostics; namespace Kermalis.VGMusicStudio.GTK4; @@ -103,7 +103,8 @@ internal sealed class MainWindow : Window _sequencesEventController; // Adjustments are for indicating the numbers and the position of the scale - private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + private Adjustment _volumeAdjustment, _sequenceNumberAdjustment; + private ScaleControl _positionAdjustment; // Sound Sequence List private SignalListItemFactory _soundSequenceFactory; @@ -210,32 +211,32 @@ public MainWindow(Application app) _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); _app.AddAction(_exportDLSAction); - _exportDLSAction.Enabled = false; - _exportDLSAction.OnActivate += ExportDLS; + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; _dataMenu.AppendItem(_exportDLSItem); _exportDLSItem.Unref(); _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); _app.AddAction(_exportSF2Action); - _exportSF2Action.Enabled = false; - _exportSF2Action.OnActivate += ExportSF2; + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; _dataMenu.AppendItem(_exportSF2Item); _exportSF2Item.Unref(); _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); _app.AddAction(_exportMIDIAction); - _exportMIDIAction.Enabled = false; - _exportMIDIAction.OnActivate += ExportMIDI; + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; _dataMenu.AppendItem(_exportMIDIItem); _exportMIDIItem.Unref(); _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); _app.AddAction(_exportWAVAction); - _exportWAVAction.Enabled = false; - _exportWAVAction.OnActivate += ExportWAV; + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; _dataMenu.AppendItem(_exportWAVItem); _exportWAVItem.Unref(); @@ -255,12 +256,12 @@ public MainWindow(Application app) _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); _app.AddAction(_endPlaylistAction); - _endPlaylistAction.Enabled = false; - _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; _playlistMenu.AppendItem(_endPlaylistItem); _endPlaylistItem.Unref(); - _mainMenu.AppendItem(_playlistItem); + _mainMenu.AppendItem(_playlistItem); _playlistItem.Unref(); // Buttons @@ -293,14 +294,13 @@ public MainWindow(Application app) _volumeScale.OnValueChanged += VolumeScale_ValueChanged; // Position Scale - _positionAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _positionAdjustment = new ScaleControl(0, 0, 0, 1, 1, 1); _positionScale = Scale.New(Orientation.Horizontal, _positionAdjustment); _positionScale.Sensitive = false; _positionScale.ShowFillLevel = true; _positionScale.DrawValue = false; _positionScale.WidthRequest = 250; _positionGestureClick = GestureClick.New(); - //_positionGestureClick.GetWidget().SetParent(_positionScale); _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; @@ -343,8 +343,12 @@ public MainWindow(Application app) _configPlayerButtonBox.Append(_buttonPause); _configPlayerButtonBox.Append(_buttonStop); - _configSpinButtonBox.Append(_sequenceNumberSpinButton); - + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + _volumeScale.MarginStart = 20; _volumeScale.MarginEnd = 20; _configScaleBox.Append(_volumeScale); @@ -355,19 +359,27 @@ public MainWindow(Application app) SetContent(_mainBox); Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; } // When the value is changed on the volume scale private void VolumeScale_ValueChanged(object sender, EventArgs e) { - Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment.Value / _volumeAdjustment.Value)); + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); } // Sets the volume scale to the specified position public void SetVolumeScale(float volume) { _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; - _volumeScale.Adjustment.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); _volumeScale.OnValueChanged += VolumeScale_ValueChanged; } @@ -376,7 +388,7 @@ private void PositionScale_MouseButtonRelease(object sender, GestureClick.Releas { if (args.NPress == 1) // Number 1 is Left Mouse Button { - Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Adjustment.Value); // Sets the value based on the position when mouse button is released + Engine.Instance.Player.SetCurrentPosition((long)_positionAdjustment.Value); // Sets the value based on the position when mouse button is released _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track } @@ -403,6 +415,10 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) bool success; try { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } Engine.Instance!.Player.LoadSong(index); success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) } @@ -423,9 +439,10 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; - _positionAdjustment.Value = _positionAdjustment.Upper / 10; - _positionAdjustment.Value = _positionAdjustment.Value / 4; + _positionAdjustment.Upper = (ulong)Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.LargeChange = (ulong)_positionAdjustment.Upper / 10; + _positionAdjustment.SmallChange = (ulong)_positionAdjustment.LargeChange / 4; + _positionScale.Show(); //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) { @@ -438,7 +455,7 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) } _positionScale.Sensitive = _exportWAVAction.Enabled = success; _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; - _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; _autoplay = true; //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; @@ -803,13 +820,13 @@ private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) { var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); OpenMP2KFinish(path!); - filterGBA.Unref(); - allFiles.Unref(); - filters.Unref(); - GObject.Internal.Object.Unref(fileHandle); - d.Unref(); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); return; - } + } d.Unref(); }; Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); @@ -1176,15 +1193,11 @@ public void LetUIKnowPlayerIsPlaying() GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything // Configures the buttons when player is playing a sequenced track - _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them _buttonPause.Label = Strings.PlayerPause; - _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); - - // Experimental attempt for _positionAdjustment to be synchronized with _timer - //timerValue = _timer.Equals(_positionAdjustment); - //timerValue.CompareTo(_timer); - + _timer.Interval = (uint)(1_000.0 / GlobalConfig.Instance.RefreshRate); _timer.Start(); + Show(); } private void Play() @@ -1208,11 +1221,16 @@ private void Pause() } private void Stop() { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } Engine.Instance!.Player.Stop(); _buttonPause.Sensitive = _buttonStop.Sensitive = false; _buttonPause.Label = Strings.PlayerPause; _timer.Stop(); UpdatePositionIndicators(0L); + Show(); } private void TogglePlayback(object? sender, EventArgs? e) { diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..f170f39 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} From 24a950a6870a4a09778d51e77fc2964307125f78 Mon Sep 17 00:00:00 2001 From: Davin Date: Fri, 25 Aug 2023 22:03:51 +1000 Subject: [PATCH 10/20] A few adjustments --- VG Music Studio - GTK3/MainWindow.cs | 17 ++- .../VG Music Studio - GTK3.csproj | 2 +- VG Music Studio - GTK4/MainWindow.cs | 141 +++++++++--------- VG Music Studio - GTK4/Util/ScaleControl.cs | 76 +++++----- 4 files changed, 121 insertions(+), 115 deletions(-) diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs index 7d593b4..01921eb 100644 --- a/VG Music Studio - GTK3/MainWindow.cs +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -218,14 +218,14 @@ public MainWindow() : base(ConfigUtils.PROGRAM_NAME) // When the value is changed on the volume scale private void VolumeScale_ValueChanged(object? sender, EventArgs? e) { - Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Value / _volumeAdjustment.Value)); + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); } // Sets the volume scale to the specified position public void SetVolumeScale(float volume) { _volumeScale.ValueChanged -= VolumeScale_ValueChanged; - _volumeScale.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); _volumeScale.ValueChanged += VolumeScale_ValueChanged; } @@ -480,8 +480,10 @@ private void OpenMP2K(object? sender, EventArgs? e) d.Destroy(); return; } - - DisposeEngine(); + if (Engine.Instance != null) + { + DisposeEngine(); + } try { _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); @@ -718,7 +720,7 @@ public void LetUIKnowPlayerIsPlaying() //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer // Configures the buttons when player is playing a sequenced track - _buttonPause.FocusOnClick = _buttonStop.FocusOnClick = true; + _buttonPause.Sensitive = _buttonStop.Sensitive = true; _buttonPause.Label = Strings.PlayerPause; GlobalConfig.Init(); _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); @@ -800,9 +802,8 @@ private void FinishLoading(long numSongs) Engine.Instance!.Player.SongEnded += SongEnded; foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) { - int i = 0; - _sequencesListStore.AppendValues(i++, playlist); - playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray(); + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); } _sequenceNumberAdjustment.Upper = numSongs - 1; #if DEBUG diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj index 7352a8a..f18377e 100644 --- a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -1,7 +1,7 @@ - WinExe + Exe net6.0 diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index e3e3ac9..44efa26 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -82,9 +82,6 @@ internal sealed class MainWindow : Window private SignalHandler _openDSEHandler; - // Menu Widgets - private Widget _exportDLSWidget, _exportSF2Widget, _exportMIDIWidget, _exportWAVWidget, _endPlaylistWidget; - // Main Box private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; @@ -92,7 +89,7 @@ internal sealed class MainWindow : Window private readonly VolumeButton _volumeButton; // One Scale controling volume and one Scale for the sequenced track - private readonly Scale _volumeScale, _positionScale; + private Scale _volumeScale, _positionScale; // Mouse Click Gesture private GestureClick _positionGestureClick, _sequencesGestureClick; @@ -103,16 +100,16 @@ internal sealed class MainWindow : Window _sequencesEventController; // Adjustments are for indicating the numbers and the position of the scale - private Adjustment _volumeAdjustment, _sequenceNumberAdjustment; - private ScaleControl _positionAdjustment; + private readonly Adjustment _volumeAdjustment, _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; // Sound Sequence List - private SignalListItemFactory _soundSequenceFactory; - private SoundSequenceList _soundSequenceList; - private SoundSequenceListItem _soundSequenceListItem; - private SortListModel _soundSequenceSortListModel; - private ListBox _soundSequenceListBox; - private DropDown _soundSequenceDropDown; + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; // Error Handle private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); @@ -291,23 +288,30 @@ public MainWindow(Application app) _volumeScale.ShowFillLevel = true; _volumeScale.DrawValue = false; _volumeScale.WidthRequest = 250; - _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + //_volumeScale.OnValueChanged += VolumeScale_ValueChanged; // Position Scale - _positionAdjustment = new ScaleControl(0, 0, 0, 1, 1, 1); - _positionScale = Scale.New(Orientation.Horizontal, _positionAdjustment); + _positionScale = Scale.New(Orientation.Horizontal, Adjustment.New(0, 0, 1, 1, 1, 1)); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup _positionScale.Sensitive = false; _positionScale.ShowFillLevel = true; _positionScale.DrawValue = false; _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + //_positionScale.SetRange(0, double.MaxValue); + //_positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + //_positionScale.OnValueChanged += PositionScale_MouseButtonPress; + // _positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; _positionGestureClick = GestureClick.New(); - _positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading - _positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; // Sound Sequence List //_soundSequenceList = new SoundSequenceList { Sensitive = false }; - _soundSequenceFactory = SignalListItemFactory.New(); - _soundSequenceListBox = ListBox.New(); + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; @@ -326,12 +330,6 @@ public MainWindow(Application app) _configScaleBox = Box.New(Orientation.Horizontal, 2); _configScaleBox.Halign = Align.Center; - _mainBox.Append(_headerBar); - _mainBox.Append(_popoverMenuBar); - _mainBox.Append(_configButtonBox); - _mainBox.Append(_configScaleBox); - _mainBox.Append(_soundSequenceListBox); - _configPlayerButtonBox.MarginStart = 40; _configPlayerButtonBox.MarginEnd = 40; _configButtonBox.Append(_configPlayerButtonBox); @@ -356,6 +354,12 @@ public MainWindow(Application app) _positionScale.MarginEnd = 20; _configScaleBox.Append(_positionScale); + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + SetContent(_mainBox); Show(); @@ -384,18 +388,18 @@ public void SetVolumeScale(float volume) } private bool _positionScaleFree = true; - private void PositionScale_MouseButtonRelease(object sender, GestureClick.ReleasedSignalArgs args) + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) { - if (args.NPress == 1) // Number 1 is Left Mouse Button + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button { - Engine.Instance.Player.SetCurrentPosition((long)_positionAdjustment.Value); // Sets the value based on the position when mouse button is released + Engine.Instance!.Player.SetCurrentPosition((long)_positionScale.Adjustment!.Value); // Sets the value based on the position when mouse button is released _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track } } - private void PositionScale_MouseButtonPress(object sender, GestureClick.PressedSignalArgs args) + private void PositionScale_MouseButtonPress(object sender, EventArgs args) { - if (args.NPress == 1) // Number 1 is Left Mouse Button + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button { _positionScaleFree = false; } @@ -439,9 +443,9 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - _positionAdjustment.Upper = (ulong)Engine.Instance!.Player.LoadedSong!.MaxTicks; - _positionAdjustment.LargeChange = (ulong)_positionAdjustment.Upper / 10; - _positionAdjustment.SmallChange = (ulong)_positionAdjustment.LargeChange / 4; + _positionScale.Adjustment!.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; _positionScale.Show(); //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) @@ -461,27 +465,27 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); } - private void SequencesListView_SelectionGet(object sender, EventArgs e) - { - var item = _soundSequenceList.SelectedItem; - if (item is Config.Song song) - { - SetAndLoadSequence(song.Index); - } - else if (item is Config.Playlist playlist) - { - if (playlist.Songs.Count > 0 - && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) - { - ResetPlaylistStuff(false); - _curPlaylist = playlist; - Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; - Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; - _endPlaylistWidget.Sensitive = true; - SetAndLoadNextPlaylistSong(); - } - } - } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} private void SetAndLoadSequence(long index) { _curSong = index; @@ -520,8 +524,8 @@ private void ResetPlaylistStuff(bool enableds) _curSong = -1; _remainingSequences.Clear(); _playedSequences.Clear(); - //_endPlaylistWidget.Sensitive = false; - _sequenceNumberSpinButton.Sensitive = _soundSequenceListBox.Sensitive = enableds; + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ enableds; } private void EndCurrentPlaylist(object sender, EventArgs e) { @@ -799,7 +803,6 @@ private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) return; } var path = d.GetFile()!.GetPath() ?? ""; - d.GetData(path); OpenMP2KFinish(path); d.Unref(); }; @@ -1188,14 +1191,16 @@ public void LetUIKnowPlayerIsPlaying() return; } - //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer - - GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } // Configures the buttons when player is playing a sequenced track _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them _buttonPause.Label = Strings.PlayerPause; - _timer.Interval = (uint)(1_000.0 / GlobalConfig.Instance.RefreshRate); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); _timer.Start(); Show(); } @@ -1273,12 +1278,12 @@ private void PlayNextSong(object? sender, EventArgs? e) private void FinishLoading(long numSongs) { Engine.Instance!.Player.SongEnded += SongEnded; - foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) - { - //_soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); - //_soundSequenceList.Add(new SoundSequenceListItem(playlist)); - //_soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); - } + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} _sequenceNumberAdjustment.Upper = numSongs - 1; #if DEBUG // [Debug methods specific to this UI will go in here] @@ -1342,7 +1347,7 @@ private void UpdatePositionIndicators(long ticks) { if (_positionScaleFree) { - _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues } } } diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs index f170f39..6d21dc2 100644 --- a/VG Music Studio - GTK4/Util/ScaleControl.cs +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -43,44 +43,44 @@ namespace Kermalis.VGMusicStudio.GTK4.Util; internal class ScaleControl : Adjustment { - internal Adjustment Instance { get; } + internal Adjustment Instance { get; } - internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) - { - Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); - } - - private double _smallChange = 1L; - public double SmallChange - { - get => _smallChange; - set - { - if (value >= 0) - { - _smallChange = value; - } - else - { - throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); - } - } - } - private double _largeChange = 5L; - public double LargeChange - { - get => _largeChange; - set - { - if (value >= 0) - { - _largeChange = value; - } - else - { - throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); - } - } - } + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } } From 5c13c54af6e5ac666226a8c62a3035ae5b60e889 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Sun, 19 Nov 2023 18:28:01 +1100 Subject: [PATCH 11/20] Sync with net-6 branch --- .gitignore | 3 +- .vscode/launch.json | 26 + .vscode/tasks.json | 41 + .../CellEditing/CellEditKeyEngine.cs | 520 + ObjectListView/CellEditing/CellEditors.cs | 325 + ObjectListView/CellEditing/EditorRegistry.cs | 213 + ObjectListView/CustomDictionary.xml | 46 + ObjectListView/DataListView.cs | 240 + ObjectListView/DataTreeListView.cs | 240 + ObjectListView/DragDrop/DragSource.cs | 219 + ObjectListView/DragDrop/DropSink.cs | 1562 +++ ObjectListView/DragDrop/OLVDataObject.cs | 185 + ObjectListView/FastDataListView.cs | 169 + ObjectListView/FastObjectListView.cs | 422 + ObjectListView/Filtering/Cluster.cs | 125 + .../Filtering/ClusteringStrategy.cs | 189 + .../Filtering/ClustersFromGroupsStrategy.cs | 70 + .../Filtering/DateTimeClusteringStrategy.cs | 187 + ObjectListView/Filtering/FilterMenuBuilder.cs | 369 + ObjectListView/Filtering/Filters.cs | 489 + .../Filtering/FlagClusteringStrategy.cs | 160 + ObjectListView/Filtering/ICluster.cs | 56 + .../Filtering/IClusteringStrategy.cs | 80 + ObjectListView/Filtering/TextMatchFilter.cs | 642 + ObjectListView/FullClassDiagram.cd | 1261 ++ ObjectListView/Implementation/Attributes.cs | 335 + ObjectListView/Implementation/Comparers.cs | 330 + .../Implementation/DataSourceAdapter.cs | 628 + ObjectListView/Implementation/Delegates.cs | 168 + ObjectListView/Implementation/DragSource.cs | 407 + ObjectListView/Implementation/DropSink.cs | 1402 ++ ObjectListView/Implementation/Enums.cs | 104 + ObjectListView/Implementation/Events.cs | 2514 ++++ .../Implementation/GroupingParameters.cs | 204 + ObjectListView/Implementation/Groups.cs | 761 ++ ObjectListView/Implementation/Munger.cs | 568 + .../Implementation/NativeMethods.cs | 1223 ++ .../Implementation/NullableDictionary.cs | 87 + ObjectListView/Implementation/OLVListItem.cs | 325 + .../Implementation/OLVListSubItem.cs | 173 + .../Implementation/OlvListViewHitTestInfo.cs | 388 + .../Implementation/TreeDataSourceAdapter.cs | 262 + .../Implementation/VirtualGroups.cs | 341 + .../Implementation/VirtualListDataSource.cs | 349 + ObjectListView/OLVColumn.cs | 1909 +++ ObjectListView/ObjectListView.DesignTime.cs | 550 + ObjectListView/ObjectListView.FxCop | 3521 +++++ ObjectListView/ObjectListView.cs | 10924 ++++++++++++++++ ObjectListView/ObjectListView.shfb | 47 + ObjectListView/ObjectListView2019.csproj | 54 + ObjectListView/ObjectListView2019.nuspec | 22 + ObjectListView/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 113 + ObjectListView/Properties/Resources.resx | 137 + ObjectListView/Rendering/Adornments.cs | 743 ++ ObjectListView/Rendering/Decorations.cs | 973 ++ ObjectListView/Rendering/Overlays.cs | 302 + ObjectListView/Rendering/Renderers.cs | 3887 ++++++ ObjectListView/Rendering/Styles.cs | 400 + ObjectListView/Rendering/TreeRenderer.cs | 309 + ObjectListView/Resources/clear-filter.png | Bin 0 -> 1381 bytes ObjectListView/Resources/coffee.jpg | Bin 0 -> 73464 bytes ObjectListView/Resources/filter-icons3.png | Bin 0 -> 1305 bytes ObjectListView/Resources/filter.png | Bin 0 -> 1331 bytes ObjectListView/Resources/sort-ascending.png | Bin 0 -> 1364 bytes ObjectListView/Resources/sort-descending.png | Bin 0 -> 1371 bytes ObjectListView/SubControls/GlassPanelForm.cs | 459 + ObjectListView/SubControls/HeaderControl.cs | 1230 ++ .../SubControls/ToolStripCheckedListBox.cs | 189 + ObjectListView/SubControls/ToolTipControl.cs | 699 + ObjectListView/TreeListView.cs | 2269 ++++ .../Utilities/ColumnSelectionForm.Designer.cs | 190 + .../Utilities/ColumnSelectionForm.cs | 263 + .../Utilities/ColumnSelectionForm.resx | 120 + ObjectListView/Utilities/Generator.cs | 563 + ObjectListView/Utilities/OLVExporter.cs | 277 + .../Utilities/TypedObjectListView.cs | 561 + ObjectListView/VirtualObjectListView.cs | 1255 ++ ObjectListView/olv-keyfile.snk | Bin 0 -> 596 bytes README.md | 129 +- VG Music Studio - Core/ADPCMDecoder.cs | 1 - VG Music Studio - Core/Assembler.cs | 31 +- VG Music Studio - Core/Config.cs | 58 +- VG Music Studio - Core/Config.yaml | 258 +- VG Music Studio - Core/Engine.cs | 2 +- .../GBA/AlphaDream/AlphaDreamChannel.cs | 18 +- .../GBA/AlphaDream/AlphaDreamConfig.cs | 18 +- .../GBA/AlphaDream/AlphaDreamEngine.cs | 4 +- .../GBA/AlphaDream/AlphaDreamEnums.cs | 15 - .../GBA/AlphaDream/AlphaDreamLoadedSong.cs | 41 - .../AlphaDream/AlphaDreamLoadedSong_Events.cs | 266 - .../AlphaDreamLoadedSong_Runtime.cs | 160 - .../GBA/AlphaDream/AlphaDreamMixer.cs | 18 +- .../GBA/AlphaDream/AlphaDreamPlayer.cs | 733 +- .../AlphaDreamSoundFontSaver_DLS.cs | 11 +- .../AlphaDreamSoundFontSaver_SF2.cs | 48 +- .../GBA/AlphaDream/AlphaDreamStructs.cs | 67 - .../GBA/AlphaDream/AlphaDreamTrack.cs | 92 - .../{AlphaDreamCommands.cs => Commands.cs} | 26 +- .../GBA/AlphaDream/Enums.cs | 16 + .../GBA/AlphaDream/Structs.cs | 40 + .../GBA/AlphaDream/Track.cs | 69 + VG Music Studio - Core/GBA/GBAUtils.cs | 6 +- .../GBA/MP2K/{MP2KChannel.cs => Channel.cs} | 348 +- .../GBA/MP2K/{MP2KCommands.cs => Commands.cs} | 46 +- VG Music Studio - Core/GBA/MP2K/Enums.cs | 76 + VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs | 18 +- VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs | 4 +- VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs | 75 - .../GBA/MP2K/MP2KLoadedSong.cs | 527 +- .../GBA/MP2K/MP2KLoadedSong_Events.cs | 542 - .../GBA/MP2K/MP2KLoadedSong_MIDI.cs | 16 +- .../GBA/MP2K/MP2KLoadedSong_Runtime.cs | 458 - VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 136 +- VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs | 797 +- .../GBA/MP2K/MP2KStructs.cs | 187 - VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs | 224 - VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs | 172 - VG Music Studio - Core/GBA/MP2K/Structs.cs | 80 + VG Music Studio - Core/GBA/MP2K/Track.cs | 174 + VG Music Studio - Core/GBA/MP2K/Utils.cs | 175 + VG Music Studio - Core/Mixer.cs | 49 +- VG Music Studio - Core/NDS/DSE/Channel.cs | 368 + .../NDS/DSE/{DSECommands.cs => Commands.cs} | 30 +- VG Music Studio - Core/NDS/DSE/DSEChannel.cs | 375 - VG Music Studio - Core/NDS/DSE/DSEConfig.cs | 11 +- VG Music Studio - Core/NDS/DSE/DSEEnums.cs | 21 - .../NDS/DSE/DSELoadedSong.cs | 62 - .../NDS/DSE/DSELoadedSong_Events.cs | 461 - .../NDS/DSE/DSELoadedSong_Runtime.cs | 288 - VG Music Studio - Core/NDS/DSE/DSEMixer.cs | 45 +- VG Music Studio - Core/NDS/DSE/DSEPlayer.cs | 1063 +- VG Music Studio - Core/NDS/DSE/DSETrack.cs | 120 - VG Music Studio - Core/NDS/DSE/DSEUtils.cs | 52 - VG Music Studio - Core/NDS/DSE/Enums.cs | 22 + VG Music Studio - Core/NDS/DSE/SMD.cs | 107 +- VG Music Studio - Core/NDS/DSE/SWD.cs | 91 +- VG Music Studio - Core/NDS/DSE/Track.cs | 71 + VG Music Studio - Core/NDS/DSE/Utils.cs | 53 + VG Music Studio - Core/NDS/NDSUtils.cs | 6 - VG Music Studio - Core/NDS/SDAT/Channel.cs | 391 + .../NDS/SDAT/{SDATCommands.cs => Commands.cs} | 0 VG Music Studio - Core/NDS/SDAT/Enums.cs | 40 + .../SDAT/{SDATFileHeader.cs => FileHeader.cs} | 4 +- VG Music Studio - Core/NDS/SDAT/SBNK.cs | 4 +- VG Music Studio - Core/NDS/SDAT/SDAT.cs | 61 +- .../NDS/SDAT/SDATChannel.cs | 394 - VG Music Studio - Core/NDS/SDAT/SDATConfig.cs | 2 +- VG Music Studio - Core/NDS/SDAT/SDATEnums.cs | 39 - .../NDS/SDAT/SDATLoadedSong.cs | 38 - .../NDS/SDAT/SDATLoadedSong_Events.cs | 746 -- .../NDS/SDAT/SDATLoadedSong_Runtime.cs | 787 -- VG Music Studio - Core/NDS/SDAT/SDATMixer.cs | 30 +- VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs | 1713 ++- VG Music Studio - Core/NDS/SDAT/SDATTrack.cs | 248 - VG Music Studio - Core/NDS/SDAT/SSEQ.cs | 39 +- VG Music Studio - Core/NDS/SDAT/SWAR.cs | 94 +- VG Music Studio - Core/NDS/SDAT/Track.cs | 196 + VG Music Studio - Core/NDS/Utils.cs | 7 + VG Music Studio - Core/Player.cs | 193 +- .../Properties/Strings.Designer.cs | 106 +- .../Properties/Strings.es.resx | 19 +- .../Properties/Strings.fr.resx | 345 - .../Properties/Strings.it.resx | 9 +- .../Properties/Strings.resx | 45 +- .../Properties/Strings.ru.resx | 345 - VG Music Studio - Core/SongState.cs | 101 +- VG Music Studio - Core/Util/ConfigUtils.cs | 41 +- VG Music Studio - Core/Util/DataUtils.cs | 14 - VG Music Studio - Core/Util/GlobalConfig.cs | 26 +- VG Music Studio - Core/Util/HSLColor.cs | 164 +- VG Music Studio - Core/Util/LanguageUtils.cs | 30 - VG Music Studio - Core/Util/SampleUtils.cs | 18 +- VG Music Studio - Core/Util/TimeBarrier.cs | 4 +- .../VG Music Studio - Core.csproj | 20 +- VG Music Studio - GTK3/MainWindow.cs | 875 ++ VG Music Studio - GTK3/Program.cs | 23 + .../VG Music Studio - GTK3.csproj | 16 + .../ExtraLibBindings/Gtk.cs | 199 + .../ExtraLibBindings/GtkInternal.cs | 425 + VG Music Studio - GTK4/MainWindow.cs | 1369 ++ VG Music Studio - GTK4/Program.cs | 48 + VG Music Studio - GTK4/Theme.cs | 224 + .../Util/FlexibleMessageBox.cs | 763 ++ VG Music Studio - GTK4/Util/ScaleControl.cs | 86 + .../Util/SoundSequenceList.cs | 156 + .../VG Music Studio - GTK4.csproj | 281 + .../Chunks/MIDITrackChunk.cs | 9 +- .../Events/NoteOffMessage.cs | 2 +- .../Events/NoteOnMessage.cs | 2 +- VG Music Studio - MIDI/MIDINote.cs | 1 - VG Music Studio - WinForms/MainForm.cs | 558 +- VG Music Studio - WinForms/PianoControl.cs | 12 +- VG Music Studio - WinForms/PlayingPlaylist.cs | 49 - VG Music Studio - WinForms/Program.cs | 5 - VG Music Studio - WinForms/SongInfoControl.cs | 15 +- .../TaskbarPlayerButtons.cs | 81 - VG Music Studio - WinForms/Theme.cs | 2 +- VG Music Studio - WinForms/TrackViewer.cs | 2 +- .../Util/ColorSlider.cs | 76 +- .../Util/FlexibleMessageBox.cs | 35 +- .../Util/ImageComboBox.cs | 4 +- VG Music Studio - WinForms/Util/VGMSDebug.cs | 24 +- .../Util/WinFormsUtils.cs | 37 - .../VG Music Studio - WinForms.csproj | 16 +- VG Music Studio - WinForms/ValueTextBox.cs | 10 +- VG Music Studio.sln | 18 + 207 files changed, 62802 insertions(+), 8821 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json create mode 100644 ObjectListView/CellEditing/CellEditKeyEngine.cs create mode 100644 ObjectListView/CellEditing/CellEditors.cs create mode 100644 ObjectListView/CellEditing/EditorRegistry.cs create mode 100644 ObjectListView/CustomDictionary.xml create mode 100644 ObjectListView/DataListView.cs create mode 100644 ObjectListView/DataTreeListView.cs create mode 100644 ObjectListView/DragDrop/DragSource.cs create mode 100644 ObjectListView/DragDrop/DropSink.cs create mode 100644 ObjectListView/DragDrop/OLVDataObject.cs create mode 100644 ObjectListView/FastDataListView.cs create mode 100644 ObjectListView/FastObjectListView.cs create mode 100644 ObjectListView/Filtering/Cluster.cs create mode 100644 ObjectListView/Filtering/ClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ClustersFromGroupsStrategy.cs create mode 100644 ObjectListView/Filtering/DateTimeClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/FilterMenuBuilder.cs create mode 100644 ObjectListView/Filtering/Filters.cs create mode 100644 ObjectListView/Filtering/FlagClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ICluster.cs create mode 100644 ObjectListView/Filtering/IClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/TextMatchFilter.cs create mode 100644 ObjectListView/FullClassDiagram.cd create mode 100644 ObjectListView/Implementation/Attributes.cs create mode 100644 ObjectListView/Implementation/Comparers.cs create mode 100644 ObjectListView/Implementation/DataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/Delegates.cs create mode 100644 ObjectListView/Implementation/DragSource.cs create mode 100644 ObjectListView/Implementation/DropSink.cs create mode 100644 ObjectListView/Implementation/Enums.cs create mode 100644 ObjectListView/Implementation/Events.cs create mode 100644 ObjectListView/Implementation/GroupingParameters.cs create mode 100644 ObjectListView/Implementation/Groups.cs create mode 100644 ObjectListView/Implementation/Munger.cs create mode 100644 ObjectListView/Implementation/NativeMethods.cs create mode 100644 ObjectListView/Implementation/NullableDictionary.cs create mode 100644 ObjectListView/Implementation/OLVListItem.cs create mode 100644 ObjectListView/Implementation/OLVListSubItem.cs create mode 100644 ObjectListView/Implementation/OlvListViewHitTestInfo.cs create mode 100644 ObjectListView/Implementation/TreeDataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/VirtualGroups.cs create mode 100644 ObjectListView/Implementation/VirtualListDataSource.cs create mode 100644 ObjectListView/OLVColumn.cs create mode 100644 ObjectListView/ObjectListView.DesignTime.cs create mode 100644 ObjectListView/ObjectListView.FxCop create mode 100644 ObjectListView/ObjectListView.cs create mode 100644 ObjectListView/ObjectListView.shfb create mode 100644 ObjectListView/ObjectListView2019.csproj create mode 100644 ObjectListView/ObjectListView2019.nuspec create mode 100644 ObjectListView/Properties/AssemblyInfo.cs create mode 100644 ObjectListView/Properties/Resources.Designer.cs create mode 100644 ObjectListView/Properties/Resources.resx create mode 100644 ObjectListView/Rendering/Adornments.cs create mode 100644 ObjectListView/Rendering/Decorations.cs create mode 100644 ObjectListView/Rendering/Overlays.cs create mode 100644 ObjectListView/Rendering/Renderers.cs create mode 100644 ObjectListView/Rendering/Styles.cs create mode 100644 ObjectListView/Rendering/TreeRenderer.cs create mode 100644 ObjectListView/Resources/clear-filter.png create mode 100644 ObjectListView/Resources/coffee.jpg create mode 100644 ObjectListView/Resources/filter-icons3.png create mode 100644 ObjectListView/Resources/filter.png create mode 100644 ObjectListView/Resources/sort-ascending.png create mode 100644 ObjectListView/Resources/sort-descending.png create mode 100644 ObjectListView/SubControls/GlassPanelForm.cs create mode 100644 ObjectListView/SubControls/HeaderControl.cs create mode 100644 ObjectListView/SubControls/ToolStripCheckedListBox.cs create mode 100644 ObjectListView/SubControls/ToolTipControl.cs create mode 100644 ObjectListView/TreeListView.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.Designer.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.resx create mode 100644 ObjectListView/Utilities/Generator.cs create mode 100644 ObjectListView/Utilities/OLVExporter.cs create mode 100644 ObjectListView/Utilities/TypedObjectListView.cs create mode 100644 ObjectListView/VirtualObjectListView.cs create mode 100644 ObjectListView/olv-keyfile.snk delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs rename VG Music Studio - Core/GBA/AlphaDream/{AlphaDreamCommands.cs => Commands.cs} (77%) create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Enums.cs create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Structs.cs create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Track.cs rename VG Music Studio - Core/GBA/MP2K/{MP2KChannel.cs => Channel.cs} (65%) rename VG Music Studio - Core/GBA/MP2K/{MP2KCommands.cs => Commands.cs} (79%) create mode 100644 VG Music Studio - Core/GBA/MP2K/Enums.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Structs.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Track.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Utils.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Channel.cs rename VG Music Studio - Core/NDS/DSE/{DSECommands.cs => Commands.cs} (80%) delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEChannel.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEEnums.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSETrack.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEUtils.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Enums.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Track.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Utils.cs delete mode 100644 VG Music Studio - Core/NDS/NDSUtils.cs create mode 100644 VG Music Studio - Core/NDS/SDAT/Channel.cs rename VG Music Studio - Core/NDS/SDAT/{SDATCommands.cs => Commands.cs} (100%) create mode 100644 VG Music Studio - Core/NDS/SDAT/Enums.cs rename VG Music Studio - Core/NDS/SDAT/{SDATFileHeader.cs => FileHeader.cs} (87%) delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATChannel.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATEnums.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATTrack.cs create mode 100644 VG Music Studio - Core/NDS/SDAT/Track.cs create mode 100644 VG Music Studio - Core/NDS/Utils.cs delete mode 100644 VG Music Studio - Core/Properties/Strings.fr.resx delete mode 100644 VG Music Studio - Core/Properties/Strings.ru.resx delete mode 100644 VG Music Studio - Core/Util/DataUtils.cs delete mode 100644 VG Music Studio - Core/Util/LanguageUtils.cs create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj delete mode 100644 VG Music Studio - WinForms/PlayingPlaylist.cs delete mode 100644 VG Music Studio - WinForms/TaskbarPlayerButtons.cs diff --git a/.gitignore b/.gitignore index 80921d3..1bbfb2e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,5 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..23ffcc2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/VG Music Studio - GTK4/bin/Debug/net6.0/VG Music Studio - GTK4.dll", + "args": [], + "cwd": "${workspaceFolder}/VG Music Studio - GTK4", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..bf93855 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/ObjectListView/CellEditing/CellEditKeyEngine.cs b/ObjectListView/CellEditing/CellEditKeyEngine.cs new file mode 100644 index 0000000..a0d67b6 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditKeyEngine.cs @@ -0,0 +1,520 @@ +/* + * CellEditKeyEngine - A engine that allows the behaviour of arbitrary keys to be configured + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * v2.8 + * 2014-05-30 JPP - When a row is disabled, skip over it when looking for another cell to edit + * v2.5 + * 2012-04-14 JPP - Fixed bug where, on a OLV with only a single editable column, tabbing + * to change rows would edit the cell above rather than the cell below + * the cell being edited. + * 2.5 + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using BrightIdeasSoftware; + +namespace BrightIdeasSoftware { + /// + /// Indicates the behavior of a key when a cell "on the edge" is being edited. + /// and the normal behavior of that key would exceed the edge. For example, + /// for a key that normally moves one column to the left, the "edge" would be + /// the left most column, since the normal action of the key cannot be taken + /// (since there are no more columns to the left). + /// + public enum CellEditAtEdgeBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will result in the cell editing wrapping to the + /// cell on the opposite edge. + /// + Wrap, + + /// + /// The key press will wrap, but the column will be changed to the + /// appropriate adjacent column. This only makes sense for keys where + /// the normal action is ChangeRow. + /// + ChangeColumn, + + /// + /// The key press will wrap, but the row will be changed to the + /// appropriate adjacent row. This only makes sense for keys where + /// the normal action is ChangeColumn. + /// + ChangeRow, + + /// + /// The key will result in the current edit operation being ended. + /// + EndEdit + }; + + /// + /// Indicates the normal behaviour of a key when used during a cell edit + /// operation. + /// + public enum CellEditCharacterBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the left. + /// + ChangeColumnLeft, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the right. + /// + ChangeColumnRight, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row above. + /// + ChangeRowUp, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row below + /// + ChangeRowDown, + + /// + /// The key press will cancel the current edit + /// + CancelEdit, + + /// + /// The key press will finish the current edit operation + /// + EndEdit, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb1, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb2, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb3, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb4, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb5, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb6, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb7, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb8, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb9, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb10, + }; + + /// + /// Instances of this class handle key presses during a cell edit operation. + /// + public class CellEditKeyEngine { + + #region Public interface + + /// + /// Sets the behaviour of a given key + /// + /// + /// + /// + public virtual void SetKeyBehaviour(Keys key, CellEditCharacterBehaviour normalBehaviour, CellEditAtEdgeBehaviour atEdgeBehaviour) { + this.CellEditKeyMap[key] = normalBehaviour; + this.CellEditKeyAtEdgeBehaviourMap[key] = atEdgeBehaviour; + } + + /// + /// Handle a key press + /// + /// + /// + /// True if the key was completely handled. + public virtual bool HandleKey(ObjectListView olv, Keys keyData) { + if (olv == null) throw new ArgumentNullException("olv"); + + CellEditCharacterBehaviour behaviour; + if (!CellEditKeyMap.TryGetValue(keyData, out behaviour)) + return false; + + this.ListView = olv; + + switch (behaviour) { + case CellEditCharacterBehaviour.Ignore: + break; + case CellEditCharacterBehaviour.CancelEdit: + this.HandleCancelEdit(); + break; + case CellEditCharacterBehaviour.EndEdit: + this.HandleEndEdit(); + break; + case CellEditCharacterBehaviour.ChangeColumnLeft: + case CellEditCharacterBehaviour.ChangeColumnRight: + this.HandleColumnChange(keyData, behaviour); + break; + case CellEditCharacterBehaviour.ChangeRowDown: + case CellEditCharacterBehaviour.ChangeRowUp: + this.HandleRowChange(keyData, behaviour); + break; + default: + return this.HandleCustomVerb(keyData, behaviour); + }; + + return true; + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the ObjectListView on which the current key is being handled. + /// This cannot be null. + /// + protected ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the row of the cell that is currently being edited + /// + protected OLVListItem ItemBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? null : this.ListView.CellEditEventArgs.ListViewItem; + } + } + + /// + /// Gets the index of the column of the cell that is being edited + /// + protected int SubItemIndexBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? -1 : this.ListView.CellEditEventArgs.SubItemIndex; + } + } + + /// + /// Gets or sets the map that remembers the normal behaviour of keys + /// + protected IDictionary CellEditKeyMap { + get { + if (cellEditKeyMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyMap; + } + set { + cellEditKeyMap = value; + } + } + private IDictionary cellEditKeyMap; + + /// + /// Gets or sets the map that remembers the desired behaviour of keys + /// on edge cases. + /// + protected IDictionary CellEditKeyAtEdgeBehaviourMap { + get { + if (cellEditKeyAtEdgeBehaviourMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyAtEdgeBehaviourMap; + } + set { + cellEditKeyAtEdgeBehaviourMap = value; + } + } + private IDictionary cellEditKeyAtEdgeBehaviourMap; + + #endregion + + #region Initialization + + /// + /// Setup the default key mapping + /// + protected virtual void InitializeCellEditKeyMaps() { + this.cellEditKeyMap = new Dictionary(); + this.cellEditKeyMap[Keys.Escape] = CellEditCharacterBehaviour.CancelEdit; + this.cellEditKeyMap[Keys.Return] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Enter] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Tab] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Tab | Keys.Shift] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Left | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Right | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Up | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowUp; + this.cellEditKeyMap[Keys.Down | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowDown; + + this.cellEditKeyAtEdgeBehaviourMap = new Dictionary(); + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab | Keys.Shift] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Left | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Right | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Up | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Down | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + } + + #endregion + + #region Command handling + + /// + /// Handle the end edit command + /// + protected virtual void HandleEndEdit() { + this.ListView.PossibleFinishCellEditing(); + } + + /// + /// Handle the cancel edit command + /// + protected virtual void HandleCancelEdit() { + this.ListView.CancelCellEdit(); + } + + /// + /// Placeholder that subclasses can override to handle any custom verbs + /// + /// + /// + /// + protected virtual bool HandleCustomVerb(Keys keyData, CellEditCharacterBehaviour behaviour) { + return false; + } + + /// + /// Handle a change row command + /// + /// + /// + protected virtual void HandleRowChange(Keys keyData, CellEditCharacterBehaviour behaviour) { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + OLVListItem olvi = this.ItemBeingEdited; + int subItemIndex = this.SubItemIndexBeingEdited; + bool isGoingUp = behaviour == CellEditCharacterBehaviour.ChangeRowUp; + + // Try to find a row above (or below) the currently edited cell + // If we find one, start editing it and we're done. + OLVListItem adjacentOlvi = this.GetAdjacentItemOrNull(olvi, isGoingUp); + if (adjacentOlvi != null) { + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + return; + } + + // There is no adjacent row in the direction we want, so we must be on an edge. + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) { + case CellEditAtEdgeBehaviour.Ignore: + break; + case CellEditAtEdgeBehaviour.EndEdit: + this.ListView.PossibleFinishCellEditing(); + break; + case CellEditAtEdgeBehaviour.Wrap: + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + case CellEditAtEdgeBehaviour.ChangeColumn: + // Figure out the next editable column + List editableColumnsInDisplayOrder = this.EditableColumnsInDisplayOrder; + int displayIndex = Math.Max(0, editableColumnsInDisplayOrder.IndexOf(this.ListView.GetColumn(subItemIndex))); + if (isGoingUp) + displayIndex = (editableColumnsInDisplayOrder.Count + displayIndex - 1) % editableColumnsInDisplayOrder.Count; + else + displayIndex = (displayIndex + 1) % editableColumnsInDisplayOrder.Count; + subItemIndex = editableColumnsInDisplayOrder[displayIndex].Index; + + // Wrap to the next row and start the cell edit + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + } + } + + /// + /// Handle a change column command + /// + /// + /// + protected virtual void HandleColumnChange(Keys keyData, CellEditCharacterBehaviour behaviour) + { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + // Changing columns only works in details mode + if (this.ListView.View != View.Details) + return; + + List editableColumns = this.EditableColumnsInDisplayOrder; + OLVListItem olvi = this.ItemBeingEdited; + int displayIndex = Math.Max(0, + editableColumns.IndexOf(this.ListView.GetColumn(this.SubItemIndexBeingEdited))); + bool isGoingLeft = behaviour == CellEditCharacterBehaviour.ChangeColumnLeft; + + // Are we trying to continue past one of the edges? + if ((isGoingLeft && displayIndex == 0) || + (!isGoingLeft && displayIndex == editableColumns.Count - 1)) + { + // Yes, so figure out our at edge behaviour + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) + { + case CellEditAtEdgeBehaviour.Ignore: + return; + case CellEditAtEdgeBehaviour.EndEdit: + this.HandleEndEdit(); + return; + case CellEditAtEdgeBehaviour.ChangeRow: + case CellEditAtEdgeBehaviour.Wrap: + if (atEdgeBehaviour == CellEditAtEdgeBehaviour.ChangeRow) + olvi = GetAdjacentItem(olvi, isGoingLeft && displayIndex == 0); + if (isGoingLeft) + displayIndex = editableColumns.Count - 1; + else + displayIndex = 0; + break; + } + } + else + { + if (isGoingLeft) + displayIndex -= 1; + else + displayIndex += 1; + } + + int subItemIndex = editableColumns[displayIndex].Index; + this.StartCellEditIfDifferent(olvi, subItemIndex); + } + + #endregion + + #region Utilities + + /// + /// Start editing the indicated cell if that cell is not already being edited + /// + /// The row to edit + /// The cell within that row to edit + protected void StartCellEditIfDifferent(OLVListItem olvi, int subItemIndex) { + if (this.ItemBeingEdited == olvi && this.SubItemIndexBeingEdited == subItemIndex) + return; + + this.ListView.EnsureVisible(olvi.Index); + this.ListView.StartCellEdit(olvi, subItemIndex); + } + + /// + /// Gets the adjacent item to the given item in the given direction. + /// If that item is disabled, continue in that direction until an enabled item is found. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more enabled items in that direction. + protected OLVListItem GetAdjacentItemOrNull(OLVListItem olvi, bool up) { + OLVListItem item = up ? this.ListView.GetPreviousItem(olvi) : this.ListView.GetNextItem(olvi); + while (item != null && !item.Enabled) + item = up ? this.ListView.GetPreviousItem(item) : this.ListView.GetNextItem(item); + return item; + } + + /// + /// Gets the adjacent item to the given item in the given direction, wrapping if needed. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more items in that direction. + protected OLVListItem GetAdjacentItem(OLVListItem olvi, bool up) { + return this.GetAdjacentItemOrNull(olvi, up) ?? this.GetAdjacentItemOrNull(null, up); + } + + /// + /// Gets a collection of columns that are editable in the order they are shown to the user + /// + protected List EditableColumnsInDisplayOrder { + get { + List editableColumnsInDisplayOrder = new List(); + foreach (OLVColumn x in this.ListView.ColumnsInDisplayOrder) + if (x.IsEditable) + editableColumnsInDisplayOrder.Add(x); + return editableColumnsInDisplayOrder; + } + } + + #endregion + } +} diff --git a/ObjectListView/CellEditing/CellEditors.cs b/ObjectListView/CellEditing/CellEditors.cs new file mode 100644 index 0000000..4314021 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditors.cs @@ -0,0 +1,325 @@ +/* + * CellEditors - Several slightly modified controls that are used as cell editors within ObjectListView. + * + * Author: Phillip Piper + * Date: 20/10/2008 5:15 PM + * + * Change log: + * 2018-05-05 JPP - Added ControlUtilities.AutoResizeDropDown() + * v2.6 + * 2012-08-02 JPP - Make most editors public so they can be reused/subclassed + * v2.3 + * 2009-08-13 JPP - Standardized code formatting + * v2.2.1 + * 2008-01-18 JPP - Added special handling for enums + * 2008-01-16 JPP - Added EditorRegistry + * v2.0.1 + * 2008-10-20 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An interface that allows cell editors to specifically handle getting and setting + /// values from ObjectListView + /// + public interface IOlvEditor { + object Value { get; set; } + } + + public static class ControlUtilities { + + /// + /// Configure the given ComboBox so that the dropped down menu is auto-sized to + /// be wide enough to show the widest item. + /// + /// + public static void AutoResizeDropDown(ComboBox dropDown) { + if (dropDown == null) + throw new ArgumentNullException("dropDown"); + + dropDown.DropDown += delegate(object sender, EventArgs args) { + + // Calculate the maximum width of the drop down items + int newWidth = 0; + foreach (object item in dropDown.Items) { + newWidth = Math.Max(newWidth, TextRenderer.MeasureText(item.ToString(), dropDown.Font).Width); + } + + int vertScrollBarWidth = dropDown.Items.Count > dropDown.MaxDropDownItems ? SystemInformation.VerticalScrollBarWidth : 0; + dropDown.DropDownWidth = newWidth + vertScrollBarWidth; + }; + } + } + + /// + /// These items allow combo boxes to remember a value and its description. + /// + public class ComboBoxItem + { + /// + /// + /// + /// + /// + public ComboBoxItem(Object key, String description) { + this.key = key; + this.description = description; + } + private readonly String description; + + /// + /// + /// + public Object Key { + get { return key; } + } + private readonly Object key; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return this.description; + } + } + + //----------------------------------------------------------------------- + // Cell editors + // These classes are simple cell editors that make it easier to get and set + // the value that the control is showing. + // In many cases, you can intercept the CellEditStarting event to + // change the characteristics of the editor. For example, changing + // the acceptable range for a numeric editor or changing the strings + // that represent true and false values for a boolean editor. + + /// + /// This editor shows and auto completes values from the given listview column. + /// + [ToolboxItem(false)] + public class AutoCompleteCellEditor : ComboBox + { + /// + /// Create an AutoCompleteCellEditor + /// + /// + /// + public AutoCompleteCellEditor(ObjectListView lv, OLVColumn column) { + this.DropDownStyle = ComboBoxStyle.DropDown; + + Dictionary alreadySeen = new Dictionary(); + for (int i = 0; i < Math.Min(lv.GetItemCount(), 1000); i++) { + String str = column.GetStringValue(lv.GetModelObject(i)); + if (!alreadySeen.ContainsKey(str)) { + this.Items.Add(str); + alreadySeen[str] = true; + } + } + + this.Sorted = true; + this.AutoCompleteSource = AutoCompleteSource.ListItems; + this.AutoCompleteMode = AutoCompleteMode.Append; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This combo box is specialized to allow editing of an enum. + /// + [ToolboxItem(false)] + public class EnumCellEditor : ComboBox + { + /// + /// + /// + /// + public EnumCellEditor(Type type) { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + foreach (object value in Enum.GetValues(type)) + values.Add(new ComboBoxItem(value, Enum.GetName(type, value))); + + this.DataSource = values; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This editor simply shows and edits integer values. + /// + [ToolboxItem(false)] + public class IntUpDown : NumericUpDown + { + /// + /// + /// + public IntUpDown() { + this.DecimalPlaces = 0; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new int Value { + get { return Decimal.ToInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits unsigned integer values. + /// + /// This class can't be made public because unsigned int is not a + /// CLS-compliant type. If you want to use, just copy the code to this class + /// into your project and use it from there. + [ToolboxItem(false)] + internal class UintUpDown : NumericUpDown + { + public UintUpDown() { + this.DecimalPlaces = 0; + this.Minimum = 0; + this.Maximum = 9999999; + } + + public new uint Value { + get { return Decimal.ToUInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits boolean values. + /// + [ToolboxItem(false)] + public class BooleanCellEditor : ComboBox + { + /// + /// + /// + public BooleanCellEditor() { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + values.Add(new ComboBoxItem(false, "False")); + values.Add(new ComboBoxItem(true, "True")); + + this.DataSource = values; + } + } + + /// + /// This editor simply shows and edits boolean values using a checkbox + /// + [ToolboxItem(false)] + public class BooleanCellEditor2 : CheckBox + { + /// + /// Gets or sets the value shown by this editor + /// + public bool? Value { + get { + switch (this.CheckState) { + case CheckState.Checked: return true; + case CheckState.Indeterminate: return null; + case CheckState.Unchecked: + default: return false; + } + } + set { + if (value.HasValue) + this.CheckState = value.Value ? CheckState.Checked : CheckState.Unchecked; + else + this.CheckState = CheckState.Indeterminate; + } + } + + /// + /// Gets or sets how the checkbox will be aligned + /// + public new HorizontalAlignment TextAlign { + get { + switch (this.CheckAlign) { + case ContentAlignment.MiddleRight: return HorizontalAlignment.Right; + case ContentAlignment.MiddleCenter: return HorizontalAlignment.Center; + case ContentAlignment.MiddleLeft: + default: return HorizontalAlignment.Left; + } + } + set { + switch (value) { + case HorizontalAlignment.Left: + this.CheckAlign = ContentAlignment.MiddleLeft; + break; + case HorizontalAlignment.Center: + this.CheckAlign = ContentAlignment.MiddleCenter; + break; + case HorizontalAlignment.Right: + this.CheckAlign = ContentAlignment.MiddleRight; + break; + } + } + } + } + + /// + /// This editor simply shows and edits floating point values. + /// + /// You can intercept the CellEditStarting event if you want + /// to change the characteristics of the editor. For example, by increasing + /// the number of decimal places. + [ToolboxItem(false)] + public class FloatCellEditor : NumericUpDown + { + /// + /// + /// + public FloatCellEditor() { + this.DecimalPlaces = 2; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new double Value { + get { return Convert.ToDouble(base.Value); } + set { base.Value = Convert.ToDecimal(value); } + } + } +} diff --git a/ObjectListView/CellEditing/EditorRegistry.cs b/ObjectListView/CellEditing/EditorRegistry.cs new file mode 100644 index 0000000..f92854f --- /dev/null +++ b/ObjectListView/CellEditing/EditorRegistry.cs @@ -0,0 +1,213 @@ +/* + * EditorRegistry - A registry mapping types to cell editors. + * + * Author: Phillip Piper + * Date: 6-March-2011 7:53 am + * + * Change log: + * 2011-03-31 JPP - Use OLVColumn.DataType if the value to be edited is null + * 2011-03-06 JPP - Separated from CellEditors.cs + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; + +namespace BrightIdeasSoftware { + + /// + /// A delegate that creates an editor for the given value + /// + /// The model from which that value came + /// The column for which the editor is being created + /// A representative value of the type to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A control which can edit the given value + public delegate Control EditorCreatorDelegate(Object model, OLVColumn column, Object value); + + /// + /// An editor registry gives a way to decide what cell editor should be used to edit + /// the value of a cell. Programmers can register non-standard types and the control that + /// should be used to edit instances of that type. + /// + /// + /// All ObjectListViews share the same editor registry. + /// + public class EditorRegistry { + #region Initializing + + /// + /// Create an EditorRegistry + /// + public EditorRegistry() { + this.InitializeStandardTypes(); + } + + private void InitializeStandardTypes() { + this.Register(typeof(Boolean), typeof(BooleanCellEditor)); + this.Register(typeof(Int16), typeof(IntUpDown)); + this.Register(typeof(Int32), typeof(IntUpDown)); + this.Register(typeof(Int64), typeof(IntUpDown)); + this.Register(typeof(UInt16), typeof(UintUpDown)); + this.Register(typeof(UInt32), typeof(UintUpDown)); + this.Register(typeof(UInt64), typeof(UintUpDown)); + this.Register(typeof(Single), typeof(FloatCellEditor)); + this.Register(typeof(Double), typeof(FloatCellEditor)); + this.Register(typeof(DateTime), delegate(Object model, OLVColumn column, Object value) { + DateTimePicker c = new DateTimePicker(); + c.Format = DateTimePickerFormat.Short; + return c; + }); + this.Register(typeof(Boolean), delegate(Object model, OLVColumn column, Object value) { + CheckBox c = new BooleanCellEditor2(); + c.ThreeState = column.TriStateCheckBoxes; + return c; + }); + } + + #endregion + + #region Registering + + /// + /// Register that values of 'type' should be edited by instances of 'controlType'. + /// + /// The type of value to be edited + /// The type of the Control that will edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), typeof(MySpecialColorEditor)); + /// + public void Register(Type type, Type controlType) { + this.Register(type, delegate(Object model, OLVColumn column, Object value) { + return controlType.InvokeMember("", BindingFlags.CreateInstance, null, null, null) as Control; + }); + } + + /// + /// Register the given delegate so that it is called to create editors + /// for values of the given type + /// + /// The type of value to be edited + /// The delegate that will create a control that can edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), CreateColorEditor); + /// ... + /// public Control CreateColorEditor(Object model, OLVColumn column, Object value) + /// { + /// return new MySpecialColorEditor(); + /// } + /// + public void Register(Type type, EditorCreatorDelegate creator) { + this.creatorMap[type] = creator; + } + + /// + /// Register a delegate that will be called to create an editor for values + /// that have not been handled. + /// + /// The delegate that will create a editor for all other types + public void RegisterDefault(EditorCreatorDelegate creator) { + this.defaultCreator = creator; + } + + /// + /// Register a delegate that will be given a chance to create a control + /// before any other option is considered. + /// + /// The delegate that will create a control + public void RegisterFirstChance(EditorCreatorDelegate creator) { + this.firstChanceCreator = creator; + } + + /// + /// Remove the registered handler for the given type + /// + /// Does nothing if the given type doesn't exist + /// The type whose registration is to be removed + public void Unregister(Type type) { + if (this.creatorMap.ContainsKey(type)) + this.creatorMap.Remove(type); + } + + #endregion + + #region Accessing + + /// + /// Create and return an editor that is appropriate for the given value. + /// Return null if no appropriate editor can be found. + /// + /// The model involved + /// The column to be edited + /// The value to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A Control that can edit the given type of values + public Control GetEditor(Object model, OLVColumn column, Object value) { + Control editor; + + // Give the first chance delegate a chance to decide + if (this.firstChanceCreator != null) { + editor = this.firstChanceCreator(model, column, value); + if (editor != null) + return editor; + } + + // Try to find a creator based on the type of the value (or the column) + Type type = value == null ? column.DataType : value.GetType(); + if (type != null && this.creatorMap.ContainsKey(type)) { + editor = this.creatorMap[type](model, column, value); + if (editor != null) + return editor; + } + + // Enums without other processing get a special editor + if (value != null && value.GetType().IsEnum) + return this.CreateEnumEditor(value.GetType()); + + // Give any default creator a final chance + if (this.defaultCreator != null) + return this.defaultCreator(model, column, value); + + return null; + } + + /// + /// Create and return an editor that will edit values of the given type + /// + /// A enum type + protected Control CreateEnumEditor(Type type) { + return new EnumCellEditor(type); + } + + #endregion + + #region Private variables + + private EditorCreatorDelegate firstChanceCreator; + private EditorCreatorDelegate defaultCreator; + private Dictionary creatorMap = new Dictionary(); + + #endregion + } +} diff --git a/ObjectListView/CustomDictionary.xml b/ObjectListView/CustomDictionary.xml new file mode 100644 index 0000000..f2cf5b9 --- /dev/null +++ b/ObjectListView/CustomDictionary.xml @@ -0,0 +1,46 @@ + + + + + br + Canceled + Center + Color + Colors + f + fmt + g + gdi + hti + i + lightbox + lv + lvi + lvsi + m + multi + Munger + n + olv + olvi + p + parms + r + Renderer + s + SubItem + Unapply + Unpause + x + y + + + ComPlus + + + + + OLV + + + diff --git a/ObjectListView/DataListView.cs b/ObjectListView/DataListView.cs new file mode 100644 index 0000000..2961d04 --- /dev/null +++ b/ObjectListView/DataListView.cs @@ -0,0 +1,240 @@ +/* + * DataListView - A data-bindable listview + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2011-02-27 JPP - Moved most of the logic to DataSourceAdapter (where it + * can be used by FastDataListView too) + * v2.3 + * 2009-01-18 JPP - Boolean columns are now handled as checkboxes + * - Auto-generated columns would fail if the data source was + * reseated, even to the same data source + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-10-03 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + + /// + /// A DataListView is a ListView that can be bound to a datasource (which would normally be a DataTable or DataView). + /// + /// + /// This listview keeps itself in sync with its source datatable by listening for change events. + /// The DataListView will automatically create columns to show all of the data source's columns/properties, if there is not already + /// a column showing that property. This allows you to define one or two columns in the designer and then have the others generated automatically. + /// If you don't want any column to be auto generated, set to false. + /// These generated columns will be only the simplest view of the world, and would look more interesting with a few delegates installed. + /// This listview will also automatically generate missing aspect getters to fetch the values from the data view. + /// Changing data sources is possible, but error prone. Before changing data sources, the programmer is responsible for modifying/resetting + /// the column collection to be valid for the new data source. + /// Internally, a CurrencyManager controls keeping the data source in-sync with other users of the data source (as per normal .NET + /// behavior). This means that the model objects in the DataListView are DataRowView objects. If you write your own AspectGetters/Setters, + /// they will be given DataRowView objects. + /// + public class DataListView : ObjectListView + { + #region Life and death + + /// + /// Make a DataListView + /// + public DataListView() + { + this.Adapter = new DataSourceAdapter(this); + } + + /// + /// + /// + /// + protected override void Dispose(bool disposing) { + this.Adapter.Dispose(); + base.Dispose(disposing); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// When a DataSource is set, the control will create OLVColumns to show any + /// data source columns that are not already shown. + /// If the DataSource is changed, you will have to remove any previously + /// created columns, since they will be configured for the previous DataSource. + /// . + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource + { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember + { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + /// + /// Adaptors cannot be shared between controls. Each DataListView needs its own adapter. + /// + protected DataSourceAdapter Adapter { + get { + Debug.Assert(adapter != null, "Data adapter should not be null"); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Object manipulations + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void AddObjects(ICollection modelObjects) + { + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// Remove the given collection of model objects from this control. + /// + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void RemoveObjects(ICollection modelObjects) + { + } + + #endregion + + #region Event Handlers + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + /// + /// Handles parent binding context changes + /// + /// Unused EventArgs. + protected override void OnParentBindingContextChanged(EventArgs e) + { + base.OnParentBindingContextChanged(e); + + // BindingContext is an ambient property - by default it simply picks + // up the parent control's context (unless something has explicitly + // given us our own). So we must respond to changes in our parent's + // binding context in the same way we would changes to our own + // binding context. + + // THINK: Do we need to forward this to the adapter? + } + + #endregion + } +} diff --git a/ObjectListView/DataTreeListView.cs b/ObjectListView/DataTreeListView.cs new file mode 100644 index 0000000..65179a9 --- /dev/null +++ b/ObjectListView/DataTreeListView.cs @@ -0,0 +1,240 @@ +/* + * DataTreeListView - A data bindable TreeListView + * + * Author: Phillip Piper + * Date: 05/05/2012 3:26 PM + * + * Change log: + + * 2012-05-05 JPP Initial version + * + * TO DO: + + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A DataTreeListView is a TreeListView that calculates its hierarchy based on + /// information in the data source. + /// + /// + /// Like a , a DataTreeListView sources all its information + /// from a combination of and . + /// can be a DataTable, DataSet, + /// or anything that implements . + /// + /// + /// To function properly, the DataTreeListView requires: + /// + /// the table to have a column which holds a unique for the row. The name of this column must be set in . + /// the table to have a column which holds id of the hierarchical parent of the row. The name of this column must be set in . + /// a value which identifies which rows are the roots of the tree (). + /// + /// The hierarchy structure is determined finding all the rows where the parent key is equal to . These rows + /// become the root objects of the hierarchy. + /// + /// Like a TreeListView, the hierarchy must not contain cycles. Bad things will happen if the data is cyclic. + /// + public partial class DataTreeListView : TreeListView + { + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of a row"), + DefaultValue(null)] + public virtual string KeyAspectName { + get { return this.Adapter.KeyAspectName; } + set { this.Adapter.KeyAspectName = value; } + } + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of the parent of a row"), + DefaultValue(null)] + public virtual string ParentKeyAspectName { + get { return this.Adapter.ParentKeyAspectName; } + set { this.Adapter.ParentKeyAspectName = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. Actually, it can be any value that can + /// be compared for equality against a basic type. + /// If this is set to the wrong value (i.e. to a value that no row + /// has in the parent id column), the list will be empty. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual object RootKeyValue { + get { return this.Adapter.RootKeyValue; } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// . The RootKeyValue can be of any type, + /// but the IDE cannot sensibly represent a value of any type, + /// so this is a typed wrapper around that property. + /// + /// + /// If you want the root value to be something other than a string, + /// you will have set it yourself. + /// + [Category("Data"), + Description("The parent id value that identifies a row as a root object"), + DefaultValue(null)] + public virtual string RootKeyValueString { + get { return Convert.ToString(this.Adapter.RootKeyValue); } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + [Category("Data"), + Description("Should the keys columns (id and parent id) be shown to the user?"), + DefaultValue(true)] + public virtual bool ShowKeyColumns { + get { return this.Adapter.ShowKeyColumns; } + set { this.Adapter.ShowKeyColumns = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected TreeDataSourceAdapter Adapter { + get { + if (this.adapter == null) + this.adapter = new TreeDataSourceAdapter(this); + return adapter; + } + set { adapter = value; } + } + private TreeDataSourceAdapter adapter; + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DragSource.cs b/ObjectListView/DragDrop/DragSource.cs new file mode 100644 index 0000000..1abf13b --- /dev/null +++ b/ObjectListView/DragDrop/DragSource.cs @@ -0,0 +1,219 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2011-03-29 JPP - Separate OLVDataObject.cs + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. The data + /// object will normally include all the selected objects. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All operations are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshes the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + return new OLVDataObject(olv); + } + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DropSink.cs b/ObjectListView/DragDrop/DropSink.cs new file mode 100644 index 0000000..c82bd67 --- /dev/null +++ b/ObjectListView/DragDrop/DropSink.cs @@ -0,0 +1,1562 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2018-04-26 JPP - Implemented LeftOfItem and RightOfItem target locations + * - Added support for rearranging on non-Detail views. + * v2.9 + * 2015-07-08 JPP - Added SimpleDropSink.EnableFeedback to allow all the pretty and helpful + * user feedback during drags to be turned off + * v2.7 + * 2011-04-20 JPP - Rewrote how ModelDropEventArgs.RefreshObjects() works on TreeListViews + * v2.4.1 + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it should be called CleverDropSink -- it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists. Defaults to true. + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. Defaults to true. + /// + /// AutoScroll does not scroll horizontally. + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Gets or sets whether the drop sink should draw feedback onto the given list + /// during the drag operation. Defaults to true. + /// + /// If this is false, you will have to give the user feedback in some + /// other fashion, like cursor changes + public bool EnableFeedback { + get { return enableFeedback; } + set { enableFeedback = value; } + } + private bool enableFeedback = true; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + /// + /// Gets or sets whether the drop sink will automatically use cursors + /// based on the drop effect. By default, this is true. If this is + /// set to false, you must set the Cursor yourself. + /// + public bool UseDefaultCursors { + get { return useDefaultCursors; } + set { useDefaultCursors = value; } + } + private bool useDefaultCursors = true; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + if (this.EnableFeedback) { + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + case DropTargetLocation.LeftOfItem: + this.DrawFeedbackLeftOfItemTarget(g, bounds); + break; + case DropTargetLocation.RightOfItem: + this.DrawFeedbackRightOfItemTarget(g, bounds); + break; + } + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.dropEventArgs.DragEventArgs = args; + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DragEventArgs = args; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + public override void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = this.UseDefaultCursors; + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.dropEventArgs.DragEventArgs = args; + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continue while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined). + // If the view is Details or List, then "between" is considered vertically. + // If the view is SmallIcon, LargeIcon or Tile, then "between" is considered horizontally. + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + switch (this.ListView.View) { + case View.LargeIcon: + case View.Tile: + case View.SmallIcon: + // If the mouse is over an item, check to see if it is near the left or right edge. + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : info.Item.Bounds.Width / 2; + if (pt.X <= info.Item.Bounds.Left + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else if (pt.X >= info.Item.Bounds.Right - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } else { + // Is there an item a little to the *right* of the mouse? + // If so, we say the drop point is *left* that item + int probeWidth = SMALL_VALUE * 2; + info = this.ListView.OlvHitTest(pt.X + probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else { + // Is there an item a little to the left of the mouse? + info = this.ListView.OlvHitTest(pt.X - probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } + } + break; + case View.Details: + case View.List: + // If the mouse is over an item, check to see if it is near the top or bottom + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : this.ListView.RowHeightEffective / 2; + + if (pt.Y <= info.Item.Bounds.Top + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else if (pt.Y >= info.Item.Bounds.Bottom - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the left of target + /// + /// + /// + protected virtual void DrawFeedbackLeftOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Left, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the right of target + /// + /// + /// + protected virtual void DrawFeedbackRightOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Right, r.Top, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * item.IndentCount; + r.X += indentWidth; + r.Width -= indentWidth; + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + if (y1 == y2) { + // Put right and left arrow on a horizontal line + DrawClosedFigure(g, b, RightPointingArrow(x1, y1)); + DrawClosedFigure(g, b, LeftPointingArrow(x2, y2)); + } else { + // Put up and down arrows on a vertical line + DrawClosedFigure(g, b, DownPointingArrow(x1, y1)); + DrawClosedFigure(g, b, UpPointingArrow(x2, y2)); + } + } + + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + private const int ARROW_SIZE = 6; + + private static void DrawClosedFigure(Graphics g, Brush b, Point[] pts) { + using (GraphicsPath gp = new GraphicsPath()) { + gp.StartFigure(); + gp.AddLines(pts); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + + private static Point[] RightPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x + ARROW_SIZE, y) + }; + } + + private static Point[] LeftPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x - ARROW_SIZE, y) + }; + } + + private static Point[] DownPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y + ARROW_SIZE) + }; + } + + private static Point[] UpPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y - ARROW_SIZE) + }; + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amongst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging the same list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + case DropTargetLocation.LeftOfItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + case DropTargetLocation.RightOfItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + + // Some views have to be "encouraged" to show the changes + switch (this.ListView.View) { + case View.LargeIcon: + case View.SmallIcon: + case View.Tile: + this.ListView.BuildList(); + break; + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occurred, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the original drag-drop event args + /// + public DragEventArgs DragEventArgs + { + get { return this.dragEventArgs; } + internal set { this.dragEventArgs = value; } + } + private DragEventArgs dragEventArgs; + + /// + /// Get the data object that is being dragged + /// + public object DataObject + { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + + toBeRefreshed.AddRange(this.SourceModels); + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv == null) + this.SourceListView.RefreshObjects(toBeRefreshed); + else + tlv.RebuildAll(true); + + TreeListView tlv2 = this.ListView as TreeListView; + if (tlv2 == null) + this.ListView.RefreshObject(this.TargetModel); + else + tlv2.RebuildAll(true); + } + } +} diff --git a/ObjectListView/DragDrop/OLVDataObject.cs b/ObjectListView/DragDrop/OLVDataObject.cs new file mode 100644 index 0000000..116861b --- /dev/null +++ b/ObjectListView/DragDrop/OLVDataObject.cs @@ -0,0 +1,185 @@ +/* + * OLVDataObject.cs - An OLE DataObject that knows how to convert rows of an OLV to text and HTML + * + * Author: Phillip Piper + * Date: 2011-03-29 3:34PM + * + * Change log: + * v2.8 + * 2014-05-02 JPP - When the listview is completely empty, don't try to set CSV text in the clipboard. + * v2.6 + * 2012-08-08 JPP - Changed to use OLVExporter. + * - Added CSV to formats exported to Clipboard + * v2.4 + * 2011-03-29 JPP - Initial version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) + : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + this.CreateTextFormats(); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private readonly bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + } + private readonly bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private readonly ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private readonly IList modelObjects; + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + + OLVExporter exporter = this.CreateExporter(); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(exporter.ExportTo(OLVExporter.ExportFormat.TabSeparated)); + string exportTo = exporter.ExportTo(OLVExporter.ExportFormat.CSV); + if (!String.IsNullOrEmpty(exportTo)) + this.SetText(exportTo, TextDataFormat.CommaSeparatedValue); + this.SetText(ConvertToHtmlFragment(exporter.ExportTo(OLVExporter.ExportFormat.HTML)), TextDataFormat.Html); + } + + /// + /// Create an exporter for the data contained in this object + /// + /// + protected OLVExporter CreateExporter() { + OLVExporter exporter = new OLVExporter(this.ListView); + exporter.IncludeColumnHeaders = this.IncludeColumnHeaders; + exporter.IncludeHiddenColumns = this.IncludeHiddenColumns; + exporter.ModelObjects = this.ModelObjects; + return exporter; + } + + /// + /// Make a HTML representation of our model objects + /// + [Obsolete("Use OLVExporter directly instead", false)] + public string CreateHtml() { + OLVExporter exporter = this.CreateExporter(); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognised as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + const string SOURCE = "http://www.codeproject.com/Articles/16009/A-Much-Easier-to-Use-ListView"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, SOURCE, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment, StringComparison.Ordinal); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, SOURCE, html); + } + } +} diff --git a/ObjectListView/FastDataListView.cs b/ObjectListView/FastDataListView.cs new file mode 100644 index 0000000..8b30d2b --- /dev/null +++ b/ObjectListView/FastDataListView.cs @@ -0,0 +1,169 @@ +/* + * FastDataListView - A data bindable listview that has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 22/09/2010 8:11 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2010-09-22 JPP - Initial version + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing.Design; + +namespace BrightIdeasSoftware +{ + /// + /// A FastDataListView virtualizes the display of data from a DataSource. It operates on + /// DataSets and DataTables in the same way as a DataListView, but does so much more efficiently. + /// + /// + /// + /// A FastDataListView still has to load all its data from the DataSource. If you have SQL statement + /// that returns 1 million rows, all 1 million rows will still need to read from the database. + /// However, once the rows are loaded, the FastDataListView will only build rows as they are displayed. + /// + /// + public class FastDataListView : FastObjectListView + { + /// + /// + /// + /// + protected override void Dispose(bool disposing) + { + if (this.adapter != null) { + this.adapter.Dispose(); + this.adapter = null; + } + + base.Dispose(disposing); + } + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the VirtualListDataSource that will be displayed in this list view. + /// + /// The VirtualListDataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// VirtualListDataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected DataSourceAdapter Adapter { + get { + if (adapter == null) + adapter = this.CreateDataSourceAdapter(); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Implementation + + /// + /// Create the DataSourceAdapter that this control will use. + /// + /// A DataSourceAdapter configured for this list + /// Subclasses should override this to create their + /// own specialized adapters + protected virtual DataSourceAdapter CreateDataSourceAdapter() { + return new DataSourceAdapter(this); + } + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() + { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + #endregion + } +} diff --git a/ObjectListView/FastObjectListView.cs b/ObjectListView/FastObjectListView.cs new file mode 100644 index 0000000..0c5fe30 --- /dev/null +++ b/ObjectListView/FastObjectListView.cs @@ -0,0 +1,422 @@ +/* + * FastObjectListView - A listview that behaves like an ObjectListView but has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2014-10-15 JPP - Fire Filter event when applying filters + * v2.8 + * 2012-06-11 JPP - Added more efficient version of FilteredObjects + * v2.5.1 + * 2011-04-25 JPP - Fixed problem with removing objects from filtered or sorted list + * v2.4 + * 2010-04-05 JPP - Added filtering + * v2.3 + * 2009-08-27 JPP - Added GroupingStrategy + * - Added optimized Objects property + * v2.2.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A FastObjectListView trades function for speed. + /// + /// + /// On my mid-range laptop, this view builds a list of 10,000 objects in 0.1 seconds, + /// as opposed to a normal ObjectListView which takes 10-15 seconds. Lists of up to 50,000 items should be + /// able to be handled with sub-second response times even on low end machines. + /// + /// A FastObjectListView is implemented as a virtual list with many of the virtual modes limits (e.g. no sorting) + /// fixed through coding. There are some functions that simply cannot be provided. Specifically, a FastObjectListView cannot: + /// + /// use Tile view + /// show groups on XP + /// + /// + /// + public class FastObjectListView : VirtualObjectListView + { + /// + /// Make a FastObjectListView + /// + public FastObjectListView() { + this.VirtualListDataSource = new FastObjectListDataSource(this); + this.GroupingStrategy = new FastListGroupingStrategy(); + } + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).FilteredObjectList; + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).ObjectList; + } + set { base.Objects = value; } + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public override void MoveObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.MoveObjects(index, modelObjects); }); + return; + } + + // If any object that is going to be moved is before the point where the insertion + // will occur, then we have to reduce the location of our insertion point + int displacedObjectCount = 0; + foreach (object modelObject in modelObjects) { + int i = this.IndexOf(modelObject); + if (i >= 0 && i <= index) + displacedObjectCount++; + } + index -= displacedObjectCount; + + this.BeginUpdate(); + try { + this.RemoveObjects(modelObjects); + this.InsertObjects(index, modelObjects); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + /// To be really honest, Unsort() doesn't work on FastObjectListViews since + /// the original ordering of model objects is lost when Sort() is called. So this method + /// effectively just turns off sorting. + public override void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.SetObjects(this.Objects); + } + } + + /// + /// Provide a data source for a FastObjectListView + /// + /// + /// This class isn't intended to be used directly, but it is left as a public + /// class just in case someone wants to subclass it. + /// + public class FastObjectListDataSource : AbstractVirtualListDataSource + { + /// + /// Create a FastObjectListDataSource + /// + /// + public FastObjectListDataSource(FastObjectListView listView) + : base(listView) { + } + + #region IVirtualListDataSource Members + + /// + /// Get n'th object + /// + /// + /// + public override object GetNthObject(int n) { + if (n >= 0 && n < this.filteredObjectList.Count) + return this.filteredObjectList[n]; + + return null; + } + + /// + /// How many items are in the data source + /// + /// + public override int GetObjectCount() { + return this.filteredObjectList.Count; + } + + /// + /// Get the index of the given model + /// + /// + /// + public override int GetObjectIndex(object model) { + int index; + + if (model != null && this.objectsToIndexMap.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// + /// + /// + /// + public override void Sort(OLVColumn column, SortOrder sortOrder) { + if (sortOrder != SortOrder.None) { + ModelObjectComparer comparer = new ModelObjectComparer(column, sortOrder, this.listView.SecondarySortColumn, this.listView.SecondarySortOrder); + this.fullObjectList.Sort(comparer); + this.filteredObjectList.Sort(comparer); + } + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void AddObjects(ICollection modelObjects) { + foreach (object modelObject in modelObjects) { + if (modelObject != null) + this.fullObjectList.Add(modelObject); + } + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + /// + public override void InsertObjects(int index, ICollection modelObjects) { + this.fullObjectList.InsertRange(index, modelObjects); + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Remove the given collection of models from this source. + /// + /// + public override void RemoveObjects(ICollection modelObjects) { + + // We have to unselect any object that is about to be deleted + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + int i = this.GetObjectIndex(modelObject); + if (i >= 0) + indicesToRemove.Add(i); + } + + // Sort the indices from highest to lowest so that we + // remove latter ones before earlier ones. In this way, the + // indices of the rows doesn't change after the deletes. + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + + foreach (int i in indicesToRemove) + this.listView.SelectedIndices.Remove(i); + + // Remove the objects from the unfiltered list + foreach (object modelObject in modelObjects) + this.fullObjectList.Remove(modelObject); + + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void SetObjects(IEnumerable collection) { + ArrayList newObjects = ObjectListView.EnumerableToArray(collection, true); + + this.fullObjectList = newObjects; + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public override void UpdateObject(int index, object modelObject) { + if (index < 0 || index >= this.filteredObjectList.Count) + return; + + int i = this.fullObjectList.IndexOf(this.filteredObjectList[index]); + if (i < 0) + return; + + if (ReferenceEquals(this.fullObjectList[i], modelObject)) + return; + + this.fullObjectList[i] = modelObject; + this.filteredObjectList[index] = modelObject; + this.objectsToIndexMap[modelObject] = index; + } + + private ArrayList fullObjectList = new ArrayList(); + private ArrayList filteredObjectList = new ArrayList(); + private IModelFilter modelFilter; + private IListFilter listFilter; + + #endregion + + #region IFilterableDataSource Members + + /// + /// Apply the given filters to this data source. One or both may be null. + /// + /// + /// + public override void ApplyFilters(IModelFilter iModelFilter, IListFilter iListFilter) { + this.modelFilter = iModelFilter; + this.listFilter = iListFilter; + this.SetObjects(this.fullObjectList); + } + + #endregion + + #region Implementation + + /// + /// Gets the full list of objects being used for this fast list. + /// This list is unfiltered. + /// + public ArrayList ObjectList { + get { return fullObjectList; } + } + + /// + /// Gets the list of objects from ObjectList which survive any installed filters. + /// + public ArrayList FilteredObjectList { + get { return filteredObjectList; } + } + + /// + /// Rebuild the map that remembers which model object is displayed at which line + /// + protected void RebuildIndexMap() { + this.objectsToIndexMap.Clear(); + for (int i = 0; i < this.filteredObjectList.Count; i++) + this.objectsToIndexMap[this.filteredObjectList[i]] = i; + } + readonly Dictionary objectsToIndexMap = new Dictionary(); + + /// + /// Build our filtered list from our full list. + /// + protected void FilterObjects() { + + // If this list isn't filtered, we don't need to do anything else + if (!this.listView.UseFiltering) { + this.filteredObjectList = new ArrayList(this.fullObjectList); + return; + } + + // Tell the world to filter the objects. If they do so, don't do anything else + // ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(this.fullObjectList); + this.listView.OnFilter(args); + if (args.FilteredObjects != null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(args.FilteredObjects, false); + return; + } + + IEnumerable objects = (this.listFilter == null) ? + this.fullObjectList : this.listFilter.Filter(this.fullObjectList); + + // Apply the object filter if there is one + if (this.modelFilter == null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(objects, false); + } else { + this.filteredObjectList = new ArrayList(); + foreach (object model in objects) { + if (this.modelFilter.Filter(model)) + this.filteredObjectList.Add(model); + } + } + } + + #endregion + } + +} diff --git a/ObjectListView/Filtering/Cluster.cs b/ObjectListView/Filtering/Cluster.cs new file mode 100644 index 0000000..f90a84d --- /dev/null +++ b/ObjectListView/Filtering/Cluster.cs @@ -0,0 +1,125 @@ +/* + * Cluster - Implements a simple cluster + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// Concrete implementation of the ICluster interface. + /// + public class Cluster : ICluster { + + #region Life and death + + /// + /// Create a cluster + /// + /// The key for the cluster + public Cluster(object key) { + this.Count = 1; + this.ClusterKey = key; + } + + #endregion + + #region Public overrides + + /// + /// Return a string representation of this cluster + /// + /// + public override string ToString() { + return this.DisplayLabel ?? "[empty]"; + } + + #endregion + + #region Implementation of ICluster + + /// + /// Gets or sets how many items belong to this cluster + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + public string DisplayLabel { + get { return displayLabel; } + set { displayLabel = value; } + } + private string displayLabel; + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + public object ClusterKey { + get { return clusterKey; } + set { clusterKey = value; } + } + private object clusterKey; + + #endregion + + #region Implementation of IComparable + + /// + /// Return an indication of the ordering between this object and the given one + /// + /// + /// + public int CompareTo(object other) { + if (other == null || other == System.DBNull.Value) + return 1; + + ICluster otherCluster = other as ICluster; + if (otherCluster == null) + return 1; + + string keyAsString = this.ClusterKey as string; + if (keyAsString != null) + return String.Compare(keyAsString, otherCluster.ClusterKey as string, StringComparison.CurrentCultureIgnoreCase); + + IComparable keyAsComparable = this.ClusterKey as IComparable; + if (keyAsComparable != null) + return keyAsComparable.CompareTo(otherCluster.ClusterKey); + + return -1; + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClusteringStrategy.cs b/ObjectListView/Filtering/ClusteringStrategy.cs new file mode 100644 index 0000000..b2380f0 --- /dev/null +++ b/ObjectListView/Filtering/ClusteringStrategy.cs @@ -0,0 +1,189 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class provides a useful base implementation of a clustering + /// strategy where the clusters are grouped around the value of a given column. + /// + public class ClusteringStrategy : IClusteringStrategy { + + #region Static properties + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is null. It is exposed so it can be localized. + /// + static public string NULL_LABEL = "[null]"; + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is empty (i.e. a string of zero length). It is exposed so it can be localized. + /// + static public string EMPTY_LABEL = "[empty]"; + + /// + /// Gets or sets the format that will be used by default for clusters that only + /// contain 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + static public string DefaultDisplayLabelFormatSingular { + get { return defaultDisplayLabelFormatSingular; } + set { defaultDisplayLabelFormatSingular = value; } + } + static private string defaultDisplayLabelFormatSingular = "{0} ({1} item)"; + + /// + /// Gets or sets the format that will be used by default for clusters that + /// contain 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + static public string DefaultDisplayLabelFormatPlural { + get { return defaultDisplayLabelFormatPural; } + set { defaultDisplayLabelFormatPural = value; } + } + static private string defaultDisplayLabelFormatPural = "{0} ({1} items)"; + + #endregion + + #region Life and death + + /// + /// Create a clustering strategy + /// + public ClusteringStrategy() { + this.DisplayLabelFormatSingular = DefaultDisplayLabelFormatSingular; + this.DisplayLabelFormatPlural = DefaultDisplayLabelFormatPlural; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets the column upon which this strategy is operating + /// + public OLVColumn Column { + get { return column; } + set { column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains only 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatSingular will be used + public string DisplayLabelFormatSingular { + get { return displayLabelFormatSingular; } + set { displayLabelFormatSingular = value; } + } + private string displayLabelFormatSingular; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatPlural will be used + public string DisplayLabelFormatPlural { + get { return displayLabelFormatPural; } + set { displayLabelFormatPural = value; } + } + private string displayLabelFormatPural; + + #endregion + + #region ICluster implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + virtual public object GetClusterKey(object model) { + return this.Column.GetValue(model); + } + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + virtual public ICluster CreateCluster(object clusterKey) { + return new Cluster(clusterKey); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + virtual public string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ValueToString(cluster.ClusterKey) ?? NULL_LABEL; + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + virtual public IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new OneOfFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + /// + /// Create a label that combines the string representation of the cluster + /// key with a format string that holds an "X [N items in cluster]" type layout. + /// + /// + /// + /// + virtual protected string ApplyDisplayFormat(ICluster cluster, string s) { + string format = (cluster.Count == 1) ? this.DisplayLabelFormatSingular : this.DisplayLabelFormatPlural; + return String.IsNullOrEmpty(format) ? s : String.Format(format, s, cluster.Count); + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs new file mode 100644 index 0000000..ca95ecf --- /dev/null +++ b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs @@ -0,0 +1,70 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 1-April-2011 8:12am + * + * Change log: + * 2011-04-01 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class calculates clusters from the groups that the column uses. + /// + /// + /// + /// This is the default strategy for all non-date, filterable columns. + /// + /// + /// This class does not strictly mimic the groups created by the given column. + /// In particular, if the programmer changes the default grouping technique + /// by listening for grouping events, this class will not mimic that behaviour. + /// + /// + public class ClustersFromGroupsStrategy : ClusteringStrategy { + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + return this.Column.GetGroupKey(model); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ConvertGroupKeyToTitle(cluster.ClusterKey); + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + } +} diff --git a/ObjectListView/Filtering/DateTimeClusteringStrategy.cs b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs new file mode 100644 index 0000000..e0a864b --- /dev/null +++ b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs @@ -0,0 +1,187 @@ +/* + * DateTimeClusteringStrategy - A strategy to cluster objects by a date time + * + * Author: Phillip Piper + * Date: 30-March-2011 9:40am + * + * Change log: + * 2011-03-30 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// This enum is used to indicate various portions of a datetime + /// + [Flags] + public enum DateTimePortion { + /// + /// Year + /// + Year = 0x01, + + /// + /// Month + /// + Month = 0x02, + + /// + /// Day of the month + /// + Day = 0x04, + + /// + /// Hour + /// + Hour = 0x08, + + /// + /// Minute + /// + Minute = 0x10, + + /// + /// Second + /// + Second = 0x20 + } + + /// + /// This class implements a strategy where the model objects are clustered + /// according to some portion of the datetime value in the configured column. + /// + /// To create a strategy that grouped people who were born in + /// the same month, you would create a strategy that extracted just + /// the month, and formatted it to show just the month's name. Like this: + /// + /// + /// someColumn.ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Month, "MMMM"); + /// + public class DateTimeClusteringStrategy : ClusteringStrategy { + #region Life and death + + /// + /// Create a strategy that clusters by month/year + /// + public DateTimeClusteringStrategy() + : this(DateTimePortion.Year | DateTimePortion.Month, "MMMM yyyy") { + } + + /// + /// Create a strategy that clusters around the given parts + /// + /// + /// + public DateTimeClusteringStrategy(DateTimePortion portions, string format) { + this.Portions = portions; + this.Format = format; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the format string that will be used to create a user-presentable + /// version of the cluster key. + /// + /// The format should use the date/time format strings, as documented + /// in the Windows SDK. Both standard formats and custom format will work. + /// "D" - long date pattern + /// "MMMM, yyyy" - "January, 1999" + public string Format { + get { return format; } + set { format = value; } + } + private string format; + + /// + /// Gets or sets the parts of the DateTime that will be extracted when + /// determining the clustering key for an object. + /// + public DateTimePortion Portions { + get { return portions; } + set { portions = value; } + } + private DateTimePortion portions = DateTimePortion.Year | DateTimePortion.Month; + + #endregion + + #region IClusterStrategy implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + // Get the data attribute we want from the given model + // Make sure the returned value is a DateTime + DateTime? dateTime = this.Column.GetValue(model) as DateTime?; + if (!dateTime.HasValue) + return null; + + // Extract the parts of the datetime that we are interested in. + // Even if we aren't interested in a particular portion, we still have to give it a reasonable default + // otherwise we won't be able to build a DateTime object for it + int year = ((this.Portions & DateTimePortion.Year) == DateTimePortion.Year) ? dateTime.Value.Year : 1; + int month = ((this.Portions & DateTimePortion.Month) == DateTimePortion.Month) ? dateTime.Value.Month : 1; + int day = ((this.Portions & DateTimePortion.Day) == DateTimePortion.Day) ? dateTime.Value.Day : 1; + int hour = ((this.Portions & DateTimePortion.Hour) == DateTimePortion.Hour) ? dateTime.Value.Hour : 0; + int minute = ((this.Portions & DateTimePortion.Minute) == DateTimePortion.Minute) ? dateTime.Value.Minute : 0; + int second = ((this.Portions & DateTimePortion.Second) == DateTimePortion.Second) ? dateTime.Value.Second : 0; + + return new DateTime(year, month, day, hour, minute, second); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + DateTime? dateTime = cluster.ClusterKey as DateTime?; + + return this.ApplyDisplayFormat(cluster, dateTime.HasValue ? this.DateToString(dateTime.Value) : NULL_LABEL); + } + + /// + /// Convert the given date into a user presentable string + /// + /// + /// + protected virtual string DateToString(DateTime dateTime) { + if (String.IsNullOrEmpty(this.Format)) + return dateTime.ToString(CultureInfo.CurrentUICulture); + + try { + return dateTime.ToString(this.Format); + } + catch (FormatException) { + return String.Format("Bad format string '{0}' for value '{1}'", this.Format, dateTime); + } + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/FilterMenuBuilder.cs b/ObjectListView/Filtering/FilterMenuBuilder.cs new file mode 100644 index 0000000..e91614a --- /dev/null +++ b/ObjectListView/Filtering/FilterMenuBuilder.cs @@ -0,0 +1,369 @@ +/* + * FilterMenuBuilder - Responsible for creating a Filter menu + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-20 JPP - Allow the same model object to be in multiple clusters + * Useful for xor'ed flag fields, and multi-value strings + * (e.g. hobbies that are stored as comma separated values). + * v2.5.1 + * 2012-04-14 JPP - Fixed rare bug with clustering an empty list (SF #3445118) + * v2.5 + * 2011-04-12 JPP - Added some images to menu + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Collections; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class know how to build a Filter menu. + /// It is responsible for clustering the values in the target column, + /// build a menu that shows those clusters, and then constructing + /// a filter that will enact the users choices. + /// + /// + /// Almost all of the methods in this class are declared as "virtual protected" + /// so that subclasses can provide alternative behaviours. + /// + public class FilterMenuBuilder { + + #region Static properties + + /// + /// Gets or sets the string that labels the Apply button. + /// Exposed so it can be localized. + /// + static public string APPLY_LABEL = "Apply"; + + /// + /// Gets or sets the string that labels the Clear All menu item. + /// Exposed so it can be localized. + /// + static public string CLEAR_ALL_FILTERS_LABEL = "Clear All Filters"; + + /// + /// Gets or sets the string that labels the Filtering menu as a whole.. + /// Exposed so it can be localized. + /// + static public string FILTERING_LABEL = "Filtering"; + + /// + /// Gets or sets the string that represents Select All values. + /// If this is set to null or empty, no Select All option will be included. + /// Exposed so it can be localized. + /// + static public string SELECT_ALL_LABEL = "Select All"; + + /// + /// Gets or sets the image that will be placed next to the Clear Filtering menu item + /// + static public Bitmap ClearFilteringImage = BrightIdeasSoftware.Properties.Resources.ClearFiltering; + + /// + /// Gets or sets the image that will be placed next to all "Apply" menu items on the filtering menu + /// + static public Bitmap FilteringImage = BrightIdeasSoftware.Properties.Resources.Filtering; + + #endregion + + #region Public properties + + /// + /// Gets or sets whether null should be considered as a valid data value. + /// If this is true (the default), then a cluster will null as a key will be allow. + /// If this is false, object that return a cluster key of null will ignored. + /// + public bool TreatNullAsDataValue { + get { return treatNullAsDataValue; } + set { treatNullAsDataValue = value; } + } + private bool treatNullAsDataValue = true; + + /// + /// Gets or sets the maximum number of objects that the clustering strategy + /// will consider. This should be large enough to collect all unique clusters, + /// but small enough to finish in a reasonable time. + /// + /// The default value is 10,000. This should be perfectly + /// acceptable for almost all lists. + public int MaxObjectsToConsider { + get { return maxObjectsToConsider; } + set { maxObjectsToConsider = value; } + } + private int maxObjectsToConsider = 10000; + + #endregion + + /// + /// Create a Filter menu on the given tool tip for the given column in the given ObjectListView. + /// + /// This is the main entry point into this class. + /// + /// + /// + /// The strip that should be shown to the user + virtual public ToolStripDropDown MakeFilterMenu(ToolStripDropDown strip, ObjectListView listView, OLVColumn column) { + if (strip == null) throw new ArgumentNullException("strip"); + if (listView == null) throw new ArgumentNullException("listView"); + if (column == null) throw new ArgumentNullException("column"); + + if (!column.UseFiltering || column.ClusteringStrategy == null || listView.Objects == null) + return strip; + + List clusters = this.Cluster(column.ClusteringStrategy, listView, column); + if (clusters.Count > 0) { + this.SortClusters(column.ClusteringStrategy, clusters); + strip.Items.Add(this.CreateFilteringMenuItem(column, clusters)); + } + + return strip; + } + + /// + /// Create a collection of clusters that should be presented to the user + /// + /// + /// + /// + /// + virtual protected List Cluster(IClusteringStrategy strategy, ObjectListView listView, OLVColumn column) { + // Build a map that correlates cluster key to clusters + NullableDictionary map = new NullableDictionary(); + int count = 0; + foreach (object model in listView.ObjectsForClustering) { + this.ClusterOneModel(strategy, map, model); + + if (count++ > this.MaxObjectsToConsider) + break; + } + + // Now that we know exactly how many items are in each cluster, create a label for it + foreach (ICluster cluster in map.Values) + cluster.DisplayLabel = strategy.GetClusterDisplayLabel(cluster); + + return new List(map.Values); + } + + private void ClusterOneModel(IClusteringStrategy strategy, NullableDictionary map, object model) { + object clusterKey = strategy.GetClusterKey(model); + + // If the returned value is an IEnumerable, that means the given model can belong to more than one cluster + IEnumerable keyEnumerable = clusterKey as IEnumerable; + if (clusterKey is string || keyEnumerable == null) + keyEnumerable = new object[] {clusterKey}; + + // Deal with nulls and DBNulls + ArrayList nullCorrected = new ArrayList(); + foreach (object key in keyEnumerable) { + if (key == null || key == System.DBNull.Value) { + if (this.TreatNullAsDataValue) + nullCorrected.Add(null); + } else nullCorrected.Add(key); + } + + // Group by key + foreach (object key in nullCorrected) { + if (map.ContainsKey(key)) + map[key].Count += 1; + else + map[key] = strategy.CreateCluster(key); + } + } + + /// + /// Order the given list of clusters in the manner in which they should be presented to the user. + /// + /// + /// + virtual protected void SortClusters(IClusteringStrategy strategy, List clusters) { + clusters.Sort(); + } + + /// + /// Do the work of making a menu that shows the clusters to the users + /// + /// + /// + /// + virtual protected ToolStripMenuItem CreateFilteringMenuItem(OLVColumn column, List clusters) { + ToolStripCheckedListBox checkedList = new ToolStripCheckedListBox(); + checkedList.Tag = column; + foreach (ICluster cluster in clusters) + checkedList.AddItem(cluster, column.ValuesChosenForFiltering.Contains(cluster.ClusterKey)); + if (!String.IsNullOrEmpty(SELECT_ALL_LABEL)) { + int checkedCount = checkedList.CheckedItems.Count; + if (checkedCount == 0) + checkedList.AddItem(SELECT_ALL_LABEL, CheckState.Unchecked); + else + checkedList.AddItem(SELECT_ALL_LABEL, checkedCount == clusters.Count ? CheckState.Checked : CheckState.Indeterminate); + } + checkedList.ItemCheck += new ItemCheckEventHandler(HandleItemCheckedWrapped); + + ToolStripMenuItem clearAll = new ToolStripMenuItem(CLEAR_ALL_FILTERS_LABEL, ClearFilteringImage, delegate(object sender, EventArgs args) { + this.ClearAllFilters(column); + }); + ToolStripMenuItem apply = new ToolStripMenuItem(APPLY_LABEL, FilteringImage, delegate(object sender, EventArgs args) { + this.EnactFilter(checkedList, column); + }); + ToolStripMenuItem subMenu = new ToolStripMenuItem(FILTERING_LABEL, null, new ToolStripItem[] { + clearAll, new ToolStripSeparator(), checkedList, apply }); + return subMenu; + } + + /// + /// Wrap a protected section around the real HandleItemChecked method, so that if + /// that method tries to change a "checkedness" of an item, we don't get a recursive + /// stack error. Effectively, this ensure that HandleItemChecked is only called + /// in response to a user action. + /// + /// + /// + private void HandleItemCheckedWrapped(object sender, ItemCheckEventArgs e) { + if (alreadyInHandleItemChecked) + return; + + try { + alreadyInHandleItemChecked = true; + this.HandleItemChecked(sender, e); + } + finally { + alreadyInHandleItemChecked = false; + } + } + bool alreadyInHandleItemChecked = false; + + /// + /// Handle a user-generated ItemCheck event + /// + /// + /// + virtual protected void HandleItemChecked(object sender, ItemCheckEventArgs e) { + + ToolStripCheckedListBox checkedList = sender as ToolStripCheckedListBox; + if (checkedList == null) return; + OLVColumn column = checkedList.Tag as OLVColumn; + if (column == null) return; + ObjectListView listView = column.ListView as ObjectListView; + if (listView == null) return; + + // Deal with the "Select All" item if there is one + int selectAllIndex = checkedList.Items.IndexOf(SELECT_ALL_LABEL); + if (selectAllIndex >= 0) + HandleSelectAllItem(e, checkedList, selectAllIndex); + } + + /// + /// Handle any checking/unchecking of the Select All option, and keep + /// its checkedness in sync with everything else that is checked. + /// + /// + /// + /// + virtual protected void HandleSelectAllItem(ItemCheckEventArgs e, ToolStripCheckedListBox checkedList, int selectAllIndex) { + // Did they check/uncheck the "Select All"? + if (e.Index == selectAllIndex) { + if (e.NewValue == CheckState.Checked) + checkedList.CheckAll(); + if (e.NewValue == CheckState.Unchecked) + checkedList.UncheckAll(); + return; + } + + // OK. The user didn't check/uncheck SelectAll. Now we have to update it's + // checkedness to reflect the state of everything else + // If all clusters are checked, we check the Select All. + // If no clusters are checked, the uncheck the Select All. + // For everything else, Select All is set to indeterminate. + + // How many items are currently checked? + int count = checkedList.CheckedItems.Count; + + // First complication. + // The value of the Select All itself doesn't count + if (checkedList.GetItemCheckState(selectAllIndex) != CheckState.Unchecked) + count -= 1; + + // Another complication. + // CheckedItems does not yet know about the item the user has just + // clicked, so we have to adjust the count of checked items to what + // it is going to be + if (e.NewValue != e.CurrentValue) { + if (e.NewValue == CheckState.Checked) + count += 1; + else + count -= 1; + } + + // Update the state of the Select All item + if (count == 0) + checkedList.SetItemState(selectAllIndex, CheckState.Unchecked); + else if (count == checkedList.Items.Count - 1) + checkedList.SetItemState(selectAllIndex, CheckState.Checked); + else + checkedList.SetItemState(selectAllIndex, CheckState.Indeterminate); + } + + /// + /// Clear all the filters that are applied to the given column + /// + /// The column from which filters are to be removed + virtual protected void ClearAllFilters(OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + olv.ResetColumnFiltering(); + } + + /// + /// Apply the selected values from the given list as a filter on the given column + /// + /// A list in which the checked items should be used as filters + /// The column for which a filter should be generated + virtual protected void EnactFilter(ToolStripCheckedListBox checkedList, OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + // Collect all the checked values + ArrayList chosenValues = new ArrayList(); + foreach (object x in checkedList.CheckedItems) { + ICluster cluster = x as ICluster; + if (cluster != null) { + chosenValues.Add(cluster.ClusterKey); + } + } + column.ValuesChosenForFiltering = chosenValues; + + olv.UpdateColumnFiltering(); + } + } +} diff --git a/ObjectListView/Filtering/Filters.cs b/ObjectListView/Filtering/Filters.cs new file mode 100644 index 0000000..db69a62 --- /dev/null +++ b/ObjectListView/Filtering/Filters.cs @@ -0,0 +1,489 @@ +/* + * Filters - Filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 03/03/2010 17:00 + * + * Change log: + * 2011-03-01 JPP Added CompositeAllFilter, CompositeAnyFilter and OneOfFilter + * v2.4.1 + * 2010-06-23 JPP Extended TextMatchFilter to handle regular expressions and string prefix matching. + * v2.4 + * 2010-03-03 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Drawing; + +namespace BrightIdeasSoftware +{ + /// + /// Interface for model-by-model filtering + /// + public interface IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + bool Filter(object modelObject); + } + + /// + /// Interface for whole list filtering + /// + public interface IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + IEnumerable Filter(IEnumerable modelObjects); + } + + /// + /// Base class for model-by-model filters + /// + public class AbstractModelFilter : IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + virtual public bool Filter(object modelObject) { + return true; + } + } + + /// + /// This filter calls a given Predicate to decide if a model object should be included + /// + public class ModelFilter : IModelFilter + { + /// + /// Create a filter based on the given predicate + /// + /// The function that will filter objects + public ModelFilter(Predicate predicate) { + this.Predicate = predicate; + } + + /// + /// Gets or sets the predicate used to filter model objects + /// + protected Predicate Predicate { + get { return predicate; } + set { predicate = value; } + } + private Predicate predicate; + + /// + /// Should the given model object be included? + /// + /// + /// + virtual public bool Filter(object modelObject) { + return this.Predicate == null ? true : this.Predicate(modelObject); + } + } + + /// + /// A CompositeFilter joins several other filters together. + /// If there are no filters, all model objects are included + /// + abstract public class CompositeFilter : IModelFilter { + + /// + /// Create an empty filter + /// + public CompositeFilter() { + } + + /// + /// Create a composite filter from the given list of filters + /// + /// A list of filters + public CompositeFilter(IEnumerable filters) { + foreach (IModelFilter filter in filters) { + if (filter != null) + Filters.Add(filter); + } + } + + /// + /// Gets or sets the filters used by this composite + /// + public IList Filters { + get { return filters; } + set { filters = value; } + } + private IList filters = new List(); + + /// + /// Get the sub filters that are text match filters + /// + public IEnumerable TextFilters { + get { + foreach (IModelFilter filter in this.Filters) { + TextMatchFilter textFilter = filter as TextMatchFilter; + if (textFilter != null) + yield return textFilter; + } + } + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// + /// True if the object is included by the filter + virtual public bool Filter(object modelObject) { + if (this.Filters == null || this.Filters.Count == 0) + return true; + + return this.FilterObject(modelObject); + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + abstract public bool FilterObject(object modelObject); + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must satisfy all filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAllFilter : CompositeFilter { + + /// + /// Create a filter + /// + /// + public CompositeAllFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (!filter.Filter(modelObject)) + return false; + + return true; + } + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must only satisfy one of the filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAnyFilter : CompositeFilter { + + /// + /// Create a filter from the given filters + /// + /// + public CompositeAnyFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (filter.Filter(modelObject)) + return true; + + return false; + } + } + + /// + /// Instances of this class extract a value from the model object + /// and compare that value to a list of fixed values. The model + /// object is included if the extracted value is in the list + /// + /// If there is no delegate installed or there are + /// no values to match, no model objects will be matched + public class OneOfFilter : IModelFilter { + + /// + /// Create a filter that will use the given delegate to extract values + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter) : + this(valueGetter, new ArrayList()) { + } + + /// + /// Create a filter that will extract values using the given delegate + /// and compare them to the values in the given list. + /// + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) { + this.ValueGetter = valueGetter; + this.PossibleValues = new ArrayList(possibleValues); + } + + /// + /// Gets or sets the delegate that will be used to extract values + /// from model objects + /// + virtual public AspectGetterDelegate ValueGetter { + get { return valueGetter; } + set { valueGetter = value; } + } + private AspectGetterDelegate valueGetter; + + /// + /// Gets or sets the list of values that the value extracted from + /// the model object must match in order to be included. + /// + virtual public IList PossibleValues { + get { return possibleValues; } + set { possibleValues = value; } + } + private IList possibleValues; + + /// + /// Should the given model object be included? + /// + /// + /// + public virtual bool Filter(object modelObject) { + if (this.ValueGetter == null || this.PossibleValues == null || this.PossibleValues.Count == 0) + return false; + + object result = this.ValueGetter(modelObject); + IEnumerable enumerable = result as IEnumerable; + if (result is string || enumerable == null) + return this.DoesValueMatch(result); + + foreach (object x in enumerable) { + if (this.DoesValueMatch(x)) + return true; + } + return false; + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected virtual bool DoesValueMatch(object result) { + return this.PossibleValues.Contains(result); + } + } + + /// + /// Instances of this class match a property of a model objects against + /// a list of bit flags. The property should be an xor-ed collection + /// of bits flags. + /// + /// Both the property compared and the list of possible values + /// must be convertible to ulongs. + public class FlagBitSetFilter : OneOfFilter { + + /// + /// Create an instance + /// + /// + /// + public FlagBitSetFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) : base(valueGetter, possibleValues) { + this.ConvertPossibleValues(); + } + + /// + /// Gets or sets the collection of values that will be matched. + /// These must be ulongs (or convertible to ulongs). + /// + public override IList PossibleValues { + get { return base.PossibleValues; } + set { + base.PossibleValues = value; + this.ConvertPossibleValues(); + } + } + + private void ConvertPossibleValues() { + this.possibleValuesAsUlongs = new List(); + foreach (object x in this.PossibleValues) + this.possibleValuesAsUlongs.Add(Convert.ToUInt64(x)); + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected override bool DoesValueMatch(object result) { + try { + UInt64 value = Convert.ToUInt64(result); + foreach (ulong flag in this.possibleValuesAsUlongs) { + if ((value & flag) == flag) + return true; + } + return false; + } + catch (InvalidCastException) { + return false; + } + catch (FormatException) { + return false; + } + } + + private List possibleValuesAsUlongs = new List(); + } + + /// + /// Base class for whole list filters + /// + public class AbstractListFilter : IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + virtual public IEnumerable Filter(IEnumerable modelObjects) { + return modelObjects; + } + } + + /// + /// Instance of this class implement delegate based whole list filtering + /// + public class ListFilter : AbstractListFilter + { + /// + /// A delegate that filters on a whole list + /// + /// + /// + public delegate IEnumerable ListFilterDelegate(IEnumerable rowObjects); + + /// + /// Create a ListFilter + /// + /// + public ListFilter(ListFilterDelegate function) { + this.Function = function; + } + + /// + /// Gets or sets the delegate that will filter the list + /// + public ListFilterDelegate Function { + get { return function; } + set { function = value; } + } + private ListFilterDelegate function; + + /// + /// Do the actual work of filtering + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Function == null) + return modelObjects; + + return this.Function(modelObjects); + } + } + + /// + /// Filter the list so only the last N entries are displayed + /// + public class TailFilter : AbstractListFilter + { + /// + /// Create a no-op tail filter + /// + public TailFilter() { + } + + /// + /// Create a filter that includes on the last N model objects + /// + /// + public TailFilter(int numberOfObjects) { + this.Count = numberOfObjects; + } + + /// + /// Gets or sets the number of model objects that will be + /// returned from the tail of the list + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Return the last N subset of the model objects + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Count <= 0) + return modelObjects; + + ArrayList list = ObjectListView.EnumerableToArray(modelObjects, false); + + if (this.Count > list.Count) + return list; + + object[] tail = new object[this.Count]; + list.CopyTo(list.Count - this.Count, tail, 0, this.Count); + return new ArrayList(tail); + } + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/FlagClusteringStrategy.cs b/ObjectListView/Filtering/FlagClusteringStrategy.cs new file mode 100644 index 0000000..519ce89 --- /dev/null +++ b/ObjectListView/Filtering/FlagClusteringStrategy.cs @@ -0,0 +1,160 @@ +/* + * FlagClusteringStrategy - Implements a clustering strategy for a field which is a single integer + * containing an XOR'ed collection of bit flags + * + * Author: Phillip Piper + * Date: 23-March-2012 8:33 am + * + * Change log: + * 2012-03-23 JPP - First version + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class cluster model objects on the basis of a + /// property that holds an xor-ed collection of bit flags. + /// + public class FlagClusteringStrategy : ClusteringStrategy + { + #region Life and death + + /// + /// Create a clustering strategy that operates on the flags of the given enum + /// + /// + public FlagClusteringStrategy(Type enumType) { + if (enumType == null) throw new ArgumentNullException("enumType"); + if (!enumType.IsEnum) throw new ArgumentException("Type must be enum", "enumType"); + if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false) == null) throw new ArgumentException("Type must have [Flags] attribute", "enumType"); + + List flags = new List(); + foreach (object x in Enum.GetValues(enumType)) + flags.Add(Convert.ToInt64(x)); + + List flagLabels = new List(); + foreach (string x in Enum.GetNames(enumType)) + flagLabels.Add(x); + + this.SetValues(flags.ToArray(), flagLabels.ToArray()); + } + + /// + /// Create a clustering strategy around the given collections of flags and their display labels. + /// There must be the same number of elements in both collections. + /// + /// The list of flags. + /// + public FlagClusteringStrategy(long[] values, string[] labels) { + this.SetValues(values, labels); + } + + #endregion + + #region Implementation + + /// + /// Gets the value that will be xor-ed to test for the presence of a particular value. + /// + public long[] Values { + get { return this.values; } + private set { this.values = value; } + } + private long[] values; + + /// + /// Gets the labels that will be used when the corresponding Value is XOR present in the data. + /// + public string[] Labels { + get { return this.labels; } + private set { this.labels = value; } + } + private string[] labels; + + private void SetValues(long[] flags, string[] flagLabels) { + if (flags == null || flags.Length == 0) throw new ArgumentNullException("flags"); + if (flagLabels == null || flagLabels.Length == 0) throw new ArgumentNullException("flagLabels"); + if (flags.Length != flagLabels.Length) throw new ArgumentException("values and labels must have the same number of entries", "flags"); + + this.Values = flags; + this.Labels = flagLabels; + } + + #endregion + + #region Implementation of IClusteringStrategy + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + List flags = new List(); + try { + long modelValue = Convert.ToInt64(this.Column.GetValue(model)); + foreach (long x in this.Values) { + if ((x & modelValue) == x) + flags.Add(x); + } + return flags; + } + catch (InvalidCastException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + catch (FormatException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + long clusterKeyAsUlong = Convert.ToInt64(cluster.ClusterKey); + for (int i = 0; i < this.Values.Length; i++ ) { + if (clusterKeyAsUlong == this.Values[i]) + return this.ApplyDisplayFormat(cluster, this.Labels[i]); + } + return this.ApplyDisplayFormat(cluster, clusterKeyAsUlong.ToString(CultureInfo.CurrentUICulture)); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + public override IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new FlagBitSetFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/ICluster.cs b/ObjectListView/Filtering/ICluster.cs new file mode 100644 index 0000000..3196595 --- /dev/null +++ b/ObjectListView/Filtering/ICluster.cs @@ -0,0 +1,56 @@ +/* + * ICluster - A cluster is a group of objects that can be included or excluded as a whole + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// A cluster is a like collection of objects that can be usefully filtered + /// as whole using the filtering UI provided by the ObjectListView. + /// + public interface ICluster : IComparable { + /// + /// Gets or sets how many items belong to this cluster + /// + int Count { get; set; } + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + string DisplayLabel { get; set; } + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + object ClusterKey { get; set; } + } +} diff --git a/ObjectListView/Filtering/IClusteringStrategy.cs b/ObjectListView/Filtering/IClusteringStrategy.cs new file mode 100644 index 0000000..fb6a4e2 --- /dev/null +++ b/ObjectListView/Filtering/IClusteringStrategy.cs @@ -0,0 +1,80 @@ +/* + * IClusterStrategy - Encapsulates the ability to create a list of clusters from an ObjectListView + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-23 JPP - Added CreateFilter() method to interface to allow the strategy + * to control the actual model filter that is created. + * v2.5 + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware{ + + /// + /// Implementation of this interface control the selecting of cluster keys + /// and how those clusters will be presented to the user + /// + public interface IClusteringStrategy { + + /// + /// Gets or sets the column upon which this strategy will operate + /// + OLVColumn Column { get; set; } + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// If the returned value is an IEnumerable, the given model is considered + /// to belong to multiple clusters + /// + /// + object GetClusterKey(object model); + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + ICluster CreateCluster(object clusterKey); + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + string GetClusterDisplayLabel(ICluster cluster); + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + IModelFilter CreateFilter(IList valuesChosenForFiltering); + } +} diff --git a/ObjectListView/Filtering/TextMatchFilter.cs b/ObjectListView/Filtering/TextMatchFilter.cs new file mode 100644 index 0000000..8df3719 --- /dev/null +++ b/ObjectListView/Filtering/TextMatchFilter.cs @@ -0,0 +1,642 @@ +/* + * TextMatchFilter - Text based filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 31/05/2011 7:45am + * + * Change log: + * 2018-05-01 JPP - Added ITextMatchFilter to allow for alternate implementations + * - Made several classes public so they can be subclassed + * v2.6 + * 2012-10-13 JPP Allow filtering to consider additional columns + * v2.5.1 + * 2011-06-22 JPP Handle searching for empty strings + * v2.5.0 + * 2011-05-31 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using System.Drawing; + +namespace BrightIdeasSoftware { + + public interface ITextMatchFilter: IModelFilter { + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + IEnumerable FindAllMatchedRanges(string cellText); + } + + /// + /// Instances of this class include only those rows of the listview + /// that match one or more given strings. + /// + /// This class can match strings by prefix, regex, or simple containment. + /// There are factory methods for each of these matching strategies. + public class TextMatchFilter : AbstractModelFilter, ITextMatchFilter { + + #region Life and death + + /// + /// Create a text filter that will include rows where any cell matches + /// any of the given regex expressions. + /// + /// + /// + /// + /// Any string that is not a valid regex expression will be ignored. + public static TextMatchFilter Regex(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.RegexStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell begins with one of the given strings + /// + /// + /// + /// + public static TextMatchFilter Prefix(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.PrefixStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell contains any of the given strings. + /// + /// + /// + /// + public static TextMatchFilter Contains(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.ContainsStrings = texts; + return filter; + } + + /// + /// Create a TextFilter + /// + /// + public TextMatchFilter(ObjectListView olv) { + this.ListView = olv; + } + + /// + /// Create a TextFilter that finds the given string + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + } + + /// + /// Create a TextFilter that finds the given string using the given comparison + /// + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text, StringComparison comparison) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + this.StringComparison = comparison; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets which columns will be used for the comparisons? If this is null, all columns will be used + /// + public OLVColumn[] Columns { + get { return columns; } + set { columns = value; } + } + private OLVColumn[] columns; + + /// + /// Gets or sets additional columns which will be used in the comparison. These will be used + /// in addition to either the Columns property or to all columns taken from the control. + /// + public OLVColumn[] AdditionalColumns { + get { return additionalColumns; } + set { additionalColumns = value; } + } + private OLVColumn[] additionalColumns; + + /// + /// Gets or sets the collection of strings that will be used for + /// contains matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable ContainsStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextContainsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets whether or not this filter has any search criteria + /// + public bool HasComponents { + get { + return this.MatchingStrategies.Count > 0; + } + } + + /// + /// Gets or set the ObjectListView upon which this filter will work + /// + /// + /// You cannot really rebase a filter after it is created, so do not change this value. + /// It is included so that it can be set in an object initialiser. + /// + public ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the collection of strings that will be used for + /// prefix matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable PrefixStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextBeginsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + /// + /// This is only used when doing Regex matching (obviously). + /// If this is not set specifically, the appropriate options are chosen to match the + /// StringComparison setting (culture invariant, case sensitive). + /// + public RegexOptions RegexOptions { + get { + if (!regexOptions.HasValue) { + switch (this.StringComparison) { + case StringComparison.CurrentCulture: + regexOptions = RegexOptions.None; + break; + case StringComparison.CurrentCultureIgnoreCase: + regexOptions = RegexOptions.IgnoreCase; + break; + case StringComparison.Ordinal: + case StringComparison.InvariantCulture: + regexOptions = RegexOptions.CultureInvariant; + break; + case StringComparison.OrdinalIgnoreCase: + case StringComparison.InvariantCultureIgnoreCase: + regexOptions = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + break; + default: + regexOptions = RegexOptions.None; + break; + } + } + return regexOptions.Value; + } + set { + regexOptions = value; + } + } + private RegexOptions? regexOptions; + + /// + /// Gets or sets the collection of strings that will be used for + /// regex pattern matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable RegexStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextRegexMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.stringComparison; } + set { this.stringComparison = value; } + } + private StringComparison stringComparison = StringComparison.InvariantCultureIgnoreCase; + + #endregion + + #region Implementation + + /// + /// Loop over the columns that are being considering by the filter + /// + /// + protected virtual IEnumerable IterateColumns() { + if (this.Columns == null) { + foreach (OLVColumn column in this.ListView.Columns) + yield return column; + } else { + foreach (OLVColumn column in this.Columns) + yield return column; + } + if (this.AdditionalColumns != null) { + foreach (OLVColumn column in this.AdditionalColumns) + yield return column; + } + } + + #endregion + + #region Public interface + + /// + /// Do the actual work of filtering + /// + /// + /// + public override bool Filter(object modelObject) { + if (this.ListView == null || !this.HasComponents) + return true; + + foreach (OLVColumn column in this.IterateColumns()) { + if (column.IsVisible && column.Searchable) { + string[] cellTexts = column.GetSearchValues(modelObject); + if (cellTexts != null && cellTexts.Length > 0) { + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (String.IsNullOrEmpty(filter.Text)) + return true; + foreach (string cellText in cellTexts) { + if (filter.MatchesText(cellText)) + return true; + } + } + } + } + } + + return false; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + public IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (!String.IsNullOrEmpty(filter.Text)) + ranges.AddRange(filter.FindAllMatchedRanges(cellText)); + } + + return ranges; + } + + /// + /// Is the given column one of the columns being used by this filter? + /// + /// + /// + public bool IsIncluded(OLVColumn column) { + if (this.Columns == null) { + return column.ListView == this.ListView; + } + + foreach (OLVColumn x in this.Columns) { + if (x == column) + return true; + } + + return false; + } + + #endregion + + #region Implementation members + + protected List MatchingStrategies = new List(); + + #endregion + + #region Components + + /// + /// Base class for the various types of string matching that TextMatchFilter provides + /// + public abstract class TextMatchingStrategy { + + /// + /// Gets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.TextFilter.StringComparison; } + } + + /// + /// Gets the text filter to which this component belongs + /// + public TextMatchFilter TextFilter { + get { return textFilter; } + set { textFilter = value; } + } + private TextMatchFilter textFilter; + + /// + /// Gets or sets the text that will be matched + /// + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public abstract IEnumerable FindAllMatchedRanges(string cellText); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public abstract bool MatchesText(string cellText); + } + + /// + /// This component provides text contains matching strategy. + /// + public class TextContainsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text contains strategy + /// + /// + /// + public TextContainsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.IndexOf(this.Text, this.StringComparison) != -1; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + int matchIndex = cellText.IndexOf(this.Text, this.StringComparison); + while (matchIndex != -1) { + ranges.Add(new CharacterRange(matchIndex, this.Text.Length)); + matchIndex = cellText.IndexOf(this.Text, matchIndex + this.Text.Length, this.StringComparison); + } + + return ranges; + } + } + + /// + /// This component provides text begins with matching strategy. + /// + public class TextBeginsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text begins strategy + /// + /// + /// + public TextBeginsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.StartsWith(this.Text, this.StringComparison); + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (cellText.StartsWith(this.Text, this.StringComparison)) + ranges.Add(new CharacterRange(0, this.Text.Length)); + + return ranges; + } + + } + + /// + /// This component provides regex matching strategy. + /// + public class TextRegexMatchingStrategy : TextMatchingStrategy { + + /// + /// Creates a regex strategy + /// + /// + /// + public TextRegexMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + public RegexOptions RegexOptions { + get { + return this.TextFilter.RegexOptions; + } + } + + /// + /// Gets or sets a compiled regular expression, based on our current Text and RegexOptions. + /// + /// + /// If Text fails to compile as a regular expression, this will return a Regex object + /// that will match all strings. + /// + protected Regex Regex { + get { + if (this.regex == null) { + try { + this.regex = new Regex(this.Text, this.RegexOptions); + } + catch (ArgumentException) { + this.regex = TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + return this.regex; + } + set { + this.regex = value; + } + } + private Regex regex; + + /// + /// Gets whether or not our current regular expression is a valid regex + /// + protected bool IsRegexInvalid { + get { + return this.Regex == TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + private static Regex InvalidRegexMarker = new Regex(".*"); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + if (this.IsRegexInvalid) + return true; + return this.Regex.Match(cellText).Success; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (!this.IsRegexInvalid) { + foreach (Match match in this.Regex.Matches(cellText)) { + if (match.Length > 0) + ranges.Add(new CharacterRange(match.Index, match.Length)); + } + } + + return ranges; + } + } + + #endregion + } +} diff --git a/ObjectListView/FullClassDiagram.cd b/ObjectListView/FullClassDiagram.cd new file mode 100644 index 0000000..3126de2 --- /dev/null +++ b/ObjectListView/FullClassDiagram.cd @@ -0,0 +1,1261 @@ + + + + + + AQCABIAAAIAhAACgAAAAAIAMAAAECAAggAIAIIAAAEA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAAAAAAAAAAQEIAAEAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAQIAAABAQAAQAAgAAAAAAABAIAAAAQAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + ABgAAAAAAAAAAgIhAAACAAAEAAAAAAAAAAAAAAAAAAA= + DataListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + BAAAAAAAAAAAAAAAAQAAAAAQAAAQEAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAMAAAAA= + DragDrop\DropSink.cs + + + + + + + ZS0gAiQEBAoQDA8YQBMAMCAFgwQHBALcAEBEiEAAAQA= + DragDrop\DropSink.cs + + + + + + BYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + IACgGiAAIBoAAAAAAAAAAAAAAALAAAAKgAQECIAEgAA= + DragDrop\DropSink.cs + + + + + + BAEAAAAAAAAAAAAAAAEQAAAAAAAAAAIAAAAAgAQAAEA= + DragDrop\DropSink.cs + + + + + + AQAAEAEABAAAAAAAEAAAAAAAAAIAAgACgAAAAAAAQBA= + DragDrop\OLVDataObject.cs + + + + + + AAAAAAAAAAAAAgIAAAACAAAEQAAAAAAAAAAAAAAAAAA= + FastDataListView.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEQAAAAAAAAAAA= + FastObjectListView.cs + + + + + + ABAAAAgAQAQAABAgAAASQ4AQAAIEAAAAAAAAAEIAgAA= + FastObjectListView.cs + + + + + + AAAAAAAQAAAAEAQEBAAAAAQAgAAAAIAAAAAAAAAAAAA= + Filtering\Cluster.cs + + + + + + + AAAAAAAEAAAAAAAAAhBABAgAQAAIKAQBAQAAAAAAoIA= + Filtering\ClusteringStrategy.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQBAAAAAAAAAAA= + Filtering\ClustersFromGroupsStrategy.cs + + + + + + AAAAAAIAAAACAAAAAAAACAAAAQgAAAQBAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + SAEAADAQgEEAAQAIAAgQIAAAAFQAAAAAAAAAoAAAAAE= + Filtering\FilterMenuBuilder.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAEAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAIAAAACAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAAAAAAAAgAAAAIAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAABAAAAAQAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAgAAACAAAABAAABAAgAQACABABAAAAyEIAAIgSgAA= + Filtering\TextMatchFilter.cs + + + + + + EgAAQTAAZAEgWGAASFwIIEYECGBGAQKAQEEGAQJAAEE= + Implementation\Attributes.cs + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AZggAAAwAGAAAgACQAYCBCAEICACACUEhAEAQKBAgQg= + Implementation\DataSourceAdapter.cs + + + + + + + 5/7+//3///fX/+//+///f/3//f/37N////+//7+///8= + Implementation\Enums.cs + + + + + + + ASgQyXBAABICBAAAAIAAACCEMAKBQAOAABDAgAUpAQA= + Implementation\Events.cs + + + + + + ABEAEAAFQAAAABAABABQEAQAQAAAECAAAAAgAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAABAAAIAAAAAAAAAEAAAQAAAAABAAAAAAAABAAIAA= + Implementation\Events.cs + + + + + + AAQABAAAAAQQAAAAAAEAAAQAAAAABAAAAAAgABQAIAE= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAEAAAAAAAAAAAAEAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAEAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAQAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAgAAAAIAAAAAAAAAAAAgAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAQAAAIAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAEA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAQAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAMABAAAAQgAZAFAAGUARAAAAAgAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + CAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAQAAAAAAAEGAAAAAAAAAAAgAACAIAAAACAAHAAA= + Implementation\Events.cs + + + + + + AAAgAAAAMAAAAAAAgARABAAEUAQIAAAAiAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAABAAAAAQAAAAAAIiAgACIAIAAA= + Implementation\Events.cs + + + + + + AEAAAAAAAAAAAAAAgAQAAAAEAAAAAQAAgAkEAIAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAEAAAAAAAAABABAAAUAQAAAAAAAgAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAIgAAAGJACRCAAEEABEAAAAJACBAAAAAAgIAAAAAAA= + Implementation\Events.cs + + + + + + QAAAEAAAAAAAABAABABQEAQAQAAAEAAAAAAAAEAAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAgAAAAIAAAAAAAAAAAIAAAACAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + QAAAgEAACggAgAAIAAAAAEAAAIAAAAAAAAAAAAAAAII= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAIMAAAACBEAEAoQAAAKAACAAUhAAgRIQAIAE= + Implementation\GroupingParameters.cs + + + + + + bEYChOwmAAQgiCQEQBgEAMwAEAAMAEQMgEFAFODAGhM= + Implementation\Groups.cs + + + + + + AAAAgAAAJAAAAAQEABCAAAAAhAAAAACAAAAAAAIAAAE= + Implementation\Munger.cs + + + + + + AAAIACAAJAAAgAAEACAAAAAABAAAIAAAAAEAAAAAEAA= + Implementation\Munger.cs + + + + + + AAEAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAABAAA= + Implementation\Munger.cs + + + + + + cChxFKmMjlNGI/LfZWKToPLMK45gioYxDANnzL7yfN4= + Implementation\NativeMethods.cs + + + + + + AAEAAAAAAAAEAAAACAAAAAAAQAAAAAAAAAAAAAAAAAA= + Implementation\NullableDictionary.cs + + + + + + ABAAAAAAAABEAACAAAAAAAAQABAAEgAQAAIAASAAAgE= + Implementation\OLVListItem.cs + + + + + + AAAAAAAAAAAEAAAAAAAAAAAAABAIAAAQCAgACSAAAAk= + Implementation\OLVListSubItem.cs + + + + + + AAAAgEAAEAgAAABEAAZABAAGAAQAEAAAgAAAAAAIAAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + + AAAAABAAAAAAAACAAAAAAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEACAAA= + Implementation\VirtualGroups.cs + + + + + + + ABAAAAAAgAAAAAAgAAASQgAQAAAEAAAAAAAAAIAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + + AABAAAAAAAAAAAAAAABCAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + MgARTxAAJEcEWCbkoNwJbE6WTnSOEnOKQhSWGDJgsFk= + OLVColumn.cs + + + + + + AACgAIAABAAAAIABACCiAIAgAACAAgAAABAIAAAAgAE= + Rendering\Adornments.cs + + + + + + ABAAAAAAAIAAAAAAAEAAAAAAEAAAABAAAEABAAAAAAA= + Rendering\Adornments.cs + + + + + + QAIggAAEIAAgBIAIAAIASEACIABAACIIAAMACCADAsA= + Rendering\Adornments.cs + + + + + + AAEAAAAAAAABAgAAAQAABAAAAAQBAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AgAAAAAAEAAAAgAAAAAAAAAAAAAAAAAAAAAQAAIAAAA= + Rendering\Decorations.cs + + + + + + YAgAgCABAAAgA4AAAAIAgAAAAAAAAAAAAAIAACBIgAA= + Rendering\Decorations.cs + + + + + + AAAAgAAgAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAAIA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA= + Rendering\Decorations.cs + + + + + + QAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAEAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAAIAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAIAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAIAAAACAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + + AAABAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AxLAQSEQZQhhAmA5IRBAASSQUhQgkFAAgJDGAAMDE8I= + Rendering\Renderers.cs + + + + + + QAggCAEAAEAAAIAwAAKAEAIQABAAEAAAAAAAAAAKAAA= + Rendering\Renderers.cs + + + + + + AAIAEBAAAQAAAAgAABAAEAAAAAAAAAAAABAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAAQBIAAAAAAAAAAAAAAAAAAAAAAACBAAAAIAAAA= + Rendering\Renderers.cs + + + + + + AAAgAAAAAAAAAAAAAIAAAAAgIAAAAABBABAAAAAEIAA= + Rendering\Renderers.cs + + + + + + AAIAAQAAAAEAAgAAEAIAABAAAAAAAAAAIAEAACADAAA= + Rendering\Styles.cs + + + + + + + AAIAAQAAAAEAAgAAAAIAAAAAAAAAAAAAAAEAAAADAAA= + Rendering\Styles.cs + + + + + + + AAAAAAAAQAiAAAAAgAIAAAAAAAAIBAAgAAAAAAAAAAA= + Rendering\Styles.cs + + + + + + AAIAAQAAAAEAAAAAAAAAAAACACAAAgAgAAEAAAADAAA= + Rendering\Styles.cs + + + + + + AAAAAAAQAAgAAAAAAAAAAICAAIAIAAAABAAAAQAEAAA= + Rendering\Styles.cs + + + + + + BgCkgAAARAoAAEAyEAAAAAIAAAAIAhCAAQIERAgAASA= + SubControls\GlassPanelForm.cs + + + + + + MAAIOQAUABAAAACQiBQCKRgAACECAAoAwAAQxJAACaE= + SubControls\HeaderControl.cs + + + + + + AkAACAgAACCACAAAAAAAAIAAwAAIAAQCAAAAAAAAAAA= + SubControls\ToolStripCheckedListBox.cs + + + + + + CkoAByAwQQAggEvSAAIQiIWIBELAYOIpiAKQUIQDqEA= + SubControls\ToolTipControl.cs + + + + + + AAAAAEAAFDAAQTAUAACIBAoWEAAAAAAoAAAAAIEAAgA= + Utilities\ColumnSelectionForm.cs + + + + + + AAABAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAACAAAAAA= + Utilities\Generator.cs + + + + + + AAAAwABEAAAAAACIAIAQEAABEAAAAAEEggAAAAACQAA= + Utilities\TypedObjectListView.cs + + + + + + AAAACAAAAEAEAABAAEAQCAAAQAAEAEAAAAgAAAAAAAA= + Utilities\TypedObjectListView.cs + + + + + + AVkQQAAAAGIEAQAkKkHAEAgRH4gBgAGOCCEigAAgIAQ= + VirtualObjectListView.cs + + + + + + AAEAAAABACAEAQAEAAAAAAAgAQCAAAAAAAMIQAABEAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAABAAAABAAAAAAAAQAAAAAAAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAIAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAIAAAABEAAAgQAAAAAAAAAAQAIAAIg= + + + + + + AAAAAAAAAAAAAgIAAAACAAEGAAAAAEAAAAAAABAAQAA= + DataTreeListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAQAAAAAAAAAAAAAAQAgAAAAAAAAAAAAAAAAAA= + Filtering\ICluster.cs + + + + + + AAAAAAAAAAAAAAAAABBAAAAAAAAAAAQBAQAAAAAAAAA= + Filtering\IClusteringStrategy.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEAAAAA= + Implementation\VirtualGroups.cs + + + + + + ABAAAAAAAAAAAAAgAAASAgAQAAAEAAAAAAAAAAAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAQAAAAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAA= + Rendering\Styles.cs + + + + + + AAAgAAAACAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAAA= + CellEditing\CellEditKeyEngine.cs + + + + + + gAEAAAAQCAIAAAAAAIAAAAAAAUAQIABAAEAgAAAgACA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAQAAAAABAAAAAAAAAAAEAAQBBAAAAAIgAAEAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAJAAAAAAAAAAAAAIAAAAAACIEAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + AEAAAAAAAAAAABAAEAQAARAAIQAAAAQAAAAAAEAAAAA= + Implementation\Groups.cs + + + + + + AgAAgAAAwABAAAAAAAUAAAIAgQAAAAAEACAgAAAFAAA= + Implementation\Groups.cs + + + + + + AAAAAAQAAAAAAAAAAAAAAQAAAAAAEAAAAIAAAAAAAAA= + Implementation\Groups.cs + + + + + + ASAAEEAAAAAAAAQAEAAAAAAAAAAAABAAAAAACAAAEAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAEAAAAAAAAAAAAAAAAAAAQAAAABAAAAAAAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAQAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAgAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAQABgAAAAACAQAAAAAAAAAAAAAAAAAAAAAAgAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAACAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAABAAAAAAgACAAAAACAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAABAAAAAAAAAA= + Implementation\Events.cs + + + + \ No newline at end of file diff --git a/ObjectListView/Implementation/Attributes.cs b/ObjectListView/Implementation/Attributes.cs new file mode 100644 index 0000000..fd8df36 --- /dev/null +++ b/ObjectListView/Implementation/Attributes.cs @@ -0,0 +1,335 @@ +/* + * Attributes - Attributes that can be attached to properties of models to allow columns to be + * built from them directly + * + * Author: Phillip Piper + * Date: 15/08/2009 22:01 + * + * Change log: + * v2.6 + * 2012-08-16 JPP - Added [OLVChildren] and [OLVIgnore] + * - OLV attributes can now only be set on properties + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This attribute is used to mark a property of a model + /// class that should be noticed by Generator class. + /// + /// + /// All the attributes of this class match their equivalent properties on OLVColumn. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVColumnAttribute : Attribute + { + #region Constructor + + // There are several property where we actually want nullable value (bool?, int?), + // but it seems attribute properties can't be nullable types. + // So we explicitly track if those properties have been set. + + /// + /// Create a new OLVColumnAttribute + /// + public OLVColumnAttribute() { + } + + /// + /// Create a new OLVColumnAttribute with the given title + /// + /// The title of the column + public OLVColumnAttribute(string title) { + this.Title = title; + } + + #endregion + + #region Public properties + + /// + /// + /// + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// + /// + public bool CheckBoxes { + get { return checkBoxes; } + set { + checkBoxes = value; + this.IsCheckBoxesSet = true; + } + } + private bool checkBoxes; + internal bool IsCheckBoxesSet = false; + + /// + /// + /// + public int DisplayIndex { + get { return displayIndex; } + set { displayIndex = value; } + } + private int displayIndex = -1; + + /// + /// + /// + public bool FillsFreeSpace { + get { return fillsFreeSpace; } + set { fillsFreeSpace = value; } + } + private bool fillsFreeSpace; + + /// + /// + /// + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { + freeSpaceProportion = value; + IsFreeSpaceProportionSet = true; + } + } + private int freeSpaceProportion; + internal bool IsFreeSpaceProportionSet = false; + + /// + /// An array of IComparables that mark the cutoff points for values when + /// grouping on this column. + /// + public object[] GroupCutoffs { + get { return groupCutoffs; } + set { groupCutoffs = value; } + } + private object[] groupCutoffs; + + /// + /// + /// + public string[] GroupDescriptions { + get { return groupDescriptions; } + set { groupDescriptions = value; } + } + private string[] groupDescriptions; + + /// + /// + /// + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// + /// + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// + /// + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// + /// + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// + /// + public bool IsEditable { + get { return isEditable; } + set { + isEditable = value; + this.IsEditableSet = true; + } + } + private bool isEditable = true; + internal bool IsEditableSet = false; + + /// + /// + /// + public bool IsVisible { + get { return isVisible; } + set { isVisible = value; } + } + private bool isVisible = true; + + /// + /// + /// + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// + /// + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + private int maximumWidth = -1; + + /// + /// + /// + public int MinimumWidth { + get { return minimumWidth; } + set { minimumWidth = value; } + } + private int minimumWidth = -1; + + /// + /// + /// + public String Name { + get { return name; } + set { name = value; } + } + private String name; + + /// + /// + /// + public HorizontalAlignment TextAlign { + get { return this.textAlign; } + set { + this.textAlign = value; + IsTextAlignSet = true; + } + } + private HorizontalAlignment textAlign = HorizontalAlignment.Left; + internal bool IsTextAlignSet = false; + + /// + /// + /// + public String Tag { + get { return tag; } + set { tag = value; } + } + private String tag; + + /// + /// + /// + public String Title { + get { return title; } + set { title = value; } + } + private String title; + + /// + /// + /// + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// + /// + public bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + this.IsTriStateCheckBoxesSet = true; + } + } + private bool triStateCheckBoxes; + internal bool IsTriStateCheckBoxesSet = false; + + /// + /// + /// + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// + /// + public int Width { + get { return width; } + set { width = value; } + } + private int width = 150; + + #endregion + } + + /// + /// Properties marked with [OLVChildren] will be used as the children source in a TreeListView. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVChildrenAttribute : Attribute + { + + } + + /// + /// Properties marked with [OLVIgnore] will not have columns generated for them. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVIgnoreAttribute : Attribute + { + + } +} diff --git a/ObjectListView/Implementation/Comparers.cs b/ObjectListView/Implementation/Comparers.cs new file mode 100644 index 0000000..1ec33d0 --- /dev/null +++ b/ObjectListView/Implementation/Comparers.cs @@ -0,0 +1,330 @@ +/* + * Comparers - Various Comparer classes used within ObjectListView + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * v2.8.1 + * 2014-12-03 JPP - Added StringComparer + * v2.3 + * 2009-08-24 JPP - Added OLVGroupComparer + * 2009-06-01 JPP - ModelObjectComparer would crash if secondary sort column was null. + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-11-25 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// ColumnComparer is the workhorse for all comparison between two values of a particular column. + /// If the column has a specific comparer, use that to compare the values. Otherwise, do + /// a case insensitive string compare of the string representations of the values. + /// + /// This class inherits from both IComparer and its generic counterpart + /// so that it can be used on untyped and typed collections. + /// This is used by normal (non-virtual) ObjectListViews. Virtual lists use + /// ModelObjectComparer + /// + public class ColumnComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column + /// + /// The column whose values will be compared + /// The ordering for column values + public ColumnComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column, and by a secondary column if the primary + /// column is equal. + /// + /// The column whose values will be compared + /// The ordering for column values + /// The column whose values will be compared for secondary sorting + /// The ordering for secondary column values + public ColumnComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2) + this.secondComparer = new ColumnComparer(col2, order2); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(object x, object y) + { + return this.Compare((OLVListItem)x, (OLVListItem)y); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVListItem x, OLVListItem y) + { + if (this.sortOrder == SortOrder.None) + return 0; + + int result = 0; + object x1 = this.column.GetValue(x.RowObject); + object y1 = this.column.GetValue(y.RowObject); + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values to be used for sorting + /// + /// The aspect extracted from the first row + /// The aspect extracted from the second row + /// An ordering indication: -1, 0, 1 + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xAsString = x as String; + if (xAsString != null) + return CompareStrings(xAsString, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ColumnComparer secondComparer; + } + + + /// + /// This comparer sort list view groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + public class OLVGroupComparer : IComparer + { + /// + /// Create a group comparer + /// + /// The ordering for column values + public OLVGroupComparer(SortOrder order) { + this.sortOrder = order; + } + + /// + /// Compare the two groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + /// group1 + /// group2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVGroup x, OLVGroup y) { + // If we can compare the sort values, do that. + // Otherwise do a case insensitive compare on the group header. + int result; + if (x.SortValue != null && y.SortValue != null) + result = x.SortValue.CompareTo(y.SortValue); + else + result = String.Compare(x.Header, y.Header, StringComparison.CurrentCultureIgnoreCase); + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + return result; + } + + private SortOrder sortOrder; + } + + /// + /// This comparer can be used to sort a collection of model objects by a given column + /// + /// + /// This is used by virtual ObjectListViews. Non-virtual lists use + /// ColumnComparer + /// + public class ModelObjectComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a model object comparer + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a model object comparer with a secondary sorting column + /// + /// + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2 && col2 != null && order2 != SortOrder.None) + this.secondComparer = new ModelObjectComparer(col2, order2); + } + + /// + /// Compare the two model objects + /// + /// + /// + /// + public int Compare(object x, object y) + { + int result = 0; + object x1 = this.column.GetValue(x); + object y1 = this.column.GetValue(y); + + if (this.sortOrder == SortOrder.None) + return 0; + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values + /// + /// + /// + /// + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xStr = x as String; + if (xStr != null) + return CompareStrings(xStr, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ModelObjectComparer secondComparer; + + #region IComparer Members + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/Implementation/DataSourceAdapter.cs b/ObjectListView/Implementation/DataSourceAdapter.cs new file mode 100644 index 0000000..80f6da3 --- /dev/null +++ b/ObjectListView/Implementation/DataSourceAdapter.cs @@ -0,0 +1,628 @@ +/* + * DataSourceAdapter - A helper class that translates DataSource events for an ObjectListView + * + * Author: Phillip Piper + * Date: 20/09/2010 7:42 AM + * + * Change log: + * 2018-04-30 JPP - Sanity check upper limit against CurrencyManager rather than ListView just in + * case the CurrencyManager has gotten ahead of the ListView's contents. + * v2.9 + * 2015-10-31 JPP - Put back sanity check on upper limit of source items + * 2015-02-02 JPP - Made CreateColumnsFromSource() only rebuild columns when new ones were added + * v2.8.1 + * 2014-11-23 JPP - Honour initial CurrencyManager.Position when setting DataSource. + * 2014-10-27 JPP - Fix issue where SelectedObject was not sync'ed with CurrencyManager.Position (SF #129) + * v2.6 + * 2012-08-16 JPP - Unify common column creation functionality with Generator when possible + * + * 2010-09-20 JPP - Initial version + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Data; +using System.Windows.Forms; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A helper class that translates DataSource events for an ObjectListView + /// + public class DataSourceAdapter : IDisposable + { + #region Life and death + + /// + /// Make a DataSourceAdapter + /// + public DataSourceAdapter(ObjectListView olv) { + if (olv == null) throw new ArgumentNullException("olv"); + + this.ListView = olv; + // ReSharper disable once DoNotCallOverridableMethodsInConstructor + this.BindListView(this.ListView); + } + + /// + /// Finalize this object + /// + ~DataSourceAdapter() { + this.Dispose(false); + } + + /// + /// Release all the resources used by this instance + /// + public void Dispose() { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Release all the resources used by this instance + /// + public virtual void Dispose(bool fromUser) { + this.UnbindListView(this.ListView); + this.UnbindDataSource(); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + public bool AutoGenerateColumns { + get { return this.autoGenerateColumns; } + set { this.autoGenerateColumns = value; } + } + private bool autoGenerateColumns = true; + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + public virtual Object DataSource { + get { return dataSource; } + set { + dataSource = value; + this.RebindDataSource(true); + } + } + private Object dataSource; + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + public virtual string DataMember { + get { return dataMember; } + set { + if (dataMember != value) { + dataMember = value; + RebindDataSource(); + } + } + } + private string dataMember = ""; + + /// + /// Gets the ObjectListView upon which this adaptor will operate + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the currency manager which is handling our binding context + /// + protected CurrencyManager CurrencyManager { + get { return currencyManager; } + set { currencyManager = value; } + } + private CurrencyManager currencyManager; + + #endregion + + #region Binding and unbinding + + /// + /// + /// + /// + protected virtual void BindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing += new EventHandler(HandleListViewFreezing); + olv.SelectionChanged += new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged += new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + /// + protected virtual void UnbindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing -= new EventHandler(HandleListViewFreezing); + olv.SelectionChanged -= new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged -= new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + protected virtual void BindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged += new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged += new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged += new ListChangedEventHandler(CurrencyManagerListChanged); + } + + /// + /// + /// + protected virtual void UnbindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged -= new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged -= new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged -= new ListChangedEventHandler(CurrencyManagerListChanged); + } + + #endregion + + #region Initialization + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource() { + RebindDataSource(false); + } + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource(bool forceDataInitialization) { + + CurrencyManager tempCurrencyManager = null; + if (this.ListView != null && this.ListView.BindingContext != null && this.DataSource != null) { + tempCurrencyManager = this.ListView.BindingContext[this.DataSource, this.DataMember] as CurrencyManager; + } + + // Has our currency manager changed? + if (this.CurrencyManager != tempCurrencyManager) { + this.UnbindDataSource(); + this.CurrencyManager = tempCurrencyManager; + this.BindDataSource(); + + // Our currency manager has changed so we have to initialize a new data source + forceDataInitialization = true; + } + + if (forceDataInitialization) + InitializeDataSource(); + } + + /// + /// The data source for this control has changed. Reconfigure the control for the new source + /// + protected virtual void InitializeDataSource() { + if (this.ListView.Frozen || this.CurrencyManager == null) + return; + + this.CreateColumnsFromSource(); + this.CreateMissingAspectGettersAndPutters(); + this.SetListContents(); + this.ListView.AutoSizeColumns(); + + // Fake a position change event so that the control matches any initial Position + this.HandleCurrencyManagerPositionChanged(null, null); + } + + /// + /// Take the contents of the currently bound list and put them into the control + /// + protected virtual void SetListContents() { + this.ListView.Objects = this.CurrencyManager.List; + } + + /// + /// Create columns for the listview based on what properties are available in the data source + /// + /// + /// This method will create columns if there is not already a column displaying that property. + /// + protected virtual void CreateColumnsFromSource() { + if (this.CurrencyManager == null) + return; + + // Don't generate any columns in design mode. If we do, the user will see them, + // but the Designer won't know about them and won't persist them, which is very confusing + if (this.ListView.IsDesignMode) + return; + + // Don't create columns if we've been told not to + if (!this.AutoGenerateColumns) + return; + + // Use a Generator to create columns + Generator generator = Generator.Instance as Generator ?? new Generator(); + + PropertyDescriptorCollection properties = this.CurrencyManager.GetItemProperties(); + if (properties.Count == 0) + return; + + bool wereColumnsAdded = false; + foreach (PropertyDescriptor property in properties) { + + if (!this.ShouldCreateColumn(property)) + continue; + + // Create a column + OLVColumn column = generator.MakeColumnFromPropertyDescriptor(property); + this.ConfigureColumn(column, property); + + // Add it to our list + this.ListView.AllColumns.Add(column); + wereColumnsAdded = true; + } + + if (wereColumnsAdded) + generator.PostCreateColumns(this.ListView); + } + + /// + /// Decide if a new column should be added to the control to display + /// the given property + /// + /// + /// + protected virtual bool ShouldCreateColumn(PropertyDescriptor property) { + + // Is there a column that already shows this property? If so, we don't show it again + if (this.ListView.AllColumns.Exists(delegate(OLVColumn x) { return x.AspectName == property.Name; })) + return false; + + // Relationships to other tables turn up as IBindibleLists. Don't make columns to show them. + // CHECK: Is this always true? What other things could be here? Constraints? Triggers? + if (property.PropertyType == typeof(IBindingList)) + return false; + + // Ignore anything marked with [OLVIgnore] + return property.Attributes[typeof(OLVIgnoreAttribute)] == null; + } + + /// + /// Configure the given column to show the given property. + /// The title and aspect name of the column are already filled in. + /// + /// + /// + protected virtual void ConfigureColumn(OLVColumn column, PropertyDescriptor property) { + + column.LastDisplayIndex = this.ListView.AllColumns.Count; + + // If our column is a BLOB, it could be an image, so assign a renderer to draw it. + // CONSIDER: Is this a common enough case to warrant this code? + if (property.PropertyType == typeof(System.Byte[])) + column.Renderer = new ImageRenderer(); + } + + /// + /// Generate aspect getters and putters for any columns that are missing them (and for which we have + /// enough information to actually generate a getter) + /// + protected virtual void CreateMissingAspectGettersAndPutters() { + foreach (OLVColumn x in this.ListView.AllColumns) { + OLVColumn column = x; // stack based variable accessible from closures + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectGetter = delegate(object row) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + return column.GetAspectByName(row); + return (drv.Row.RowState == DataRowState.Detached) ? null : drv[column.AspectName]; + }; + } + if (column.IsEditable && column.AspectPutter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectPutter = delegate(object row, object newValue) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + column.PutAspectByName(row, newValue); + else { + if (drv.Row.RowState != DataRowState.Detached) + drv[column.AspectName] = newValue; + } + }; + } + } + } + + #endregion + + #region Event Handlers + + /// + /// CurrencyManager ListChanged event handler. + /// Deals with fine-grained changes to list items. + /// + /// + /// It's actually difficult to deal with these changes in a fine-grained manner. + /// If our listview is grouped, then any change may make a new group appear or + /// an old group disappear. It is rarely enough to simply update the affected row. + /// + /// + /// + protected virtual void CurrencyManagerListChanged(object sender, ListChangedEventArgs e) { + Debug.Assert(sender == this.CurrencyManager); + + // Ignore changes make while frozen, since we will do a complete rebuild when we unfreeze + if (this.ListView.Frozen) + return; + + //System.Diagnostics.Debug.WriteLine(e.ListChangedType); + Stopwatch sw = Stopwatch.StartNew(); + switch (e.ListChangedType) { + + case ListChangedType.Reset: + this.HandleListChangedReset(e); + break; + + case ListChangedType.ItemChanged: + this.HandleListChangedItemChanged(e); + break; + + case ListChangedType.ItemAdded: + this.HandleListChangedItemAdded(e); + break; + + // An item has gone away. + case ListChangedType.ItemDeleted: + this.HandleListChangedItemDeleted(e); + break; + + // An item has changed its index. + case ListChangedType.ItemMoved: + this.HandleListChangedItemMoved(e); + break; + + // Something has changed in the metadata. + // CHECK: When are these events actually fired? + case ListChangedType.PropertyDescriptorAdded: + case ListChangedType.PropertyDescriptorChanged: + case ListChangedType.PropertyDescriptorDeleted: + this.HandleListChangedMetadataChanged(e); + break; + } + sw.Stop(); + System.Diagnostics.Debug.WriteLine(String.Format("PERF - Processing {0} event on {1} rows took {2}ms", e.ListChangedType, this.ListView.GetItemCount(), sw.ElapsedMilliseconds)); + + } + + /// + /// Handle PropertyDescriptor* events + /// + /// + protected virtual void HandleListChangedMetadataChanged(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle ItemMoved event + /// + /// + protected virtual void HandleListChangedItemMoved(ListChangedEventArgs e) { + // When is this actually triggered? + this.InitializeDataSource(); + } + + /// + /// Handle the ItemDeleted event + /// + /// + protected virtual void HandleListChangedItemDeleted(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle an ItemAdded event. + /// + /// + protected virtual void HandleListChangedItemAdded(ListChangedEventArgs e) { + // We get this event twice if certain grid controls are used to add a new row to a + // datatable: once when the editing of a new row begins, and once again when that + // editing commits. (If the user cancels the creation of the new row, we never see + // the second creation.) We detect this by seeing if this is a view on a row in a + // DataTable, and if it is, testing to see if it's a new row under creation. + + Object newRow = this.CurrencyManager.List[e.NewIndex]; + DataRowView drv = newRow as DataRowView; + if (drv == null || !drv.IsNew) { + // Either we're not dealing with a view on a data table, or this is the commit + // notification. Either way, this is the final notification, so we want to + // handle the new row now! + this.InitializeDataSource(); + } + } + + /// + /// Handle the Reset event + /// + /// + protected virtual void HandleListChangedReset(ListChangedEventArgs e) { + // The whole list has changed utterly, so reload it. + this.InitializeDataSource(); + } + + /// + /// Handle ItemChanged event. This is triggered when a single item + /// has changed, so just refresh that one item. + /// + /// + /// Even in this simple case, we should probably rebuild the list. + /// For example, the change could put the item into its own new group. + protected virtual void HandleListChangedItemChanged(ListChangedEventArgs e) { + // A single item has changed, so just refresh that. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleListChangedItemChanged: {0}, {1}", e.NewIndex, e.PropertyDescriptor.Name)); + + Object changedRow = this.CurrencyManager.List[e.NewIndex]; + this.ListView.RefreshObject(changedRow); + } + + /// + /// The CurrencyManager calls this if the data source looks + /// different. We just reload everything. + /// + /// + /// + /// + /// CHECK: Do we need this if we are handle ListChanged metadata events? + /// + protected virtual void HandleCurrencyManagerMetaDataChanged(object sender, EventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Called by the CurrencyManager when the currently selected item + /// changes. We update the ListView selection so that we stay in sync + /// with any other controls bound to the same source. + /// + /// + /// + protected virtual void HandleCurrencyManagerPositionChanged(object sender, EventArgs e) { + int index = this.CurrencyManager.Position; + + // Make sure the index is sane (-1 pops up from time to time) + if (index < 0 || index >= this.CurrencyManager.Count) + return; + + // Avoid recursion. If we are currently changing the index, don't + // start the process again. + if (this.isChangingIndex) + return; + + try { + this.isChangingIndex = true; + this.ChangePosition(index); + } + finally { + this.isChangingIndex = false; + } + } + private bool isChangingIndex = false; + + /// + /// Change the control's position (which is it's currently selected row) + /// to the nth row in the dataset + /// + /// The index of the row to be selected + protected virtual void ChangePosition(int index) { + // We can't use the index directly, since our listview may be sorted + this.ListView.SelectedObject = this.CurrencyManager.List[index]; + + // THINK: Do we always want to bring it into view? + if (this.ListView.SelectedIndices.Count > 0) + this.ListView.EnsureVisible(this.ListView.SelectedIndices[0]); + } + + #endregion + + #region ObjectListView event handlers + + /// + /// Handle the selection changing in our ListView. + /// We need to tell our currency manager about the new position. + /// + /// + /// + protected virtual void HandleListViewSelectionChanged(object sender, EventArgs e) { + // Prevent recursion + if (this.isChangingIndex) + return; + + // Sanity + if (this.CurrencyManager == null) + return; + + // If only one item is selected, tell the currency manager which item is selected. + // CurrencyManager can't handle multiple selection so there's nothing we can do + // if more than one row is selected. + if (this.ListView.SelectedIndices.Count != 1) + return; + + try { + this.isChangingIndex = true; + + // We can't use the selectedIndex directly, since our listview may be sorted and/or filtered + // So we have to find the index of the selected object within the original list. + this.CurrencyManager.Position = this.CurrencyManager.List.IndexOf(this.ListView.SelectedObject); + } finally { + this.isChangingIndex = false; + } + } + + /// + /// Handle the frozenness of our ListView changing. + /// + /// + /// + protected virtual void HandleListViewFreezing(object sender, FreezeEventArgs e) { + if (!alreadyFreezing && e.FreezeLevel == 0) { + try { + alreadyFreezing = true; + this.RebindDataSource(true); + } finally { + alreadyFreezing = false; + } + } + } + private bool alreadyFreezing = false; + + /// + /// Handle a change to the BindingContext of our ListView. + /// + /// + /// + protected virtual void HandleListViewBindingContextChanged(object sender, EventArgs e) { + this.RebindDataSource(false); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/Delegates.cs b/ObjectListView/Implementation/Delegates.cs new file mode 100644 index 0000000..52da366 --- /dev/null +++ b/ObjectListView/Implementation/Delegates.cs @@ -0,0 +1,168 @@ +/* + * Delegates - All delegate definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * v2.10 + * 2015-12-30 JPP - Added CellRendererGetterDelegate + * v2.? + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + #region Delegate declarations + + /// + /// These delegates are used to extract an aspect from a row object + /// + public delegate Object AspectGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed value back into a model object + /// + public delegate void AspectPutterDelegate(Object rowObject, Object newValue); + + /// + /// These delegates can be used to convert an aspect value to a display string, + /// instead of using the default ToString() + /// + public delegate string AspectToStringConverterDelegate(Object value); + + /// + /// These delegates are used to get the tooltip for a cell + /// + public delegate String CellToolTipGetterDelegate(OLVColumn column, Object modelObject); + + /// + /// These delegates are used to the state of the checkbox for a row object. + /// + /// + /// For reasons known only to someone in Microsoft, we can only set + /// a boolean on the ListViewItem to indicate it's "checked-ness", but when + /// we receive update events, we have to use a tristate CheckState. So we can + /// be told about an indeterminate state, but we can't set it ourselves. + /// + /// As of version 2.0, we can now return indeterminate state. + /// + public delegate CheckState CheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to get the state of the checkbox for a row object. + /// + /// + /// + public delegate bool BooleanCheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + public delegate CheckState CheckStatePutterDelegate(Object rowObject, CheckState newValue); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + /// + /// + /// + public delegate bool BooleanCheckStatePutterDelegate(Object rowObject, bool newValue); + + /// + /// These delegates are used to get the renderer for a particular cell + /// + public delegate IRenderer CellRendererGetterDelegate(Object rowObject, OLVColumn column); + + /// + /// The callbacks for RightColumnClick events + /// + public delegate void ColumnRightClickEventHandler(object sender, ColumnClickEventArgs e); + + /// + /// This delegate will be used to own draw header column. + /// + public delegate bool HeaderDrawingDelegate(Graphics g, Rectangle r, int columnIndex, OLVColumn column, bool isPressed, HeaderStateStyle stateStyle); + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + public delegate void GroupFormatterDelegate(OLVGroup group, GroupingParameters parms); + + /// + /// These delegates are used to retrieve the object that is the key of the group to which the given row belongs. + /// + public delegate Object GroupKeyGetterDelegate(Object rowObject); + + /// + /// These delegates are used to convert a group key into a title for the group + /// + public delegate string GroupKeyToTitleConverterDelegate(Object groupKey); + + /// + /// These delegates are used to get the tooltip for a column header + /// + public delegate String HeaderToolTipGetterDelegate(OLVColumn column); + + /// + /// These delegates are used to fetch the image selector that should be used + /// to choose an image for this column. + /// + public delegate Object ImageGetterDelegate(Object rowObject); + + /// + /// These delegates are used to draw a cell + /// + public delegate bool RenderDelegate(EventArgs e, Graphics g, Rectangle r, Object rowObject); + + /// + /// These delegates are used to fetch a row object for virtual lists + /// + public delegate Object RowGetterDelegate(int rowIndex); + + /// + /// These delegates are used to format a listviewitem before it is added to the control. + /// + public delegate void RowFormatterDelegate(OLVListItem olvItem); + + /// + /// These delegates can be used to return the array of texts that should be searched for text filtering + /// + public delegate string[] SearchValueGetterDelegate(Object value); + + /// + /// These delegates are used to sort the listview in some custom fashion + /// + public delegate void SortDelegate(OLVColumn column, SortOrder sortOrder); + + /// + /// These delegates are used to order two strings. + /// x cannot be null. y can be null. + /// + public delegate int StringCompareDelegate(string x, string y); + + #endregion +} diff --git a/ObjectListView/Implementation/DragSource.cs b/ObjectListView/Implementation/DragSource.cs new file mode 100644 index 0000000..f0f4783 --- /dev/null +++ b/ObjectListView/Implementation/DragSource.cs @@ -0,0 +1,407 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * UNFINISHED + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All opertions are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshe the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + OLVDataObject data = new OLVDataObject(olv); + data.CreateTextFormats(); + return data; + } + + #endregion + } + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject + { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders + { + get { return includeColumnHeaders; } + } + private bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + // Build text and html versions of the selection + StringBuilder sbText = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (includeColumnHeaders) + { + sbHtml.Append(""); + } + + foreach (object modelObject in this.ModelObjects) + { + sbHtml.Append(""); + } + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) + { + if (col != columns[0]) + { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.Text; + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
      "); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(sbText.ToString()); + this.SetText(ConvertToHtmlFragment(sbHtml.ToString()), TextDataFormat.Html); + } + + /// + /// Make a HTML representation of our model objects + /// + public string CreateHtml() { + IList columns = this.ListView.ColumnsInDisplayOrder; + + // Build html version of the selection + StringBuilder sbHtml = new StringBuilder(""); + + foreach (object modelObject in this.ModelObjects) { + sbHtml.Append(""); + } + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbHtml.AppendLine("
      "); + + return sbHtml.ToString(); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognized as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + string source = "http://www.codeproject.com/KB/list/ObjectListView.aspx"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, source, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, source, html); + } + } +} diff --git a/ObjectListView/Implementation/DropSink.cs b/ObjectListView/Implementation/DropSink.cs new file mode 100644 index 0000000..03818d8 --- /dev/null +++ b/ObjectListView/Implementation/DropSink.cs @@ -0,0 +1,1402 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2010 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target (not currently used) + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target (not currently used) + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. + /// + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continune while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + //ListViewHitTestInfo info = this.ListView.HitTest(pt.X, pt.Y); + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined) + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + // If the mouse is over an item, check to see if it is near the top or bottom + if (location == DropTargetLocation.Item) { + if (pt.Y - SMALL_VALUE <= info.Item.Bounds.Top) + location = DropTargetLocation.AboveItem; + if (pt.Y + SMALL_VALUE >= info.Item.Bounds.Bottom) + location = DropTargetLocation.BelowItem; + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width; + r.X += (indentWidth * item.IndentCount); + r.Width -= (indentWidth * item.IndentCount); + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + int x = x1; + int y = y1; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 5, + x, y - 5); + gp.AddBezier( + x, y - 6, + x + 3, y - 2, + x + 6, y - 1, + x + 11, y); + gp.AddBezier( + x + 11, y, + x + 6, y + 1, + x + 3, y + 2, + x, y + 6); + gp.CloseFigure(); + g.FillPath(b, gp); + } + x = x2; + y = y2; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 6, + x, y - 6); + gp.AddBezier( + x, y - 7, + x - 3, y - 2, + x - 6, y - 1, + x - 11, y); + gp.AddBezier( + x - 11, y, + x - 6, y + 1, + x - 3, y + 2, + x, y + 7); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amonst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging a list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occured, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the data object that is being dragged + /// + public object DataObject { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + toBeRefreshed.AddRange(this.SourceModels); + if (this.ListView == this.SourceListView) { + toBeRefreshed.Add(this.TargetModel); + this.ListView.RefreshObjects(toBeRefreshed); + } else { + this.SourceListView.RefreshObjects(toBeRefreshed); + this.ListView.RefreshObject(this.TargetModel); + } + } + } +} diff --git a/ObjectListView/Implementation/Enums.cs b/ObjectListView/Implementation/Enums.cs new file mode 100644 index 0000000..572b4b4 --- /dev/null +++ b/ObjectListView/Implementation/Enums.cs @@ -0,0 +1,104 @@ +/* + * Enums - All enum definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + public partial class ObjectListView { + /// + /// How does a user indicate that they want to edit cells? + /// + public enum CellEditActivateMode { + /// + /// This list cannot be edited. F2 does nothing. + /// + None = 0, + + /// + /// A single click on a subitem will edit the value. Single clicking the primary column, + /// selects the row just like normal. The user must press F2 to edit the primary column. + /// + SingleClick = 1, + + /// + /// Double clicking a subitem or the primary column will edit that cell. + /// F2 will edit the primary column. + /// + DoubleClick = 2, + + /// + /// Pressing F2 is the only way to edit the cells. Once the primary column is being edited, + /// the other cells in the row can be edited by pressing Tab. + /// + F2Only = 3, + + /// + /// A single click on a any cell will edit the value, even the primary column. + /// + SingleClickAlways = 4, + } + + /// + /// These values specify how column selection will be presented to the user + /// + public enum ColumnSelectBehaviour { + /// + /// No column selection will be presented + /// + None, + + /// + /// The columns will be show in the main menu + /// + InlineMenu, + + /// + /// The columns will be shown in a submenu + /// + Submenu, + + /// + /// A model dialog will be presented to allow the user to choose columns + /// + ModelDialog, + + /* + * NonModelDialog is just a little bit tricky since the OLV can change views while the dialog is showing + * So, just comment this out for the time being. + + /// + /// A non-model dialog will be presented to allow the user to choose columns + /// + NonModelDialog + * + */ + } + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/Events.cs b/ObjectListView/Implementation/Events.cs new file mode 100644 index 0000000..7a1c466 --- /dev/null +++ b/ObjectListView/Implementation/Events.cs @@ -0,0 +1,2514 @@ +/* + * Events - All the events that can be triggered within an ObjectListView. + * + * Author: Phillip Piper + * Date: 17/10/2008 9:15 PM + * + * Change log: + * v2.8.0 + * 2014-05-20 JPP - Added IsHyperlinkEventArgs.IsHyperlink + * v2.6 + * 2012-04-17 JPP - Added group state change and group expansion events + * v2.5 + * 2010-08-08 JPP - CellEdit validation and finish events now have NewValue property. + * v2.4 + * 2010-03-04 JPP - Added filtering events + * v2.3 + * 2009-08-16 JPP - Added group events + * 2009-08-08 JPP - Added HotItem event + * 2009-07-24 JPP - Added Hyperlink events + * - Added Formatting events + * v2.2.1 + * 2009-06-13 JPP - Added Cell events + * - Moved all event parameter blocks to this file. + * - Added Handled property to AfterSearchEventArgs + * v2.2 + * 2009-06-01 JPP - Added ColumnToGroupBy and GroupByOrder to sorting events + - Gave all event descriptions + * 2009-04-23 JPP - Added drag drop events + * v2.1 + * 2009-01-18 JPP - Moved SelectionChanged event to this file + * v2.0 + * 2008-12-06 JPP - Added searching events + * 2008-12-01 JPP - Added secondary sort information to Before/AfterSorting events + * 2008-10-17 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + /// + /// The callbacks for CellEditing events + /// + /// this + /// We could replace this with EventHandler<CellEditEventArgs> but that would break all + /// cell editing event code from v1.x. + /// + public delegate void CellEditEventHandler(object sender, CellEditEventArgs e); + + public partial class ObjectListView { + //----------------------------------------------------------------------------------- + + #region Events + + /// + /// Triggered after a ObjectListView has been searched by the user typing into the list + /// + [Category("ObjectListView"), + Description("This event is triggered after the control has done a search-by-typing action.")] + public event EventHandler AfterSearching; + + /// + /// Triggered after a ObjectListView has been sorted + /// + [Category("ObjectListView"), + Description("This event is triggered after the items in the list have been sorted.")] + public event EventHandler AfterSorting; + + /// + /// Triggered before a ObjectListView is searched by the user typing into the list + /// + /// + /// Set Cancelled to true to prevent the searching from taking place. + /// Changing StringToFind or StartSearchFrom will change the subsequent search. + /// + [Category("ObjectListView"), + Description("This event is triggered before the control does a search-by-typing action.")] + public event EventHandler BeforeSearching; + + /// + /// Triggered before a ObjectListView is sorted + /// + /// + /// Set Cancelled to true to prevent the sort from taking place. + /// Changing ColumnToSort or SortOrder will change the subsequent sort. + /// + [Category("ObjectListView"), + Description("This event is triggered before the items in the list are sorted.")] + public event EventHandler BeforeSorting; + + /// + /// Triggered after a ObjectListView has created groups + /// + [Category("ObjectListView"), + Description("This event is triggered after the groups are created.")] + public event EventHandler AfterCreatingGroups; + + /// + /// Triggered before a ObjectListView begins to create groups + /// + /// + /// Set Groups to prevent the default group creation process + /// + [Category("ObjectListView"), + Description("This event is triggered before the groups are created.")] + public event EventHandler BeforeCreatingGroups; + + /// + /// Triggered just before a ObjectListView creates groups + /// + /// + /// You can make changes to the groups, which have been created, before those + /// groups are created within the listview. + /// + [Category("ObjectListView"), + Description("This event is triggered when the groups are just about to be created.")] + public event EventHandler AboutToCreateGroups; + + /// + /// Triggered when a button in a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a button.")] + public event EventHandler ButtonClick; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the user drop the currently dragged items at the current mouse location?")] + public event EventHandler CanDrop; + + /// + /// Triggered when a cell has finished being edited. + /// + [Category("ObjectListView"), + Description("This event is triggered cell edit operation has completely finished")] + public event CellEditEventHandler CellEditFinished; + + /// + /// Triggered when a cell is about to finish being edited. + /// + /// If Cancel is already true, the user is cancelling the edit operation. + /// Set Cancel to true to prevent the value from the cell being written into the model. + /// You cannot prevent the editing from finishing within this event -- you need + /// the CellEditValidating event for that. + [Category("ObjectListView"), + Description("This event is triggered cell edit operation is finishing.")] + public event CellEditEventHandler CellEditFinishing; + + /// + /// Triggered when a cell is about to be edited. + /// + /// Set Cancel to true to prevent the cell being edited. + /// You can change the Control to be something completely different. + [Category("ObjectListView"), + Description("This event is triggered when cell edit is about to begin.")] + public event CellEditEventHandler CellEditStarting; + + /// + /// Triggered when a cell editor needs to be validated + /// + /// + /// If this event is cancelled, focus will remain on the cell editor. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell editor is about to lose focus and its new contents need to be validated.")] + public event CellEditEventHandler CellEditValidating; + + /// + /// Triggered when a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a cell.")] + public event EventHandler CellClick; + + /// + /// Triggered when the mouse is above a cell. + /// + [Category("ObjectListView"), + Description("This event is triggered when the mouse is over a cell.")] + public event EventHandler CellOver; + + /// + /// Triggered when a cell is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a cell.")] + public event EventHandler CellRightClick; + + /// + /// This event is triggered when a cell needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs a tool tip.")] + public event EventHandler CellToolTipShowing; + + /// + /// This event is triggered when a checkbox is checked/unchecked on a subitem + /// + [Category("ObjectListView"), + Description("This event is triggered when a checkbox is checked/unchecked on a subitem.")] + public event EventHandler SubItemChecking; + + /// + /// Triggered when a column header is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a column header.")] + public event ColumnRightClickEventHandler ColumnRightClick; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user dropped items onto the control.")] + public event EventHandler Dropped; + + /// + /// This event is triggered when the control needs to filter its collection of objects. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to filter its collection of objects.")] + public event EventHandler Filter; + + /// + /// This event is triggered when a cell needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs to be formatted.")] + public event EventHandler FormatCell; + + /// + /// This event is triggered when the frozenness of the control changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when frozenness of the control changes.")] + public event EventHandler Freezing; + + /// + /// This event is triggered when a row needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a row needs to be formatted.")] + public event EventHandler FormatRow; + + /// + /// This event is triggered when a group is about to collapse or expand. + /// This can be cancelled to prevent the expansion. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group is about to collapse or expand.")] + public event EventHandler GroupExpandingCollapsing; + + /// + /// This event is triggered when a group changes state. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group changes state.")] + public event EventHandler GroupStateChanged; + + /// + /// This event is triggered when a header checkbox is changing value + /// + [Category("ObjectListView"), + Description("This event is triggered when a header checkbox changes value.")] + public event EventHandler HeaderCheckBoxChanging; + + /// + /// This event is triggered when a header needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a header needs a tool tip.")] + public event EventHandler HeaderToolTipShowing; + + /// + /// Triggered when the "hot" item changes + /// + [Category("ObjectListView"), + Description("This event is triggered when the hot item changed.")] + public event EventHandler HotItemChanged; + + /// + /// Triggered when a hyperlink cell is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when a hyperlink cell is clicked.")] + public event EventHandler HyperlinkClicked; + + /// + /// Triggered when the task text of a group is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the task text of a group is clicked.")] + public event EventHandler GroupTaskClicked; + + /// + /// Is the value in the given cell a hyperlink. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to know if a given cell contains a hyperlink.")] + public event EventHandler IsHyperlink; + + /// + /// Some new objects are about to be added to an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are about to be added to the control")] + public event EventHandler ItemsAdding; + + /// + /// The contents of the ObjectListView has changed. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control have changed.")] + public event EventHandler ItemsChanged; + + /// + /// The contents of the ObjectListView is about to change via a SetObjects call + /// + /// + /// Set Cancelled to true to prevent the contents of the list changing. This does not work with virtual lists. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control changes.")] + public event EventHandler ItemsChanging; + + /// + /// Some objects are about to be removed from an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are removed from the control.")] + public event EventHandler ItemsRemoving; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler, and when the source control + /// for the drag was an ObjectListView. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the dragged collection of model objects be dropped at the current mouse location")] + public event EventHandler ModelCanDrop; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler and when the source control + /// for the drag was an ObjectListView. + /// + [Category("ObjectListView"), + Description("A collection of model objects from a ObjectListView has been dropped on this control")] + public event EventHandler ModelDropped; + + /// + /// This event is triggered once per user action that changes the selection state + /// of one or more rows. + /// + [Category("ObjectListView"), + Description("This event is triggered once per user action that changes the selection state of one or more rows.")] + public event EventHandler SelectionChanged; + + /// + /// This event is triggered when the contents of the ObjectListView has scrolled. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the ObjectListView has scrolled.")] + public event EventHandler Scroll; + + #endregion + + //----------------------------------------------------------------------------------- + + #region OnEvents + + /// + /// + /// + /// + protected virtual void OnAboutToCreateGroups(CreateGroupsEventArgs e) { + if (this.AboutToCreateGroups != null) + this.AboutToCreateGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeCreatingGroups(CreateGroupsEventArgs e) { + if (this.BeforeCreatingGroups != null) + this.BeforeCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterCreatingGroups(CreateGroupsEventArgs e) { + if (this.AfterCreatingGroups != null) + this.AfterCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSearching(AfterSearchingEventArgs e) { + if (this.AfterSearching != null) + this.AfterSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSorting(AfterSortingEventArgs e) { + if (this.AfterSorting != null) + this.AfterSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSearching(BeforeSearchingEventArgs e) { + if (this.BeforeSearching != null) + this.BeforeSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSorting(BeforeSortingEventArgs e) { + if (this.BeforeSorting != null) + this.BeforeSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnButtonClick(CellClickEventArgs args) { + if (this.ButtonClick != null) + this.ButtonClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellClick(CellClickEventArgs args) { + if (this.CellClick != null) + this.CellClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellOver(CellOverEventArgs args) { + if (this.CellOver != null) + this.CellOver(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellRightClick(CellRightClickEventArgs args) { + if (this.CellRightClick != null) + this.CellRightClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellToolTip(ToolTipShowingEventArgs args) { + if (this.CellToolTipShowing != null) + this.CellToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSubItemChecking(SubItemCheckingEventArgs args) { + if (this.SubItemChecking != null) + this.SubItemChecking(this, args); + } + + /// + /// + /// + /// + protected virtual void OnColumnRightClick(ColumnRightClickEventArgs e) { + if (this.ColumnRightClick != null) + this.ColumnRightClick(this, e); + } + + /// + /// + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// + /// + /// + internal protected virtual void OnFilter(FilterEventArgs e) { + if (this.Filter != null) + this.Filter(this, e); + } + + /// + /// + /// + /// + protected virtual void OnFormatCell(FormatCellEventArgs args) { + if (this.FormatCell != null) + this.FormatCell(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFormatRow(FormatRowEventArgs args) { + if (this.FormatRow != null) + this.FormatRow(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFreezing(FreezeEventArgs args) { + if (this.Freezing != null) + this.Freezing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupExpandingCollapsing(GroupExpandingCollapsingEventArgs args) { + if (this.GroupExpandingCollapsing != null) + this.GroupExpandingCollapsing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupStateChanged(GroupStateChangedEventArgs args) { + if (this.GroupStateChanged != null) + this.GroupStateChanged(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderCheckBoxChanging(HeaderCheckBoxChangingEventArgs args) { + if (this.HeaderCheckBoxChanging != null) + this.HeaderCheckBoxChanging(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderToolTip(ToolTipShowingEventArgs args) { + if (this.HeaderToolTipShowing != null) + this.HeaderToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHotItemChanged(HotItemChangedEventArgs e) { + if (this.HotItemChanged != null) + this.HotItemChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnHyperlinkClicked(HyperlinkClickedEventArgs e) { + if (this.HyperlinkClicked != null) + this.HyperlinkClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnGroupTaskClicked(GroupTaskClickedEventArgs e) { + if (this.GroupTaskClicked != null) + this.GroupTaskClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnIsHyperlink(IsHyperlinkEventArgs e) { + if (this.IsHyperlink != null) + this.IsHyperlink(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsAdding(ItemsAddingEventArgs e) { + if (this.ItemsAdding != null) + this.ItemsAdding(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanged(ItemsChangedEventArgs e) { + if (this.ItemsChanged != null) + this.ItemsChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanging(ItemsChangingEventArgs e) { + if (this.ItemsChanging != null) + this.ItemsChanging(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsRemoving(ItemsRemovingEventArgs e) { + if (this.ItemsRemoving != null) + this.ItemsRemoving(this, e); + } + + /// + /// + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSelectionChanged(EventArgs e) { + if (this.SelectionChanged != null) + this.SelectionChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnScroll(ScrollEventArgs e) { + if (this.Scroll != null) + this.Scroll(this, e); + } + + + /// + /// Tell the world when a cell is about to be edited. + /// + protected virtual void OnCellEditStarting(CellEditEventArgs e) { + if (this.CellEditStarting != null) + this.CellEditStarting(this, e); + } + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditorValidating(CellEditEventArgs e) { + // Hack. ListView is an imperfect control container. It does not manage validation + // perfectly. If the ListView is part of a TabControl, and the cell editor loses + // focus by the user clicking on another tab, the TabControl processes the click + // and switches tabs, even if this Validating event cancels. This results in the + // strange situation where the cell editor is active, but isn't visible. When the + // user switches back to the tab with the ListView, composite controls like spin + // controls, DateTimePicker and ComboBoxes do not work properly. Specifically, + // keyboard input still works fine, but the controls do not respond to mouse + // input. SO, if the validation fails, we have to specifically give focus back to + // the cell editor. (this is the Select() call in the code below). + // But (there is always a 'but'), doing that changes the focus so the cell editor + // triggers another Validating event -- which fails again. From the user's point + // of view, they click away from the cell editor, and the validating code + // complains twice. So we only trigger a Validating event if more than 0.1 seconds + // has elapsed since the last validate event. + // I know it's a hack. I'm very open to hear a neater solution. + + // Also, this timed response stops us from sending a series of validation events + // if the user clicks and holds on the OLV scroll bar. + //System.Diagnostics.Debug.WriteLine(Environment.TickCount - lastValidatingEvent); + if ((Environment.TickCount - lastValidatingEvent) < 100) { + e.Cancel = true; + } else { + lastValidatingEvent = Environment.TickCount; + if (this.CellEditValidating != null) + this.CellEditValidating(this, e); + } + + lastValidatingEvent = Environment.TickCount; + } + + private int lastValidatingEvent = 0; + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditFinishing(CellEditEventArgs e) { + if (this.CellEditFinishing != null) + this.CellEditFinishing(this, e); + } + + /// + /// Tell the world when a cell has finished being edited. + /// + protected virtual void OnCellEditFinished(CellEditEventArgs e) { + if (this.CellEditFinished != null) + this.CellEditFinished(this, e); + } + + #endregion + } + + public partial class TreeListView { + + #region Events + + /// + /// This event is triggered when user input requests the expansion of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to expand.")] + public event EventHandler Expanding; + + /// + /// This event is triggered when user input requests the collapse of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to collapsed.")] + public event EventHandler Collapsing; + + /// + /// This event is triggered after the expansion of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been expanded.")] + public event EventHandler Expanded; + + /// + /// This event is triggered after the collapse of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been collapsed.")] + public event EventHandler Collapsed; + + #endregion + + #region OnEvents + + /// + /// Trigger the expanding event + /// + /// + protected virtual void OnExpanding(TreeBranchExpandingEventArgs e) { + if (this.Expanding != null) + this.Expanding(this, e); + } + + /// + /// Trigger the collapsing event + /// + /// + protected virtual void OnCollapsing(TreeBranchCollapsingEventArgs e) { + if (this.Collapsing != null) + this.Collapsing(this, e); + } + + /// + /// Trigger the expanded event + /// + /// + protected virtual void OnExpanded(TreeBranchExpandedEventArgs e) { + if (this.Expanded != null) + this.Expanded(this, e); + } + + /// + /// Trigger the collapsed event + /// + /// + protected virtual void OnCollapsed(TreeBranchCollapsedEventArgs e) { + if (this.Collapsed != null) + this.Collapsed(this, e); + } + + #endregion + } + + //----------------------------------------------------------------------------------- + + #region Event Parameter Blocks + + /// + /// Let the world know that a cell edit operation is beginning or ending + /// + public class CellEditEventArgs : EventArgs { + /// + /// Create an event args + /// + /// + /// + /// + /// + /// + public CellEditEventArgs(OLVColumn column, Control control, Rectangle cellBounds, OLVListItem item, int subItemIndex) { + this.Control = control; + this.column = column; + this.cellBounds = cellBounds; + this.listViewItem = item; + this.rowObject = item.RowObject; + this.subItemIndex = subItemIndex; + this.value = column.GetValue(item.RowObject); + } + + /// + /// Change this to true to cancel the cell editing operation. + /// + /// + /// During the CellEditStarting event, setting this to true will prevent the cell from being edited. + /// During the CellEditFinishing event, if this value is already true, this indicates that the user has + /// cancelled the edit operation and that the handler should perform cleanup only. Setting this to true, + /// will prevent the ObjectListView from trying to write the new value into the model object. + /// + public bool Cancel; + + /// + /// During the CellEditStarting event, this can be modified to be the control that you want + /// to edit the value. You must fully configure the control before returning from the event, + /// including its bounds and the value it is showing. + /// During the CellEditFinishing event, you can use this to get the value that the user + /// entered and commit that value to the model. Changing the control during the finishing + /// event has no effect. + /// + public Control Control; + + /// + /// The column of the cell that is going to be or has been edited. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is going to be or has been edited. + /// + public Object RowObject { + get { return this.rowObject; } + } + + private Object rowObject; + + /// + /// The listview item of the cell that is going to be or has been edited. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The data value of the cell as it stands in the control. + /// + /// Only validate during Validating and Finishing events. + public Object NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private Object newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + + /// + /// The data value of the cell before the edit operation began. + /// + public Object Value { + get { return this.value; } + } + + private Object value; + + /// + /// The bounds of the cell that is going to be or has been edited. + /// + public Rectangle CellBounds { + get { return this.cellBounds; } + } + + private Rectangle cellBounds; + + /// + /// Gets or sets whether the control used for editing should be auto matically disposed + /// when the cell edit operation finishes. Defaults to true + /// + /// If the control is expensive to create, you might want to cache it and reuse for + /// for various cells. If so, you don't want ObjectListView to dispose of the control automatically + public bool AutoDispose { + get { return autoDispose; } + set { autoDispose = value; } + } + + private bool autoDispose = true; + } + + /// + /// Event blocks for events that can be cancelled + /// + public class CancellableEventArgs : EventArgs { + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled; + } + + /// + /// BeforeSorting + /// + public class BeforeSortingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = column; + this.GroupByOrder = order; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = groupColumn; + this.GroupByOrder = groupOrder; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Did the event handler already do the sorting for us? + /// + public bool Handled; + + /// + /// What column will be used for grouping + /// + public OLVColumn ColumnToGroupBy; + + /// + /// How will groups be ordered + /// + public SortOrder GroupByOrder; + + /// + /// What column will be used for sorting + /// + public OLVColumn ColumnToSort; + + /// + /// What order will be used for sorting. None means no sorting. + /// + public SortOrder SortOrder; + + /// + /// What column will be used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort; + + /// + /// What order will be used for secondary sorting? + /// + public SortOrder SecondarySortOrder; + } + + /// + /// Sorting has just occurred. + /// + public class AfterSortingEventArgs : EventArgs { + /// + /// Create a AfterSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public AfterSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.columnToGroupBy = groupColumn; + this.groupByOrder = groupOrder; + this.columnToSort = column; + this.sortOrder = order; + this.secondaryColumnToSort = column2; + this.secondarySortOrder = order2; + } + + /// + /// Create a AfterSortingEventArgs + /// + /// + public AfterSortingEventArgs(BeforeSortingEventArgs args) { + this.columnToGroupBy = args.ColumnToGroupBy; + this.groupByOrder = args.GroupByOrder; + this.columnToSort = args.ColumnToSort; + this.sortOrder = args.SortOrder; + this.secondaryColumnToSort = args.SecondaryColumnToSort; + this.secondarySortOrder = args.SecondarySortOrder; + } + + /// + /// What column was used for grouping? + /// + public OLVColumn ColumnToGroupBy { + get { return columnToGroupBy; } + } + + private OLVColumn columnToGroupBy; + + /// + /// What ordering was used for grouping? + /// + public SortOrder GroupByOrder { + get { return groupByOrder; } + } + + private SortOrder groupByOrder; + + /// + /// What column was used for sorting? + /// + public OLVColumn ColumnToSort { + get { return columnToSort; } + } + + private OLVColumn columnToSort; + + /// + /// What ordering was used for sorting? + /// + public SortOrder SortOrder { + get { return sortOrder; } + } + + private SortOrder sortOrder; + + /// + /// What column was used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort { + get { return secondaryColumnToSort; } + } + + private OLVColumn secondaryColumnToSort; + + /// + /// What order was used for secondary sorting? + /// + public SortOrder SecondarySortOrder { + get { return secondarySortOrder; } + } + + private SortOrder secondarySortOrder; + } + + /// + /// This event is triggered when the contents of a list have changed + /// and we want the world to have a chance to filter the list. + /// + public class FilterEventArgs : EventArgs { + /// + /// Create a FilterEventArgs + /// + /// + public FilterEventArgs(IEnumerable objects) { + this.Objects = objects; + } + + /// + /// Gets or sets what objects are being filtered + /// + public IEnumerable Objects; + + /// + /// Gets or sets what objects survived the filtering + /// + public IEnumerable FilteredObjects; + } + + /// + /// This event is triggered after the items in the list have been changed, + /// either through SetObjects, AddObjects or RemoveObjects. + /// + public class ItemsChangedEventArgs : EventArgs { + /// + /// Create a ItemsChangedEventArgs + /// + public ItemsChangedEventArgs() { } + + /// + /// Constructor for this event when used by a virtual list + /// + /// + /// + public ItemsChangedEventArgs(int oldObjectCount, int newObjectCount) { + this.oldObjectCount = oldObjectCount; + this.newObjectCount = newObjectCount; + } + + /// + /// Gets how many items were in the list before it changed + /// + public int OldObjectCount { + get { return oldObjectCount; } + } + + private int oldObjectCount; + + /// + /// Gets how many objects are in the list after the change. + /// + public int NewObjectCount { + get { return newObjectCount; } + } + + private int newObjectCount; + } + + /// + /// This event is triggered by AddObjects before any change has been made to the list. + /// + public class ItemsAddingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsAddingEventArgs + /// + /// + public ItemsAddingEventArgs(ICollection objectsToAdd) { + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Create an ItemsAddingEventArgs + /// + /// + /// + public ItemsAddingEventArgs(int index, ICollection objectsToAdd) { + this.Index = index; + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Gets or sets where the collection is going to be inserted. + /// + public int Index; + + /// + /// Gets or sets the objects to be added to the list + /// + public ICollection ObjectsToAdd; + } + + /// + /// This event is triggered by SetObjects before any change has been made to the list. + /// + /// + /// When used with a virtual list, OldObjects will always be null. + /// + public class ItemsChangingEventArgs : CancellableEventArgs { + /// + /// Create ItemsChangingEventArgs + /// + /// + /// + public ItemsChangingEventArgs(IEnumerable oldObjects, IEnumerable newObjects) { + this.oldObjects = oldObjects; + this.NewObjects = newObjects; + } + + /// + /// Gets the objects that were in the list before it change. + /// For virtual lists, this will always be null. + /// + public IEnumerable OldObjects { + get { return oldObjects; } + } + + private IEnumerable oldObjects; + + /// + /// Gets or sets the objects that will be in the list after it changes. + /// + public IEnumerable NewObjects; + } + + /// + /// This event is triggered by RemoveObjects before any change has been made to the list. + /// + public class ItemsRemovingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsRemovingEventArgs + /// + /// + public ItemsRemovingEventArgs(ICollection objectsToRemove) { + this.ObjectsToRemove = objectsToRemove; + } + + /// + /// Gets or sets the objects that will be removed + /// + public ICollection ObjectsToRemove; + } + + /// + /// Triggered after the user types into a list + /// + public class AfterSearchingEventArgs : EventArgs { + /// + /// Create an AfterSearchingEventArgs + /// + /// + /// + public AfterSearchingEventArgs(string stringToFind, int indexSelected) { + this.stringToFind = stringToFind; + this.indexSelected = indexSelected; + } + + /// + /// Gets the string that was actually searched for + /// + public string StringToFind { + get { return this.stringToFind; } + } + + private string stringToFind; + + /// + /// Gets or sets whether an the event handler already handled this event + /// + public bool Handled; + + /// + /// Gets the index of the row that was selected by the search. + /// -1 means that no row was matched + /// + public int IndexSelected { + get { return this.indexSelected; } + } + + private int indexSelected; + } + + /// + /// Triggered when the user types into a list + /// + public class BeforeSearchingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSearchingEventArgs + /// + /// + /// + public BeforeSearchingEventArgs(string stringToFind, int startSearchFrom) { + this.StringToFind = stringToFind; + this.StartSearchFrom = startSearchFrom; + } + + /// + /// Gets or sets the string that will be found by the search routine + /// + /// Modifying this value does not modify the memory of what the user has typed. + /// When the user next presses a character, the search string will revert to what + /// the user has actually typed. + public string StringToFind; + + /// + /// Gets or sets the index of the first row that will be considered to matching. + /// + public int StartSearchFrom; + } + + /// + /// The parameter block when telling the world about a cell based event + /// + public class CellEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + /// This is null for events triggered by the header. + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + /// This is -1 for events triggered by the header. + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location { + get { return this.location; } + internal set { this.location = value; } + } + + private Point location; + + /// + /// Gets the state of the modifier keys at the time of the event + /// + public Keys ModifierKeys { + get { return this.modifierKeys; } + internal set { this.modifierKeys = value; } + } + + private Keys modifierKeys; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view and + /// for event triggered by the header + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the HitTest object that determined which cell was hit + /// + public OlvListViewHitTestInfo HitTest { + get { return hitTest; } + internal set { hitTest = value; } + } + + private OlvListViewHitTestInfo hitTest; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled; + } + + /// + /// Tells the world that a cell was clicked + /// + public class CellClickEventArgs : CellEventArgs { + /// + /// Gets or sets the number of clicks associated with this event + /// + public int ClickCount { + get { return this.clickCount; } + set { this.clickCount = value; } + } + + private int clickCount; + } + + /// + /// Tells the world that a cell was right clicked + /// + public class CellRightClickEventArgs : CellEventArgs { + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ContextMenuStrip MenuStrip; + } + + /// + /// Tell the world that the mouse is over a given cell + /// + public class CellOverEventArgs : CellEventArgs { } + + /// + /// Tells the world that the frozen-ness of the ObjectListView has changed. + /// + public class FreezeEventArgs : EventArgs { + /// + /// Make a FreezeEventArgs + /// + /// + public FreezeEventArgs(int freeze) { + this.FreezeLevel = freeze; + } + + /// + /// How frozen is the control? 0 means that the control is unfrozen, + /// more than 0 indicates froze. + /// + public int FreezeLevel { + get { return this.freezeLevel; } + set { this.freezeLevel = value; } + } + + private int freezeLevel; + } + + /// + /// The parameter block when telling the world that a tool tip is about to be shown. + /// + public class ToolTipShowingEventArgs : CellEventArgs { + /// + /// Gets the tooltip control that is triggering the tooltip event + /// + public ToolTipControl ToolTipControl { + get { return this.toolTipControl; } + internal set { this.toolTipControl = value; } + } + + private ToolTipControl toolTipControl; + + /// + /// Gets or sets the text should be shown on the tooltip for this event + /// + /// Setting this to empty or null prevents any tooltip from showing + public string Text; + + /// + /// In what direction should the text for this tooltip be drawn? + /// + public RightToLeft RightToLeft; + + /// + /// Should the tooltip for this event been shown in bubble style? + /// + /// This doesn't work reliable under Vista + public bool? IsBalloon; + + /// + /// What color should be used for the background of the tooltip + /// + /// Setting this does nothing under Vista + public Color? BackColor; + + /// + /// What color should be used for the foreground of the tooltip + /// + /// Setting this does nothing under Vista + public Color? ForeColor; + + /// + /// What string should be used as the title for the tooltip for this event? + /// + public string Title; + + /// + /// Which standard icon should be used for the tooltip for this event + /// + public ToolTipControl.StandardIcons? StandardIcon; + + /// + /// How many milliseconds should the tooltip remain before it automatically + /// disappears. + /// + public int? AutoPopDelay; + + /// + /// What font should be used to draw the text of the tooltip? + /// + public Font Font; + } + + /// + /// Common information to all hyperlink events + /// + public class HyperlinkEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the ObjectListView that is the source of the event + /// + public string Url { + get { return this.url; } + internal set { this.url = value; } + } + + private string url; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + } + + /// + /// + /// + public class IsHyperlinkEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the text of the cell + /// + public string Text { + get { return this.text; } + internal set { this.text = value; } + } + + private string text; + + /// + /// Gets or sets whether or not this cell is a hyperlink. + /// Defaults to true for enabled rows and false for disabled rows. + /// + public bool IsHyperlink { + get { return this.isHyperlink; } + set { this.isHyperlink = value; } + } + + private bool isHyperlink; + + /// + /// Gets or sets the url that should be invoked when this cell is clicked. + /// + /// Setting this to None or String.Empty means that this cell is not a hyperlink + public string Url; + } + + /// + /// + public class FormatRowEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.Item.RowObject; } + } + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the display index of the row + /// + public int DisplayIndex { + get { return this.displayIndex; } + internal set { this.displayIndex = value; } + } + + private int displayIndex = -1; + + /// + /// Should events be triggered for each cell in this row? + /// + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + + private bool useCellFormatEvents; + } + + /// + /// Parameter block for FormatCellEvent + /// + public class FormatCellEventArgs : FormatRowEventArgs { + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the model value that is being displayed by the cell. + /// + /// This is null when the view is not in details view + public object CellValue { + get { return this.SubItem == null ? null : this.SubItem.ModelValue; } + } + } + + /// + /// The event args when a hyperlink is clicked + /// + public class HyperlinkClickedEventArgs : CellEventArgs { + /// + /// Gets the url that was associated with this cell. + /// + public string Url { + get { return url; } + set { url = value; } + } + + private string url; + + } + + /// + /// The event args when the check box in a column header is changing + /// + public class HeaderCheckBoxChangingEventArgs : CancelEventArgs { + + /// + /// Get the column whose checkbox is changing + /// + public OLVColumn Column { + get { return column; } + internal set { column = value; } + } + + private OLVColumn column; + + /// + /// Get or set the new state that should be used by the column + /// + public CheckState NewCheckState { + get { return newCheckState; } + set { newCheckState = value; } + } + + private CheckState newCheckState; + } + + /// + /// The event args when the hot item changed + /// + public class HotItemChangedEventArgs : EventArgs { + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + /// + /// Gets the part of the cell that the mouse is over + /// + public HitTestLocation HotCellHitLocation { + get { return newHotCellHitLocation; } + internal set { newHotCellHitLocation = value; } + } + + private HitTestLocation newHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + public virtual HitTestLocationEx HotCellHitLocationEx { + get { return this.hotCellHitLocationEx; } + internal set { this.hotCellHitLocationEx = value; } + } + + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse is over + /// + /// In non-details view, this will always be 0. + public int HotColumnIndex { + get { return newHotColumnIndex; } + internal set { newHotColumnIndex = value; } + } + + private int newHotColumnIndex; + + /// + /// Gets the index of the row that the mouse is over + /// + public int HotRowIndex { + get { return newHotRowIndex; } + internal set { newHotRowIndex = value; } + } + + private int newHotRowIndex; + + /// + /// Gets the group that the mouse is over + /// + public OLVGroup HotGroup { + get { return hotGroup; } + internal set { hotGroup = value; } + } + + private OLVGroup hotGroup; + + /// + /// Gets the part of the cell that the mouse used to be over + /// + public HitTestLocation OldHotCellHitLocation { + get { return oldHotCellHitLocation; } + internal set { oldHotCellHitLocation = value; } + } + + private HitTestLocation oldHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse used to be over + /// + public virtual HitTestLocationEx OldHotCellHitLocationEx { + get { return this.oldHotCellHitLocationEx; } + internal set { this.oldHotCellHitLocationEx = value; } + } + + private HitTestLocationEx oldHotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse used to be over + /// + public int OldHotColumnIndex { + get { return oldHotColumnIndex; } + internal set { oldHotColumnIndex = value; } + } + + private int oldHotColumnIndex; + + /// + /// Gets the index of the row that the mouse used to be over + /// + public int OldHotRowIndex { + get { return oldHotRowIndex; } + internal set { oldHotRowIndex = value; } + } + + private int oldHotRowIndex; + + /// + /// Gets the group that the mouse used to be over + /// + public OLVGroup OldHotGroup { + get { return oldHotGroup; } + internal set { oldHotGroup = value; } + } + + private OLVGroup oldHotGroup; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return string.Format("NewHotCellHitLocation: {0}, HotCellHitLocationEx: {1}, NewHotColumnIndex: {2}, NewHotRowIndex: {3}, HotGroup: {4}", this.newHotCellHitLocation, this.hotCellHitLocationEx, this.newHotColumnIndex, this.newHotRowIndex, this.hotGroup); + } + } + + /// + /// Let the world know that a checkbox on a subitem is changing + /// + public class SubItemCheckingEventArgs : CancellableEventArgs { + /// + /// Create a new event block + /// + /// + /// + /// + /// + /// + public SubItemCheckingEventArgs(OLVColumn column, OLVListItem item, int subItemIndex, CheckState currentValue, CheckState newValue) { + this.column = column; + this.listViewItem = item; + this.subItemIndex = subItemIndex; + this.currentValue = currentValue; + this.newValue = newValue; + } + + /// + /// The column of the cell that is having its checkbox changed. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is having its checkbox changed. + /// + public Object RowObject { + get { return this.listViewItem.RowObject; } + } + + /// + /// The listview item of the cell that is having its checkbox changed. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The current check state of the cell. + /// + public CheckState CurrentValue { + get { return this.currentValue; } + } + + private CheckState currentValue; + + /// + /// The proposed new check state of the cell. + /// + public CheckState NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private CheckState newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + } + + /// + /// This event argument block is used when groups are created for a list. + /// + public class CreateGroupsEventArgs : EventArgs { + /// + /// Create a CreateGroupsEventArgs + /// + /// + public CreateGroupsEventArgs(GroupingParameters parms) { + this.parameters = parms; + } + + /// + /// Gets the settings that control the creation of groups + /// + public GroupingParameters Parameters { + get { return this.parameters; } + } + + private GroupingParameters parameters; + + /// + /// Gets or sets the groups that should be used + /// + public IList Groups { + get { return this.groups; } + set { this.groups = value; } + } + + private IList groups; + + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled { + get { return canceled; } + set { canceled = value; } + } + + private bool canceled; + + } + + /// + /// This event argument block is used when the text of a group task is clicked + /// + public class GroupTaskClickedEventArgs : EventArgs { + /// + /// Create a GroupTaskClickedEventArgs + /// + /// + public GroupTaskClickedEventArgs(OLVGroup group) { + this.group = group; + } + + /// + /// Gets which group was clicked + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + } + + /// + /// This event argument block is used when a group is about to expand or collapse + /// + public class GroupExpandingCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a GroupExpandingCollapsingEventArgs + /// + /// + public GroupExpandingCollapsingEventArgs(OLVGroup group) { + if (group == null) throw new ArgumentNullException("group"); + this.olvGroup = group; + } + + /// + /// Gets which group is expanding/collapsing + /// + public OLVGroup Group { + get { return this.olvGroup; } + } + + private readonly OLVGroup olvGroup; + + /// + /// Gets whether this event is going to expand the group. + /// If this is false, the group must be collapsing. + /// + public bool IsExpanding { + get { return this.Group.Collapsed; } + } + } + + /// + /// This event argument block is used when the state of group has changed (collapsed, selected) + /// + public class GroupStateChangedEventArgs : EventArgs { + /// + /// Create a GroupStateChangedEventArgs + /// + /// + /// + /// + public GroupStateChangedEventArgs(OLVGroup group, GroupState oldState, GroupState newState) { + this.group = group; + this.oldState = oldState; + this.newState = newState; + } + + /// + /// Gets whether the group was collapsed by this event + /// + public bool Collapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was focused by this event + /// + public bool Focused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was selected by this event + /// + public bool Selected { + get { + return ((oldState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets whether the group was uncollapsed by this event + /// + public bool Uncollapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was unfocused by this event + /// + public bool Unfocused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was unselected by this event + /// + public bool Unselected { + get { + return ((oldState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets which group had its state changed + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + + /// + /// Gets the previous state of the group + /// + public GroupState OldState { + get { return this.oldState; } + } + + private readonly GroupState oldState; + + + /// + /// Gets the new state of the group + /// + public GroupState NewState { + get { return this.newState; } + } + + private readonly GroupState newState; + } + + /// + /// This event argument block is used when a branch of a tree is about to be expanded + /// + public class TreeBranchExpandingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to expand. If null, all branches are going to be expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree has just been expanded + /// + public class TreeBranchExpandedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was expanded. If null, all branches were expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree is about to be collapsed + /// + public class TreeBranchCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to collapse. If this is null, all models are going to collapse. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be collapsed. Can be null + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + } + + + /// + /// This event argument block is used when a branch of a tree has just been collapsed + /// + public class TreeBranchCollapsedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was collapsed. If null, all branches were collapsed + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was collapsed + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// Tells the world that a column header was right clicked + /// + public class ColumnRightClickEventArgs : ColumnClickEventArgs { + public ColumnRightClickEventArgs(int columnIndex, ToolStripDropDown menu, Point location) : base(columnIndex) { + MenuStrip = menu; + Location = location; + } + + /// + /// Set this to true to cancel the right click operation. + /// + public bool Cancel; + + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ToolStripDropDown MenuStrip; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location; + } + + #endregion +} diff --git a/ObjectListView/Implementation/GroupingParameters.cs b/ObjectListView/Implementation/GroupingParameters.cs new file mode 100644 index 0000000..a87f217 --- /dev/null +++ b/ObjectListView/Implementation/GroupingParameters.cs @@ -0,0 +1,204 @@ +/* + * GroupingParameters - All the data that is used to create groups in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// This class contains all the settings used when groups are created + /// + public class GroupingParameters { + /// + /// Create a GroupingParameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public GroupingParameters(ObjectListView olv, OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder, + string titleFormat, string titleSingularFormat, bool sortItemsByPrimaryColumn) { + this.ListView = olv; + this.GroupByColumn = groupByColumn; + this.GroupByOrder = groupByOrder; + this.PrimarySort = column; + this.PrimarySortOrder = order; + this.SecondarySort = secondaryColumn; + this.SecondarySortOrder = secondaryOrder; + this.SortItemsByPrimaryColumn = sortItemsByPrimaryColumn; + this.TitleFormat = titleFormat; + this.TitleSingularFormat = titleSingularFormat; + } + + /// + /// Gets or sets the ObjectListView being grouped + /// + public ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the column used to create groups + /// + public OLVColumn GroupByColumn { + get { return this.groupByColumn; } + set { this.groupByColumn = value; } + } + private OLVColumn groupByColumn; + + /// + /// In what order will the groups themselves be sorted? + /// + public SortOrder GroupByOrder { + get { return this.groupByOrder; } + set { this.groupByOrder = value; } + } + private SortOrder groupByOrder; + + /// + /// If this is set, this comparer will be used to order the groups + /// + public IComparer GroupComparer { + get { return this.groupComparer; } + set { this.groupComparer = value; } + } + private IComparer groupComparer; + + /// + /// If this is set, this comparer will be used to order items within each group + /// + public IComparer ItemComparer { + get { return this.itemComparer; } + set { this.itemComparer = value; } + } + private IComparer itemComparer; + + /// + /// Gets or sets the column that will be the primary sort + /// + public OLVColumn PrimarySort { + get { return this.primarySort; } + set { this.primarySort = value; } + } + private OLVColumn primarySort; + + /// + /// Gets or sets the ordering for the primary sort + /// + public SortOrder PrimarySortOrder { + get { return this.primarySortOrder; } + set { this.primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets the column used for secondary sorting + /// + public OLVColumn SecondarySort { + get { return this.secondarySort; } + set { this.secondarySort = value; } + } + private OLVColumn secondarySort; + + /// + /// Gets or sets the ordering for the secondary sort + /// + public SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder; + + /// + /// Gets or sets the title format used for groups with zero or more than one element + /// + public string TitleFormat { + get { return this.titleFormat; } + set { this.titleFormat = value; } + } + private string titleFormat; + + /// + /// Gets or sets the title format used for groups with only one element + /// + public string TitleSingularFormat { + get { return this.titleSingularFormat; } + set { this.titleSingularFormat = value; } + } + private string titleSingularFormat; + + /// + /// Gets or sets whether the items should be sorted by the primary column + /// + public bool SortItemsByPrimaryColumn { + get { return this.sortItemsByPrimaryColumn; } + set { this.sortItemsByPrimaryColumn = value; } + } + private bool sortItemsByPrimaryColumn; + + /// + /// Create an OLVGroup for the given information + /// + /// + /// + /// + /// + public OLVGroup CreateGroup(object key, int count, bool hasCollapsibleGroups) { + string title = GroupByColumn.ConvertGroupKeyToTitle(key); + if (!String.IsNullOrEmpty(TitleFormat)) + { + string format = (count == 1 ? TitleSingularFormat : TitleFormat); + try + { + title = String.Format(format, title, count); + } + catch (FormatException) + { + title = "Invalid group format: " + format; + } + } + OLVGroup lvg = new OLVGroup(title); + lvg.Column = GroupByColumn; + lvg.Collapsible = hasCollapsibleGroups; + lvg.Key = key; + lvg.SortValue = key as IComparable; + return lvg; + } + } +} diff --git a/ObjectListView/Implementation/Groups.cs b/ObjectListView/Implementation/Groups.cs new file mode 100644 index 0000000..33a7cb2 --- /dev/null +++ b/ObjectListView/Implementation/Groups.cs @@ -0,0 +1,761 @@ +/* + * Groups - Enhancements to the normal ListViewGroup + * + * Author: Phillip Piper + * Date: 22/08/2009 6:03PM + * + * Change log: + * v2.3 + * 2009-09-09 JPP - Added Collapsed and Collapsible properties + * 2009-09-01 JPP - Cleaned up code, added more docs + * - Works under VS2005 again + * 2009-08-22 JPP - Initial version + * + * To do: + * - Implement subseting + * - Implement footer items + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// These values indicate what is the state of the group. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupState + { + /// + /// Normal + /// + LVGS_NORMAL = 0x0, + + /// + /// Collapsed + /// + LVGS_COLLAPSED = 0x1, + + /// + /// Hidden + /// + LVGS_HIDDEN = 0x2, + + /// + /// NoHeader + /// + LVGS_NOHEADER = 0x4, + + /// + /// Can be collapsed + /// + LVGS_COLLAPSIBLE = 0x8, + + /// + /// Has focus + /// + LVGS_FOCUSED = 0x10, + + /// + /// Is Selected + /// + LVGS_SELECTED = 0x20, + + /// + /// Is subsetted + /// + LVGS_SUBSETED = 0x40, + + /// + /// Subset link has focus + /// + LVGS_SUBSETLINKFOCUSED = 0x80, + + /// + /// All styles + /// + LVGS_ALL = 0xFFFF + } + + /// + /// This mask indicates which members of a LVGROUP have valid data. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupMask + { + /// + /// No mask + /// + LVGF_NONE = 0, + + /// + /// Group has header + /// + LVGF_HEADER = 1, + + /// + /// Group has footer + /// + LVGF_FOOTER = 2, + + /// + /// Group has state + /// + LVGF_STATE = 4, + + /// + /// + /// + LVGF_ALIGN = 8, + + /// + /// + /// + LVGF_GROUPID = 0x10, + + /// + /// pszSubtitle is valid + /// + LVGF_SUBTITLE = 0x00100, + + /// + /// pszTask is valid + /// + LVGF_TASK = 0x00200, + + /// + /// pszDescriptionTop is valid + /// + LVGF_DESCRIPTIONTOP = 0x00400, + + /// + /// pszDescriptionBottom is valid + /// + LVGF_DESCRIPTIONBOTTOM = 0x00800, + + /// + /// iTitleImage is valid + /// + LVGF_TITLEIMAGE = 0x01000, + + /// + /// iExtendedImage is valid + /// + LVGF_EXTENDEDIMAGE = 0x02000, + + /// + /// iFirstItem and cItems are valid + /// + LVGF_ITEMS = 0x04000, + + /// + /// pszSubsetTitle is valid + /// + LVGF_SUBSET = 0x08000, + + /// + /// readonly, cItems holds count of items in visible subset, iFirstItem is valid + /// + LVGF_SUBSETITEMS = 0x10000 + } + + /// + /// This mask indicates which members of a GROUPMETRICS structure are valid + /// + [Flags] + public enum GroupMetricsMask + { + /// + /// + /// + LVGMF_NONE = 0, + + /// + /// + /// + LVGMF_BORDERSIZE = 1, + + /// + /// + /// + LVGMF_BORDERCOLOR = 2, + + /// + /// + /// + LVGMF_TEXTCOLOR = 4 + } + + /// + /// Instances of this class enhance the capabilities of a normal ListViewGroup, + /// enabling the functionality that was released in v6 of the common controls. + /// + /// + /// + /// In this implementation (2009-09), these objects are essentially passive. + /// Setting properties does not automatically change the associated group in + /// the listview. Collapsed and Collapsible are two exceptions to this and + /// give immediate results. + /// + /// + /// This really should be a subclass of ListViewGroup, but that class is + /// sealed (why is that?). So this class provides the same interface as a + /// ListViewGroup, plus many other new properties. + /// + /// + public class OLVGroup + { + #region Creation + + /// + /// Create an OLVGroup + /// + public OLVGroup() : this("Default group header") { + } + + /// + /// Create a group with the given title + /// + /// Title of the group + public OLVGroup(string header) { + this.Header = header; + this.Id = OLVGroup.nextId++; + this.TitleImage = -1; + this.ExtendedImage = -1; + } + private static int nextId; + + #endregion + + #region Public properties + + /// + /// Gets or sets the bottom description of the group + /// + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + /// + /// THIS PROPERTY IS CURRENTLY NOT USED. + /// + /// + public string BottomDescription { + get { return this.bottomDescription; } + set { this.bottomDescription = value; } + } + private string bottomDescription; + + /// + /// Gets or sets whether or not this group is collapsed + /// + public bool Collapsed { + get { return this.GetOneState(GroupState.LVGS_COLLAPSED); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSED); } + } + + /// + /// Gets or sets whether or not this group can be collapsed + /// + public bool Collapsible { + get { return this.GetOneState(GroupState.LVGS_COLLAPSIBLE); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSIBLE); } + } + + /// + /// Gets or sets the column that was used to construct this group. + /// + public OLVColumn Column { + get { return this.column; } + set { this.column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets some representation of the contents of this group + /// + /// This is user defined (like Tag) + public IList Contents { + get { return this.contents; } + set { this.contents = value; } + } + private IList contents; + + /// + /// Gets whether this group has been created. + /// + public bool Created { + get { return this.ListView != null; } + } + + /// + /// Gets or sets the int or string that will select the extended image to be shown against the title + /// + public object ExtendedImage { + get { return this.extendedImage; } + set { this.extendedImage = value; } + } + private object extendedImage; + + /// + /// Gets or sets the footer of the group + /// + public string Footer { + get { return this.footer; } + set { this.footer = value; } + } + private string footer; + + /// + /// Gets the internal id of our associated ListViewGroup. + /// + public int GroupId { + get { + if (this.ListViewGroup == null) + return this.Id; + + // Use reflection to get around the access control on the ID property + if (OLVGroup.groupIdPropInfo == null) { + OLVGroup.groupIdPropInfo = typeof(ListViewGroup).GetProperty("ID", + BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(OLVGroup.groupIdPropInfo != null); + } + + int? groupId = OLVGroup.groupIdPropInfo.GetValue(this.ListViewGroup, null) as int?; + return groupId.HasValue ? groupId.Value : -1; + } + } + private static PropertyInfo groupIdPropInfo; + + /// + /// Gets or sets the header of the group + /// + public string Header { + get { return this.header; } + set { this.header = value; } + } + private string header; + + /// + /// Gets or sets the horizontal alignment of the group header + /// + public HorizontalAlignment HeaderAlignment { + get { return this.headerAlignment; } + set { this.headerAlignment = value; } + } + private HorizontalAlignment headerAlignment; + + /// + /// Gets or sets the internally created id of the group + /// + public int Id { + get { return this.id; } + set { this.id = value; } + } + private int id; + + /// + /// Gets or sets ListViewItems that are members of this group + /// + /// Listener of the BeforeCreatingGroups event can populate this collection. + /// It is only used on non-virtual lists. + public IList Items { + get { return this.items; } + set { this.items = value; } + } + private IList items = new List(); + + /// + /// Gets or sets the key that was used to partition objects into this group + /// + /// This is user defined (like Tag) + public object Key { + get { return this.key; } + set { this.key = value; } + } + private object key; + + /// + /// Gets the ObjectListView that this group belongs to + /// + /// If this is null, the group has not yet been created. + public ObjectListView ListView { + get { return this.listView; } + protected set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the name of the group + /// + /// As of 2009-09-01, this property is not used. + public string Name { + get { return this.name; } + set { this.name = value; } + } + private string name; + + /// + /// Gets or sets whether this group is focused + /// + public bool Focused + { + get { return this.GetOneState(GroupState.LVGS_FOCUSED); } + set { this.SetOneState(value, GroupState.LVGS_FOCUSED); } + } + + /// + /// Gets or sets whether this group is selected + /// + public bool Selected + { + get { return this.GetOneState(GroupState.LVGS_SELECTED); } + set { this.SetOneState(value, GroupState.LVGS_SELECTED); } + } + + /// + /// Gets or sets the text that will show that this group is subsetted + /// + /// + /// As of WinSDK v7.0, subsetting of group is officially unimplemented. + /// We can get around this using undocumented interfaces and may do so. + /// + public string SubsetTitle { + get { return this.subsetTitle; } + set { this.subsetTitle = value; } + } + private string subsetTitle; + + /// + /// Gets or set the subtitleof the task + /// + public string Subtitle { + get { return this.subtitle; } + set { this.subtitle = value; } + } + private string subtitle; + + /// + /// Gets or sets the value by which this group will be sorted. + /// + public IComparable SortValue { + get { return this.sortValue; } + set { this.sortValue = value; } + } + private IComparable sortValue; + + /// + /// Gets or sets the state of the group + /// + public GroupState State { + get { return this.state; } + set { this.state = value; } + } + private GroupState state; + + /// + /// Gets or sets which bits of State are valid + /// + public GroupState StateMask { + get { return this.stateMask; } + set { this.stateMask = value; } + } + private GroupState stateMask; + + /// + /// Gets or sets whether this group is showing only a subset of its elements + /// + /// + /// As of WinSDK v7.0, this property officially does nothing. + /// + public bool Subseted { + get { return this.GetOneState(GroupState.LVGS_SUBSETED); } + set { this.SetOneState(value, GroupState.LVGS_SUBSETED); } + } + + /// + /// Gets or sets the user-defined data attached to this group + /// + public object Tag { + get { return this.tag; } + set { this.tag = value; } + } + private object tag; + + /// + /// Gets or sets the task of this group + /// + /// This task is the clickable text that appears on the right margin + /// of the group header. + public string Task { + get { return this.task; } + set { this.task = value; } + } + private string task; + + /// + /// Gets or sets the int or string that will select the image to be shown against the title + /// + public object TitleImage { + get { return this.titleImage; } + set { this.titleImage = value; } + } + private object titleImage; + + /// + /// Gets or sets the top description of the group + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + public string TopDescription { + get { return this.topDescription; } + set { this.topDescription = value; } + } + private string topDescription; + + /// + /// Gets or sets the number of items that are within this group. + /// + /// This should only be used for virtual groups. + public int VirtualItemCount { + get { return this.virtualItemCount; } + set { this.virtualItemCount = value; } + } + private int virtualItemCount; + + #endregion + + #region Protected properties + + /// + /// Gets or sets the ListViewGroup that is shadowed by this group. + /// + /// For virtual groups, this will always be null. + protected ListViewGroup ListViewGroup { + get { return this.listViewGroup; } + set { this.listViewGroup = value; } + } + private ListViewGroup listViewGroup; + #endregion + + #region Calculations/Conversions + + /// + /// Calculate the index into the group image list of the given image selector + /// + /// + /// + public int GetImageIndex(object imageSelector) { + if (imageSelector == null || this.ListView == null || this.ListView.GroupImageList == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null) + return this.ListView.GroupImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Convert this object to a string representation + /// + /// + public override string ToString() { + return this.Header; + } + + #endregion + + #region Commands + + /// + /// Insert a native group into the underlying Windows control, + /// *without* using a ListViewGroup + /// + /// + /// This is used when creating virtual groups + public void InsertGroupNewStyle(ObjectListView olv) { + this.ListView = olv; + NativeMethods.InsertGroup(olv, this.AsNativeGroup(true)); + } + + /// + /// Insert a native group into the underlying control via a ListViewGroup + /// + /// + public void InsertGroupOldStyle(ObjectListView olv) { + this.ListView = olv; + + // Create/update the associated ListViewGroup + if (this.ListViewGroup == null) + this.ListViewGroup = new ListViewGroup(); + this.ListViewGroup.Header = this.Header; + this.ListViewGroup.HeaderAlignment = this.HeaderAlignment; + this.ListViewGroup.Name = this.Name; + + // Remember which OLVGroup created the ListViewGroup + this.ListViewGroup.Tag = this; + + // Add the group to the control + olv.Groups.Add(this.ListViewGroup); + + // Add any extra information + NativeMethods.SetGroupInfo(olv, this.GroupId, this.AsNativeGroup(false)); + } + + /// + /// Change the members of the group to match the current contents of Items, + /// using a ListViewGroup + /// + public void SetItemsOldStyle() { + List list = this.Items as List; + if (list == null) { + foreach (OLVListItem item in this.Items) { + this.ListViewGroup.Items.Add(item); + } + } else { + this.ListViewGroup.Items.AddRange(list.ToArray()); + } + } + + #endregion + + #region Implementation + + /// + /// Create a native LVGROUP structure that matches this group + /// + internal NativeMethods.LVGROUP2 AsNativeGroup(bool withId) { + + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2)); + group.mask = (uint)(GroupMask.LVGF_HEADER ^ GroupMask.LVGF_ALIGN ^ GroupMask.LVGF_STATE); + group.pszHeader = this.Header; + group.uAlign = (uint)this.HeaderAlignment; + group.stateMask = (uint)this.StateMask; + group.state = (uint)this.State; + + if (withId) { + group.iGroupId = this.GroupId; + group.mask ^= (uint)GroupMask.LVGF_GROUPID; + } + + if (!String.IsNullOrEmpty(this.Footer)) { + group.pszFooter = this.Footer; + group.mask ^= (uint)GroupMask.LVGF_FOOTER; + } + + if (!String.IsNullOrEmpty(this.Subtitle)) { + group.pszSubtitle = this.Subtitle; + group.mask ^= (uint)GroupMask.LVGF_SUBTITLE; + } + + if (!String.IsNullOrEmpty(this.Task)) { + group.pszTask = this.Task; + group.mask ^= (uint)GroupMask.LVGF_TASK; + } + + if (!String.IsNullOrEmpty(this.TopDescription)) { + group.pszDescriptionTop = this.TopDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONTOP; + } + + if (!String.IsNullOrEmpty(this.BottomDescription)) { + group.pszDescriptionBottom = this.BottomDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONBOTTOM; + } + + int imageIndex = this.GetImageIndex(this.TitleImage); + if (imageIndex >= 0) { + group.iTitleImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_TITLEIMAGE; + } + + imageIndex = this.GetImageIndex(this.ExtendedImage); + if (imageIndex >= 0) { + group.iExtendedImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_EXTENDEDIMAGE; + } + + if (!String.IsNullOrEmpty(this.SubsetTitle)) { + group.pszSubsetTitle = this.SubsetTitle; + group.mask ^= (uint)GroupMask.LVGF_SUBSET; + } + + if (this.VirtualItemCount > 0) { + group.cItems = this.VirtualItemCount; + group.mask ^= (uint)GroupMask.LVGF_ITEMS; + } + + return group; + } + + private bool GetOneState(GroupState mask) { + if (this.Created) + this.State = this.GetState(); + return (this.State & mask) == mask; + } + + /// + /// Get the current state of this group from the underlying control + /// + protected GroupState GetState() { + return NativeMethods.GetGroupState(this.ListView, this.GroupId, GroupState.LVGS_ALL); + } + + /// + /// Get the current state of this group from the underlying control + /// + protected int SetState(GroupState newState, GroupState mask) { + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2))); + group.mask = (uint)GroupMask.LVGF_STATE; + group.state = (uint)newState; + group.stateMask = (uint)mask; + return NativeMethods.SetGroupInfo(this.ListView, this.GroupId, group); + } + + private void SetOneState(bool value, GroupState mask) + { + this.StateMask ^= mask; + if (value) + this.State ^= mask; + else + this.State &= ~mask; + + if (this.Created) + this.SetState(this.State, mask); + } + + #endregion + + } +} diff --git a/ObjectListView/Implementation/Munger.cs b/ObjectListView/Implementation/Munger.cs new file mode 100644 index 0000000..8b81aec --- /dev/null +++ b/ObjectListView/Implementation/Munger.cs @@ -0,0 +1,568 @@ +/* + * Munger - An Interface pattern on getting and setting values from object through Reflection + * + * Author: Phillip Piper + * Date: 28/11/2008 17:15 + * + * Change log: + * v2.5.1 + * 2012-05-01 JPP - Added IgnoreMissingAspects property + * v2.5 + * 2011-05-20 JPP - Accessing through an indexer when the target had both a integer and + * a string indexer didn't work reliably. + * v2.4.1 + * 2010-08-10 JPP - Refactored into Munger/SimpleMunger. 3x faster! + * v2.3 + * 2009-02-15 JPP - Made Munger a public class + * 2009-01-20 JPP - Made the Munger capable of handling indexed access. + * Incidentally, this removed the ugliness that the last change introduced. + * 2009-01-18 JPP - Handle target objects from a DataListView (normally DataRowViews) + * v2.0 + * 2008-11-28 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace BrightIdeasSoftware +{ + /// + /// An instance of Munger gets a value from or puts a value into a target object. The property + /// to be peeked (or poked) is determined from a string. The peeking or poking is done using reflection. + /// + /// + /// Name of the aspect to be peeked can be a field, property or parameterless method. The name of an + /// aspect to poke can be a field, writable property or single parameter method. + /// + /// Aspect names can be dotted to chain a series of references. + /// + /// Order.Customer.HomeAddress.State + /// + public class Munger + { + #region Life and death + + /// + /// Create a do nothing Munger + /// + public Munger() + { + } + + /// + /// Create a Munger that works on the given aspect name + /// + /// The name of the + public Munger(String aspectName) + { + this.AspectName = aspectName; + } + + #endregion + + #region Static utility methods + + /// + /// A helper method to put the given value into the given aspect of the given object. + /// + /// This method catches and silently ignores any errors that occur + /// while modifying the target object + /// The object to be modified + /// The name of the property/field to be modified + /// The value to be assigned + /// Did the modification work? + public static bool PutProperty(object target, string propertyName, object value) { + try { + Munger munger = new Munger(propertyName); + return munger.PutValue(target, value); + } + catch (MungerException) { + // Not a lot we can do about this. Something went wrong in the bowels + // of the property. Let's take the ostrich approach and just ignore it :-) + + // Normally, we would never just silently ignore an exception. + // However, in this case, this is a utility method that explicitly + // contracts to catch and ignore errors. If this is not acceptable, + // the programmer should not use this method. + } + + return false; + } + + /// + /// Gets or sets whether Mungers will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if a Munger is asked to fetch a field/property/method + /// that does not exist from a model, it returns an error message, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error, and the munger should simply keep quiet. + /// + /// By default this is true during release builds. + /// + public static bool IgnoreMissingAspects { + get { return ignoreMissingAspects; } + set { ignoreMissingAspects = value; } + } + private static bool ignoreMissingAspects +#if !DEBUG + = true +#endif + ; + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or parameter-less method. + /// + /// + /// The name can be dotted, which chains references. If any link in the chain returns + /// null, the entire chain is considered to return null. + /// + /// + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + public string AspectName + { + get { return aspectName; } + set { + aspectName = value; + + // Clear any cache + aspectParts = null; + } + } + private string aspectName; + + #endregion + + + #region Public interface + + /// + /// Extract the value indicated by our AspectName from the given target. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValue(Object target) { + if (this.Parts.Count == 0) + return null; + + try { + return this.EvaluateParts(target, this.Parts); + } catch (MungerException ex) { + if (Munger.IgnoreMissingAspects) + return null; + + return String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", + ex.Munger.AspectName, ex.Target.GetType()); + } + } + + /// + /// Extract the value indicated by our AspectName from the given target, raising exceptions + /// if the munger fails. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValueEx(Object target) { + if (this.Parts.Count == 0) + return null; + + return this.EvaluateParts(target, this.Parts); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// + /// + /// If the AspectName is a dotted path, all the selectors bar the last + /// are used to find the object that should be updated, and the last + /// selector is used as the property to update on that object. + /// + /// + /// So, if 'target' is a Person and the AspectName is "HomeAddress.Postcode", + /// this method will first fetch "HomeAddress" property, and then try to set the + /// "Postcode" property on the home address object. + /// + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating whether the put worked + public bool PutValue(Object target, Object value) + { + if (this.Parts.Count == 0) + return false; + + SimpleMunger lastPart = this.Parts[this.Parts.Count - 1]; + + if (this.Parts.Count > 1) { + List parts = new List(this.Parts); + parts.RemoveAt(parts.Count - 1); + try { + target = this.EvaluateParts(target, parts); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + return false; + } + } + + if (target != null) { + try { + return lastPart.PutValue(target, value); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + } + } + + return false; + } + + #endregion + + #region Implementation + + /// + /// Gets the list of SimpleMungers that match our AspectName + /// + private IList Parts { + get { + if (aspectParts == null) + aspectParts = BuildParts(this.AspectName); + return aspectParts; + } + } + private IList aspectParts; + + /// + /// Convert a possibly dotted AspectName into a list of SimpleMungers + /// + /// + /// + private IList BuildParts(string aspect) { + List parts = new List(); + if (!String.IsNullOrEmpty(aspect)) { + foreach (string part in aspect.Split('.')) { + parts.Add(new SimpleMunger(part.Trim())); + } + } + return parts; + } + + /// + /// Evaluate the given chain of SimpleMungers against an initial target. + /// + /// + /// + /// + private object EvaluateParts(object target, IList parts) { + foreach (SimpleMunger part in parts) { + if (target == null) + break; + target = part.GetValue(target); + } + return target; + } + + private void ReportPutValueException(MungerException ex) { + //TODO: How should we report this error? + System.Diagnostics.Debug.WriteLine("PutValue failed"); + System.Diagnostics.Debug.WriteLine(String.Format("- Culprit aspect: {0}", ex.Munger.AspectName)); + System.Diagnostics.Debug.WriteLine(String.Format("- Target: {0} of type {1}", ex.Target, ex.Target.GetType())); + System.Diagnostics.Debug.WriteLine(String.Format("- Inner exception: {0}", ex.InnerException)); + } + + #endregion + } + + /// + /// A SimpleMunger deals with a single property/field/method on its target. + /// + /// + /// Munger uses a chain of these resolve a dotted aspect name. + /// + public class SimpleMunger + { + #region Life and death + + /// + /// Create a SimpleMunger + /// + /// + public SimpleMunger(String aspectName) + { + this.aspectName = aspectName; + } + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or method. + /// When using a method to get a value, the method must be parameter-less. + /// When using a method to set a value, the method must accept 1 parameter. + /// + /// + /// It cannot be a dotted name. + /// + /// + public string AspectName { + get { return aspectName; } + } + private readonly string aspectName; + + #endregion + + #region Public interface + + /// + /// Get a value from the given target + /// + /// + /// + public Object GetValue(Object target) { + if (target == null) + return null; + + this.ResolveName(target, this.AspectName, 0); + + try { + if (this.resolvedPropertyInfo != null) + return this.resolvedPropertyInfo.GetValue(target, null); + + if (this.resolvedMethodInfo != null) + return this.resolvedMethodInfo.Invoke(target, null); + + if (this.resolvedFieldInfo != null) + return this.resolvedFieldInfo.GetValue(target); + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) + return this.indexerPropertyInfo.GetValue(target, new object[] { this.AspectName }); + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + // If we get to here, we couldn't find a match for the aspect + throw new MungerException(this, target, new MissingMethodException()); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating if the put worked + public bool PutValue(object target, object value) { + if (target == null) + return false; + + this.ResolveName(target, this.AspectName, 1); + + try { + if (this.resolvedPropertyInfo != null) { + this.resolvedPropertyInfo.SetValue(target, value, null); + return true; + } + + if (this.resolvedMethodInfo != null) { + this.resolvedMethodInfo.Invoke(target, new object[] { value }); + return true; + } + + if (this.resolvedFieldInfo != null) { + this.resolvedFieldInfo.SetValue(target, value); + return true; + } + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) { + this.indexerPropertyInfo.SetValue(target, value, new object[] { this.AspectName }); + return true; + } + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + return false; + } + + #endregion + + #region Implementation + + private void ResolveName(object target, string name, int numberMethodParameters) { + + if (cachedTargetType == target.GetType() && cachedName == name && cachedNumberParameters == numberMethodParameters) + return; + + cachedTargetType = target.GetType(); + cachedName = name; + cachedNumberParameters = numberMethodParameters; + + resolvedFieldInfo = null; + resolvedPropertyInfo = null; + resolvedMethodInfo = null; + indexerPropertyInfo = null; + + const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.NonPublic*/; + + foreach (PropertyInfo pinfo in target.GetType().GetProperties(flags)) { + if (pinfo.Name == name) { + resolvedPropertyInfo = pinfo; + return; + } + + // See if we can find an string indexer property while we are here. + // We also need to allow for old style keyed collections. + if (indexerPropertyInfo == null && pinfo.Name == "Item") { + ParameterInfo[] par = pinfo.GetGetMethod().GetParameters(); + if (par.Length > 0) { + Type parameterType = par[0].ParameterType; + if (parameterType == typeof(string) || parameterType == typeof(object)) + indexerPropertyInfo = pinfo; + } + } + } + + foreach (FieldInfo info in target.GetType().GetFields(flags)) { + if (info.Name == name) { + resolvedFieldInfo = info; + return; + } + } + + foreach (MethodInfo info in target.GetType().GetMethods(flags)) { + if (info.Name == name && info.GetParameters().Length == numberMethodParameters) { + resolvedMethodInfo = info; + return; + } + } + } + + private Type cachedTargetType; + private string cachedName; + private int cachedNumberParameters; + + private FieldInfo resolvedFieldInfo; + private PropertyInfo resolvedPropertyInfo; + private MethodInfo resolvedMethodInfo; + private PropertyInfo indexerPropertyInfo; + + #endregion + } + + /// + /// These exceptions are raised when a munger finds something it cannot process + /// + public class MungerException : ApplicationException + { + /// + /// Create a MungerException + /// + /// + /// + /// + public MungerException(SimpleMunger munger, object target, Exception ex) + : base("Munger failed", ex) { + this.munger = munger; + this.target = target; + } + + /// + /// Get the munger that raised the exception + /// + public SimpleMunger Munger { + get { return munger; } + } + private readonly SimpleMunger munger; + + /// + /// Gets the target that threw the exception + /// + public object Target { + get { return target; } + } + private readonly object target; + } + + /* + * We don't currently need this + * 2010-08-06 + * + + internal class SimpleBinder : Binder + { + public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, System.Globalization.CultureInfo culture) { + //return Type.DefaultBinder.BindToField( + throw new NotImplementedException(); + } + + public override object ChangeType(object value, Type type, System.Globalization.CultureInfo culture) { + throw new NotImplementedException(); + } + + public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] names, out object state) { + throw new NotImplementedException(); + } + + public override void ReorderArgumentArray(ref object[] args, object state) { + throw new NotImplementedException(); + } + + public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { + throw new NotImplementedException(); + } + + public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { + if (match == null) + throw new ArgumentNullException("match"); + + if (match.Length == 0) + return null; + + return match[0]; + } + } + */ + +} diff --git a/ObjectListView/Implementation/NativeMethods.cs b/ObjectListView/Implementation/NativeMethods.cs new file mode 100644 index 0000000..d48588f --- /dev/null +++ b/ObjectListView/Implementation/NativeMethods.cs @@ -0,0 +1,1223 @@ +/* + * NativeMethods - All the Windows SDK structures and imports + * + * Author: Phillip Piper + * Date: 10/10/2006 + * + * Change log: + * v2.8.0 + * 2014-05-21 JPP - Added DeselectOneItem + * - Added new imagelist drawing + * v2.3 + * 2006-10-10 JPP - Initial version + * + * To do: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Wrapper for all native method calls on ListView controls + /// + internal static class NativeMethods + { + #region Constants + + private const int LVM_FIRST = 0x1000; + private const int LVM_GETCOLUMN = LVM_FIRST + 95; + private const int LVM_GETCOUNTPERPAGE = LVM_FIRST + 40; + private const int LVM_GETGROUPINFO = LVM_FIRST + 149; + private const int LVM_GETGROUPSTATE = LVM_FIRST + 92; + private const int LVM_GETHEADER = LVM_FIRST + 31; + private const int LVM_GETTOOLTIPS = LVM_FIRST + 78; + private const int LVM_GETTOPINDEX = LVM_FIRST + 39; + private const int LVM_HITTEST = LVM_FIRST + 18; + private const int LVM_INSERTGROUP = LVM_FIRST + 145; + private const int LVM_REMOVEALLGROUPS = LVM_FIRST + 160; + private const int LVM_SCROLL = LVM_FIRST + 20; + private const int LVM_SETBKIMAGE = LVM_FIRST + 0x8A; + private const int LVM_SETCOLUMN = LVM_FIRST + 96; + private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54; + private const int LVM_SETGROUPINFO = LVM_FIRST + 147; + private const int LVM_SETGROUPMETRICS = LVM_FIRST + 155; + private const int LVM_SETIMAGELIST = LVM_FIRST + 3; + private const int LVM_SETITEM = LVM_FIRST + 76; + private const int LVM_SETITEMCOUNT = LVM_FIRST + 47; + private const int LVM_SETITEMSTATE = LVM_FIRST + 43; + private const int LVM_SETSELECTEDCOLUMN = LVM_FIRST + 140; + private const int LVM_SETTOOLTIPS = LVM_FIRST + 74; + private const int LVM_SUBITEMHITTEST = LVM_FIRST + 57; + private const int LVS_EX_SUBITEMIMAGES = 0x0002; + + private const int LVIF_TEXT = 0x0001; + private const int LVIF_IMAGE = 0x0002; + private const int LVIF_PARAM = 0x0004; + private const int LVIF_STATE = 0x0008; + private const int LVIF_INDENT = 0x0010; + private const int LVIF_NORECOMPUTE = 0x0800; + + private const int LVIS_SELECTED = 2; + + private const int LVCF_FMT = 0x0001; + private const int LVCF_WIDTH = 0x0002; + private const int LVCF_TEXT = 0x0004; + private const int LVCF_SUBITEM = 0x0008; + private const int LVCF_IMAGE = 0x0010; + private const int LVCF_ORDER = 0x0020; + private const int LVCFMT_LEFT = 0x0000; + private const int LVCFMT_RIGHT = 0x0001; + private const int LVCFMT_CENTER = 0x0002; + private const int LVCFMT_JUSTIFYMASK = 0x0003; + + private const int LVCFMT_IMAGE = 0x0800; + private const int LVCFMT_BITMAP_ON_RIGHT = 0x1000; + private const int LVCFMT_COL_HAS_IMAGES = 0x8000; + + private const int LVBKIF_SOURCE_NONE = 0x0; + private const int LVBKIF_SOURCE_HBITMAP = 0x1; + private const int LVBKIF_SOURCE_URL = 0x2; + private const int LVBKIF_SOURCE_MASK = 0x3; + private const int LVBKIF_STYLE_NORMAL = 0x0; + private const int LVBKIF_STYLE_TILE = 0x10; + private const int LVBKIF_STYLE_MASK = 0x10; + private const int LVBKIF_FLAG_TILEOFFSET = 0x100; + private const int LVBKIF_TYPE_WATERMARK = 0x10000000; + private const int LVBKIF_FLAG_ALPHABLEND = 0x20000000; + + private const int LVSICF_NOINVALIDATEALL = 1; + private const int LVSICF_NOSCROLL = 2; + + private const int HDM_FIRST = 0x1200; + private const int HDM_HITTEST = HDM_FIRST + 6; + private const int HDM_GETITEMRECT = HDM_FIRST + 7; + private const int HDM_GETITEM = HDM_FIRST + 11; + private const int HDM_SETITEM = HDM_FIRST + 12; + + private const int HDI_WIDTH = 0x0001; + private const int HDI_TEXT = 0x0002; + private const int HDI_FORMAT = 0x0004; + private const int HDI_BITMAP = 0x0010; + private const int HDI_IMAGE = 0x0020; + + private const int HDF_LEFT = 0x0000; + private const int HDF_RIGHT = 0x0001; + private const int HDF_CENTER = 0x0002; + private const int HDF_JUSTIFYMASK = 0x0003; + private const int HDF_RTLREADING = 0x0004; + private const int HDF_STRING = 0x4000; + private const int HDF_BITMAP = 0x2000; + private const int HDF_BITMAP_ON_RIGHT = 0x1000; + private const int HDF_IMAGE = 0x0800; + private const int HDF_SORTUP = 0x0400; + private const int HDF_SORTDOWN = 0x0200; + + private const int SB_HORZ = 0; + private const int SB_VERT = 1; + private const int SB_CTL = 2; + private const int SB_BOTH = 3; + + private const int SIF_RANGE = 0x0001; + private const int SIF_PAGE = 0x0002; + private const int SIF_POS = 0x0004; + private const int SIF_DISABLENOSCROLL = 0x0008; + private const int SIF_TRACKPOS = 0x0010; + private const int SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS); + + private const int ILD_NORMAL = 0x0; + private const int ILD_TRANSPARENT = 0x1; + private const int ILD_MASK = 0x10; + private const int ILD_IMAGE = 0x20; + private const int ILD_BLEND25 = 0x2; + private const int ILD_BLEND50 = 0x4; + + const int SWP_NOSIZE = 1; + const int SWP_NOMOVE = 2; + const int SWP_NOZORDER = 4; + const int SWP_NOREDRAW = 8; + const int SWP_NOACTIVATE = 16; + public const int SWP_FRAMECHANGED = 32; + + const int SWP_ZORDERONLY = SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOACTIVATE; + const int SWP_SIZEONLY = SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER | SWP_NOACTIVATE; + const int SWP_UPDATE_FRAME = SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED; + + #endregion + + #region Structures + + [StructLayout(LayoutKind.Sequential)] + public struct HDITEM + { + public int mask; + public int cxy; + public IntPtr pszText; + public IntPtr hbm; + public int cchTextMax; + public int fmt; + public IntPtr lParam; + public int iImage; + public int iOrder; + //if (_WIN32_IE >= 0x0500) + public int type; + public IntPtr pvFilter; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDLAYOUT + { + public IntPtr prc; + public IntPtr pwpos; + } + + [StructLayout(LayoutKind.Sequential)] + public struct IMAGELISTDRAWPARAMS + { + public int cbSize; + public IntPtr himl; + public int i; + public IntPtr hdcDst; + public int x; + public int y; + public int cx; + public int cy; + public int xBitmap; + public int yBitmap; + public uint rgbBk; + public uint rgbFg; + public uint fStyle; + public uint dwRop; + public uint fState; + public uint Frame; + public uint crEffect; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVBKIMAGE + { + public int ulFlags; + public IntPtr hBmp; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszImage; + public int cchImageMax; + public int xOffset; + public int yOffset; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVCOLUMN + { + public int mask; + public int fmt; + public int cx; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iSubItem; + // These are available in Common Controls >= 0x0300 + public int iImage; + public int iOrder; + }; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVFINDINFO + { + public int flags; + public string psz; + public IntPtr lParam; + public int ptX; + public int ptY; + public int vkDirection; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public int cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP2 + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public uint cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubtitle; + public uint cchSubtitle; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszTask; + public uint cchTask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionTop; + public uint cchDescriptionTop; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionBottom; + public uint cchDescriptionBottom; + public int iTitleImage; + public int iExtendedImage; + public int iFirstItem; // Read only + public int cItems; // Read only + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubsetTitle; // NULL if group is not subset + public uint cchSubsetTitle; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUPMETRICS + { + public uint cbSize; + public uint mask; + public uint Left; + public uint Top; + public uint Right; + public uint Bottom; + public int crLeft; + public int crTop; + public int crRight; + public int crBottom; + public int crHeader; + public int crFooter; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + public int iSubItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVITEM + { + public int mask; + public int iItem; + public int iSubItem; + public int state; + public int stateMask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iImage; + public IntPtr lParam; + // These are available in Common Controls >= 0x0300 + public int iIndent; + // These are available in Common Controls >= 0x056 + public int iGroupId; + public int cColumns; + public IntPtr puColumns; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct NMHDR + { + public IntPtr hwndFrom; + public IntPtr idFrom; + public int code; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMCUSTOMDRAW + { + public NativeMethods.NMHDR nmcd; + public int dwDrawStage; + public IntPtr hdc; + public NativeMethods.RECT rc; + public IntPtr dwItemSpec; + public int uItemState; + public IntPtr lItemlParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMHEADER + { + public NMHDR nhdr; + public int iItem; + public int iButton; + public IntPtr pHDITEM; + } + + const int MAX_LINKID_TEXT = 48; + const int L_MAX_URL_LENGTH = 2048 + 32 + 4; + //#define L_MAX_URL_LENGTH (2048 + 32 + sizeof("://")) + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct LITEM + { + public uint mask; + public int iLink; + public uint state; + public uint stateMask; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_LINKID_TEXT)] + public string szID; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = L_MAX_URL_LENGTH)] + public string szUrl; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLISTVIEW + { + public NativeMethods.NMHDR hdr; + public int iItem; + public int iSubItem; + public int uNewState; + public int uOldState; + public int uChanged; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVCUSTOMDRAW + { + public NativeMethods.NMCUSTOMDRAW nmcd; + public int clrText; + public int clrTextBk; + public int iSubItem; + public int dwItemType; + public int clrFace; + public int iIconEffect; + public int iIconPhase; + public int iPartId; + public int iStateId; + public NativeMethods.RECT rcText; + public uint uAlign; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVFINDITEM + { + public NativeMethods.NMHDR hdr; + public int iStart; + public NativeMethods.LVFINDINFO lvfi; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGETINFOTIP + { + public NativeMethods.NMHDR hdr; + public int dwFlags; + public string pszText; + public int cchTextMax; + public int iItem; + public int iSubItem; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGROUP + { + public NMHDR hdr; + public int iGroupId; // which group is changing + public uint uNewState; // LVGS_xxx flags + public uint uOldState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVLINK + { + public NMHDR hdr; + public LITEM link; + public int iItem; + public int iSubItem; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVSCROLL + { + public NativeMethods.NMHDR hdr; + public int dx; + public int dy; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct NMTTDISPINFO + { + public NativeMethods.NMHDR hdr; + [MarshalAs(UnmanagedType.LPTStr)] + public string lpszText; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] + public string szText; + public IntPtr hinst; + public int uFlags; + public IntPtr lParam; + //public int hbmp; This is documented but doesn't work + } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + } + + [StructLayout(LayoutKind.Sequential)] + public class SCROLLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO)); + public int fMask; + public int nMin; + public int nMax; + public int nPage; + public int nPos; + public int nTrackPos; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class TOOLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.TOOLINFO)); + public int uFlags; + public IntPtr hwnd; + public IntPtr uId; + public NativeMethods.RECT rect; + public IntPtr hinst = IntPtr.Zero; + public IntPtr lpszText; + public IntPtr lParam = IntPtr.Zero; + } + + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPOS + { + public IntPtr hwnd; + public IntPtr hwndInsertAfter; + public int x; + public int y; + public int cx; + public int cy; + public int flags; + } + + #endregion + + #region Entry points + + // Various flavours of SendMessage: plain vanilla, and passing references to various structures + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVHITTESTINFO ht); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageRECT(IntPtr hWnd, int msg, int wParam, ref RECT r); + //[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + //private static extern IntPtr SendMessageLVColumn(IntPtr hWnd, int m, int wParam, ref LVCOLUMN lvc); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + private static extern IntPtr SendMessageHDItem(IntPtr hWnd, int msg, int wParam, ref HDITEM hdi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageHDHITTESTINFO(IntPtr hWnd, int Msg, IntPtr wParam, [In, Out] HDHITTESTINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageTOOLINFO(IntPtr hWnd, int Msg, int wParam, NativeMethods.TOOLINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVBKIMAGE(IntPtr hWnd, int Msg, int wParam, ref NativeMethods.LVBKIMAGE lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageString(IntPtr hWnd, int Msg, int wParam, string lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageIUnknown(IntPtr hWnd, int msg, [MarshalAs(UnmanagedType.IUnknown)] object wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP2 lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUPMETRICS lParam); + + [DllImport("gdi32.dll")] + public static extern bool DeleteObject(IntPtr objectHandle); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetClientRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo); + + [DllImport("user32.dll", EntryPoint = "GetUpdateRect", CharSet = CharSet.Auto)] + private static extern bool GetUpdateRectInternal(IntPtr hWnd, ref Rectangle r, bool eraseBackground); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_Draw(IntPtr himl, int i, IntPtr hdcDst, int x, int y, int fStyle); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_DrawIndirect(ref IMAGELISTDRAWPARAMS parms); + + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll", EntryPoint = "ValidateRect", CharSet = CharSet.Auto)] + private static extern IntPtr ValidatedRectInternal(IntPtr hWnd, ref Rectangle r); + + #endregion + + //[DllImport("user32.dll", EntryPoint = "LockWindowUpdate", CharSet = CharSet.Auto)] + //private static extern int LockWindowUpdateInternal(IntPtr hWnd); + + //public static void LockWindowUpdate(IWin32Window window) { + // if (window == null) + // NativeMethods.LockWindowUpdateInternal(IntPtr.Zero); + // else + // NativeMethods.LockWindowUpdateInternal(window.Handle); + //} + + /// + /// Put an image under the ListView. + /// + /// + /// + /// The ListView must have its handle created before calling this. + /// + /// + /// This doesn't work very well. Specifically, it doesn't play well with owner drawn, + /// and grid lines are drawn over it. + /// + /// + /// + /// The image to be used as the background. If this is null, any existing background image will be cleared. + /// If this is true, the image is pinned to the bottom right and does not scroll. The other parameters are ignored + /// If this is true, the image will be tiled to fill the whole control background. The offset parameters will be ignored. + /// If both watermark and tiled are false, this indicates the horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// If both watermark and tiled are false, this indicates the vertical percentage where the image will be placed. + /// + public static bool SetBackgroundImage(ListView lv, Image image, bool isWatermark, bool isTiled, int xOffset, int yOffset) { + + LVBKIMAGE lvbkimage = new LVBKIMAGE(); + + // We have to clear any pre-existing background image, otherwise the attempt to set the image will fail. + // We don't know which type may already have been set, so we just clear both the watermark and the image. + lvbkimage.ulFlags = LVBKIF_TYPE_WATERMARK; + IntPtr result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + lvbkimage.ulFlags = LVBKIF_SOURCE_HBITMAP; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + + Bitmap bm = image as Bitmap; + if (bm != null) { + lvbkimage.hBmp = bm.GetHbitmap(); + lvbkimage.ulFlags = isWatermark ? LVBKIF_TYPE_WATERMARK : (isTiled ? LVBKIF_SOURCE_HBITMAP | LVBKIF_STYLE_TILE : LVBKIF_SOURCE_HBITMAP); + lvbkimage.xOffset = xOffset; + lvbkimage.yOffset = yOffset; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + } + + return (result != IntPtr.Zero); + } + + public static bool DrawImageList(Graphics g, ImageList il, int index, int x, int y, bool isSelected, bool isDisabled) { + ImageListDrawItemConstants flags = (isSelected ? ImageListDrawItemConstants.ILD_SELECTED : ImageListDrawItemConstants.ILD_NORMAL) | ImageListDrawItemConstants.ILD_TRANSPARENT; + ImageListDrawStateConstants state = isDisabled ? ImageListDrawStateConstants.ILS_SATURATE : ImageListDrawStateConstants.ILS_NORMAL; + try { + IntPtr hdc = g.GetHdc(); + return DrawImage(il, hdc, index, x, y, flags, 0, 0, state); + } + finally { + g.ReleaseHdc(); + } + } + + /// + /// Flags controlling how the Image List item is + /// drawn + /// + [Flags] + public enum ImageListDrawItemConstants + { + /// + /// Draw item normally. + /// + ILD_NORMAL = 0x0, + /// + /// Draw item transparently. + /// + ILD_TRANSPARENT = 0x1, + /// + /// Draw item blended with 25% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_BLEND25 = 0x2, + /// + /// Draw item blended with 50% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_SELECTED = 0x4, + /// + /// Draw the icon's mask + /// + ILD_MASK = 0x10, + /// + /// Draw the icon image without using the mask + /// + ILD_IMAGE = 0x20, + /// + /// Draw the icon using the ROP specified. + /// + ILD_ROP = 0x40, + /// + /// Preserves the alpha channel in dest. XP only. + /// + ILD_PRESERVEALPHA = 0x1000, + /// + /// Scale the image to cx, cy instead of clipping it. XP only. + /// + ILD_SCALE = 0x2000, + /// + /// Scale the image to the current DPI of the display. XP only. + /// + ILD_DPISCALE = 0x4000 + } + + /// + /// Enumeration containing XP ImageList Draw State options + /// + [Flags] + public enum ImageListDrawStateConstants + { + /// + /// The image state is not modified. + /// + ILS_NORMAL = (0x00000000), + /// + /// Adds a glow effect to the icon, which causes the icon to appear to glow + /// with a given color around the edges. (Note: does not appear to be implemented) + /// + ILS_GLOW = (0x00000001), //The color for the glow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Adds a drop shadow effect to the icon. (Note: does not appear to be implemented) + /// + ILS_SHADOW = (0x00000002), //The color for the drop shadow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Saturates the icon by increasing each color component + /// of the RGB triplet for each pixel in the icon. (Note: only ever appears to result in a completely unsaturated icon) + /// + ILS_SATURATE = (0x00000004), // The amount to increase is indicated by the frame member in the IMAGELISTDRAWPARAMS method. + /// + /// Alpha blends the icon. Alpha blending controls the transparency + /// level of an icon, according to the value of its alpha channel. + /// (Note: does not appear to be implemented). + /// + ILS_ALPHA = (0x00000008) //The value of the alpha channel is indicated by the frame member in the IMAGELISTDRAWPARAMS method. The alpha channel can be from 0 to 255, with 0 being completely transparent, and 255 being completely opaque. + } + + private const uint CLR_DEFAULT = 0xFF000000; + + /// + /// Draws an image using the specified flags and state on XP systems. + /// + /// The image list from which an item will be drawn + /// Device context to draw to + /// Index of image to draw + /// X Position to draw at + /// Y Position to draw at + /// Drawing flags + /// Width to draw + /// Height to draw + /// State flags + public static bool DrawImage(ImageList il, IntPtr hdc, int index, int x, int y, ImageListDrawItemConstants flags, int cx, int cy, ImageListDrawStateConstants stateFlags) { + IMAGELISTDRAWPARAMS pimldp = new IMAGELISTDRAWPARAMS(); + pimldp.hdcDst = hdc; + pimldp.cbSize = Marshal.SizeOf(pimldp.GetType()); + pimldp.i = index; + pimldp.x = x; + pimldp.y = y; + pimldp.cx = cx; + pimldp.cy = cy; + pimldp.rgbFg = CLR_DEFAULT; + pimldp.fStyle = (uint) flags; + pimldp.fState = (uint) stateFlags; + pimldp.himl = il.Handle; + return ImageList_DrawIndirect(ref pimldp); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + public static void ForceSubItemImagesExStyle(ListView list) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES); + } + + /// + /// Change the virtual list size of the given ListView (which must be in virtual mode) + /// + /// This will not change the scroll position + /// The listview to send a message to + /// How many rows should the list have? + public static void SetItemCount(ListView list, int count) { + SendMessage(list.Handle, LVM_SETITEMCOUNT, count, LVSICF_NOSCROLL); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + /// + /// + public static void SetExtendedStyle(ListView list, int style, int styleMask) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, styleMask, style); + } + + /// + /// Calculates the number of items that can fit vertically in the visible area of a list-view (which + /// must be in details or list view. + /// + /// The listView + /// Number of visible items per page + public static int GetCountPerPage(ListView list) { + return (int)SendMessage(list.Handle, LVM_GETCOUNTPERPAGE, 0, 0); + } + /// + /// For the given item and subitem, make it display the given image + /// + /// The listview to send a m to + /// row number (0 based) + /// subitem (0 is the item itself) + /// index into the image list + public static void SetSubItemImage(ListView list, int itemIndex, int subItemIndex, int imageIndex) { + LVITEM lvItem = new LVITEM(); + lvItem.mask = LVIF_IMAGE; + lvItem.iItem = itemIndex; + lvItem.iSubItem = subItemIndex; + lvItem.iImage = imageIndex; + SendMessageLVItem(list.Handle, LVM_SETITEM, 0, ref lvItem); + } + + /// + /// Setup the given column of the listview to show the given image to the right of the text. + /// If the image index is -1, any previous image is cleared + /// + /// The listview to send a m to + /// Index of the column to modify + /// + /// Index into the small image list + public static void SetColumnImage(ListView list, int columnIndex, SortOrder order, int imageIndex) { + IntPtr hdrCntl = NativeMethods.GetHeaderControl(list); + if (hdrCntl.ToInt32() == 0) + return; + + HDITEM item = new HDITEM(); + item.mask = HDI_FORMAT; + IntPtr result = SendMessageHDItem(hdrCntl, HDM_GETITEM, columnIndex, ref item); + + item.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN | HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + + if (NativeMethods.HasBuiltinSortIndicators()) { + if (order == SortOrder.Ascending) + item.fmt |= HDF_SORTUP; + if (order == SortOrder.Descending) + item.fmt |= HDF_SORTDOWN; + } else { + item.mask |= HDI_IMAGE; + item.fmt |= (HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + item.iImage = imageIndex; + } + + result = SendMessageHDItem(hdrCntl, HDM_SETITEM, columnIndex, ref item); + } + + /// + /// Does this version of the operating system have builtin sort indicators? + /// + /// Are there builtin sort indicators + /// XP and later have these + public static bool HasBuiltinSortIndicators() { + return OSFeature.Feature.GetVersionPresent(OSFeature.Themes) != null; + } + + /// + /// Return the bounds of the update region on the given control. + /// + /// The BeginPaint() system call validates the update region, effectively wiping out this information. + /// So this call has to be made before the BeginPaint() call. + /// The control whose update region is be calculated + /// A rectangle + public static Rectangle GetUpdateRect(Control cntl) { + Rectangle r = new Rectangle(); + GetUpdateRectInternal(cntl.Handle, ref r, false); + return r; + } + + /// + /// Validate an area of the given control. A validated area will not be repainted at the next redraw. + /// + /// The control to be validated + /// The area of the control to be validated + public static void ValidateRect(Control cntl, Rectangle r) { + ValidatedRectInternal(cntl.Handle, ref r); + } + + /// + /// Select all rows on the given listview + /// + /// The listview whose items are to be selected + public static void SelectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, LVIS_SELECTED); + } + + /// + /// Deselect all rows on the given listview + /// + /// The listview whose items are to be deselected + public static void DeselectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, 0); + } + + /// + /// Deselect a single row + /// + /// + /// + public static void DeselectOneItem(ListView list, int index) { + NativeMethods.SetItemState(list, index, LVIS_SELECTED, 0); + } + + /// + /// Set the item state on the given item + /// + /// The listview whose item's state is to be changed + /// The index of the item to be changed + /// Which bits of the value are to be set? + /// The value to be set + public static void SetItemState(ListView list, int itemIndex, int mask, int value) { + LVITEM lvItem = new LVITEM(); + lvItem.stateMask = mask; + lvItem.state = value; + SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem); + } + + /// + /// Scroll the given listview by the given deltas + /// + /// + /// + /// + /// true if the scroll succeeded + public static bool Scroll(ListView list, int dx, int dy) { + return SendMessage(list.Handle, LVM_SCROLL, dx, dy) != IntPtr.Zero; + } + + /// + /// Return the handle to the header control on the given list + /// + /// The listview whose header control is to be returned + /// The handle to the header control + public static IntPtr GetHeaderControl(ListView list) { + return SendMessage(list.Handle, LVM_GETHEADER, 0, 0); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetColumnSides(ObjectListView lv, int columnIndex) { + Point sides = new Point(-1, -1); + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + return new Point(r.left, r.right); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetScrolledColumnSides(ListView lv, int columnIndex) { + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + IntPtr result = NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + int scrollH = NativeMethods.GetScrollPosition(lv, true); + return new Point(r.left - scrollH, r.right - scrollH); + } + + /// + /// Return the index of the column of the header that is under the given point. + /// Return -1 if no column is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the column under the point, or -1 if no column header is under that point + public static int GetColumnUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONHEADER = 2; + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONHEADER | HHT_ONDIVIDER); + } + + private static int HeaderControlHitTest(IntPtr handle, Point pt, int flag) { + HDHITTESTINFO testInfo = new HDHITTESTINFO(); + testInfo.pt_x = pt.X; + testInfo.pt_y = pt.Y; + IntPtr result = NativeMethods.SendMessageHDHITTESTINFO(handle, HDM_HITTEST, IntPtr.Zero, testInfo); + if ((testInfo.flags & flag) != 0) + return testInfo.iItem; + else + return -1; + } + + /// + /// Return the index of the divider under the given point. Return -1 if no divider is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the divider under the point, or -1 if no divider is under that point + public static int GetDividerUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONDIVIDER); + } + + /// + /// Get the scroll position of the given scroll bar + /// + /// + /// + /// + public static int GetScrollPosition(ListView lv, bool horizontalBar) { + int fnBar = (horizontalBar ? SB_HORZ : SB_VERT); + + SCROLLINFO scrollInfo = new SCROLLINFO(); + scrollInfo.fMask = SIF_POS; + if (GetScrollInfo(lv.Handle, fnBar, scrollInfo)) + return scrollInfo.nPos; + else + return -1; + } + + /// + /// Change the z-order to the window 'toBeMoved' so it appear directly on top of 'reference' + /// + /// + /// + /// + public static bool ChangeZOrder(IWin32Window toBeMoved, IWin32Window reference) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, reference.Handle, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Make the given control/window a topmost window + /// + /// + /// + public static bool MakeTopMost(IWin32Window toBeMoved) { + IntPtr HWND_TOPMOST = (IntPtr)(-1); + return NativeMethods.SetWindowPos(toBeMoved.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Change the size of the window without affecting any other attributes + /// + /// + /// + /// + /// + public static bool ChangeSize(IWin32Window toBeMoved, int width, int height) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, IntPtr.Zero, 0, 0, width, height, SWP_SIZEONLY); + } + + /// + /// Show the given window without activating it + /// + /// The window to show + static public void ShowWithoutActivate(IWin32Window win) { + const int SW_SHOWNA = 8; + NativeMethods.ShowWindow(win.Handle, SW_SHOWNA); + } + + /// + /// Mark the given column as being selected. + /// + /// + /// The OLVColumn or null to clear + /// + /// This method works, but it prevents subitems in the given column from having + /// back colors. + /// + static public void SetSelectedColumn(ListView objectListView, ColumnHeader value) { + NativeMethods.SendMessage(objectListView.Handle, + LVM_SETSELECTEDCOLUMN, (value == null) ? -1 : value.Index, 0); + } + + static public int GetTopIndex(ListView lv) { + return (int)SendMessage(lv.Handle, LVM_GETTOPINDEX, 0, 0); + } + + static public IntPtr GetTooltipControl(ListView lv) { + return SendMessage(lv.Handle, LVM_GETTOOLTIPS, 0, 0); + } + + static public IntPtr SetTooltipControl(ListView lv, ToolTipControl tooltip) { + return SendMessage(lv.Handle, LVM_SETTOOLTIPS, 0, tooltip.Handle); + } + + static public bool HasHorizontalScrollBar(ListView lv) { + const int GWL_STYLE = -16; + const int WS_HSCROLL = 0x00100000; + + return (NativeMethods.GetWindowLong(lv.Handle, GWL_STYLE) & WS_HSCROLL) != 0; + } + + public static int GetWindowLong(IntPtr hWnd, int nIndex) { + if (IntPtr.Size == 4) + return (int)GetWindowLong32(hWnd, nIndex); + else + return (int)(long)GetWindowLongPtr64(hWnd, nIndex); + } + + public static int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong) { + if (IntPtr.Size == 4) + return (int)SetWindowLongPtr32(hWnd, nIndex, dwNewLong); + else + return (int)(long)SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + } + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetBkColor(IntPtr hDC, int clr); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetTextColor(IntPtr hDC, int crColor); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj); + + [DllImport("uxtheme.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetWindowTheme(IntPtr hWnd, string subApp, string subIdList); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool InvalidateRect(IntPtr hWnd, int ignored, bool erase); + + [StructLayout(LayoutKind.Sequential)] + public struct LVITEMINDEX + { + public int iItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential)] + public struct POINT + { + public int x; + public int y; + } + + public static int GetGroupInfo(ObjectListView olv, int groupId, ref LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPINFO, groupId, ref group); + } + + public static GroupState GetGroupState(ObjectListView olv, int groupId, GroupState mask) { + return (GroupState)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPSTATE, groupId, (int)mask); + } + + public static int InsertGroup(ObjectListView olv, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_INSERTGROUP, -1, ref group); + } + + public static int SetGroupInfo(ObjectListView olv, int groupId, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPINFO, groupId, ref group); + } + + public static int SetGroupMetrics(ObjectListView olv, LVGROUPMETRICS metrics) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPMETRICS, 0, ref metrics); + } + + public static void ClearGroups(VirtualObjectListView virtualObjectListView) { + NativeMethods.SendMessage(virtualObjectListView.Handle, LVM_REMOVEALLGROUPS, 0, 0); + } + + public static void SetGroupImageList(ObjectListView olv, ImageList il) { + const int LVSIL_GROUPHEADER = 3; + NativeMethods.SendMessage(olv.Handle, LVM_SETIMAGELIST, LVSIL_GROUPHEADER, il == null ? IntPtr.Zero : il.Handle); + } + + public static int HitTest(ObjectListView olv, ref LVHITTESTINFO hittest) + { + return (int)NativeMethods.SendMessage(olv.Handle, olv.View == View.Details ? LVM_SUBITEMHITTEST : LVM_HITTEST, -1, ref hittest); + } + } +} diff --git a/ObjectListView/Implementation/NullableDictionary.cs b/ObjectListView/Implementation/NullableDictionary.cs new file mode 100644 index 0000000..79b3c1e --- /dev/null +++ b/ObjectListView/Implementation/NullableDictionary.cs @@ -0,0 +1,87 @@ +/* + * NullableDictionary - A simple Dictionary that can handle null as a key + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2017 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace BrightIdeasSoftware { + + /// + /// A simple-minded implementation of a Dictionary that can handle null as a key. + /// + /// The type of the dictionary key + /// The type of the values to be stored + /// This is not a full implementation and is only meant to handle + /// collecting groups by their keys, since groups can have null as a key value. + internal class NullableDictionary : Dictionary { + private bool hasNullKey; + private TValue nullValue; + + new public TValue this[TKey key] { + get { + if (key != null) + return base[key]; + + if (this.hasNullKey) + return this.nullValue; + + throw new KeyNotFoundException(); + } + set { + if (key == null) { + this.hasNullKey = true; + this.nullValue = value; + } else + base[key] = value; + } + } + + new public bool ContainsKey(TKey key) { + return key == null ? this.hasNullKey : base.ContainsKey(key); + } + + new public IList Keys { + get { + ArrayList list = new ArrayList(base.Keys); + if (this.hasNullKey) + list.Add(null); + return list; + } + } + + new public IList Values { + get { + List list = new List(base.Values); + if (this.hasNullKey) + list.Add(this.nullValue); + return list; + } + } + } +} diff --git a/ObjectListView/Implementation/OLVListItem.cs b/ObjectListView/Implementation/OLVListItem.cs new file mode 100644 index 0000000..d488123 --- /dev/null +++ b/ObjectListView/Implementation/OLVListItem.cs @@ -0,0 +1,325 @@ +/* + * OLVListItem - A row in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-09-01 JPP - Handle rare case of getting subitems when there are no columns + * v2.9 + * 2015-08-22 JPP - Added OLVListItem.SelectedBackColor and SelectedForeColor + * 2015-06-09 JPP - Added HasAnyHyperlinks property + * v2.8 + * 2014-09-27 JPP - Remove faulty caching of CheckState + * 2014-05-06 JPP - Added OLVListItem.Enabled flag + * vOld + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// OLVListItems are specialized ListViewItems that know which row object they came from, + /// and the row index at which they are displayed, even when in group view mode. They + /// also know the image they should draw against themselves + /// + public class OLVListItem : ListViewItem { + #region Constructors + + /// + /// Create a OLVListItem for the given row object + /// + public OLVListItem(object rowObject) { + this.rowObject = rowObject; + } + + /// + /// Create a OLVListItem for the given row object, represented by the given string and image + /// + public OLVListItem(object rowObject, string text, Object image) + : base(text, -1) { + this.rowObject = rowObject; + this.imageSelector = image; + } + + #endregion. + + #region Properties + + /// + /// Gets the bounding rectangle of the item, including all subitems + /// + new public Rectangle Bounds { + get { + try { + return base.Bounds; + } + catch (System.ArgumentException) { + // If the item is part of a collapsed group, Bounds will throw an exception + return Rectangle.Empty; + } + } + } + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how the cells of this item will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the checkedness of this item. + /// + /// + /// Virtual lists don't handle checkboxes well, so we have to intercept attempts to change them + /// through the items, and change them into something that will work. + /// Unfortunately, this won't work if this property is set through the base class, since + /// the property is not declared as virtual. + /// + new public bool Checked { + get { + return base.Checked; + } + set { + if (this.Checked != value) { + if (value) + ((ObjectListView)this.ListView).CheckObject(this.RowObject); + else + ((ObjectListView)this.ListView).UncheckObject(this.RowObject); + } + } + } + + /// + /// Enable tri-state checkbox. + /// + /// .NET's Checked property was not built to handle tri-state checkboxes, + /// and will return True for both Checked and Indeterminate states. + public CheckState CheckState { + get { + switch (this.StateImageIndex) { + case 0: + return System.Windows.Forms.CheckState.Unchecked; + case 1: + return System.Windows.Forms.CheckState.Checked; + case 2: + return System.Windows.Forms.CheckState.Indeterminate; + default: + return System.Windows.Forms.CheckState.Unchecked; + } + } + set { + switch (value) { + case System.Windows.Forms.CheckState.Unchecked: + this.StateImageIndex = 0; + break; + case System.Windows.Forms.CheckState.Checked: + this.StateImageIndex = 1; + break; + case System.Windows.Forms.CheckState.Indeterminate: + this.StateImageIndex = 2; + break; + } + } + } + + /// + /// Gets if this item has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + if (this.HasDecoration) + return this.Decorations[0]; + else + return null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Gets whether or not this row can be selected and activated + /// + public bool Enabled + { + get { return this.enabled; } + internal set { this.enabled = value; } + } + private bool enabled; + + /// + /// Gets whether any cell on this item is showing a hyperlink + /// + public bool HasAnyHyperlinks { + get { + foreach (OLVListSubItem subItem in this.SubItems) { + if (!String.IsNullOrEmpty(subItem.Url)) + return true; + } + return false; + } + } + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { + imageSelector = value; + if (value is Int32) + this.ImageIndex = (Int32)value; + else if (value is String) + this.ImageKey = (String)value; + else + this.ImageIndex = -1; + } + } + private Object imageSelector; + + /// + /// Gets or sets the model object that is source of the data for this list item. + /// + public object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + private object rowObject; + + /// + /// Gets or sets the color that will be used for this row's background when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection BackColor will be used. + /// + /// + public Color? SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color? selectedBackColor; + + /// + /// Gets or sets the color that will be used for this row's foreground when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection ForeColor will be used. + /// + /// + public Color? SelectedForeColor + { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color? selectedForeColor; + + #endregion + + #region Accessing + + /// + /// Return the sub item at the given index + /// + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index) { + if (index >= 0 && index < this.SubItems.Count) + // If the control has 0 columns, ListViewItem.SubItems will auto create a + // SubItem of the wrong type. Casting using 'as' handles this rare case. + return this.SubItems[index] as OLVListSubItem; + + return null; + } + + + /// + /// Return bounds of the given subitem + /// + /// This correctly calculates the bounds even for column 0. + public virtual Rectangle GetSubItemBounds(int subItemIndex) { + if (subItemIndex == 0) { + Rectangle r = this.Bounds; + Point sides = NativeMethods.GetScrolledColumnSides(this.ListView, subItemIndex); + r.X = sides.X + 1; + r.Width = sides.Y - sides.X; + return r; + } + + OLVListSubItem subItem = this.GetSubItem(subItemIndex); + return subItem == null ? new Rectangle() : subItem.Bounds; + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/OLVListSubItem.cs b/ObjectListView/Implementation/OLVListSubItem.cs new file mode 100644 index 0000000..e4f5bfe --- /dev/null +++ b/ObjectListView/Implementation/OLVListSubItem.cs @@ -0,0 +1,173 @@ +/* + * OLVListSubItem - A single cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.ComponentModel; + +namespace BrightIdeasSoftware { + + /// + /// A ListViewSubItem that knows which image should be drawn against it. + /// + [Browsable(false)] + public class OLVListSubItem : ListViewItem.ListViewSubItem { + #region Constructors + + /// + /// Create a OLVListSubItem + /// + public OLVListSubItem() { + } + + /// + /// Create a OLVListSubItem that shows the given string and image + /// + public OLVListSubItem(object modelValue, string text, Object image) { + this.ModelValue = modelValue; + this.Text = text; + this.ImageSelector = image; + } + + #endregion + + #region Properties + + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how this cell will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the model value is being displayed by this subitem. + /// + public object ModelValue + { + get { return modelValue; } + private set { modelValue = value; } + } + private object modelValue; + + /// + /// Gets if this subitem has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + return this.HasDecoration ? this.Decorations[0] : null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + private Object imageSelector; + + /// + /// Gets or sets the url that should be invoked when this subitem is clicked + /// + public string Url + { + get { return this.url; } + set { this.url = value; } + } + private string url; + + /// + /// Gets or sets whether this cell is selected + /// + public bool Selected + { + get { return this.selected; } + set { this.selected = value; } + } + private bool selected; + + #endregion + + #region Implementation Properties + + /// + /// Return the state of the animation of the image on this subitem. + /// Null means there is either no image, or it is not an animation + /// + internal ImageRenderer.AnimationState AnimationState; + + #endregion + } + +} diff --git a/ObjectListView/Implementation/OlvListViewHitTestInfo.cs b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs new file mode 100644 index 0000000..7cc28eb --- /dev/null +++ b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs @@ -0,0 +1,388 @@ +/* + * OlvListViewHitTestInfo - All information gathered during a OlvHitTest() operation + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// An indication of where a hit was within ObjectListView cell + /// + public enum HitTestLocation { + /// + /// Nowhere + /// + Nothing, + + /// + /// On the text + /// + Text, + + /// + /// On the image + /// + Image, + + /// + /// On the checkbox + /// + CheckBox, + + /// + /// On the expand button (TreeListView) + /// + ExpandButton, + + /// + /// in a button (cell must have ButtonRenderer) + /// + Button, + + /// + /// in the cell but not in any more specific location + /// + InCell, + + /// + /// UserDefined location1 (used for custom renderers) + /// + UserDefined, + + /// + /// On the expand/collapse widget of the group + /// + GroupExpander, + + /// + /// Somewhere on a group + /// + Group, + + /// + /// Somewhere in a column header + /// + Header, + + /// + /// Somewhere in a column header checkbox + /// + HeaderCheckBox, + + /// + /// Somewhere in a header divider + /// + HeaderDivider, + } + + /// + /// A collection of ListViewHitTest constants + /// + [Flags] + public enum HitTestLocationEx { + /// + /// + /// + LVHT_NOWHERE = 0x00000001, + /// + /// + /// + LVHT_ONITEMICON = 0x00000002, + /// + /// + /// + LVHT_ONITEMLABEL = 0x00000004, + /// + /// + /// + LVHT_ONITEMSTATEICON = 0x00000008, + /// + /// + /// + LVHT_ONITEM = (LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON), + + /// + /// + /// + LVHT_ABOVE = 0x00000008, + /// + /// + /// + LVHT_BELOW = 0x00000010, + /// + /// + /// + LVHT_TORIGHT = 0x00000020, + /// + /// + /// + LVHT_TOLEFT = 0x00000040, + + /// + /// + /// + LVHT_EX_GROUP_HEADER = 0x10000000, + /// + /// + /// + LVHT_EX_GROUP_FOOTER = 0x20000000, + /// + /// + /// + LVHT_EX_GROUP_COLLAPSE = 0x40000000, + /// + /// + /// + LVHT_EX_GROUP_BACKGROUND = -2147483648, // 0x80000000 + /// + /// + /// + LVHT_EX_GROUP_STATEICON = 0x01000000, + /// + /// + /// + LVHT_EX_GROUP_SUBSETLINK = 0x02000000, + /// + /// + /// + LVHT_EX_GROUP = (LVHT_EX_GROUP_BACKGROUND | LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_FOOTER | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD = (LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_ONCONTENTS = 0x04000000, // On item AND not on the background + /// + /// + /// + LVHT_EX_FOOTER = 0x08000000, + } + + /// + /// Instances of this class encapsulate the information gathered during a OlvHitTest() + /// operation. + /// + /// Custom renderers can use HitTestLocation.UserDefined and the UserData + /// object to store more specific locations for use during event handlers. + public class OlvListViewHitTestInfo { + + /// + /// Create a OlvListViewHitTestInfo + /// + public OlvListViewHitTestInfo(OLVListItem olvListItem, OLVListSubItem subItem, int flags, OLVGroup group, int iColumn) + { + this.item = olvListItem; + this.subItem = subItem; + this.location = ConvertNativeFlagsToDotNetLocation(olvListItem, flags); + this.HitTestLocationEx = (HitTestLocationEx)flags; + this.Group = group; + this.ColumnIndex = iColumn; + this.ListView = olvListItem == null ? null : (ObjectListView)olvListItem.ListView; + + switch (location) { + case ListViewHitTestLocations.StateImage: + this.HitTestLocation = HitTestLocation.CheckBox; + break; + case ListViewHitTestLocations.Image: + this.HitTestLocation = HitTestLocation.Image; + break; + case ListViewHitTestLocations.Label: + this.HitTestLocation = HitTestLocation.Text; + break; + default: + if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) == HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) + this.HitTestLocation = HitTestLocation.GroupExpander; + else if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD) != 0) + this.HitTestLocation = HitTestLocation.Group; + else + this.HitTestLocation = HitTestLocation.Nothing; + break; + } + } + + /// + /// Create a OlvListViewHitTestInfo when the header was hit + /// + public OlvListViewHitTestInfo(ObjectListView olv, int iColumn, bool isOverCheckBox, int iDivider) { + this.ListView = olv; + this.ColumnIndex = iColumn; + this.HeaderDividerIndex = iDivider; + this.HitTestLocation = isOverCheckBox ? HitTestLocation.HeaderCheckBox : (iDivider < 0 ? HitTestLocation.Header : HitTestLocation.HeaderDivider); + } + + private static ListViewHitTestLocations ConvertNativeFlagsToDotNetLocation(OLVListItem hitItem, int flags) + { + // Untangle base .NET behaviour. + + // In Windows SDK, the value 8 can have two meanings here: LVHT_ONITEMSTATEICON or LVHT_ABOVE. + // .NET changes these to be: + // - LVHT_ABOVE becomes ListViewHitTestLocations.AboveClientArea (which is 0x100). + // - LVHT_ONITEMSTATEICON becomes ListViewHitTestLocations.StateImage (which is 0x200). + // So, if we see the 8 bit set in flags, we change that to either a state image hit + // (if we hit an item) or to AboveClientAream if nothing was hit. + + if ((8 & flags) == 8) + return (ListViewHitTestLocations)(0xf7 & flags | (hitItem == null ? 0x100 : 0x200)); + + // Mask off the LVHT_EX_XXXX values since ListViewHitTestLocations doesn't have them + return (ListViewHitTestLocations)(flags & 0xffff); + } + + #region Public fields + + /// + /// Where is the hit location? + /// + public HitTestLocation HitTestLocation; + + /// + /// Where is the hit location? + /// + public HitTestLocationEx HitTestLocationEx; + + /// + /// Which group was hit? + /// + public OLVGroup Group; + + /// + /// Custom renderers can use this information to supply more details about the hit location + /// + public Object UserData; + + #endregion + + #region Public read-only properties + + /// + /// Gets the item that was hit + /// + public OLVListItem Item { + get { return item; } + internal set { item = value; } + } + private OLVListItem item; + + /// + /// Gets the subitem that was hit + /// + public OLVListSubItem SubItem { + get { return subItem; } + internal set { subItem = value; } + } + private OLVListSubItem subItem; + + /// + /// Gets the part of the subitem that was hit + /// + public ListViewHitTestLocations Location { + get { return location; } + internal set { location = value; } + } + private ListViewHitTestLocations location; + + /// + /// Gets the ObjectListView that was tested + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the model object that was hit + /// + public Object RowObject { + get { + return this.Item == null ? null : this.Item.RowObject; + } + } + + /// + /// Gets the index of the row under the hit point or -1 + /// + public int RowIndex { + get { return this.Item == null ? -1 : this.Item.Index; } + } + + /// + /// Gets the index of the column under the hit point + /// + public int ColumnIndex { + get { return columnIndex; } + internal set { columnIndex = value; } + } + private int columnIndex; + + /// + /// Gets the index of the header divider + /// + public int HeaderDividerIndex { + get { return headerDividerIndex; } + internal set { headerDividerIndex = value; } + } + private int headerDividerIndex = -1; + + /// + /// Gets the column that was hit + /// + public OLVColumn Column { + get { + int index = this.ColumnIndex; + return index < 0 || this.ListView == null ? null : this.ListView.GetColumn(index); + } + } + + #endregion + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() + { + return string.Format("HitTestLocation: {0}, HitTestLocationEx: {1}, Item: {2}, SubItem: {3}, Location: {4}, Group: {5}, ColumnIndex: {6}", + this.HitTestLocation, this.HitTestLocationEx, this.item, this.subItem, this.location, this.Group, this.ColumnIndex); + } + + internal class HeaderHitTestInfo + { + public int ColumnIndex; + public bool IsOverCheckBox; + public int OverDividerIndex; + } + } +} diff --git a/ObjectListView/Implementation/TreeDataSourceAdapter.cs b/ObjectListView/Implementation/TreeDataSourceAdapter.cs new file mode 100644 index 0000000..e54cf10 --- /dev/null +++ b/ObjectListView/Implementation/TreeDataSourceAdapter.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeDataSourceAdapter knows how to build a tree structure from a binding list. + /// + /// To build a tree + public class TreeDataSourceAdapter : DataSourceAdapter + { + #region Life and death + + /// + /// Create a data source adaptor that knows how to build a tree structure + /// + /// + public TreeDataSourceAdapter(DataTreeListView tlv) + : base(tlv) { + this.treeListView = tlv; + this.treeListView.CanExpandGetter = delegate(object model) { return this.CalculateHasChildren(model); }; + this.treeListView.ChildrenGetter = delegate(object model) { return this.CalculateChildren(model); }; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + public virtual string KeyAspectName { + get { return keyAspectName; } + set { + if (keyAspectName == value) + return; + keyAspectName = value; + this.keyMunger = new Munger(this.KeyAspectName); + this.InitializeDataSource(); + } + } + private string keyAspectName; + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + public virtual string ParentKeyAspectName { + get { return parentKeyAspectName; } + set { + if (parentKeyAspectName == value) + return; + parentKeyAspectName = value; + this.parentKeyMunger = new Munger(this.ParentKeyAspectName); + this.InitializeDataSource(); + } + } + private string parentKeyAspectName; + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. + /// + public virtual object RootKeyValue { + get { return rootKeyValue; } + set { + if (Equals(rootKeyValue, value)) + return; + rootKeyValue = value; + this.InitializeDataSource(); + } + } + private object rootKeyValue; + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + public virtual bool ShowKeyColumns { + get { return showKeyColumns; } + set { showKeyColumns = value; } + } + private bool showKeyColumns = true; + + + #endregion + + #region Implementation properties + + /// + /// Gets the DataTreeListView that is being managed + /// + protected DataTreeListView TreeListView { + get { return treeListView; } + } + private readonly DataTreeListView treeListView; + + #endregion + + #region Implementation + + /// + /// + /// + protected override void InitializeDataSource() { + base.InitializeDataSource(); + this.TreeListView.RebuildAll(true); + } + + /// + /// + /// + protected override void SetListContents() { + this.TreeListView.Roots = this.CalculateRoots(); + } + + /// + /// + /// + /// + /// + protected override bool ShouldCreateColumn(PropertyDescriptor property) { + // If the property is a key column, and we aren't supposed to show keys, don't show it + if (!this.ShowKeyColumns && (property.Name == this.KeyAspectName || property.Name == this.ParentKeyAspectName)) + return false; + + return base.ShouldCreateColumn(property); + } + + /// + /// + /// + /// + protected override void HandleListChangedItemChanged(System.ComponentModel.ListChangedEventArgs e) { + // If the id or the parent id of a row changes, we just rebuild everything. + // We can't do anything more specific. We don't know what the previous values, so we can't + // tell the previous parent to refresh itself. If the id itself has changed, things that used + // to be children will no longer be children. Just rebuild everything. + // It seems PropertyDescriptor is only filled in .NET 4 :( + if (e.PropertyDescriptor != null && + (e.PropertyDescriptor.Name == this.KeyAspectName || + e.PropertyDescriptor.Name == this.ParentKeyAspectName)) + this.InitializeDataSource(); + else + base.HandleListChangedItemChanged(e); + } + + /// + /// + /// + /// + protected override void ChangePosition(int index) { + // We can't use our base method directly, since the normal position management + // doesn't know about our tree structure. They treat our dataset as a flat list + // but we have a collapsible structure. This means that the 5'th row to them + // may not even be visible to us + + // To display the n'th row, we have to make sure that all its ancestors + // are expanded. Then we will be able to select it. + object model = this.CurrencyManager.List[index]; + object parent = this.CalculateParent(model); + while (parent != null && !this.TreeListView.IsExpanded(parent)) { + this.TreeListView.Expand(parent); + parent = this.CalculateParent(parent); + } + + base.ChangePosition(index); + } + + private IEnumerable CalculateRoots() { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(this.RootKeyValue, parentKey)) + yield return x; + } + } + + private bool CalculateHasChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue == null) + return false; + + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + return true; + } + return false; + } + + private IEnumerable CalculateChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue != null) { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + yield return x; + } + } + } + + private object CalculateParent(object model) { + object parentValue = this.GetParentValue(model); + if (parentValue == null) + return null; + + foreach (object x in this.CurrencyManager.List) { + object key = this.GetKeyValue(x); + if (Object.Equals(parentValue, key)) + return x; + } + return null; + } + + private object GetKeyValue(object model) { + return this.keyMunger == null ? null : this.keyMunger.GetValue(model); + } + + private object GetParentValue(object model) { + return this.parentKeyMunger == null ? null : this.parentKeyMunger.GetValue(model); + } + + #endregion + + private Munger keyMunger; + private Munger parentKeyMunger; + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/VirtualGroups.cs b/ObjectListView/Implementation/VirtualGroups.cs new file mode 100644 index 0000000..1466ebb --- /dev/null +++ b/ObjectListView/Implementation/VirtualGroups.cs @@ -0,0 +1,341 @@ +/* + * Virtual groups - Classes and interfaces needed to implement virtual groups + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * 2011-02-21 JPP - Correctly honor group comparer and collapsible groups settings + * v2.3 + * 2009-08-28 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A IVirtualGroups is the interface that a virtual list must implement to support virtual groups + /// + public interface IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + IList GetGroups(GroupingParameters parameters); + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + int GetGroupMember(OLVGroup group, int indexWithinGroup); + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + int GetGroup(int itemIndex); + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + int GetIndexWithinGroup(OLVGroup group, int itemIndex); + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex); + } + + /// + /// This is a safe, do nothing implementation of a grouping strategy + /// + public class AbstractVirtualGroups : IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + public virtual IList GetGroups(GroupingParameters parameters) { + return new List(); + } + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + public virtual int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return -1; + } + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + public virtual int GetGroup(int itemIndex) { + return -1; + } + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + public virtual int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return -1; + } + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + public virtual void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex) { + } + } + + + /// + /// Provides grouping functionality to a FastObjectListView + /// + public class FastListGroupingStrategy : AbstractVirtualGroups + { + /// + /// Create groups for FastListView + /// + /// + /// + public override IList GetGroups(GroupingParameters parameters) { + + // There is a lot of overlap between this method and ObjectListView.MakeGroups() + // Any changes made here may need to be reflected there + + // This strategy can only be used on FastObjectListViews + FastObjectListView folv = (FastObjectListView)parameters.ListView; + + // Separate the list view items into groups, using the group key as the descrimanent + int objectCount = 0; + NullableDictionary> map = new NullableDictionary>(); + foreach (object model in folv.FilteredObjects) { + object key = parameters.GroupByColumn.GetGroupKey(model); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(model); + objectCount++; + } + + // Sort the items within each group + OLVColumn primarySortColumn = parameters.SortItemsByPrimaryColumn ? parameters.ListView.GetColumn(0) : parameters.PrimarySort; + ModelObjectComparer sorter = new ModelObjectComparer(primarySortColumn, parameters.PrimarySortOrder, + parameters.SecondarySort, parameters.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(sorter); + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parameters.CreateGroup(key, map[key].Count, folv.HasCollapsibleGroups); + lvg.Contents = map[key].ConvertAll(delegate(object x) { return folv.IndexOf(x); }); + lvg.VirtualItemCount = map[key].Count; + if (parameters.GroupByColumn.GroupFormatter != null) + parameters.GroupByColumn.GroupFormatter(lvg, parameters); + groups.Add(lvg); + } + + // Sort the groups + if (parameters.GroupByOrder != SortOrder.None) + groups.Sort(parameters.GroupComparer ?? new OLVGroupComparer(parameters.GroupByOrder)); + + // Build an array that remembers which group each item belongs to. + this.indexToGroupMap = new List(objectCount); + this.indexToGroupMap.AddRange(new int[objectCount]); + + for (int i = 0; i < groups.Count; i++) { + OLVGroup group = groups[i]; + List members = (List)group.Contents; + foreach (int j in members) + this.indexToGroupMap[j] = i; + } + + return groups; + } + private List indexToGroupMap; + + /// + /// + /// + /// + /// + /// + public override int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return (int)group.Contents[indexWithinGroup]; + } + + /// + /// + /// + /// + /// + public override int GetGroup(int itemIndex) { + return this.indexToGroupMap[itemIndex]; + } + + /// + /// + /// + /// + /// + /// + public override int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return group.Contents.IndexOf(itemIndex); + } + } + + + /// + /// This is the COM interface that a ListView must be given in order for groups in virtual lists to work. + /// + /// + /// This interface is NOT documented by MS. It was found on Greg Chapell's site. This means that there is + /// no guarantee that it will work on future versions of Windows, nor continue to work on current ones. + /// + [ComImport(), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown), + Guid("44C09D56-8D3B-419D-A462-7B956B105B47")] + internal interface IOwnerDataCallback + { + /// + /// Not sure what this does + /// + /// + /// + void GetItemPosition(int i, out NativeMethods.POINT pt); + + /// + /// Not sure what this does + /// + /// + /// + void SetItemPosition(int t, NativeMethods.POINT pt); + + /// + /// Get the index of the item that occurs at the n'th position of the indicated group. + /// + /// Index of the group + /// Index within the group + /// Index of the item within the whole list + void GetItemInGroup(int groupIndex, int n, out int itemIndex); + + /// + /// Get the index of the group to which the given item belongs + /// + /// Index of the item within the whole list + /// Which occurrences of the item is wanted + /// Index of the group + void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex); + + /// + /// Get the number of groups that contain the given item + /// + /// Index of the item within the whole list + /// How many groups does it occur within + void GetItemGroupCount(int itemIndex, out int occurrenceCount); + + /// + /// A hint to prepare any cache for the given range of requests + /// + /// + /// + void OnCacheHint(NativeMethods.LVITEMINDEX i, NativeMethods.LVITEMINDEX j); + } + + /// + /// A default implementation of the IOwnerDataCallback interface + /// + [Guid("6FC61F50-80E8-49b4-B200-3F38D3865ABD")] + internal class OwnerDataCallbackImpl : IOwnerDataCallback + { + public OwnerDataCallbackImpl(VirtualObjectListView olv) { + this.olv = olv; + } + VirtualObjectListView olv; + + #region IOwnerDataCallback Members + + public void GetItemPosition(int i, out NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("GetItemPosition"); + throw new NotSupportedException(); + } + + public void SetItemPosition(int t, NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("SetItemPosition"); + throw new NotSupportedException(); + } + + public void GetItemInGroup(int groupIndex, int n, out int itemIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("-> GetItemInGroup({0}, {1})", groupIndex, n)); + itemIndex = this.olv.GroupingStrategy.GetGroupMember(this.olv.OLVGroups[groupIndex], n); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", itemIndex)); + } + + public void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroup({0}, {1})", itemIndex, occurrenceCount)); + groupIndex = this.olv.GroupingStrategy.GetGroup(itemIndex); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", groupIndex)); + } + + public void GetItemGroupCount(int itemIndex, out int occurrenceCount) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroupCount({0})", itemIndex)); + occurrenceCount = 1; + } + + public void OnCacheHint(NativeMethods.LVITEMINDEX from, NativeMethods.LVITEMINDEX to) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnCacheHint({0}, {1}, {2}, {3})", from.iGroup, from.iItem, to.iGroup, to.iItem)); + this.olv.GroupingStrategy.CacheHint(from.iGroup, from.iItem, to.iGroup, to.iItem); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/VirtualListDataSource.cs b/ObjectListView/Implementation/VirtualListDataSource.cs new file mode 100644 index 0000000..7bc378d --- /dev/null +++ b/ObjectListView/Implementation/VirtualListDataSource.cs @@ -0,0 +1,349 @@ +/* + * VirtualListDataSource - Encapsulate how data is provided to a virtual list + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * v2.4 + * 2010-04-01 JPP - Added IFilterableDataSource + * v2.3 + * 2009-08-28 JPP - Initial version (Separated from VirtualObjectListView.cs) + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A VirtualListDataSource is a complete manner to provide functionality to a virtual list. + /// An object that implements this interface provides a VirtualObjectListView with all the + /// information it needs to be fully functional. + /// + /// Implementors must provide functioning implementations of at least GetObjectCount() + /// and GetNthObject(), otherwise nothing will appear in the list. + public interface IVirtualListDataSource + { + /// + /// Return the object that should be displayed at the n'th row. + /// + /// The index of the row whose object is to be returned. + /// The model object at the n'th row, or null if the fetching was unsuccessful. + Object GetNthObject(int n); + + /// + /// Return the number of rows that should be visible in the virtual list + /// + /// The number of rows the list view should have. + int GetObjectCount(); + + /// + /// Get the index of the row that is showing the given model object + /// + /// The model object sought + /// The index of the row showing the model, or -1 if the object could not be found. + int GetObjectIndex(Object model); + + /// + /// The ListView is about to request the given range of items. Do + /// whatever caching seems appropriate. + /// + /// + /// + void PrepareCache(int first, int last); + + /// + /// Find the first row that "matches" the given text in the given range. + /// + /// The text typed by the user + /// Start searching from this index. This may be greater than the 'to' parameter, + /// in which case the search should descend + /// Do not search beyond this index. This may be less than the 'from' parameter. + /// The column that should be considered when looking for a match. + /// Return the index of row that was matched, or -1 if no match was found + int SearchText(string value, int first, int last, OLVColumn column); + + /// + /// Sort the model objects in the data source. + /// + /// + /// + void Sort(OLVColumn column, SortOrder order); + + //----------------------------------------------------------------------------------- + // Modification commands + // THINK: Should we split these four into a separate interface? + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + void AddObjects(ICollection modelObjects); + + /// + /// Insert the given collection of model objects to this control at the position + /// + /// Index where the collection will be added + /// A collection of model objects + void InsertObjects(int index, ICollection modelObjects); + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + void RemoveObjects(ICollection modelObjects); + + /// + /// Set the collection of objects that this control will show. + /// + /// + void SetObjects(IEnumerable collection); + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + void UpdateObject(int index, object modelObject); + } + + /// + /// This extension allow virtual lists to filter their contents + /// + public interface IFilterableDataSource + { + /// + /// All subsequent retrievals on this data source should be filtered + /// through the given filters. null means no filtering of that kind. + /// + /// + /// + void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter); + } + + /// + /// A do-nothing implementation of the VirtualListDataSource interface. + /// + public class AbstractVirtualListDataSource : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Creates an AbstractVirtualListDataSource + /// + /// + public AbstractVirtualListDataSource(VirtualObjectListView listView) { + this.listView = listView; + } + + /// + /// The list view that this data source is giving information to. + /// + protected VirtualObjectListView listView; + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return -1; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int from, int to) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + } + + /// + /// + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void SetObjects(IEnumerable collection) { + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public virtual void UpdateObject(int index, object modelObject) { + } + + /// + /// This is a useful default implementation of SearchText method, intended to be called + /// by implementors of IVirtualListDataSource. + /// + /// + /// + /// + /// + /// + /// + static public int DefaultSearchText(string value, int first, int last, OLVColumn column, IVirtualListDataSource source) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + virtual public void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter) { + } + + #endregion + } + + /// + /// This class mimics the behavior of VirtualObjectListView v1.x. + /// + public class VirtualListVersion1DataSource : AbstractVirtualListDataSource + { + /// + /// Creates a VirtualListVersion1DataSource + /// + /// + public VirtualListVersion1DataSource(VirtualObjectListView listView) + : base(listView) { + } + + #region Public properties + + /// + /// How will the n'th object of the data source be fetched? + /// + public RowGetterDelegate RowGetter { + get { return rowGetter; } + set { rowGetter = value; } + } + private RowGetterDelegate rowGetter; + + #endregion + + #region IVirtualListDataSource implementation + + /// + /// + /// + /// + /// + public override object GetNthObject(int n) { + if (this.RowGetter == null) + return null; + else + return this.RowGetter(n); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string value, int first, int last, OLVColumn column) { + return DefaultSearchText(value, first, last, column, this); + } + + #endregion + } +} diff --git a/ObjectListView/OLVColumn.cs b/ObjectListView/OLVColumn.cs new file mode 100644 index 0000000..21ce4f9 --- /dev/null +++ b/ObjectListView/OLVColumn.cs @@ -0,0 +1,1909 @@ +/* + * OLVColumn - A column in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-05-05 JPP - Added EditorCreator to OLVColumn + * 2015-06-12 JPP - HeaderTextAlign became nullable so that it can be "not set" (this was always the intent) + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-27 JPP - Added Sortable, Hideable, Groupable, Searchable, ShowTextInHeader properties + * 2011-04-12 JPP - Added HasFilterIndicator + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Diagnostics; +using System.Drawing.Design; + +namespace BrightIdeasSoftware { + + // TODO + //[TypeConverter(typeof(ExpandableObjectConverter))] + //public class CheckBoxSettings + //{ + // private bool useSettings; + // private Image checkedImage; + + // public bool UseSettings { + // get { return useSettings; } + // set { useSettings = value; } + // } + + // public Image CheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image UncheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image IndeterminateImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + //} + + /// + /// An OLVColumn knows which aspect of an object it should present. + /// + /// + /// The column knows how to: + /// + /// extract its aspect from the row object + /// convert an aspect to a string + /// calculate the image for the row object + /// extract a group "key" from the row object + /// convert a group "key" into a title for the group + /// + /// For sorting to work correctly, aspects from the same column + /// must be of the same type, that is, the same aspect cannot sometimes + /// return strings and other times integers. + /// + [Browsable(false)] + public partial class OLVColumn : ColumnHeader { + + /// + /// How should the button be sized? + /// + public enum ButtonSizingMode + { + /// + /// Every cell will have the same sized button, as indicated by ButtonSize property + /// + FixedBounds, + + /// + /// Every cell will draw a button that fills the cell, inset by ButtonPadding + /// + CellBounds, + + /// + /// Each button will be resized to contain the text of the Aspect + /// + TextBounds + } + + #region Life and death + + /// + /// Create an OLVColumn + /// + public OLVColumn() { + } + + /// + /// Initialize a column to have the given title, and show the given aspect + /// + /// The title of the column + /// The aspect to be shown in the column + public OLVColumn(string title, string aspect) + : this() { + this.Text = title; + this.AspectName = aspect; + } + + #endregion + + #region Public Properties + + /// + /// This delegate will be used to extract a value to be displayed in this column. + /// + /// + /// If this is set, AspectName is ignored. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectGetterDelegate AspectGetter { + get { return aspectGetter; } + set { aspectGetter = value; } + } + private AspectGetterDelegate aspectGetter; + + /// + /// Remember if this aspect getter for this column was generated internally, and can therefore + /// be regenerated at will + /// + [Obsolete("This property is no longer maintained", true), + Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AspectGetterAutoGenerated { + get { return aspectGetterAutoGenerated; } + set { aspectGetterAutoGenerated = value; } + } + private bool aspectGetterAutoGenerated; + + /// + /// The name of the property or method that should be called to get the value to display in this column. + /// This is only used if a ValueGetterDelegate has not been given. + /// + /// This name can be dotted to chain references to properties or parameter-less methods. + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(null)] + public string AspectName { + get { return aspectName; } + set { + aspectName = value; + this.aspectMunger = null; + } + } + private string aspectName; + + /// + /// This delegate will be used to put an edited value back into the model object. + /// + /// + /// This does nothing if IsEditable == false. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { aspectPutter = value; } + } + private AspectPutterDelegate aspectPutter; + + /// + /// The delegate that will be used to translate the aspect to display in this column into a string. + /// + /// If this value is set, AspectToStringFormat will be ignored. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectToStringConverterDelegate AspectToStringConverter { + get { return aspectToStringConverter; } + set { aspectToStringConverter = value; } + } + private AspectToStringConverterDelegate aspectToStringConverter; + + /// + /// This format string will be used to convert an aspect to its string representation. + /// + /// + /// This string is passed as the first parameter to the String.Format() method. + /// This is only used if AspectToStringConverter has not been set. + /// "{0:C}" to convert a number to currency + [Category("ObjectListView"), + Description("The format string that will be used to convert an aspect to its string representation"), + DefaultValue(null)] + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(true)] + public bool AutoCompleteEditor { + get { return this.AutoCompleteEditorMode != AutoCompleteMode.None; } + set { + if (value) { + if (this.AutoCompleteEditorMode == AutoCompleteMode.None) + this.AutoCompleteEditorMode = AutoCompleteMode.Append; + } else + this.AutoCompleteEditorMode = AutoCompleteMode.None; + } + } + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(AutoCompleteMode.Append)] + public AutoCompleteMode AutoCompleteEditorMode { + get { return autoCompleteEditorMode; } + set { autoCompleteEditorMode = value; } + } + private AutoCompleteMode autoCompleteEditorMode = AutoCompleteMode.Append; + + /// + /// Gets whether this column can be hidden by user actions + /// + /// This take into account both the Hideable property and whether this column + /// is the primary column of the listview (column 0). + [Browsable(false)] + public bool CanBeHidden { + get { + return this.Hideable && (this.Index != 0); + } + } + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false (the default) and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// If this property is not set on the column, the value from the control will be used + /// + /// This value is only used when the control is in Details view. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(null)] + public virtual bool? CellEditUseWholeCell + { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool? cellEditUseWholeCell; + + /// + /// Get whether the whole cell should be used when editing a cell in this column + /// + /// This calculates the current effective value, which may be different to CellEditUseWholeCell + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CellEditUseWholeCellEffective { + get { + bool? columnSpecificValue = this.ListView.View == View.Details ? this.CellEditUseWholeCell : (bool?) null; + return (columnSpecificValue ?? ((ObjectListView) this.ListView).CellEditUseWholeCell); + } + } + + /// + /// Gets or sets how many pixels will be left blank around this cells in this column + /// + /// This setting only takes effect when the control is owner drawn. + [Category("ObjectListView"), + Description("How many pixels will be left blank around the cells in this column?"), + DefaultValue(null)] + public Rectangle? CellPadding + { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells in this column will be vertically aligned. + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// + /// If this is not set, the value from the control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets whether this column will show a checkbox. + /// + /// + /// Setting this on column 0 has no effect. Column 0 check box is controlled + /// by the CheckBoxes property on the ObjectListView itself. + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a checkbox, rather than a string?"), + DefaultValue(false)] + public virtual bool CheckBoxes { + get { return checkBoxes; } + set { + if (this.checkBoxes == value) + return; + + this.checkBoxes = value; + if (this.checkBoxes) { + if (this.Renderer == null) + this.Renderer = new CheckStateRenderer(); + } else { + if (this.Renderer is CheckStateRenderer) + this.Renderer = null; + } + } + } + private bool checkBoxes; + + /// + /// Gets or sets the clustering strategy used for this column. + /// + /// + /// + /// The clustering strategy is used to build a Filtering menu for this item. + /// If this is null, a useful default will be chosen. + /// + /// + /// To disable filtering on this column, set UseFiltering to false. + /// + /// + /// Cluster strategies belong to a particular column. The same instance + /// cannot be shared between multiple columns. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IClusteringStrategy ClusteringStrategy { + get { + if (this.clusteringStrategy == null) + this.ClusteringStrategy = this.DecideDefaultClusteringStrategy(); + return clusteringStrategy; + } + set { + this.clusteringStrategy = value; + if (this.clusteringStrategy != null) + this.clusteringStrategy.Column = this; + } + } + private IClusteringStrategy clusteringStrategy; + + /// + /// Gets or sets a delegate that will create an editor for a cell in this column. + /// + /// + /// If you need different editors for different cells in the same column, this + /// delegate is your solution. Return null to use the default editor for the cell. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public EditorCreatorDelegate EditorCreator { + get { return editorCreator; } + set { editorCreator = value; } + } + private EditorCreatorDelegate editorCreator; + + /// + /// Gets or sets whether the button in this column (if this column is drawing buttons) will be enabled + /// even if the row itself is disabled + /// + [Category("ObjectListView"), + Description("If this column contains a button, should the button be enabled even if the row is disabled?"), + DefaultValue(false)] + public bool EnableButtonWhenItemIsDisabled + { + get { return this.enableButtonWhenItemIsDisabled; } + set { this.enableButtonWhenItemIsDisabled = value; } + } + private bool enableButtonWhenItemIsDisabled; + + /// + /// Should this column resize to fill the free space in the listview? + /// + /// + /// + /// If you want two (or more) columns to equally share the available free space, set this property to True. + /// If you want this column to have a larger or smaller share of the free space, you must + /// set the FreeSpaceProportion property explicitly. + /// + /// + /// Space filling columns are still governed by the MinimumWidth and MaximumWidth properties. + /// + /// /// + [Category("ObjectListView"), + Description("Will this column resize to fill unoccupied horizontal space in the listview?"), + DefaultValue(false)] + public bool FillsFreeSpace { + get { return this.FreeSpaceProportion > 0; } + set { this.FreeSpaceProportion = value ? 1 : 0; } + } + + /// + /// What proportion of the unoccupied horizontal space in the control should be given to this column? + /// + /// + /// + /// There are situations where it would be nice if a column (normally the rightmost one) would expand as + /// the list view expands, so that as much of the column was visible as possible without having to scroll + /// horizontally (you should never, ever make your users have to scroll anything horizontally!). + /// + /// + /// A space filling column is resized to occupy a proportion of the unoccupied width of the listview (the + /// unoccupied width is the width left over once all the non-filling columns have been given their space). + /// This property indicates the relative proportion of that unoccupied space that will be given to this column. + /// The actual value of this property is not important -- only its value relative to the value in other columns. + /// For example: + /// + /// + /// If there is only one space filling column, it will be given all the free space, regardless of the value in FreeSpaceProportion. + /// + /// + /// If there are two or more space filling columns and they all have the same value for FreeSpaceProportion, + /// they will share the free space equally. + /// + /// + /// If there are three space filling columns with values of 3, 2, and 1 + /// for FreeSpaceProportion, then the first column with occupy half the free space, the second will + /// occupy one-third of the free space, and the third column one-sixth of the free space. + /// + /// + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { freeSpaceProportion = Math.Max(0, value); } + } + private int freeSpaceProportion; + + /// + /// Gets or sets whether groups will be rebuild on this columns values when this column's header is clicked. + /// + /// + /// This setting is only used when ShowGroups is true. + /// + /// If this is false, clicking the header will not rebuild groups. It will not provide + /// any feedback as to why the list is not being regrouped. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeCreatingGroups events are still fired, which can be used to allow grouping + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will the list create groups when this header is clicked?"), + DefaultValue(true)] + public bool Groupable { + get { return groupable; } + set { groupable = value; } + } + private bool groupable = true; + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupFormatterDelegate GroupFormatter { + get { return groupFormatter; } + set { groupFormatter = value; } + } + private GroupFormatterDelegate groupFormatter; + + /// + /// This delegate is called to get the object that is the key for the group + /// to which the given row belongs. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { groupKeyGetter = value; } + } + private GroupKeyGetterDelegate groupKeyGetter; + + /// + /// This delegate is called to convert a group key into a title for that group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyToTitleConverterDelegate GroupKeyToTitleConverter { + get { return groupKeyToTitleConverter; } + set { groupKeyToTitleConverter = value; } + } + private GroupKeyToTitleConverterDelegate groupKeyToTitleConverter; + + /// + /// When the listview is grouped by this column and group title has an item count, + /// how should the label be formatted? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Gets this.GroupWithItemCountFormat or a reasonable default + /// + /// + /// If GroupWithItemCountFormat is not set, its value will be taken from the ObjectListView if possible. + /// + [Browsable(false)] + public string GroupWithItemCountFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountFormat)) + return this.GroupWithItemCountFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountFormat = ((ObjectListView)this.ListView).GroupWithItemCountFormatOrDefault; + return cachedGroupWithItemCountFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountFormat ?? "{0} [{1} items]"; + } + } + private string cachedGroupWithItemCountFormat; + + /// + /// When the listview is grouped by this column and a group title has an item count, + /// how should the label be formatted if there is only one item in the group? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Get this.GroupWithItemCountSingularFormat or a reasonable default + /// + /// + /// If this value is not set, the values from the list view will be used + /// + [Browsable(false)] + public string GroupWithItemCountSingularFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat)) + return this.GroupWithItemCountSingularFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountSingularFormat = ((ObjectListView)this.ListView).GroupWithItemCountSingularFormatOrDefault; + return cachedGroupWithItemCountSingularFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountSingularFormat ?? "{0} [{1} item]"; + } + } + private string cachedGroupWithItemCountSingularFormat; + + /// + /// Gets whether this column should be drawn with a filter indicator in the column header. + /// + [Browsable(false)] + public bool HasFilterIndicator { + get { + return this.UseFiltering && this.ValuesChosenForFiltering != null && this.ValuesChosenForFiltering.Count > 0; + } + } + + /// + /// Gets or sets a delegate that will be used to own draw header column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public HeaderDrawingDelegate HeaderDrawing { + get { return headerDrawing; } + set { headerDrawing = value; } + } + private HeaderDrawingDelegate headerDrawing; + + /// + /// Gets or sets the style that will be used to draw the header for this column + /// + /// This is only uses when the owning ObjectListView has HeaderUsesThemes set to false. + [Category("ObjectListView"), + Description("What style will be used to draw the header of this column"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the font in which the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Which font will be used to draw the header?"), + DefaultValue(null)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the color in which the text of the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("In what color will the header text be drawn?"), + DefaultValue(typeof(Color), "")] + public Color HeaderForeColor { + get { return this.HeaderFormatStyle == null ? Color.Empty : this.HeaderFormatStyle.Normal.ForeColor; } + set { + if (value.IsEmpty && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetForeColor(value); + } + } + + /// + /// Gets or sets the ImageList key of the image that will be drawn in the header of this column. + /// + /// This is only taken into account when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Name of the image that will be shown in the column header."), + DefaultValue(null), + TypeConverter(typeof(ImageKeyConverter)), + Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), + RefreshProperties(RefreshProperties.Repaint)] + public string HeaderImageKey { + get { return headerImageKey; } + set { headerImageKey = value; } + } + private string headerImageKey; + + + /// + /// Gets or sets how the text of the header will be drawn? + /// + [Category("ObjectListView"), + Description("How will the header text be aligned? If this is not set, the alignment of the header will follow the alignment of the column"), + DefaultValue(null)] + public HorizontalAlignment? HeaderTextAlign { + get { return headerTextAlign; } + set { headerTextAlign = value; } + } + private HorizontalAlignment? headerTextAlign; + + /// + /// Return the text alignment of the header. This will either have been set explicitly, + /// or will follow the alignment of the text in the column + /// + [Browsable(false)] + public HorizontalAlignment HeaderTextAlignOrDefault + { + get { return headerTextAlign.HasValue ? headerTextAlign.Value : this.TextAlign; } + } + + /// + /// Gets the header alignment converted to a StringAlignment + /// + [Browsable(false)] + public StringAlignment HeaderTextAlignAsStringAlignment { + get { + switch (this.HeaderTextAlignOrDefault) { + case HorizontalAlignment.Left: return StringAlignment.Near; + case HorizontalAlignment.Center: return StringAlignment.Center; + case HorizontalAlignment.Right: return StringAlignment.Far; + default: return StringAlignment.Near; + } + } + } + + /// + /// Gets whether or not this column has an image in the header + /// + [Browsable(false)] + public bool HasHeaderImage { + get { + return (this.ListView != null && + this.ListView.SmallImageList != null && + this.ListView.SmallImageList.Images.ContainsKey(this.HeaderImageKey)); + } + } + + /// + /// Gets or sets whether this header will place a checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderCheckBox + { + get { return headerCheckBox; } + set { headerCheckBox = value; } + } + private bool headerCheckBox; + + /// + /// Gets or sets whether this header will place a tri-state checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a tri-state checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderTriStateCheckBox + { + get { return headerTriStateCheckBox; } + set { headerTriStateCheckBox = value; } + } + private bool headerTriStateCheckBox; + + /// + /// Gets or sets the checkedness of the checkbox in the header of this column + /// + [Category("ObjectListView"), + Description("Checkedness of the header checkbox"), + DefaultValue(CheckState.Unchecked)] + public CheckState HeaderCheckState + { + get { return headerCheckState; } + set { headerCheckState = value; } + } + private CheckState headerCheckState = CheckState.Unchecked; + + /// + /// Gets or sets whether the + /// checking/unchecking the value of the header's checkbox will result in the + /// checkboxes for all cells in this column being set to the same checked/unchecked. + /// Defaults to true. + /// + /// + /// + /// There is no reverse of this function that automatically updates the header when the + /// checkedness of a cell changes. + /// + /// + /// This property's behaviour on a TreeListView is probably best describes as undefined + /// and should be avoided. + /// + /// + /// The performance of this action (checking/unchecking all rows) is O(n) where n is the + /// number of rows. It will work on large virtual lists, but it may take some time. + /// + /// + [Category("ObjectListView"), + Description("Update row checkboxes when the header checkbox is clicked by the user"), + DefaultValue(true)] + public bool HeaderCheckBoxUpdatesRowCheckBoxes { + get { return headerCheckBoxUpdatesRowCheckBoxes; } + set { headerCheckBoxUpdatesRowCheckBoxes = value; } + } + private bool headerCheckBoxUpdatesRowCheckBoxes = true; + + /// + /// Gets or sets whether the checkbox in the header is disabled + /// + /// + /// Clicking on a disabled checkbox does not change its value, though it does raise + /// a HeaderCheckBoxChanging event, which allows the programmer the opportunity to do + /// something appropriate. + [Category("ObjectListView"), + Description("Is the checkbox in the header of this column disabled"), + DefaultValue(false)] + public bool HeaderCheckBoxDisabled + { + get { return headerCheckBoxDisabled; } + set { headerCheckBoxDisabled = value; } + } + private bool headerCheckBoxDisabled; + + /// + /// Gets or sets whether this column can be hidden by the user. + /// + /// + /// Column 0 can never be hidden, regardless of this setting. + /// + [Category("ObjectListView"), + Description("Will the user be able to choose to hide this column?"), + DefaultValue(true)] + public bool Hideable { + get { return hideable; } + set { hideable = value; } + } + private bool hideable = true; + + /// + /// Gets or sets whether the text values in this column will act like hyperlinks + /// + [Category("ObjectListView"), + Description("Will the text values in the cells of this column act like hyperlinks?"), + DefaultValue(false)] + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// This is the name of property that will be invoked to get the image selector of the + /// image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// + /// This is ignored if ImageGetter is not null. + /// The property can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Category("ObjectListView"), + Description("The name of the property that holds the image selector"), + DefaultValue(null)] + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// This delegate is called to get the image selector of the image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// This delegate can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { imageGetter = value; } + } + private ImageGetterDelegate imageGetter; + + /// + /// Gets or sets whether this column will draw buttons in its cells + /// + /// + /// + /// When this is set to true, the renderer for the column is become a ColumnButtonRenderer + /// if it isn't already. If this is set to false, any previous button renderer will be discarded + /// + /// If the cell's aspect is null or empty, nothing will be drawn in the cell. + [Category("ObjectListView"), + Description("Does this column draw its cells as buttons?"), + DefaultValue(false)] + public bool IsButton { + get { return isButton; } + set { + isButton = value; + if (value) { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) { + this.Renderer = this.CreateColumnButtonRenderer(); + this.FillInColumnButtonRenderer(); + } + } else { + if (this.Renderer is ColumnButtonRenderer) + this.Renderer = null; + } + } + } + private bool isButton; + + /// + /// Create a ColumnButtonRenderer to draw buttons in this column + /// + /// + protected virtual ColumnButtonRenderer CreateColumnButtonRenderer() { + return new ColumnButtonRenderer(); + } + + /// + /// Fill in details to our ColumnButtonRenderer based on the properties set on the column + /// + protected virtual void FillInColumnButtonRenderer() { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) + return; + + buttonRenderer.SizingMode = this.ButtonSizing; + buttonRenderer.ButtonSize = this.ButtonSize; + buttonRenderer.ButtonPadding = this.ButtonPadding; + buttonRenderer.MaxButtonWidth = this.ButtonMaxWidth; + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int ButtonMaxWidth { + get { return this.buttonMaxWidth; } + set { + this.buttonMaxWidth = value; + FillInColumnButtonRenderer(); + } + } + private int buttonMaxWidth = -1; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds"), + DefaultValue(null)] + public Size? ButtonPadding { + get { return this.buttonPadding; } + set { + this.buttonPadding = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonPadding; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize { + get { return this.buttonSize; } + set { + this.buttonSize = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonSize; + + /// + /// Gets or sets how each button will be sized if this column is displaying buttons + /// + [Category("ObjectListView"), + Description("If this column is showing buttons, how each button will be sized"), + DefaultValue(ButtonSizingMode.TextBounds)] + public ButtonSizingMode ButtonSizing { + get { return this.buttonSizing; } + set { + this.buttonSizing = value; + this.FillInColumnButtonRenderer(); + } + } + private ButtonSizingMode buttonSizing = ButtonSizingMode.TextBounds; + + /// + /// Can the values shown in this column be edited? + /// + /// This defaults to true, since the primary means to control the editability of a listview + /// is on the listview itself. Once a listview is editable, all the columns are too, unless the + /// programmer explicitly marks them as not editable + [Category("ObjectListView"), + Description("Can the value in this column be edited?"), + DefaultValue(true)] + public bool IsEditable + { + get { return isEditable; } + set { isEditable = value; } + } + private bool isEditable = true; + + /// + /// Is this column a fixed width column? + /// + [Browsable(false)] + public bool IsFixedWidth { + get { + return (this.MinimumWidth != -1 && this.MaximumWidth != -1 && this.MinimumWidth >= this.MaximumWidth); + } + } + + /// + /// Get/set whether this column should be used when the view is switched to tile view. + /// + /// Column 0 is always included in tileview regardless of this setting. + /// Tile views do not work well with many "columns" of information. + /// Two or three works best. + [Category("ObjectListView"), + Description("Will this column be used when the view is switched to tile view"), + DefaultValue(false)] + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// Gets or sets whether the text of this header should be rendered vertically. + /// + /// + /// If this is true, it is a good idea to set ToolTipText to the name of the column so it's easy to read. + /// Vertical headers are text only. They do not draw their image. + /// + [Category("ObjectListView"), + Description("Will the header for this column be drawn vertically?"), + DefaultValue(false)] + public bool IsHeaderVertical { + get { return isHeaderVertical; } + set { isHeaderVertical = value; } + } + private bool isHeaderVertical; + + /// + /// Can this column be seen by the user? + /// + /// After changing this value, you must call RebuildColumns() before the changes will take effect. + [Category("ObjectListView"), + Description("Can this column be seen by the user?"), + DefaultValue(true)] + public bool IsVisible { + get { return isVisible; } + set + { + if (isVisible == value) + return; + + isVisible = value; + OnVisibilityChanged(EventArgs.Empty); + } + } + private bool isVisible = true; + + /// + /// Where was this column last positioned within the Detail view columns + /// + /// DisplayIndex is volatile. Once a column is removed from the control, + /// there is no way to discover where it was in the display order. This property + /// guards that information even when the column is not in the listview's active columns. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int LastDisplayIndex { + get { return this.lastDisplayIndex; } + set { this.lastDisplayIndex = value; } + } + private int lastDisplayIndex = -1; + + /// + /// What is the maximum width that the user can give to this column? + /// + /// -1 means there is no maximum width. Give this the same value as MinimumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the maximum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MaximumWidth { + get { return maxWidth; } + set { + maxWidth = value; + if (maxWidth != -1 && this.Width > maxWidth) + this.Width = maxWidth; + } + } + private int maxWidth = -1; + + /// + /// What is the minimum width that the user can give to this column? + /// + /// -1 means there is no minimum width. Give this the same value as MaximumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the minimum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MinimumWidth { + get { return minWidth; } + set { + minWidth = value; + if (this.Width < minWidth) + this.Width = minWidth; + } + } + private int minWidth = -1; + + /// + /// Get/set the renderer that will be invoked when a cell needs to be redrawn + /// + [Category("ObjectListView"), + Description("The renderer will draw this column when the ListView is owner drawn"), + DefaultValue(null)] + public IRenderer Renderer { + get { return renderer; } + set { renderer = value; } + } + private IRenderer renderer; + + /// + /// This delegate is called when a cell needs to be drawn in OwnerDrawn mode. + /// + /// This method is kept primarily for backwards compatibility. + /// New code should implement an IRenderer, though this property will be maintained. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public RenderDelegate RendererDelegate { + get { + Version1Renderer version1Renderer = this.Renderer as Version1Renderer; + return version1Renderer != null ? version1Renderer.RenderDelegate : null; + } + set { + this.Renderer = value == null ? null : new Version1Renderer(value); + } + } + + /// + /// Gets or sets whether the text in this column's cell will be used when doing text searching. + /// + /// + /// + /// If this is false, text filters will not trying searching this columns cells when looking for matches. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the cells in this column be considered when searching?"), + DefaultValue(true)] + public bool Searchable { + get { return searchable; } + set { searchable = value; } + } + private bool searchable = true; + + /// + /// Gets or sets a delegate which will return the array of text values that should be + /// considered for text matching when using a text based filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public SearchValueGetterDelegate SearchValueGetter { + get { return searchValueGetter; } + set { searchValueGetter = value; } + } + private SearchValueGetterDelegate searchValueGetter; + + /// + /// Gets or sets whether the header for this column will include the column's Text. + /// + /// + /// + /// If this is false, the only thing rendered in the column header will be the image from . + /// + /// This setting is only considered when is false on the owning ObjectListView. + /// + [Category("ObjectListView"), + Description("Will the header for this column include text?"), + DefaultValue(true)] + public bool ShowTextInHeader { + get { return showTextInHeader; } + set { showTextInHeader = value; } + } + private bool showTextInHeader = true; + + /// + /// Gets or sets whether the contents of the list will be resorted when the user clicks the + /// header of this column. + /// + /// + /// + /// If this is false, clicking the header will not sort the list, but will not provide + /// any feedback as to why the list is not being sorted. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeSorting events are still fired, which can be used to allow sorting + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will clicking this columns header resort the list?"), + DefaultValue(true)] + public bool Sortable { + get { return sortable; } + set { sortable = value; } + } + private bool sortable = true; + + /// + /// Gets or sets the horizontal alignment of the contents of the column. + /// + /// .NET will not allow column 0 to have any alignment except + /// to the left. We can't change the basic behaviour of the listview, + /// but when owner drawn, column 0 can now have other alignments. + new public HorizontalAlignment TextAlign { + get { + return this.textAlign.HasValue ? this.textAlign.Value : base.TextAlign; + } + set { + this.textAlign = value; + base.TextAlign = value; + } + } + private HorizontalAlignment? textAlign; + + /// + /// Gets the StringAlignment equivalent of the column text alignment + /// + [Browsable(false)] + public StringAlignment TextStringAlign { + get { + switch (this.TextAlign) { + case HorizontalAlignment.Center: + return StringAlignment.Center; + case HorizontalAlignment.Left: + return StringAlignment.Near; + case HorizontalAlignment.Right: + return StringAlignment.Far; + default: + return StringAlignment.Near; + } + } + } + + /// + /// What string should be displayed when the mouse is hovered over the header of this column? + /// + /// If a HeaderToolTipGetter is installed on the owning ObjectListView, this + /// value will be ignored. + [Category("ObjectListView"), + Description("The tooltip to show when the mouse is hovered over the header of this column"), + DefaultValue((String)null), + Localizable(true)] + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// Should this column have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + } + } + private bool triStateCheckBoxes; + + /// + /// Group objects by the initial letter of the aspect of the column + /// + /// + /// One common pattern is to group column by the initial letter of the value for that group. + /// The aspect must be a string (obviously). + /// + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(false)] + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// Gets or sets whether or not this column should be user filterable + /// + [Category("ObjectListView"), + Description("Does this column want to show a Filter menu item when its header is right clicked"), + DefaultValue(true)] + public bool UseFiltering { + get { return useFiltering; } + set { useFiltering = value; } + } + private bool useFiltering = true; + + /// + /// Gets or sets a filter that will only include models where the model's value + /// for this column is one of the values in ValuesChosenForFiltering + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IModelFilter ValueBasedFilter { + get { + if (!this.UseFiltering) + return null; + + if (valueBasedFilter != null) + return valueBasedFilter; + + if (this.ClusteringStrategy == null) + return null; + + if (this.ValuesChosenForFiltering == null || this.ValuesChosenForFiltering.Count == 0) + return null; + + return this.ClusteringStrategy.CreateFilter(this.ValuesChosenForFiltering); + } + set { valueBasedFilter = value; } + } + private IModelFilter valueBasedFilter; + + /// + /// Gets or sets the values that will be used to generate a filter for this + /// column. For a model to be included by the generated filter, its value for this column + /// must be in this list. If the list is null or empty, this column will + /// not be used for filtering. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList ValuesChosenForFiltering { + get { return this.valuesChosenForFiltering; } + set { this.valuesChosenForFiltering = value; } + } + private IList valuesChosenForFiltering = new ArrayList(); + + /// + /// What is the width of this column? + /// + [Category("ObjectListView"), + Description("The width in pixels of this column"), + DefaultValue(60)] + public new int Width { + get { return base.Width; } + set { + if (this.MaximumWidth != -1 && value > this.MaximumWidth) + base.Width = this.MaximumWidth; + else + base.Width = Math.Max(this.MinimumWidth, value); + } + } + + /// + /// Gets or set whether the contents of this column's cells should be word wrapped + /// + /// If this column uses a custom IRenderer (that is, one that is not descended + /// from BaseRenderer), then that renderer is responsible for implementing word wrapping. + [Category("ObjectListView"), + Description("Draw this column cell's word wrapped"), + DefaultValue(false)] + public bool WordWrap { + get { return wordWrap; } + set { wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Object commands + + /// + /// For a given group value, return the string that should be used as the groups title. + /// + /// The group key that is being converted to a title + /// string + public string ConvertGroupKeyToTitle(object value) { + if (this.groupKeyToTitleConverter != null) + return this.groupKeyToTitleConverter(value); + + return value == null ? ObjectListView.GroupTitleDefault : this.ValueToString(value); + } + + /// + /// Get the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// The checkedness of the object + public CheckState GetCheckState(object rowObject) { + if (!this.CheckBoxes) + return CheckState.Unchecked; + + bool? aspectAsBool = this.GetValue(rowObject) as bool?; + if (aspectAsBool.HasValue) { + if (aspectAsBool.Value) + return CheckState.Checked; + else + return CheckState.Unchecked; + } else + return CheckState.Indeterminate; + } + + /// + /// Put the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// + /// The checkedness of the object + public void PutCheckState(object rowObject, CheckState newState) { + if (newState == CheckState.Checked) + this.PutValue(rowObject, true); + else + if (newState == CheckState.Unchecked) + this.PutValue(rowObject, false); + else + this.PutValue(rowObject, null); + } + + /// + /// For a given row object, extract the value indicated by the AspectName property of this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect named by AspectName + public object GetAspectByName(object rowObject) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + return this.aspectMunger.GetValue(rowObject); + } + private Munger aspectMunger; + + /// + /// For a given row object, return the object that is the key of the group that this row belongs to. + /// + /// The row object that is being displayed + /// Group key object + public object GetGroupKey(object rowObject) { + if (this.groupKeyGetter != null) + return this.groupKeyGetter(rowObject); + + object key = this.GetValue(rowObject); + + if (this.UseInitialLetterForGroup) { + String keyAsString = key as String; + if (!String.IsNullOrEmpty(keyAsString)) + return keyAsString.Substring(0, 1).ToUpper(); + } + + return key; + } + + /// + /// For a given row object, return the image selector of the image that should displayed in this column. + /// + /// The row object that is being displayed + /// int or string or Image. int or string will be used as index into image list. null or -1 means no image + public Object GetImage(object rowObject) { + if (this.CheckBoxes) + return this.GetCheckStateImage(rowObject); + + if (this.ImageGetter != null) + return this.ImageGetter(rowObject); + + if (!String.IsNullOrEmpty(this.ImageAspectName)) { + if (this.imageAspectMunger == null) + this.imageAspectMunger = new Munger(this.ImageAspectName); + + return this.imageAspectMunger.GetValue(rowObject); + } + + // I think this is wrong. ImageKey is meant for the image in the header, not in the rows + if (!String.IsNullOrEmpty(this.ImageKey)) + return this.ImageKey; + + return this.ImageIndex; + } + private Munger imageAspectMunger; + + /// + /// Return the image that represents the check box for the given model + /// + /// + /// + public string GetCheckStateImage(Object rowObject) { + CheckState checkState = this.GetCheckState(rowObject); + + if (checkState == CheckState.Checked) + return ObjectListView.CHECKED_KEY; + + if (checkState == CheckState.Unchecked) + return ObjectListView.UNCHECKED_KEY; + + return ObjectListView.INDETERMINATE_KEY; + } + + /// + /// For a given row object, return the strings that will be searched when trying to filter by string. + /// + /// + /// This will normally be the simple GetStringValue result, but if this column is non-textual (e.g. image) + /// you might want to install a SearchValueGetter delegate which can return something that could be used + /// for text filtering. + /// + /// + /// The array of texts to be searched. If this returns null, search will not match that object. + public string[] GetSearchValues(object rowObject) { + if (this.SearchValueGetter != null) + return this.SearchValueGetter(rowObject); + + var stringValue = this.GetStringValue(rowObject); + + DescribedTaskRenderer dtr = this.Renderer as DescribedTaskRenderer; + if (dtr != null) { + return new string[] { stringValue, dtr.GetDescription(rowObject) }; + } + + return new string[] { stringValue }; + } + + /// + /// For a given row object, return the string representation of the value shown in this column. + /// + /// + /// For aspects that are string (e.g. aPerson.Name), the aspect and its string representation are the same. + /// For non-strings (e.g. aPerson.DateOfBirth), the string representation is very different. + /// + /// + /// + public string GetStringValue(object rowObject) + { + return this.ValueToString(this.GetValue(rowObject)); + } + + /// + /// For a given row object, return the object that is to be displayed in this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect to be displayed + public object GetValue(object rowObject) { + if (this.AspectGetter == null) + return this.GetAspectByName(rowObject); + else + return this.AspectGetter(rowObject); + } + + /// + /// Update the given model object with the given value using the column's + /// AspectName. + /// + /// The model object to be updated + /// The value to be put into the model + public void PutAspectByName(Object rowObject, Object newValue) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + this.aspectMunger.PutValue(rowObject, newValue); + } + + /// + /// Update the given model object with the given value + /// + /// The model object to be updated + /// The value to be put into the model + public void PutValue(Object rowObject, Object newValue) { + if (this.aspectPutter == null) + this.PutAspectByName(rowObject, newValue); + else + this.aspectPutter(rowObject, newValue); + } + + /// + /// Convert the aspect object to its string representation. + /// + /// + /// If the column has been given a AspectToStringConverter, that will be used to do + /// the conversion, otherwise just use ToString(). + /// The returned value will not be null. Nulls are always converted + /// to empty strings. + /// + /// The value of the aspect that should be displayed + /// A string representation of the aspect + public string ValueToString(object value) { + // Give the installed converter a chance to work (even if the value is null) + if (this.AspectToStringConverter != null) + return this.AspectToStringConverter(value) ?? String.Empty; + + // Without a converter, nulls become simple empty strings + if (value == null) + return String.Empty; + + string fmt = this.AspectToStringFormat; + if (String.IsNullOrEmpty(fmt)) + return value.ToString(); + else + return String.Format(fmt, value); + } + + #endregion + + #region Utilities + + /// + /// Decide the clustering strategy that will be used for this column + /// + /// + private IClusteringStrategy DecideDefaultClusteringStrategy() { + if (!this.UseFiltering) + return null; + + if (this.DataType == typeof(DateTime)) + return new DateTimeClusteringStrategy(); + + return new ClustersFromGroupsStrategy(); + } + + /// + /// Gets or sets the type of data shown in this column. + /// + /// If this is not set, it will try to get the type + /// by looking through the rows of the listview. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Type DataType { + get { + if (this.dataType == null) { + ObjectListView olv = this.ListView as ObjectListView; + if (olv != null) { + object value = olv.GetFirstNonNullValue(this); + if (value != null) + return value.GetType(); // THINK: Should we cache this? + } + } + return this.dataType; + } + set { + this.dataType = value; + } + } + private Type dataType; + + #region Events + + /// + /// This event is triggered when the visibility of this column changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when the visibility of the column changes.")] + public event EventHandler VisibilityChanged; + + /// + /// Tell the world when visibility of a column changes. + /// + public virtual void OnVisibilityChanged(EventArgs e) + { + if (this.VisibilityChanged != null) + this.VisibilityChanged(this, e); + } + + #endregion + + /// + /// Create groupies + /// This is an untyped version to help with Generator and OLVColumn attributes + /// + /// + /// + public void MakeGroupies(object[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images) { + this.MakeGroupies(values, descriptions, images, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles) { + this.MakeGroupies(values, descriptions, images, subtitles, null); + } + + /// + /// Create groupies. + /// Install delegates that will group the columns aspects into progressive partitions. + /// If an aspect is less than value[n], it will be grouped with description[n]. + /// If an aspect has a value greater than the last element in "values", it will be grouped + /// with the last element in "descriptions". + /// + /// Array of values. Values must be able to be + /// compared to the aspect (using IComparable) + /// The description for the matching value. The last element is the default description. + /// If there are n values, there must be n+1 descriptions. + /// + /// this.salaryColumn.MakeGroupies( + /// new UInt32[] { 20000, 100000 }, + /// new string[] { "Lowly worker", "Middle management", "Rarified elevation"}); + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length + 1 != descriptions.Length) + throw new ArgumentException("descriptions must have one more element than values."); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + Object aspect = this.GetValue(row); + if (aspect == null || aspect == DBNull.Value) + return -1; + IComparable comparable = (IComparable)aspect; + for (int i = 0; i < values.Length; i++) { + if (comparable.CompareTo(values[i]) < 0) + return i; + } + + // Display the last element in the array + return descriptions.Length - 1; + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + if ((int)key < 0) + return ""; + + return descriptions[(int)key]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + /// + /// Create groupies based on exact value matches. + /// + /// + /// Install delegates that will group rows into partitions based on equality of this columns aspects. + /// If an aspect is equal to value[n], it will be grouped with description[n]. + /// If an aspect is not equal to any value, it will be grouped with "[other]". + /// + /// Array of values. Values must be able to be + /// equated to the aspect + /// The description for the matching value. + /// + /// this.marriedColumn.MakeEqualGroupies( + /// new MaritalStatus[] { MaritalStatus.Single, MaritalStatus.Married, MaritalStatus.Divorced, MaritalStatus.Partnered }, + /// new string[] { "Looking", "Content", "Looking again", "Mostly content" }); + /// + /// + /// + /// + /// + public void MakeEqualGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length != descriptions.Length) + throw new ArgumentException("descriptions must have the same number of elements as values."); + + ArrayList valuesArray = new ArrayList(values); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + return valuesArray.IndexOf(this.GetValue(row)); + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + int intKey = (int)key; // we know this is an int since we created it in GroupKeyGetter + return (intKey < 0) ? "[other]" : descriptions[intKey]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.DesignTime.cs b/ObjectListView/ObjectListView.DesignTime.cs new file mode 100644 index 0000000..2fac113 --- /dev/null +++ b/ObjectListView/ObjectListView.DesignTime.cs @@ -0,0 +1,550 @@ +/* + * DesignSupport - Design time support for the various classes within ObjectListView + * + * Author: Phillip Piper + * Date: 12/08/2009 8:36 PM + * + * Change log: + * 2012-08-27 JPP - Fall back to more specific type name for the ListViewDesigner if + * the first GetType() fails. + * v2.5.1 + * 2012-04-26 JPP - Filter group events from TreeListView since it can't have groups + * 2011-06-06 JPP - Vastly improved ObjectListViewDesigner, based off information in + * "'Inheriting' from an Internal WinForms Designer" on CodeProject. + * v2.3 + * 2009-08-12 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Windows.Forms.Design; + +namespace BrightIdeasSoftware.Design +{ + + /// + /// Designer for and its subclasses. + /// + /// + /// + /// This designer removes properties and events that are available on ListView but that are not + /// useful on ObjectListView. + /// + /// + /// We can't inherit from System.Windows.Forms.Design.ListViewDesigner, since it is marked internal. + /// So, this class uses reflection to create a ListViewDesigner and then forwards messages to that designer. + /// + /// + public class ObjectListViewDesigner : ControlDesigner + { + + #region Initialize & Dispose + + /// + /// Initialises the designer with the specified component. + /// + /// The to associate the designer with. This component must always be an instance of, or derive from, . + public override void Initialize(IComponent component) { + // Debug.WriteLine("ObjectListViewDesigner.Initialize"); + + // Use reflection to bypass the "internal" marker on ListViewDesigner + // If we can't get the unversioned designer, look specifically for .NET 4.0 version of it. + Type tListViewDesigner = Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design") ?? + Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design, " + + "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + if (tListViewDesigner == null) throw new ArgumentException("Could not load ListViewDesigner"); + + this.listViewDesigner = (ControlDesigner)Activator.CreateInstance(tListViewDesigner, BindingFlags.Instance | BindingFlags.Public, null, null, null); + this.designerFilter = this.listViewDesigner; + + // Fetch the methods from the ListViewDesigner that we know we want to use + this.listViewDesignGetHitTest = tListViewDesigner.GetMethod("GetHitTest", BindingFlags.Instance | BindingFlags.NonPublic); + this.listViewDesignWndProc = tListViewDesigner.GetMethod("WndProc", BindingFlags.Instance | BindingFlags.NonPublic); + + Debug.Assert(this.listViewDesignGetHitTest != null, "Required method (GetHitTest) not found on ListViewDesigner"); + Debug.Assert(this.listViewDesignWndProc != null, "Required method (WndProc) not found on ListViewDesigner"); + + // Tell the Designer to use properties of default designer as well as the properties of this class (do before base.Initialize) + TypeDescriptor.CreateAssociation(component, this.listViewDesigner); + + IServiceContainer site = (IServiceContainer)component.Site; + if (site != null && GetService(typeof(DesignerCommandSet)) == null) { + site.AddService(typeof(DesignerCommandSet), new CDDesignerCommandSet(this)); + } else { + Debug.Fail("site != null && GetService(typeof (DesignerCommandSet)) == null"); + } + + this.listViewDesigner.Initialize(component); + base.Initialize(component); + + RemoveDuplicateDockingActionList(); + } + + /// + /// Initialises a newly created component. + /// + /// A name/value dictionary of default values to apply to properties. May be null if no default values are specified. + public override void InitializeNewComponent(IDictionary defaultValues) { + // Debug.WriteLine("ObjectListViewDesigner.InitializeNewComponent"); + base.InitializeNewComponent(defaultValues); + this.listViewDesigner.InitializeNewComponent(defaultValues); + } + + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) { + // Debug.WriteLine("ObjectListViewDesigner.Dispose"); + if (disposing) { + if (this.listViewDesigner != null) { + this.listViewDesigner.Dispose(); + // Normally we would now null out the designer, but this designer + // still has methods called AFTER it is disposed. + } + } + + base.Dispose(disposing); + } + + /// + /// Removes the duplicate DockingActionList added by this designer to the . + /// + /// + /// adds an internal DockingActionList : 'Dock/Undock in Parent Container'. + /// But the default designer has already added that action list. So we need to remove one. + /// + private void RemoveDuplicateDockingActionList() { + // This is a true hack -- in a class that is basically a huge hack itself. + // Reach into the bowel of our base class, get a private field, and use that fields value to + // remove an action from the designer. + // In ControlDesigner, there is "private DockingActionList dockingAction;" + // Don't you just love Reflector?! + FieldInfo fi = typeof(ControlDesigner).GetField("dockingAction", BindingFlags.Instance | BindingFlags.NonPublic); + if (fi != null) { + DesignerActionList dockingAction = (DesignerActionList)fi.GetValue(this); + if (dockingAction != null) { + DesignerActionService service = (DesignerActionService)GetService(typeof(DesignerActionService)); + if (service != null) { + service.Remove(this.Control, dockingAction); + } + } + } + } + + #endregion + + #region IDesignerFilter overrides + + /// + /// Adjusts the set of properties the component exposes through a . + /// + /// An containing the properties for the class of the component. + protected override void PreFilterProperties(IDictionary properties) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterProperties"); + + // Always call the base PreFilterProperties implementation + // before you modify the properties collection. + base.PreFilterProperties(properties); + + // Give the listviewdesigner a chance to filter the properties + // (though we already know it's not going to do anything) + this.designerFilter.PreFilterProperties(properties); + + // I'd like to just remove the redundant properties, but that would + // break backward compatibility. The deserialiser that handles the XXX.Designer.cs file + // works off the designer, so even if the property exists in the class, the deserialiser will + // throw an error if the associated designer actually removes that property. + // So we shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + + List unwantedProperties = new List(new string[] { + "BackgroundImage", "BackgroundImageTiled", "HotTracking", "HoverSelection", + "LabelEdit", "VirtualListSize", "VirtualMode" }); + + // Also hid Tooltip properties, since giving a tooltip to the control through the IDE + // messes up the tooltip handling + foreach (string propertyName in properties.Keys) { + if (propertyName.StartsWith("ToolTip")) { + unwantedProperties.Add(propertyName); + } + } + + // If we are looking at a TreeListView, remove group related properties + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwantedProperties.AddRange(new string[] { + "GroupImageList", "GroupWithItemCountFormat", "GroupWithItemCountSingularFormat", "HasCollapsibleGroups", + "SpaceBetweenGroups", "ShowGroups", "SortGroupItemsByPrimaryColumn", "ShowItemCountOnGroups" + }); + } + + // Shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + foreach (string unwantedProperty in unwantedProperties) { + PropertyDescriptor propertyDesc = TypeDescriptor.CreateProperty( + typeof(ObjectListView), + (PropertyDescriptor)properties[unwantedProperty], + new BrowsableAttribute(false)); + properties[unwantedProperty] = propertyDesc; + } + } + + /// + /// Allows a designer to add to the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PreFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterEvents"); + base.PreFilterEvents(events); + this.designerFilter.PreFilterEvents(events); + + // Remove the events that don't make sense for an ObjectListView. + // See PreFilterProperties() for why we do this dance rather than just remove the event. + List unwanted = new List(new string[] { + "AfterLabelEdit", + "BeforeLabelEdit", + "DrawColumnHeader", + "DrawItem", + "DrawSubItem", + "RetrieveVirtualItem", + "SearchForVirtualItem", + "VirtualItemsSelectionRangeChanged" + }); + + // If we are looking at a TreeListView, remove group related events + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwanted.AddRange(new string[] { + "AboutToCreateGroups", + "AfterCreatingGroups", + "BeforeCreatingGroups", + "GroupTaskClicked", + "GroupExpandingCollapsing", + "GroupStateChanged" + }); + } + + foreach (string unwantedEvent in unwanted) { + EventDescriptor eventDesc = TypeDescriptor.CreateEvent( + typeof(ObjectListView), + (EventDescriptor)events[unwantedEvent], + new BrowsableAttribute(false)); + events[unwantedEvent] = eventDesc; + } + } + + /// + /// Allows a designer to change or remove items from the set of attributes that it exposes through a . + /// + /// The attributes for the class of the component. + protected override void PostFilterAttributes(IDictionary attributes) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterAttributes"); + this.designerFilter.PostFilterAttributes(attributes); + base.PostFilterAttributes(attributes); + } + + /// + /// Allows a designer to change or remove items from the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PostFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterEvents"); + this.designerFilter.PostFilterEvents(events); + base.PostFilterEvents(events); + } + + #endregion + + #region Overrides + + /// + /// Gets the design-time action lists supported by the component associated with the designer. + /// + /// + /// The design-time action lists supported by the component associated with the designer. + /// + public override DesignerActionListCollection ActionLists { + get { + // We want to change the first action list so it only has the commands we want + DesignerActionListCollection actionLists = this.listViewDesigner.ActionLists; + if (actionLists.Count > 0 && !(actionLists[0] is ListViewActionListAdapter)) { + actionLists[0] = new ListViewActionListAdapter(this, actionLists[0]); + } + return actionLists; + } + } + + /// + /// Gets the collection of components associated with the component managed by the designer. + /// + /// + /// The components that are associated with the component managed by the designer. + /// + public override ICollection AssociatedComponents { + get { + ArrayList components = new ArrayList(base.AssociatedComponents); + components.AddRange(this.listViewDesigner.AssociatedComponents); + return components; + } + } + + /// + /// Indicates whether a mouse click at the specified point should be handled by the control. + /// + /// + /// true if a click at the specified point is to be handled by the control; otherwise, false. + /// + /// A indicating the position at which the mouse was clicked, in screen coordinates. + protected override bool GetHitTest(Point point) { + // The ListViewDesigner wants to allow column dividers to be resized + return (bool)this.listViewDesignGetHitTest.Invoke(listViewDesigner, new object[] { point }); + } + + /// + /// Processes Windows messages and optionally routes them to the control. + /// + /// The to process. + protected override void WndProc(ref Message m) { + switch (m.Msg) { + case 0x4e: + case 0x204e: + // The listview designer is interested in HDN_ENDTRACK notifications + this.listViewDesignWndProc.Invoke(listViewDesigner, new object[] { m }); + break; + default: + base.WndProc(ref m); + break; + } + } + + #endregion + + #region Implementation variables + + private ControlDesigner listViewDesigner; + private IDesignerFilter designerFilter; + private MethodInfo listViewDesignGetHitTest; + private MethodInfo listViewDesignWndProc; + + #endregion + + #region Custom action list + + /// + /// This class modifies a ListViewActionList, by removing the "Edit Items" and "Edit Groups" actions. + /// + /// + /// + /// That class is internal, so we cannot simply subclass it, which would be simpler. + /// + /// + /// Action lists use reflection to determine if that action can be executed, so we not + /// only have to modify the returned collection of actions, but we have to implement + /// the properties and commands that the returned actions use. + /// + private class ListViewActionListAdapter : DesignerActionList + { + public ListViewActionListAdapter(ObjectListViewDesigner designer, DesignerActionList wrappedList) + : base(wrappedList.Component) { + this.designer = designer; + this.wrappedList = wrappedList; + } + + public override DesignerActionItemCollection GetSortedActionItems() { + DesignerActionItemCollection items = wrappedList.GetSortedActionItems(); + items.RemoveAt(2); // remove Edit Groups + items.RemoveAt(0); // remove Edit Items + return items; + } + + private void EditValue(ComponentDesigner componentDesigner, IComponent iComponent, string propertyName) { + // One more complication. The ListViewActionList classes uses an internal class, EditorServiceContext, to + // edit the items/columns/groups collections. So, we use reflection to bypass the data hiding. + Type tEditorServiceContext = Type.GetType("System.Windows.Forms.Design.EditorServiceContext, System.Design"); + tEditorServiceContext.InvokeMember("EditValue", BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object[] { componentDesigner, iComponent, propertyName }); + } + + private void SetValue(object target, string propertyName, object value) { + TypeDescriptor.GetProperties(target)[propertyName].SetValue(target, value); + } + + public void InvokeColumnsDialog() { + EditValue(this.designer, base.Component, "Columns"); + } + + // Don't need these since we removed their corresponding actions from the list. + // Keep the methods just in case. + + //public void InvokeGroupsDialog() { + // EditValue(this.designer, base.Component, "Groups"); + //} + + //public void InvokeItemsDialog() { + // EditValue(this.designer, base.Component, "Items"); + //} + + public ImageList LargeImageList { + get { return ((ListView)base.Component).LargeImageList; } + set { SetValue(base.Component, "LargeImageList", value); } + } + + public ImageList SmallImageList { + get { return ((ListView)base.Component).SmallImageList; } + set { SetValue(base.Component, "SmallImageList", value); } + } + + public View View { + get { return ((ListView)base.Component).View; } + set { SetValue(base.Component, "View", value); } + } + + ObjectListViewDesigner designer; + DesignerActionList wrappedList; + } + + #endregion + + #region DesignerCommandSet + + private class CDDesignerCommandSet : DesignerCommandSet + { + + public CDDesignerCommandSet(ComponentDesigner componentDesigner) { + this.componentDesigner = componentDesigner; + } + + public override ICollection GetCommands(string name) { + // Debug.WriteLine("CDDesignerCommandSet.GetCommands:" + name); + if (componentDesigner != null) { + if (name.Equals("Verbs")) { + return componentDesigner.Verbs; + } + if (name.Equals("ActionLists")) { + return componentDesigner.ActionLists; + } + } + return base.GetCommands(name); + } + + private readonly ComponentDesigner componentDesigner; + } + + #endregion + } + + /// + /// This class works in conjunction with the OLVColumns property to allow OLVColumns + /// to be added to the ObjectListView. + /// + public class OLVColumnCollectionEditor : System.ComponentModel.Design.CollectionEditor + { + /// + /// Create a OLVColumnCollectionEditor + /// + /// + public OLVColumnCollectionEditor(Type t) + : base(t) { + } + + /// + /// What type of object does this editor create? + /// + /// + protected override Type CreateCollectionItemType() { + return typeof(OLVColumn); + } + + /// + /// Edit a given value + /// + /// + /// + /// + /// + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + if (context == null) + throw new ArgumentNullException("context"); + if (provider == null) + throw new ArgumentNullException("provider"); + + // Figure out which ObjectListView we are working on. This should be the Instance of the context. + ObjectListView olv = context.Instance as ObjectListView; + Debug.Assert(olv != null, "Instance must be an ObjectListView"); + + // Edit all the columns, not just the ones that are visible + base.EditValue(context, provider, olv.AllColumns); + + // Set the columns on the ListView to just the visible columns + List newColumns = olv.GetFilteredColumns(View.Details); + olv.Columns.Clear(); + olv.Columns.AddRange(newColumns.ToArray()); + + return olv.Columns; + } + + /// + /// What text should be shown in the list for the given object? + /// + /// + /// + protected override string GetDisplayText(object value) { + OLVColumn col = value as OLVColumn; + if (col == null || String.IsNullOrEmpty(col.AspectName)) + return base.GetDisplayText(value); + + return String.Format("{0} ({1})", base.GetDisplayText(value), col.AspectName); + } + } + + /// + /// Control how the overlay is presented in the IDE + /// + internal class OverlayConverter : ExpandableObjectConverter + { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { + return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); + } + + public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { + if (destinationType == typeof(string)) { + ImageOverlay imageOverlay = value as ImageOverlay; + if (imageOverlay != null) { + return imageOverlay.Image == null ? "(none)" : "(set)"; + } + TextOverlay textOverlay = value as TextOverlay; + if (textOverlay != null) { + return String.IsNullOrEmpty(textOverlay.Text) ? "(none)" : "(set)"; + } + } + + return base.ConvertTo(context, culture, value, destinationType); + } + } +} diff --git a/ObjectListView/ObjectListView.FxCop b/ObjectListView/ObjectListView.FxCop new file mode 100644 index 0000000..b5653dd --- /dev/null +++ b/ObjectListView/ObjectListView.FxCop @@ -0,0 +1,3521 @@ + + + + True + c:\program files\microsoft fxcop 1.36\Xml\FxCopReport.xsl + + + + + + True + True + True + 10 + 1 + + False + + False + 120 + True + 2.0 + + + + $(ProjectDir)/trunk/ObjectListView/bin/Debug/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 'ObjectListView.dll' + + + + + + + + + + + 'BarRenderer' + 'Pen' + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(int, int, Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BackgroundColor' + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + + + + + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetForegroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetImageSelector()' + + + + + + + + + 'BaseRenderer.GetText()' + + + + + + + + + + + + + + 'BaseRenderer.GetTextBackgroundColor()' + + + + + + + + + + + + + + + + 'BorderDecoration' + 'SolidBrush' + + + + + + + + + 'CellEditEventHandler' + + + + + + + + + + + + + + + + 'g' + 'CheckStateRenderer.CalculateCheckBoxBounds(Graphics, Rectangle)' + + + + + + + + + + + 'ColumnRightClickEventHandler' + + + + + + + + + + + + + + + + + + 'ComboBoxItem.Key.get()' + + + + + + + + + + + + + + + 'DataListView.currencyManager_ListChanged(object, ListChangedEventArgs)' + + + + + + + + + 'DataListView.currencyManager_MetaDataChanged(object, EventArgs)' + + + + + + + + + 'DataListView.currencyManager_PositionChanged(object, EventArgs)' + + + + + + + + + + + + + 'DescribedTaskRenderer.GetDescription()' + + + + + + + + + + + 'DropTargetLocation' + + + + + + + + + + + 'collection' + 'ICollection' + 'FastObjectListDataSource.EnumerableToArray(IEnumerable)' + castclass + + + + + + + + + + + 'FastObjectListDataSource.FilteredObjectList.get()' + + + + + + + + + + + + + Flag + 'FlagRenderer' + + + + + + + + + + + + + 'FloatCellEditor.Value.get()' + + + + + + + + + + + + + + 'FloatCellEditor.Value.set(double)' + + + + + + + + + + + + + + + + + + + + + + 'GlassPanelForm.CreateParams.get()' + 'Form.CreateParams.get()' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GlassPanelForm.WndProc(ref Message)' + 'Form.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GroupMetricsMask' + 'GroupMetricsMask.LVGMF_NONE' + + + + + + + + + + 'GroupMetricsMask' + + + + + + + + + + + + + + 'GroupState' + 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 + + + + + 'GroupState' + 'GroupState.LVGS_NORMAL' + + + + + 'GroupState' + + + + + + + + + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.AssignHandle(IntPtr)' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.NativeWindow()' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + + + + + + + + + + + + 'g' + 'HeaderControl.CalculateHeight(Graphics)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawHeaderText(Graphics, Rectangle, OLVColumn, HeaderStateStyle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedBackground(Graphics, Rectangle, int, bool)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedSortIndicator(Graphics, Rectangle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedBackground(Graphics, Rectangle, int, bool, HeaderStateStyle)' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedSortIndicator(Graphics, Rectangle)' + + + + + + + + + 'm' + 'HeaderControl.HandleDestroy(ref Message)' + + + + + + + + + 'm' + 'HeaderControl.HandleMouseMove(ref Message)' + + + + + 'm' + + + + + + + + + + + + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.LParam.get()' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + + + 'value' + 'HeaderControl.HotFontStyle.set(FontStyle)' + + + + + + + + + + + Flags + 'HeaderControl.TextFormatFlags' + + + + + + + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'HeaderControl.WndProc(ref Message)' + 'Message.Msg.get()' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'text' + 'HighlightTextRenderer.HighlightTextRenderer(string)' + + + + + + + + + + + 'value' + 'HighlightTextRenderer.StringComparison.set(StringComparison)' + + + + + + + + + + + + + 'value' + 'HighlightTextRenderer.TextToHighlight.set(string)' + + + + + + + + + + + + + + + + + 'HyperlinkEventArgs.Column.set(OLVColumn)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ColumnIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Item.set(OLVListItem)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ListView.set(ObjectListView)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Model.set(object)' + + + + + + + + + + + + + 'HyperlinkEventArgs.RowIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.SubItem.set(OLVListSubItem)' + + + + + + + + + + + 'HyperlinkEventArgs.Url' + + + + + + + + + 'HyperlinkEventArgs.Url.set(string)' + + + + + + + + + + + + + + + 'ImageRenderer.GetImageFromAspect()' + + + + + + + + + + + + + + + + + + + + 'IntUpDown.Value.get()' + + + + + + + + + + + + + + 'IntUpDown.Value.set(int)' + + + + + + + + + + + + + + + + + + + + 'IVirtualListDataSource.GetObjectCount()' + + + + + + + + + + + + + + + + Multi + 'MultiImageRenderer' + + + + + + + + + + + + + + 'MultiImageRenderer.ImageSelector' + 'BaseRenderer.GetImageSelector()' + + + + + + + + + + + + + 'Munger.GetValue(object)' + 'object' + + + + + + + + + + + + + + 'Munger.PutValue(object, object)' + 'object' + + + 'Munger.PutValue(object, object)' + 'object' + + + + + + + + + + + + + + + + + + 'NativeMethods.ChangeSize(IWin32Window, int, int)' + + + + + + + + + 'NativeMethods.ChangeZOrder(IWin32Window, IWin32Window)' + + + + + + + + + 'NativeMethods.DeleteObject(IntPtr)' + + + + + + + + + 'NativeMethods.DrawImageList(Graphics, ImageList, int, int, int, bool)' + + + + + + + + + 'NativeMethods.GetClientRect(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + 'Point' + + + + + + + + + 'NativeMethods.GetGroupInfo(ObjectListView, int, ref NativeMethods.LVGROUP2)' + + + + + + + + + 'NativeMethods.GetScrollInfo(IntPtr, int, NativeMethods.SCROLLINFO)' + + + + + + + + + 'NativeMethods.GetUpdateRect(Control)' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'eraseBackground' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'NativeMethods.GetWindowLong32(IntPtr, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'NativeMethods.GetWindowLongPtr64(IntPtr, int)' + 'user32.dll' + GetWindowLongPtr + + + + + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + + + + + 'erase' + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP2)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUPMETRICS)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, IntPtr)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, IntPtr, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageHDItem(IntPtr, int, int, ref NativeMethods.HDITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + + + + + 'lParam' + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + + + + + 'wParam' + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageLVItem(IntPtr, int, int, ref NativeMethods.LVITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageRECT(IntPtr, int, int, ref NativeMethods.RECT)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageString(IntPtr, int, int, string)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageTOOLINFO(IntPtr, int, int, NativeMethods.TOOLINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SetBackgroundImage(ListView, Image)' + + + + + + + + + 'NativeMethods.SetBkColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetSelectedColumn(ListView, ColumnHeader)' + + + + + + + + + 'NativeMethods.SetTextColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetTooltipControl(ListView, ToolTipControl)' + + + + + + + + + 'NativeMethods.SetWindowLongPtr32(IntPtr, int, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'dwNewLong' + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 'user32.dll' + SetWindowLongPtr + + + + + + + + + 'NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, uint)' + + + + + + + + + 'NativeMethods.SetWindowTheme(IntPtr, string, string)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + 'subApp' + + + + + 'subIdList' + + + + + + + + + 'NativeMethods.ShowWindow(IntPtr, int)' + + + + + + + + + 'NativeMethods.ValidatedRectInternal(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.ValidateRect(Control, Rectangle)' + + + + + + + + + + + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.ColumnIndexUnderCursor.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.IsCursorOverLockedDivider.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'OLVListItem.GetSubItemBounds(int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellTextBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.OlvHitTest(int, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'TintedColumnDecoration.Draw(ObjectListView, Graphics, Rectangle)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.EnsureGroupVisible(ListViewGroup)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleBeginScroll(ref Message)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleKeyDown(ref Message)' + + + + + + + + + + + + + + + + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.AddTool(IWin32Window)' + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.RemoveToolTip(IWin32Window)' + + + + + + + + + + + + + + + + + + 'ObjectListView.AllColumns' + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.AllColumns' + + + + + + + + + + + + + + 'rowIndex' + 'ObjectListView.ApplyHyperlinkStyle(int, OLVListItem)' + + + + + + + + + 'ObjectListView.BooleanCheckStateGetter' + + + + + + + + + 'ObjectListView.BooleanCheckStatePutter' + + + + + + + + + 'item' + 'ObjectListView.CalculateCellBounds(OLVListItem, int)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'ObjectListView.CellEditor' + 'ObjectListView.GetCellEditor(OLVListItem, int)' + + + + + + + + + 'ObjectListView.CellEditor_Validating(object, CancelEventArgs)' + + + + + + + + + 'ObjectListView.CellToolTip' + 'ObjectListView.GetCellToolTip(int, int)' + + + + + + + + + 'ObjectListView.CheckedObject' + 'ObjectListView.GetCheckedObject()' + + + + + + + + + 'ObjectListView.CheckedObjects' + 'ObjectListView.GetCheckedObjects()' + + + + + 'ObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.ColumnsInDisplayOrder' + + + + + + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn)' + tb + 'tb' + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn, int)' + tb + 'tb' + + + + + + + + + 'List<OLVListItem>' + 'ObjectListView.DrawAllDecorations(Graphics, List<OLVListItem>)' + + + + + + + + + 'ObjectListView.EditorRegistry' + + + + + + + + + 'ObjectListView.EnsureGroupVisible(ListViewGroup)' + lvg + 'lvg' + + + + + + + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aListFilter' + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aModelFilter' + + + + + + + + + 'control' + 'CheckBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'ComboBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'TextBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.GetFilteredColumns(View)' + + + + + + + + + + + + + + 'selectedColumn' + + + + + + + + + + + + + + 'ObjectListView.GetItemCount()' + + + + + + + + + + + + + + 'ObjectListView.GetLastItemInDisplayOrder()' + + + + + + + + + 'ObjectListView.GetSelectedObject()' + + + + + + + + + + + + + + 'ObjectListView.GetSelectedObjects()' + + + + + + + + + + + + + + 'ObjectListView.HandleApplicationIdle(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleApplicationIdle_ResizeColumns(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleCellToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleChar(ref Message)' + 'Control.ProcessKeyEventArgs(ref Message)' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + 'ObjectListView.HandleChar(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleColumnClick(object, ColumnClickEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanged(object, ColumnWidthChangedEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanging(object, ColumnWidthChangingEventArgs)' + + + + + + + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleHeaderToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleLayout(object, LayoutEventArgs)' + + + + + + + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.PtrToStructure(IntPtr, Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'NativeWindow.Handle.get()' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HeaderToolTip' + 'ObjectListView.GetHeaderToolTip(int)' + + + + + + + + + 'url' + 'ObjectListView.IsUrlVisited(string)' + + + + + + + + + 'url' + 'ObjectListView.MarkUrlVisited(string)' + + + + + + + + + Unsort + 'ObjectListView.MenuLabelUnsort' + + + + + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)] + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + ->'ObjectListView.ProcessDialogKey(Keys)' ->'ObjectListView.ProcessDialogKey(Keys)' + + + + + + + + + + + + + + 'ObjectListView.SelectedObject' + 'ObjectListView.GetSelectedObject()' + + + + + + + + + 'ObjectListView.SelectedObjects' + 'ObjectListView.GetSelectedObjects()' + + + + + 'ObjectListView.SelectedObjects' + + + + + + + + + + + + + + 'control' + 'ComboBox' + 'ObjectListView.SetControlValue(Control, object, string)' + castclass + + + + + + + + + Checkedness + 'ObjectListView.SetObjectCheckedness(object, CheckState)' + + + + + + + + + + + + + + 'item' + 'ObjectListView.SetSubItemImages(int, OLVListItem, bool)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'columnToSort' + 'ObjectListView.ShowSortIndicator(OLVColumn, SortOrder)' + 'OLVColumn' + 'ColumnHeader' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_DOWN_KEY' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_UP_KEY' + + + + + + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.BeginInit()' + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.EndInit()' + + + + + + + + + Renderering + 'ObjectListView.TextRendereringHint' + + + + + + + + + Unsort + 'ObjectListView.Unsort()' + + + + + + + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'ObjectListView.WndProc(ref Message)' + 'Control.DefWndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'Message.Msg.get()' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'ObjectListView.ObjectListViewState.VersionNumber' + + + + + + + + + + + + + + + + 'OLVColumnAttribute' + + + + + 'OLVColumnAttribute.Title' + 'title' + + + + + 'OLVColumnAttribute' + + + + + + + + + Cutoffs + 'OLVColumnAttribute.GroupCutoffs' + + + + + 'OLVColumnAttribute.GroupCutoffs' + + + + + + + + + 'OLVColumnAttribute.GroupDescriptions' + + + + + + + + + + + + + 'OLVDataObject.ConvertToHtmlFragment(string)' + 'string.IndexOf(string)' + 'string.IndexOf(string, StringComparison)' + + + + + + + + + + + + + 'OLVGroup.GetState()' + + + + + + + + + 'OLVGroup.State' + 'OLVGroup.GetState()' + + + + + + + + + Subseted + 'OLVGroup.Subseted' + + + + + + + + + + + 'OLVListItem' + + + + + + + + + 'OLVListItem.Bounds' + 'ListViewItem.GetBounds(ItemBoundsPortion)' + + + + + + + + + + + 'value' + 'string' + 'OLVListItem.ImageSelector.set(object)' + castclass + + + + + + + + + + + + + + + 'OLVListSubItem.Url' + + + + + + + + + + + 'SimpleDropSink' + 'Timer' + + + + + + + + + 'Timer.Interval.set(int)' + 'SimpleDropSink.SimpleDropSink()' + + + + + + + + + + + 'TextAdornment' + 'StringFormat' + + + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[])' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, TextMatchFilter.MatchKind)' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.Columns' + + + + + + + + + 'TextMatchFilter.IsIncluded(OLVColumn)' + + + + + + + + + + + 'TextMatchFilter.MatchKind' + + + + + + + + + + + + + + 'TintedColumnDecoration' + 'SolidBrush' + + + + + + + + + + + Disp + 'ToolTipControl.HandleGetDispInfo(ref Message)' + + + + + + + + + + + + + + 'window' + 'ToolTipControl.PopToolTip(IWin32Window)' + + + + + + + + + + + 'ToolTipControl.StandardIcons' + + + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.ChildBranches' + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.FilteredChildBranches' + + + + + + + + + Flag + 'TreeListView.Branch.ManageLastChildFlag(MethodInvoker)' + + + + + + + + + + + Flags + 'TreeListView.Branch.BranchFlags' + + + + + + + + + + + 'TreeListView.Tree.GetBranchComparer()' + + + + + + + + + + + + + + + + + + 'TreeListView.TreeRenderer.PIXELS_PER_LEVEL' + + + + + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStateGetter' + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStatePutter' + + + + + + + + + 'TypedObjectListView<T>.CellToolTipGetter' + + + + + + + + + 'TypedObjectListView<T>.CheckedObjects' + + + + + + + + + + + + + + 'TypedObjectListView<T>.SelectedObjects' + + + + + + + + + + + + + + + + + + + + 'UintUpDown.Value.get()' + + + + + + + + + + + + + + 'UintUpDown.Value.set(uint)' + + + + + + + + + + + + + + + + + + + + 'VirtualObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'VirtualObjectListView.HandleCacheVirtualItems(object, CacheVirtualItemsEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleRetrieveVirtualItem(object, RetrieveVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleSearchForVirtualItem(object, SearchForVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.SetVirtualListSize(int)' + 'Exception' + + + + + + + + + + + + + + + + + + + + + These should be methods rather than properties + The out parameter is necessary since this method returns two pieces of information: the item under the point and the subitem item too + This is used to ensure we understand the newly load state. + All these properties should be assignable. + Our project is build with unsafe code enabled, so it automatically has the SecurityProperty set + These initializations are not unnecessary + We have to pass the windows message by reference + Instances of this class do not need to be disposable + These are utility methods that could well be used at runtime + Old style constants. Can't change now + These are OK like this. We need List<>, not IList<> since only List has a ToArray() method + Legacy cases that have to be kept like this + These are acceptable as methods rather than properties + windows messages should be passed by reference + This is not a security risk + There are several problems that can occur here and we want to ignore them all + These spellings are acceptable + These will only be used by OL types + + + Not appropriate here + Can't change now + we want to catch everthing + MS! + not flags + MS! + MS + + + + + Sign {0} with a strong name key. + + + Consider a design that does not require that {0} be an out parameter. + + + {0} appears to have no upstream public or protected callers. + + + Seal {0}, if possible. + + + It appears that field {0} is never used or is only ever assigned to. Use this field or remove it. + + + Change {0} to be read-only by removing the property setter. + + + Consider changing the type of parameter {0} in {1} from {2} to its base type {3}. This method appears to only require base class members in its implementation. Suppress this violation if there is a compelling reason to require the more derived type in the method signature. + + + Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. + + + {0}, a parameter, is cast to type {1} multiple times in method {2}. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant {3} instruction. + + + Modify {0} to catch a more specific exception than {1} or rethrow the exception. + + + Change {0} in {1} to use Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V> + + + {0} calls {1} but does not use the HRESULT or error code that the method returns. This could lead to unexpected behavior in error conditions or low-resource situations. Use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method. + {0} creates a new instance of {1} which is never used. Pass the instance as an argument to another method, assign the instance to a variable, or remove the object creation if it is unnecessary. + + + + {0} initializes field {1} of type {2} to {3}. Remove this initialization because it will be done automatically by the runtime. + + + {0} is marked with FlagsAttribute but a discrete member cannot be found for every settable bit that is used across the range of enum values. Remove FlagsAttribute from the type or define new members for the following (currently missing) values: {1} + + + + Modify the call to {0} in method {1} to set the timer interval to a value that's greater than or equal to one second. + + + In enum {0}, change the name of {1} to 'None'. + + + If enumeration name {0} is singular, change it to a plural form. + + + Correct the spelling of '{0}' in member name {1} or remove it entirely if it represents any sort of Hungarian notation. + In method {0}, correct the spelling of '{1}' in parameter name {2} or remove it entirely if it represents any sort of Hungarian notation. + Correct the spelling of '{0}' in type name {1}. + + + + Make {0} sealed (a breaking change if this class has previously shipped), implement the method non-explicitly, or implement a new method that exposes the functionality of {1} and is visible to derived classes. + + + Specify AttributeUsage on {0}. + + + Add the MarshalAsAttribute to parameter {0} of P/Invoke {1}. If the corresponding unmanaged parameter is a 4-byte Win32 'BOOL', use [MarshalAs(UnmanagedType.Bool)]. For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + Add the MarshalAsAttribute to the return type of P/Invoke {0}. If the corresponding unmanaged return type is a 4-byte Win32 'BOOL', use MarshalAs(UnmanagedType.Bool). For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + + + The constituent members of {0} appear to represent flags that can be combined rather than discrete values. If this is correct, mark the enumeration with FlagsAttribute. + + + Add [Serializable] to {0} as this type implements ISerializable. + + + Consider making {0} non-public or a constant. + + + If the name {0} is plural, change it to its singular form. + + + Add the following security attribute to {0} in order to match a LinkDemand on base method {1}: {2}. + + + As it is declared in your code, parameter {0} of P/Invoke {1} will be {2} bytes wide on {3} platforms. This is not correct, as the actual native declaration of this API indicates it should be {4} bytes wide on {3} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {5}. + As it is declared in your code, the return type of P/Invoke {0} will be {1} bytes wide on {2} platforms. This is not correct, as the actual native declaration of this API indicates it should be {3} bytes wide on {2} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {4}. + + + Correct the declaration of {0} so that it correctly points to an existing entry point in {1}. The unmanaged entry point name currently linked to is {2}. + + + Because property {0} is write-only, either add a property getter with an accessibility that is greater than or equal to its setter or convert this property into a method. + + + Change {0} to return a collection or make it a method. + + + The property name {0} is confusing given the existence of inherited method {1}. Rename or remove this property. + The property name {0} is confusing given the existence of method {1}. Rename or remove one of these members. + + + Parameter {0} of {1} is never used. Remove the parameter or use it in the method body. + + + Consider making {0} not externally visible. + + + To reduce security risk, marshal parameter {0} as Unicode, by setting DllImport.CharSet to CharSet.Unicode, or by explicitly marshaling the parameter as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, set BestFitMapping=false; for added security, also set ThrowOnUnmappableChar=true. + + + {0} makes a call to {1} that does not explicitly provide a StringComparison. This should be replaced with a call to {2}. + + + Implement IDisposable on {0} because it creates members of the following IDisposable types: {1}. If {0} has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers. + + + Change the type of parameter {0} of method {1} from string to System.Uri, or provide an overload of {1}, that allows {0} to be passed as a System.Uri object. + + + Change the type of property {0} from string to System.Uri. + + + Remove {0} and replace its usage with EventHandler<T> + + + {0} passes {1} as an argument to {2}. Replace this usage with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase if appropriate. + + + Replace the term '{0}' in member name {1} with an appropriate alternate or remove it entirely. + Replace the term '{0}' in type name {1} with an appropriate alternate or remove it entirely. + + + Change {0} to a property if appropriate. + + + + diff --git a/ObjectListView/ObjectListView.cs b/ObjectListView/ObjectListView.cs new file mode 100644 index 0000000..7b4bbe5 --- /dev/null +++ b/ObjectListView/ObjectListView.cs @@ -0,0 +1,10924 @@ +/* + * ObjectListView - A listview to show various aspects of a collection of objects + * + * Author: Phillip Piper + * Date: 9/10/2006 11:15 AM + * + * Change log + * 2018-10-06 JPP - InsertObjects() when in a non-Detail View now correctly positions the items (SF bug #154) + * 2018-09-01 JPP - Hardened code against the rare case of the control having no columns (SF bug #174) + * The underlying ListView does not like having rows when there are no columns and throws exceptions.j + * 2018-05-05 JPP - Added OLVColumn.EditorCreator to allow fine control over what control is used to edit + * a particular cell. + * - Added IOlvEditor to allow custom editor to easily integrate with our editing scheme + * - ComboBoxes resize drop downs to show the widest entry via ControlUtilities.AutoResizeDropDown() + * 2018-05-03 JPP - Extend OnColumnRightClick so the event handler can tweak the menu to be shown + * 2018-04-27 JPP - Sorting now works when grouping is locked on a column AND SortGroupItemsByPrimaryColumn is true + * - Correctly report right clicks on group headers via CellRightClick events. + * v2.9.2 + * 2016-06-02 JPP - Cell editors now respond to mouse wheel events. Set AllowCellEditorsToProcessMouseWheel + * to false revert to previous behaviour. + * - Fixed issue in PauseAnimations() that prevented it from working until + * after the control had been rendered at least once. + * - CellEditUseWholeCell now has correct default value (true). + * - Dropping on a subitem when CellEditActivation is set to SingleClick no longer + * initiates a cell edit + * v2.9.1 + * 2015-12-30 JPP - Added CellRendererGetter to allow each cell to have a different renderer. + * - Obsolete properties are no longer code-gen'ed. + * + * v2.9.0 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * - Renamed properties related to selection colours: + * - HighlightBackgroundColor -> SelectedBackColor + * - HighlightForegroundColor -> SelectedForeColor + * - UnfocusedHighlightBackgroundColor -> UnfocusedSelectedBackColor + * - UnfocusedHighlightForegroundColor -> UnfocusedSelectedForeColor + * - UseCustomSelectionColors is no longer used + * 2015-08-03 JPP - Added ObjectListView.CellEditFinished event + * - Added EditorRegistry.Unregister() + * 2015-07-08 JPP - All ObjectListViews are now OwnerDrawn by default. This allows all the great features + * of ObjectListView to work correctly at the slight cost of more processing at render time. + * It also avoids the annoying "hot item background ignored in column 0" behaviour that native + * ListView has. Programmers can still turn it back off if they wish. + * 2015-06-27 JPP - Yet another attempt to disable ListView's "shift click toggles checkboxes" behaviour. + * The last strategy (fake right click) worked, but had nasty side effects. This one works + * by intercepting a HITTEST message so that it fails. It no longer creates fake right mouse events. + * - Trigger SelectionChanged when filter is changed + * 2015-06-23 JPP - [BIG] Added support for Buttons + * 2015-06-22 JPP - Added OLVColumn.SearchValueGetter to allow the text used when text filtering to be customised + * - The default DefaultRenderer is now a HighlightTextRenderer, since that seems more generally useful + * 2015-06-17 JPP - Added FocusedObject property + * - Hot item is now always applied to the row even if FullRowSelect is false + * 2015-06-11 JPP - Added DefaultHotItemStyle property + * 2015-06-07 JPP - Added HeaderMinimumHeight property + * - Added ObjectListView.CellEditUsesWholeCell and OLVColumn.CellEditUsesWholeCell properties. + * 2015-05-15 JPP - Allow ImageGetter to return an Image (which I can't believe didn't work from the beginning!) + * 2015-04-27 JPP - Fix bug where setting View to LargeIcon in the designer was not persisted + * 2015-04-07 JPP - Ensure changes to row.Font in FormatRow are not wiped out by FormatCell (SF #141) + * + * v2.8.1 + * 2014-10-15 JPP - Added CellEditActivateMode.SingleClickAlways mode + * - Fire Filter event even if ModelFilter and ListFilter are null (SF #126) + * - Fixed issue where single-click editing didn't work (SF #128) + * v2.8.0 + * 2014-10-11 JPP - Fixed some XP-only flicker issues + * 2014-09-26 JPP - Fixed intricate bug involving checkboxes on non-owner-drawn virtual lists. + * - Fixed long standing (but previously unreported) error on non-details virtual lists where + * users could not click on checkboxes. + * 2014-09-07 JPP - (Major) Added ability to have checkboxes in headers + * - CellOver events are raised when the mouse moves over the header. Set TriggerCellOverEventsWhenOverHeader + * to false to disable this behaviour. + * - Freeze/Unfreeze now use BeginUpdate/EndUpdate to disable Window level drawing + * - Changed default value of ObjectListView.HeaderUsesThemes from true to false. Too many people were + * being confused, trying to make something interesting appear in the header and nothing showing up + * 2014-08-04 JPP - Final attempt to fix the multiple hyperlink events being raised. This involves turning + * a NM_CLICK notification into a NM_RCLICK. + * 2014-05-21 JPP - (Major) Added ability to disable rows. DisabledObjects, DisableObjects(), DisabledItemStyle. + * 2014-04-25 JPP - Fixed issue where virtual lists containing a single row didn't update hyperlinks on MouseOver + * - Added sanity check before BuildGroups() + * 2014-03-22 JPP - Fixed some subtle bugs resulting from misuse of TryGetValue() + * 2014-03-09 JPP - Added CollapsedGroups property + * - Several minor Resharper complaints quiesced. + * v2.7 + * 2014-02-14 JPP - Fixed issue with ShowHeaderInAllViews (another one!) where setting it to false caused the list to lose + * its other extended styles, leading to nasty flickering and worse. + * 2014-02-06 JPP - Fix issue on virtual lists where the filter was not correctly reapplied after columns were added or removed. + * - Made disposing of cell editors optional (defaults to true). This allows controls to be cached and reused. + * - Bracketed column resizing with BeginUpdate/EndUpdate to smooth redraws (thanks to Davide) + * 2014-02-01 JPP - Added static property ObjectListView.GroupTitleDefault to allow the default group title to be localised. + * 2013-09-24 JPP - Fixed issue in RefreshObjects() when model objects overrode the Equals()/GetHashCode() methods. + * - Made sure get state checker were used when they should have been + * 2013-04-21 JPP - Clicking on a non-groupable column header when showing groups will now sort + * the group contents by that column. + * v2.6 + * 2012-08-16 JPP - Added ObjectListView.EditModel() -- a convenience method to start an edit operation on a model + * 2012-08-10 JPP - Don't trigger selection changed events during sorting/grouping or add/removing columns + * 2012-08-06 JPP - Don't start a cell edit operation when the user clicks on the background of a checkbox cell. + * - Honor values from the BeforeSorting event when calling a CustomSorter + * 2012-08-02 JPP - Added CellVerticalAlignment and CellPadding properties. + * 2012-07-04 JPP - Fixed issue with cell editing where the cell editing didn't finish until the first idle event. + * This meant that if you clicked and held on the scroll thumb to finish a cell edit, the editor + * wouldn't be removed until the mouse was released. + * 2012-07-03 JPP - Fixed issue with SingleClick cell edit mode where the cell editing would not begin until the + * mouse moved after the click. + * 2012-06-25 JPP - Fixed bug where removing a column from a LargeIcon or SmallIcon view would crash the control. + * 2012-06-15 JPP - Added Reset() method, which definitively removes all rows *and* columns from an ObjectListView. + * 2012-06-11 JPP - Added FilteredObjects property which returns the collection of objects that survives any installed filters. + * 2012-06-04 JPP - [Big] Added UseNotifyPropertyChanged to allow OLV to listen for INotifyPropertyChanged events on models. + * 2012-05-30 JPP - Added static property ObjectListView.IgnoreMissingAspects. If this is set to true, all + * ObjectListViews will silently ignore missing aspect errors. Read the remarks to see why this would be useful. + * 2012-05-23 JPP - Setting UseFilterIndicator to true now sets HeaderUsesTheme to false. + * Also, changed default value of UseFilterIndicator to false. Previously, HeaderUsesTheme and UseFilterIndicator + * defaulted to true, which was pointless since when the HeaderUsesTheme is true, UseFilterIndicator does nothing. + * v2.5.1 + * 2012-05-06 JPP - Fix bug where collapsing the first group would cause decorations to stop being drawn (SR #3502608) + * 2012-04-23 JPP - Trigger GroupExpandingCollapsing event to allow the expand/collapse to be cancelled + * - Fixed SetGroupSpacing() so it corrects updates the space between all groups. + * - ResizeLastGroup() now does nothing since it was broken and I can't remember what it was + * even supposed to do :) + * 2012-04-18 JPP - Upgraded hit testing to include hits on groups. + * - HotItemChanged is now correctly recalculated on each mouse move. Includes "hot" group information. + * 2012-04-14 JPP - Added GroupStateChanged event. Useful for knowing when a group is collapsed/expanded. + * - Added AdditionalFilter property. This filter is combined with the Excel-like filtering that + * the end user might enact at runtime. + * 2012-04-10 JPP - Added PersistentCheckBoxes property to allow primary checkboxes to remember their values + * across list rebuilds. + * 2012-04-05 JPP - Reverted some code to .NET 2.0 standard. + * - Tweaked some code + * 2012-02-05 JPP - Fixed bug when selecting a separator on a drop down menu + * 2011-06-24 JPP - Added CanUseApplicationIdle property to cover cases where Application.Idle events + * are not triggered. For example, when used within VS (and probably Office) extensions + * Application.Idle is never triggered. Set CanUseApplicationIdle to false to handle + * these cases. + * - Handle cases where a second tool tip is installed onto the ObjectListView. + * - Correctly recolour rows after an Insert or Move + * - Removed m.LParam cast which could cause overflow issues on Win7/64 bit. + * v2.5.0 + * 2011-05-31 JPP - SelectObject() and SelectObjects() no longer deselect all other rows. + Set the SelectedObject or SelectedObjects property to do that. + * - Added CheckedObjectsEnumerable + * - Made setting CheckedObjects more efficient on large collections + * - Deprecated GetSelectedObject() and GetSelectedObjects() + * 2011-04-25 JPP - Added SubItemChecking event + * - Fixed bug in handling of NewValue on CellEditFinishing event + * 2011-04-12 JPP - Added UseFilterIndicator + * - Added some more localizable messages + * 2011-04-10 JPP - FormatCellEventArgs now has a CellValue property, which is the model value displayed + * by the cell. For example, for the Birthday column, the CellValue might be + * DateTime(1980, 12, 31), whereas the cell's text might be 'Dec 31, 1980'. + * 2011-04-04 JPP - Tweaked UseTranslucentSelection and UseTranslucentHotItem to look (a little) more + * like Vista/Win7. + * - Alternate colours are now only applied in Details view (as they always should have been) + * - Alternate colours are now correctly recalculated after removing objects + * 2011-03-29 JPP - Added SelectColumnsOnRightClickBehaviour to allow the selecting of columns mechanism + * to be changed. Can now be InlineMenu (the default), SubMenu, or ModelDialog. + * - ColumnSelectionForm was moved from the demo into the ObjectListView project itself. + * - Ctrl-C copying is now able to use the DragSource to create the data transfer object. + * 2011-03-19 JPP - All model object comparisons now use Equals rather than == (thanks to vulkanino) + * - [Small Break] GetNextItem() and GetPreviousItem() now accept and return OLVListView + * rather than ListViewItems. + * 2011-03-07 JPP - [Big] Added Excel-style filtering. Right click on a header to show a Filtering menu. + * - Added CellEditKeyEngine to allow key handling when cell editing to be completely customised. + * Add CellEditTabChangesRows and CellEditEnterChangesRows to show some of these abilities. + * 2011-03-06 JPP - Added OLVColumn.AutoCompleteEditorMode in preference to AutoCompleteEditor + * (which is now just a wrapper). Thanks to Clive Haskins + * - Added lots of docs to new classes + * 2011-02-25 JPP - Preserve word wrap settings on TreeListView + * - Resize last group to keep it on screen (thanks to ?) + * 2010-11-16 JPP - Fixed (once and for all) DisplayIndex problem with Generator + * - Changed the serializer used in SaveState()/RestoreState() so that it resolves on + * class name alone. + * - Fixed bug in GroupWithItemCountSingularFormatOrDefault + * - Fixed strange flickering in grouped, owner drawn OLV's using RefreshObject() + * v2.4.1 + * 2010-08-25 JPP - Fixed bug where setting OLVColumn.CheckBoxes to false gave it a renderer + * specialized for checkboxes. Oddly, this made Generator created owner drawn + * lists appear to be completely empty. + * - In IDE, all ObjectListView properties are now in a single "ObjectListView" category, + * rather than splitting them between "Appearance" and "Behavior" categories. + * - Added GroupingParameters.GroupComparer to allow groups to be sorted in a customizable fashion. + * - Sorting of items within a group can be disabled by setting + * GroupingParameters.PrimarySortOrder to None. + * 2010-08-24 JPP - Added OLVColumn.IsHeaderVertical to make a column draw its header vertical. + * - Added OLVColumn.HeaderTextAlign to control the alignment of a column's header text. + * - Added HeaderMaximumHeight to limit how tall the header section can become + * 2010-08-18 JPP - Fixed long standing bug where having 0 columns caused a InvalidCast exception. + * - Added IncludeAllColumnsInDataObject property + * - Improved BuildList(bool) so that it preserves scroll position even when + * the listview is grouped. + * 2010-08-08 JPP - Added OLVColumn.HeaderImageKey to allow column headers to have an image. + * - CellEdit validation and finish events now have NewValue property. + * 2010-08-03 JPP - Subitem checkboxes improvements: obey IsEditable, can be hot, can be disabled. + * - No more flickering of selection when tabbing between cells + * - Added EditingCellBorderDecoration to make it clearer which cell is being edited. + * 2010-08-01 JPP - Added ObjectListView.SmoothingMode to control the smoothing of all graphics + * operations + * - Columns now cache their group item format strings so that they still work as + * grouping columns after they have been removed from the listview. This cached + * value is only used when the column is not part of the listview. + * 2010-07-25 JPP - Correctly trigger a Click event when the mouse is clicked. + * 2010-07-16 JPP - Invalidate the control before and after cell editing to make sure it looks right + * 2010-06-23 JPP - Right mouse clicks on checkboxes no longer confuse them + * 2010-06-21 JPP - Avoid bug in underlying ListView control where virtual lists in SmallIcon view + * generate GETTOOLINFO msgs with invalid item indices. + * - Fixed bug where FastObjectListView would throw an exception when showing hyperlinks + * in any view except Details. + * 2010-06-15 JPP - Fixed bug in ChangeToFilteredColumns() that resulted in column display order + * being lost when a column was hidden. + * - Renamed IsVista property to IsVistaOrLater which more accurately describes its function. + * v2.4 + * 2010-04-14 JPP - Prevent object disposed errors when mouse event handlers cause the + * ObjectListView to be destroyed (e.g. closing a form during a + * double click event). + * - Avoid checkbox munging bug in standard ListView when shift clicking on non-primary + * columns when FullRowSelect is true. + * 2010-04-12 JPP - Fixed bug in group sorting (thanks Mike). + * 2010-04-07 JPP - Prevent hyperlink processing from triggering spurious MouseUp events. + * This showed itself by launching the same url multiple times. + * 2010-04-06 JPP - Space filling columns correctly resize upon initial display + * - ShowHeaderInAllViews is better but still not working reliably. + * See comments on property for more details. + * 2010-03-23 JPP - Added ObjectListView.HeaderFormatStyle and OLVColumn.HeaderFormatStyle. + * This makes HeaderFont and HeaderForeColor properties unnecessary -- + * they will be marked obsolete in the next version and removed after that. + * 2010-03-16 JPP - Changed object checking so that objects can be pre-checked before they + * are added to the list. Normal ObjectListViews managed "checkedness" in + * the ListViewItem, so this won't work for them, unless check state getters + * and putters have been installed. It will work not on virtual lists (thus fast lists and + * tree views) since they manage their own check state. + * 2010-03-06 JPP - Hide "Items" and "Groups" from the IDE properties grid since they shouldn't be set like that. + * They can still be accessed through "Custom Commands" and there's nothing we can do + * about that. + * 2010-03-05 JPP - Added filtering + * 2010-01-18 JPP - Overlays can be turned off. They also only work on 32-bit displays + * v2.3 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * 2009-10-28 JPP - Fix bug when right clicking in the empty area of the header + * 2009-10-20 JPP - Redraw the control after setting EmptyListMsg property + * v2.3 + * 2009-09-30 JPP - Added Dispose() method to properly release resources + * 2009-09-16 JPP - Added OwnerDrawnHeader, which you can set to true if you want to owner draw + * the header yourself. + * 2009-09-15 JPP - Added UseExplorerTheme, which allow complete visual compliance with Vista explorer. + * But see property documentation for its many limitations. + * - Added ShowHeaderInAllViews. To make this work, Columns are no longer + * changed when switching to/from Tile view. + * 2009-09-11 JPP - Added OLVColumn.AutoCompleteEditor to allow the autocomplete of cell editors + * to be disabled. + * 2009-09-01 JPP - Added ObjectListView.TextRenderingHint property which controls the + * text rendering hint of all drawn text. + * 2009-08-28 JPP - [BIG] Added group formatting to supercharge what is possible with groups + * - [BIG] Virtual groups now work + * - Extended MakeGroupies() to handle more aspects of group creation + * 2009-08-19 JPP - Added ability to show basic column commands when header is right clicked + * - Added SelectedRowDecoration, UseTranslucentSelection and UseTranslucentHotItem. + * - Added PrimarySortColumn and PrimarySortOrder + * 2009-08-15 JPP - Correct problems with standard hit test and subitems + * 2009-08-14 JPP - [BIG] Support Decorations + * - [BIG] Added header formatting capabilities: font, color, word wrap + * - Gave ObjectListView its own designer to hide unwanted properties + * - Separated design time stuff into separate file + * - Added FormatRow and FormatCell events + * 2009-08-09 JPP - Get around bug in HitTest when not FullRowSelect + * - Added OLVListItem.GetSubItemBounds() method which works correctly + * for all columns including column 0 + * 2009-08-07 JPP - Added Hot* properties that track where the mouse is + * - Added HotItemChanged event + * - Overrode TextAlign on columns so that column 0 can have something other + * than just left alignment. This is only honored when owner drawn. + * v2.2.1 + * 2009-08-03 JPP - Subitem edit rectangles always allowed for an image in the cell, even if there was none. + * Now they only allow for an image when there actually is one. + * - Added Bounds property to OLVListItem which handles items being part of collapsed groups. + * 2009-07-29 JPP - Added GetSubItem() methods to ObjectListView and OLVListItem + * 2009-07-26 JPP - Avoided bug in .NET framework involving column 0 of owner drawn listviews not being + * redrawn when the listview was scrolled horizontally (this was a LOT of work to track + * down and fix!) + * - The cell edit rectangle is now correctly calculated when the listview is scrolled + * horizontally. + * 2009-07-14 JPP - If the user clicks/double clicks on a tree list cell, an edit operation will no longer begin + * if the click was to the left of the expander. This is implemented in such a way that + * other renderers can have similar "dead" zones. + * 2009-07-11 JPP - CalculateCellBounds() messed with the FullRowSelect property, which confused the + * tooltip handling on the underlying control. It no longer does this. + * - The cell edit rectangle is now correctly calculated for owner-drawn, non-Details views. + * 2009-07-08 JPP - Added Cell events (CellClicked, CellOver, CellRightClicked) + * - Made BuildList(), AddObject() and RemoveObject() thread-safe + * 2009-07-04 JPP - Space bar now properly toggles checkedness of selected rows + * 2009-07-02 JPP - Fixed bug with tooltips when the underlying Windows control was destroyed. + * - CellToolTipShowing events are now triggered in all views. + * v2.2 + * 2009-06-02 JPP - BeforeSortingEventArgs now has a Handled property to let event handlers do + * the item sorting themselves. + * - AlwaysGroupByColumn works again, as does SortGroupItemsByPrimaryColumn and all their + * various permutations. + * - SecondarySortOrder and SecondarySortColumn are now "null" by default + * 2009-05-15 JPP - Fixed bug so that KeyPress events are again triggered + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-07 JPP - Don't use glass panel for overlays when in design mode. It's too confusing. + * 2009-05-05 JPP - Added Scroll event (thanks to Christophe Hosten for the complete patch to implement this) + * - Added Unfocused foreground and background colors (also thanks to Christophe Hosten) + * 2009-04-29 JPP - Added SelectedColumn property, which puts a slight tint on that column. Combine + * this with TintSortColumn property and the sort column is automatically tinted. + * - Use an overlay to implement "empty list" msg. Default empty list msg is now prettier. + * 2009-04-28 JPP - Fixed bug where DoubleClick events were not triggered when CheckBoxes was true + * 2009-04-23 JPP - Fixed various bugs under Vista. + * - Made groups collapsible - Vista only. Thanks to Crustyapplesniffer. + * - Forward events from DropSink to the control itself. This allows handlers to be defined + * within the IDE for drop events + * 2009-04-16 JPP - Made several properties localizable. + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-11 JPP - Implemented overlay architecture, based on CustomDraw scheme. + * This unified drag drop feedback, empty list msgs and overlay images. + * - Added OverlayImage and friends, which allows an image to be drawn + * transparently over the listview + * 2009-04-10 JPP - Fixed long-standing annoying flicker on owner drawn virtual lists! + * This means, amongst other things, that grid lines no longer get confused, + * and drag-select no longer flickers. + * 2009-04-07 JPP - Calculate edit rectangles more accurately + * 2009-04-06 JPP - Double-clicking no longer toggles the checkbox + * - Double-clicking on a checkbox no longer confuses the checkbox + * 2009-03-16 JPP - Optimized the build of autocomplete lists + * v2.1 + * 2009-02-24 JPP - Fix bug where double-clicking VERY quickly on two different cells + * could give two editors + * - Maintain focused item when rebuilding list (SF #2547060) + * 2009-02-22 JPP - Reworked checkboxes so that events are triggered for virtual lists + * 2009-02-15 JPP - Added ObjectListView.ConfigureAutoComplete utility method + * 2009-02-02 JPP - Fixed bug with AlwaysGroupByColumn where column header clicks would not resort groups. + * 2009-02-01 JPP - OLVColumn.CheckBoxes and TriStateCheckBoxes now work. + * 2009-01-28 JPP - Complete overhaul of renderers! + * - Use IRenderer + * - Added ObjectListView.ItemRenderer to draw whole items + * 2009-01-23 JPP - Simple Checkboxes now work properly + * - Added TriStateCheckBoxes property to control whether the user can + * set the row checkbox to have the Indeterminate value + * - CheckState property is now just a wrapper around the StateImageIndex property + * 2009-01-20 JPP - Changed to always draw columns when owner drawn, rather than falling back on DrawDefault. + * This simplified several owner drawn problems + * - Added DefaultRenderer property to help with the above + * - HotItem background color is applied to all cells even when FullRowSelect is false + * - Allow grouping by CheckedAspectName columns + * - Commented out experimental animations. Still needs work. + * 2009-01-17 JPP - Added HotItemStyle and UseHotItem to highlight the row under the cursor + * - Added UseCustomSelectionColors property + * - Owner draw mode now honors ForeColor and BackColor settings on the list + * 2009-01-16 JPP - Changed to use EditorRegistry rather than hard coding cell editors + * 2009-01-10 JPP - Changed to use Equals() method rather than == to compare model objects. + * v2.0.1 + * 2009-01-08 JPP - Fixed long-standing "multiple columns generated" problem. + * Thanks to pinkjones for his help with solving this one! + * - Added EnsureGroupVisible() + * 2009-01-07 JPP - Made all public and protected methods virtual + * - FinishCellEditing, PossibleFinishCellEditing and CancelCellEditing are now public + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-12-19 JPP - Fixed bug with space filling columns and layout events + * - Fixed RowHeight so that it only changes the row height, not the width of the images. + * v2.0 + * 2008-12-10 JPP - Handle Backspace key. Resets the search-by-typing state without delay + * - Made some changes to the column collection editor to try and avoid + * the multiple column generation problem. + * - Updated some documentation + * 2008-12-07 JPP - Search-by-typing now works when showing groups + * - Added BeforeSearching and AfterSearching events which are triggered when the user types + * into the list. + * - Added secondary sort information to Before/AfterSorting events + * - Reorganized group sorting code. Now triggers Sorting events. + * - Added GetItemIndexInDisplayOrder() + * - Tweaked in the interaction of the column editor with the IDE so that we (normally) + * don't rely on a hack to find the owning ObjectListView + * - Changed all 'DefaultValue(typeof(Color), "Empty")' to 'DefaultValue(typeof(Color), "")' + * since the first does not given Color.Empty as I thought, but the second does. + * 2008-11-28 JPP - Fixed long standing bug with horizontal scrollbar when shrinking the window. + * (thanks to Bartosz Borowik) + * 2008-11-25 JPP - Added support for dynamic tooltips + * - Split out comparers and header controls stuff into their own files + * 2008-11-21 JPP - Fixed bug where enabling grouping when there was not a sort column would not + * produce a grouped list. Grouping column now defaults to column 0. + * - Preserve selection on virtual lists when sorting + * 2008-11-20 JPP - Added ability to search by sort column to ObjectListView. Unified this with + * ability that was already in VirtualObjectListView + * 2008-11-19 JPP - Fixed bug in ChangeToFilteredColumns() where DisplayOrder was not always restored correctly. + * 2008-10-29 JPP - Event argument blocks moved to directly within the namespace, rather than being + * nested inside ObjectListView class. + * - Removed OLVColumn.CellEditor since it was never used. + * - Marked OLVColumn.AspectGetterAutoGenerated as obsolete (it has not been used for + * several versions now). + * 2008-10-28 JPP - SelectedObjects is now an IList, rather than an ArrayList. This allows + * it to accept generic list (e.g. List). + * 2008-10-09 JPP - Support indeterminate checkbox values. + * [BREAKING CHANGE] CheckStateGetter/CheckStatePutter now use CheckState types only. + * BooleanCheckStateGetter and BooleanCheckStatePutter added to ease transition. + * 2008-10-08 JPP - Added setFocus parameter to SelectObject(), which allows focus to be set + * at the same time as selecting. + * 2008-09-27 JPP - BIG CHANGE: Fissioned this file into separate files for each component + * 2008-09-24 JPP - Corrected bug with owner drawn lists where a column 0 with a renderer + * would draw at column 0 even if column 0 was dragged to another position. + * - Correctly handle space filling columns when columns are added/removed + * 2008-09-16 JPP - Consistently use try..finally for BeginUpdate()/EndUpdate() pairs + * 2008-08-24 JPP - If LastSortOrder is None when adding objects, don't force a resort. + * 2008-08-22 JPP - Catch and ignore some problems with setting TopIndex on FastObjectListViews. + * 2008-08-05 JPP - In the right-click column select menu, columns are now sorted by display order, rather than alphabetically + * v1.13 + * 2008-07-23 JPP - Consistently use copy-on-write semantics with Add/RemoveObject methods + * 2008-07-10 JPP - Enable validation on cell editors through a CellEditValidating event. + * (thanks to Artiom Chilaru for the initial suggestion and implementation). + * 2008-07-09 JPP - Added HeaderControl.Handle to allow OLV to be used within UserControls. + * (thanks to Michael Coffey for tracking this down). + * 2008-06-23 JPP - Split the more generally useful CopyObjectsToClipboard() method + * out of CopySelectionToClipboard() + * 2008-06-22 JPP - Added AlwaysGroupByColumn and AlwaysGroupBySortOrder, which + * force the list view to always be grouped by a particular column. + * 2008-05-31 JPP - Allow check boxes on FastObjectListViews + * - Added CheckedObject and CheckedObjects properties + * 2008-05-11 JPP - Allow selection foreground and background colors to be changed. + * Windows doesn't allow this, so we can only make it happen when owner + * drawing. Set the HighlightForegroundColor and HighlightBackgroundColor + * properties and then call EnableCustomSelectionColors(). + * v1.12 + * 2008-05-08 JPP - Fixed bug where the column select menu would not appear if the + * ObjectListView has a context menu installed. + * 2008-05-05 JPP - Non detail views can now be owner drawn. The renderer installed for + * primary column is given the chance to render the whole item. + * See BusinessCardRenderer in the demo for an example. + * - BREAKING CHANGE: RenderDelegate now returns a bool to indicate if default + * rendering should be done. Previously returned void. Only important if your + * code used RendererDelegate directly. Renderers derived from BaseRenderer + * are unchanged. + * 2008-05-03 JPP - Changed cell editing to use values directly when the values are Strings. + * Previously, values were always handed to the AspectToStringConverter. + * - When editing a cell, tabbing no longer tries to edit the next subitem + * when not in details view! + * 2008-05-02 JPP - MappedImageRenderer can now handle a Aspects that return a collection + * of values. Each value will be drawn as its own image. + * - Made AddObjects() and RemoveObjects() work for all flavours (or at least not crash) + * - Fixed bug with clearing virtual lists that has been scrolled vertically + * - Made TopItemIndex work with virtual lists. + * 2008-05-01 JPP - Added AddObjects() and RemoveObjects() to allow faster mods to the list + * - Reorganised public properties. Now alphabetical. + * - Made the class ObjectListViewState internal, as it always should have been. + * v1.11 + * 2008-04-29 JPP - Preserve scroll position when building the list or changing columns. + * - Added TopItemIndex property. Due to problems with the underlying control, this + * property is not always reliable. See property docs for info. + * 2008-04-27 JPP - Added SelectedIndex property. + * - Use a different, more general strategy to handle Invoke(). Removed all delegates + * that were only declared to support Invoke(). + * - Check all native structures for 64-bit correctness. + * 2008-04-25 JPP - Released on SourceForge. + * 2008-04-13 JPP - Added ColumnRightClick event. + * - Made the assembly CLS-compliant. To do this, our cell editors were made internal, and + * the constraint on FlagRenderer template parameter was removed (the type must still + * be an IConvertible, but if it isn't, the error will be caught at runtime, not compile time). + * 2008-04-12 JPP - Changed HandleHeaderRightClick() to have a columnIndex parameter, which tells + * exactly which column was right-clicked. + * 2008-03-31 JPP - Added SaveState() and RestoreState() + * - When cell editing, scrolling with a mouse wheel now ends the edit operation. + * v1.10 + * 2008-03-25 JPP - Added space filling columns. See OLVColumn.FreeSpaceProportion property for details. + * A space filling columns fills all (or a portion) of the width unoccupied by other columns. + * 2008-03-23 JPP - Finished tinkering with support for Mono. Compile with conditional compilation symbol 'MONO' + * to enable. On Windows, current problems with Mono: + * - grid lines on virtual lists crashes + * - when grouped, items sometimes are not drawn when any item is scrolled out of view + * - i can't seem to get owner drawing to work + * - when editing cell values, the editing controls always appear behind the listview, + * where they function fine -- the user just can't see them :-) + * 2008-03-16 JPP - Added some methods suggested by Chris Marlowe (thanks for the suggestions Chris) + * - ClearObjects() + * - GetCheckedObject(), GetCheckedObjects() + * - GetItemAt() variation that gets both the item and the column under a point + * 2008-02-28 JPP - Fixed bug with subitem colors when using OwnerDrawn lists and a RowFormatter. + * v1.9.1 + * 2008-01-29 JPP - Fixed bug that caused owner-drawn virtual lists to use 100% CPU + * - Added FlagRenderer to help draw bitwise-OR'ed flag values + * 2008-01-23 JPP - Fixed bug (introduced in v1.9) that made alternate row colour with groups not quite right + * - Ensure that DesignerSerializationVisibility.Hidden is set on all non-browsable properties + * - Make sure that sort indicators are shown after changing which columns are visible + * 2008-01-21 JPP - Added FastObjectListView + * v1.9 + * 2008-01-18 JPP - Added IncrementalUpdate() + * 2008-01-16 JPP - Right clicking on column header will allow the user to choose which columns are visible. + * Set SelectColumnsOnRightClick to false to prevent this behaviour. + * - Added ImagesRenderer to draw more than one images in a column + * - Changed the positioning of the empty list m to use all the client area. Thanks to Matze. + * 2007-12-13 JPP - Added CopySelectionToClipboard(). Ctrl-C invokes this method. Supports text + * and HTML formats. + * 2007-12-12 JPP - Added support for checkboxes via CheckStateGetter and CheckStatePutter properties. + * - Made ObjectListView and OLVColumn into partial classes so that others can extend them. + * 2007-12-09 JPP - Added ability to have hidden columns, i.e. columns that the ObjectListView knows + * about but that are not visible to the user. Controlled by OLVColumn.IsVisible. + * Added ColumnSelectionForm to the project to show how it could be used in an application. + * + * v1.8 + * 2007-11-26 JPP - Cell editing fully functional + * 2007-11-21 JPP - Added SelectionChanged event. This event is triggered once when the + * selection changes, no matter how many items are selected or deselected (in + * contrast to SelectedIndexChanged which is called once for every row that + * is selected or deselected). Thanks to lupokehl42 (Daniel) for his suggestions and + * improvements on this idea. + * 2007-11-19 JPP - First take at cell editing + * 2007-11-17 JPP - Changed so that items within a group are not sorted if lastSortOrder == None + * - Only call MakeSortIndicatorImages() if we haven't already made the sort indicators + * (Corrected misspelling in the name of the method too) + * 2007-11-06 JPP - Added ability to have secondary sort criteria when sorting + * (SecondarySortColumn and SecondarySortOrder properties) + * - Added SortGroupItemsByPrimaryColumn to allow group items to be sorted by the + * primary column. Previous default was to sort by the grouping column. + * v1.7 + * No big changes to this version but made to work with ListViewPrinter and released with it. + * + * 2007-11-05 JPP - Changed BaseRenderer to use DrawString() rather than TextRenderer, since TextRenderer + * does not work when printing. + * v1.6 + * 2007-11-03 JPP - Fixed some bugs in the rebuilding of DataListView. + * 2007-10-31 JPP - Changed to use builtin sort indicators on XP and later. This also avoids alignment + * problems on Vista. (thanks to gravybod for the suggestion and example implementation) + * 2007-10-21 JPP - Added MinimumWidth and MaximumWidth properties to OLVColumn. + * - Added ability for BuildList() to preserve selection. Calling BuildList() directly + * tries to preserve selection; calling SetObjects() does not. + * - Added SelectAll() and DeselectAll() methods. Useful for working with large lists. + * 2007-10-08 JPP - Added GetNextItem() and GetPreviousItem(), which walk sequentially through the + * listview items, even when the view is grouped. + * - Added SelectedItem property + * 2007-09-28 JPP - Optimized aspect-to-string conversion. BuildList() 15% faster. + * - Added empty implementation of RefreshObjects() to VirtualObjectListView since + * RefreshObjects() cannot work on virtual lists. + * 2007-09-13 JPP - Corrected bug with custom sorter in VirtualObjectListView (thanks for mpgjunky) + * 2007-09-07 JPP - Corrected image scaling bug in DrawAlignedImage() (thanks to krita970) + * 2007-08-29 JPP - Allow item count labels on groups to be set per column (thanks to cmarlow for idea) + * 2007-08-14 JPP - Major rework of DataListView based on Ian Griffiths's great work + * 2007-08-11 JPP - When empty, the control can now draw a "List Empty" m + * - Added GetColumn() and GetItem() methods + * v1.5 + * 2007-08-03 JPP - Support animated GIFs in ImageRenderer + * - Allow height of rows to be specified - EXPERIMENTAL! + * 2007-07-26 JPP - Optimised redrawing of owner-drawn lists by remembering the update rect + * - Allow sort indicators to be turned off + * 2007-06-30 JPP - Added RowFormatter delegate + * - Allow a different label when there is only one item in a group (thanks to cmarlow) + * v1.4 + * 2007-04-12 JPP - Allow owner drawn on steriods! + * - Column headers now display sort indicators + * - ImageGetter delegates can now return ints, strings or Images + * (Images are only visible if the list is owner drawn) + * - Added OLVColumn.MakeGroupies to help with group partitioning + * - All normal listview views are now supported + * - Allow dotted aspect names, e.g. Owner.Workgroup.Name (thanks to OlafD) + * - Added SelectedObject and SelectedObjects properties + * v1.3 + * 2007-03-01 JPP - Added DataListView + * - Added VirtualObjectListView + * - Added Freeze/Unfreeze capabilities + * - Allowed sort handler to be installed + * - Simplified sort comparisons: handles 95% of cases with only 6 lines of code! + * - Fixed bug with alternative line colors on unsorted lists (thanks to cmarlow) + * 2007-01-13 JPP - Fixed bug with lastSortOrder (thanks to Kwan Fu Sit) + * - Non-OLVColumns are no longer allowed + * 2007-01-04 JPP - Clear sorter before rebuilding list. 10x faster! (thanks to aaberg) + * - Include GetField in GetAspectByName() so field values can be Invoked too. + * - Fixed subtle bug in RefreshItem() that erased background colors. + * 2006-11-01 JPP - Added alternate line colouring + * 2006-10-20 JPP - Refactored all sorting comparisons and made it extendable. See ComparerManager. + * - Improved IDE integration + * - Made control DoubleBuffered + * - Added object selection methods + * 2006-10-13 JPP Implemented grouping and column sorting + * 2006-10-09 JPP Initial version + * + * TO DO: + * - Support undocumented group features: subseted groups, group footer items + * + * Copyright (C) 2006-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Serialization.Formatters.Binary; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Runtime.Serialization.Formatters; +using System.Threading; + +namespace BrightIdeasSoftware +{ + /// + /// An ObjectListView is a much easier to use, and much more powerful, version of the ListView. + /// + /// + /// + /// An ObjectListView automatically populates a ListView control with information taken + /// from a given collection of objects. It can do this because each column is configured + /// to know which bit of the model object (the "aspect") it should be displaying. Columns similarly + /// understand how to sort the list based on their aspect, and how to construct groups + /// using their aspect. + /// + /// + /// Aspects are extracted by giving the name of a method to be called or a + /// property to be fetched. These names can be simple names or they can be dotted + /// to chain property access e.g. "Owner.Address.Postcode". + /// Aspects can also be extracted by installing a delegate. + /// + /// + /// An ObjectListView can show a "this list is empty" message when there is nothing to show in the list, + /// so that the user knows the control is supposed to be empty. + /// + /// + /// Right clicking on a column header should present a menu which can contain: + /// commands (sort, group, ungroup); filtering; and column selection. Whether these + /// parts of the menu appear is controlled by ShowCommandMenuOnRightClick, + /// ShowFilterMenuOnRightClick and SelectColumnsOnRightClick respectively. + /// + /// + /// The groups created by an ObjectListView can be configured to include other formatting + /// information, including a group icon, subtitle and task button. Using some undocumented + /// interfaces, these groups can even on virtual lists. + /// + /// + /// ObjectListView supports dragging rows to other places, including other application. + /// Special support is provide for drops from other ObjectListViews in the same application. + /// In many cases, an ObjectListView becomes a full drag source by setting to + /// true. Similarly, to accept drops, it is usually enough to set to true, + /// and then handle the and events (or the and + /// events, if you only want to handle drops from other ObjectListViews in your application). + /// + /// + /// For these classes to build correctly, the project must have references to these assemblies: + /// + /// + /// System + /// System.Data + /// System.Design + /// System.Drawing + /// System.Windows.Forms (obviously) + /// + /// + [Designer(typeof(BrightIdeasSoftware.Design.ObjectListViewDesigner))] + public partial class ObjectListView : ListView, ISupportInitialize { + + #region Life and death + + /// + /// Create an ObjectListView + /// + public ObjectListView() { + this.ColumnClick += new ColumnClickEventHandler(this.HandleColumnClick); + this.Layout += new LayoutEventHandler(this.HandleLayout); + this.ColumnWidthChanging += new ColumnWidthChangingEventHandler(this.HandleColumnWidthChanging); + this.ColumnWidthChanged += new ColumnWidthChangedEventHandler(this.HandleColumnWidthChanged); + + base.View = View.Details; + + // Turn on owner draw so that we are responsible for our own fates (and isolated from bugs in the underlying ListView) + this.OwnerDraw = true; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.DoubleBuffered = true; // kill nasty flickers. hiss... me hates 'em + this.ShowSortIndicators = true; + + // Setup the overlays that will be controlled by the IDE settings + this.InitializeStandardOverlays(); + this.InitializeEmptyListMsgOverlay(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + } + + /// + /// Dispose of any resources this instance has been using + /// + /// + protected override void Dispose(bool disposing) { + base.Dispose(disposing); + + if (!disposing) + return; + + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Unbind(); + glassPanel.Dispose(); + } + this.glassPanels.Clear(); + + this.UnsubscribeNotifications(null); + } + + #endregion + + // TODO + //public CheckBoxSettings CheckBoxSettings { + // get { return checkBoxSettings; } + // private set { checkBoxSettings = value; } + //} + + #region Static properties + + /// + /// Gets whether or not the left mouse button is down at this very instant + /// + public static bool IsLeftMouseDown { + get { return (Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left; } + } + + /// + /// Gets whether the program running on Vista or later? + /// + public static bool IsVistaOrLater { + get { + if (!ObjectListView.sIsVistaOrLater.HasValue) + ObjectListView.sIsVistaOrLater = Environment.OSVersion.Version.Major >= 6; + return ObjectListView.sIsVistaOrLater.Value; + } + } + private static bool? sIsVistaOrLater; + + /// + /// Gets whether the program running on Win7 or later? + /// + public static bool IsWin7OrLater { + get { + if (!ObjectListView.sIsWin7OrLater.HasValue) { + // For some reason, Win7 is v6.1, not v7.0 + Version version = Environment.OSVersion.Version; + ObjectListView.sIsWin7OrLater = version.Major > 6 || (version.Major == 6 && version.Minor > 0); + } + return ObjectListView.sIsWin7OrLater.Value; + } + } + private static bool? sIsWin7OrLater; + + /// + /// Gets or sets how what smoothing mode will be applied to graphic operations. + /// + public static System.Drawing.Drawing2D.SmoothingMode SmoothingMode { + get { return ObjectListView.sSmoothingMode; } + set { ObjectListView.sSmoothingMode = value; } + } + private static System.Drawing.Drawing2D.SmoothingMode sSmoothingMode = + System.Drawing.Drawing2D.SmoothingMode.HighQuality; + + /// + /// Gets or sets how should text be rendered. + /// + public static System.Drawing.Text.TextRenderingHint TextRenderingHint { + get { return ObjectListView.sTextRendereringHint; } + set { ObjectListView.sTextRendereringHint = value; } + } + private static System.Drawing.Text.TextRenderingHint sTextRendereringHint = + System.Drawing.Text.TextRenderingHint.SystemDefault; + + /// + /// Gets or sets the string that will be used to title groups when the group key is null. + /// Exposed so it can be localized. + /// + public static string GroupTitleDefault { + get { return ObjectListView.sGroupTitleDefault; } + set { ObjectListView.sGroupTitleDefault = value ?? "{null}"; } + } + private static string sGroupTitleDefault = "{null}"; + + /// + /// Convert the given enumerable into an ArrayList as efficiently as possible + /// + /// The source collection + /// If true, this method will always create a new + /// collection. + /// An ArrayList with the same contents as the given collection. + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static ArrayList EnumerableToArray(IEnumerable collection, bool alwaysCreate) { + if (collection == null) + return new ArrayList(); + + if (!alwaysCreate) { + ArrayList array = collection as ArrayList; + if (array != null) + return array; + + IList iList = collection as IList; + if (iList != null) + return ArrayList.Adapter(iList); + } + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return new ArrayList(iCollection); + + ArrayList newObjects = new ArrayList(); + foreach (object x in collection) + newObjects.Add(x); + return newObjects; + } + + + /// + /// Return the count of items in the given enumerable + /// + /// + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + public static int EnumerableCount(IEnumerable collection) { + if (collection == null) + return 0; + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return iCollection.Count; + + int i = 0; +// ReSharper disable once UnusedVariable + foreach (object x in collection) + i++; + return i; + } + + /// + /// Return whether or not the given enumerable is empty. A string is regarded as + /// an empty collection. + /// + /// + /// True if the given collection is null or empty + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static bool IsEnumerableEmpty(IEnumerable collection) { + return collection == null || (collection is string) || !collection.GetEnumerator().MoveNext(); + } + + /// + /// Gets or sets whether all ObjectListViews will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if an ObjectListView is asked to display an aspect + /// (i.e. a field/property/method) + /// that does not exist from a model, it displays an error message in that cell, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error -- in those cases, set this to true and ObjectListView will + /// simply display an empty cell. + /// + /// Be warned: if you set this to true, it can be very difficult to track down + /// typing mistakes or name changes in AspectNames. + /// + public static bool IgnoreMissingAspects { + get { return Munger.IgnoreMissingAspects; } + set { Munger.IgnoreMissingAspects = value; } + } + + /// + /// Gets or sets whether the control will draw a rectangle in each cell showing the cell padding. + /// + /// + /// + /// This can help with debugging display problems from cell padding. + /// + /// As with all cell padding, this setting only takes effect when the control is owner drawn. + /// + public static bool ShowCellPaddingBounds { + get { return sShowCellPaddingBounds; } + set { sShowCellPaddingBounds = value; } + } + private static bool sShowCellPaddingBounds; + + /// + /// Gets the style that will be used by default to format disabled rows + /// + public static SimpleItemStyle DefaultDisabledItemStyle { + get { + if (sDefaultDisabledItemStyle == null) { + sDefaultDisabledItemStyle = new SimpleItemStyle(); + sDefaultDisabledItemStyle.ForeColor = Color.DarkGray; + } + return sDefaultDisabledItemStyle; + } + } + private static SimpleItemStyle sDefaultDisabledItemStyle; + + /// + /// Gets the style that will be used by default to format hot rows + /// + public static HotItemStyle DefaultHotItemStyle { + get { + if (sDefaultHotItemStyle == null) { + sDefaultHotItemStyle = new HotItemStyle(); + sDefaultHotItemStyle.BackColor = Color.FromArgb(224, 235, 253); + } + return sDefaultHotItemStyle; + } + } + private static HotItemStyle sDefaultHotItemStyle; + + #endregion + + #region Public properties + + /// + /// Gets or sets an model filter that is combined with any column filtering that the end-user specifies. + /// + /// This is different from the ModelFilter property, since setting that will replace + /// any column filtering, whereas setting this will combine this filter with the column filtering + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter AdditionalFilter + { + get { return this.additionalFilter; } + set + { + if (this.additionalFilter == value) + return; + this.additionalFilter = value; + this.UpdateColumnFiltering(); + } + } + private IModelFilter additionalFilter; + + /// + /// Get or set all the columns that this control knows about. + /// Only those columns where IsVisible is true will be seen by the user. + /// + /// + /// + /// If you want to add new columns programmatically, add them to + /// AllColumns and then call RebuildColumns(). Normally, you do not have to + /// deal with this property directly. Just use the IDE. + /// + /// If you do add or remove columns from the AllColumns collection, + /// you have to call RebuildColumns() to make those changes take effect. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public virtual List AllColumns { + get { return this.allColumns; } + set { this.allColumns = value ?? new List(); } + } + private List allColumns = new List(); + + /// + /// Gets or sets whether or not ObjectListView will allow cell editors to response to mouse wheel events. Default is true. + /// If this is true, cell editors that respond to mouse wheel events (e.g. numeric edit, DateTimeEditor, combo boxes) will operate + /// as expected. + /// If this is false, a mouse wheel event is interpreted as a request to scroll the control vertically. This will automatically + /// finish any cell edit operation that was in flight. This was the default behaviour prior to v2.9. + /// + [Category("ObjectListView"), + Description("Should ObjectListView allow cell editors to response to mouse wheel events (default: true)"), + DefaultValue(true)] + public virtual bool AllowCellEditorsToProcessMouseWheel + { + get { return allowCellEditorsToProcessMouseWheel; } + set { allowCellEditorsToProcessMouseWheel = value; } + } + private bool allowCellEditorsToProcessMouseWheel = true; + + /// + /// Gets or sets the background color of every second row + /// + [Category("ObjectListView"), + Description("If using alternate colors, what color should the background of alternate rows be?"), + DefaultValue(typeof(Color), "")] + public Color AlternateRowBackColor { + get { return alternateRowBackColor; } + set { alternateRowBackColor = value; } + } + private Color alternateRowBackColor = Color.Empty; + + /// + /// Gets the alternate row background color that has been set, or the default color + /// + [Browsable(false)] + public virtual Color AlternateRowBackColorOrDefault { + get { + return this.alternateRowBackColor == Color.Empty ? Color.LemonChiffon : this.alternateRowBackColor; + } + } + + /// + /// This property forces the ObjectListView to always group items by the given column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn AlwaysGroupByColumn { + get { return alwaysGroupByColumn; } + set { alwaysGroupByColumn = value; } + } + private OLVColumn alwaysGroupByColumn; + + /// + /// If AlwaysGroupByColumn is not null, this property will be used to decide how + /// those groups are sorted. If this property has the value SortOrder.None, then + /// the sort order will toggle according to the users last header click. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder AlwaysGroupBySortOrder { + get { return alwaysGroupBySortOrder; } + set { alwaysGroupBySortOrder = value; } + } + private SortOrder alwaysGroupBySortOrder = SortOrder.None; + + /// + /// Give access to the image list that is actually being used by the control + /// + /// + /// Normally, it is preferable to use SmallImageList. Only use this property + /// if you know exactly what you are doing. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ImageList BaseSmallImageList { + get { return base.SmallImageList; } + set { base.SmallImageList = value; } + } + + /// + /// How does the user indicate that they want to edit a cell? + /// None means that the listview cannot be edited. + /// + /// Columns can also be marked as editable. + [Category("ObjectListView"), + Description("How does the user indicate that they want to edit a cell?"), + DefaultValue(CellEditActivateMode.None)] + public virtual CellEditActivateMode CellEditActivation { + get { return cellEditActivation; } + set { + cellEditActivation = value; + if (this.Created) + this.Invalidate(); + } + } + private CellEditActivateMode cellEditActivation = CellEditActivateMode.None; + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// Defaults to true. + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// Each column can have a different value for property. This value from the control is only + /// used when a column is not specified one way or another. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(true)] + public virtual bool CellEditUseWholeCell { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool cellEditUseWholeCell = true; + + /// + /// Gets or sets the engine that will handle key presses during a cell edit operation. + /// Settings this to null will reset it to default value. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public CellEditKeyEngine CellEditKeyEngine { + get { return this.cellEditKeyEngine ?? (this.cellEditKeyEngine = new CellEditKeyEngine()); } + set { this.cellEditKeyEngine = value; } + } + private CellEditKeyEngine cellEditKeyEngine; + + /// + /// Gets the control that is currently being used for editing a cell. + /// + /// This will obviously be null if no cell is being edited. + [Browsable(false)] + public Control CellEditor { + get { + return this.cellEditor; + } + } + + /// + /// Gets or sets the behaviour of the Tab key when editing a cell on the left or right + /// edge of the control. If this is false (the default), pressing Tab will wrap to the other side + /// of the same row. If this is true, pressing Tab when editing the right most cell will advance + /// to the next row + /// and Shift-Tab when editing the left-most cell will change to the previous row. + /// + [Category("ObjectListView"), + Description("Should Tab/Shift-Tab change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditTabChangesRows { + get { return cellEditTabChangesRows; } + set { + cellEditTabChangesRows = value; + if (cellEditTabChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.ChangeRow); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab|Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.ChangeRow); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.Wrap); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab | Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.Wrap); + } + } + } + private bool cellEditTabChangesRows; + + /// + /// Gets or sets the behaviour of the Enter keys while editing a cell. + /// If this is false (the default), pressing Enter will simply finish the editing operation. + /// If this is true, Enter will finish the edit operation and start a new edit operation + /// on the cell below the current cell, wrapping to the top of the next row when at the bottom cell. + /// + [Category("ObjectListView"), + Description("Should Enter change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditEnterChangesRows { + get { return cellEditEnterChangesRows; } + set { + cellEditEnterChangesRows = value; + if (cellEditEnterChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.ChangeRowDown, CellEditAtEdgeBehaviour.ChangeColumn); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.ChangeRowUp, CellEditAtEdgeBehaviour.ChangeColumn); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + } + } + } + private bool cellEditEnterChangesRows; + + /// + /// Gets the tool tip control that shows tips for the cells + /// + [Browsable(false)] + public ToolTipControl CellToolTip { + get { + if (this.cellToolTip == null) { + this.CreateCellToolTip(); + } + return this.cellToolTip; + } + } + private ToolTipControl cellToolTip; + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item. + /// Cell contents are aligned after padding has been taken into account. + /// + /// + /// Each value of the given rectangle will be treated as an inset from + /// the corresponding side. The width of the rectangle is the padding for the + /// right cell edge. The height of the rectangle is the padding for the bottom + /// cell edge. + /// + /// + /// So, this.olv1.CellPadding = new Rectangle(1, 2, 3, 4); will leave one pixel + /// of space to the left of the cell, 2 pixels at the top, 3 pixels of space + /// on the right edge, and 4 pixels of space at the bottom of each cell. + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// This setting only affects the contents of the cell. The background is + /// not affected. + /// If you set this to a foolish value, your control will appear to be empty. + /// + [Category("ObjectListView"), + Description("How much padding will be applied to each cell in this control?"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells will be vertically aligned by default. + /// + /// This setting only takes effect when the control is owner drawn. It will only be noticeable + /// when RowHeight has been set such that there is some vertical space in each row. + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(StringAlignment.Center)] + public virtual StringAlignment CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment cellVerticalAlignment = StringAlignment.Center; + + /// + /// Should this list show checkboxes? + /// + public new bool CheckBoxes { + get { return base.CheckBoxes; } + set { + // Due to code in the base ListView class, turning off CheckBoxes on a virtual + // list always throws an InvalidOperationException. We have to do some major hacking + // to get around that + if (this.VirtualMode) { + // Leave virtual mode + this.StateImageList = null; + this.VirtualListSize = 0; + this.VirtualMode = false; + + // Change the CheckBox setting while not in virtual mode + base.CheckBoxes = value; + + // Reinstate virtual mode + this.VirtualMode = true; + + // Re-enact the bits that we lost by switching to virtual mode + this.ShowGroups = this.ShowGroups; + this.BuildList(true); + } else { + base.CheckBoxes = value; + // Initialize the state image list so we can display indeterminate values. + this.InitializeStateImageList(); + } + } + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object CheckedObject { + get { + IList checkedObjects = this.CheckedObjects; + return checkedObjects.Count == 1 ? checkedObjects[0] : null; + } + set { + this.CheckedObjects = new ArrayList(new Object[] { value }); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// .NET's CheckedItems property is not helpful. It is just a short-hand for + /// iterating through the list looking for items that are checked. + /// + /// + /// The performance of the get method is O(n), where n is the number of items + /// in the control. The performance of the set method is + /// O(n + m) where m is the number of objects being checked. Be careful on long lists. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList CheckedObjects { + get { + ArrayList list = new ArrayList(); + if (this.CheckBoxes) { + for (int i = 0; i < this.GetItemCount(); i++) { + OLVListItem olvi = this.GetItem(i); + if (olvi.CheckState == CheckState.Checked) + list.Add(olvi.RowObject); + } + } + return list; + } + set { + if (!this.CheckBoxes) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + foreach (Object x in this.Objects) { + this.SetObjectCheckedness(x, table.ContainsKey(x) ? CheckState.Checked : CheckState.Unchecked); + } + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + + } + } + + /// + /// Gets or sets the checked objects from an enumerable. + /// + /// + /// Useful for checking all objects in the list. + /// + /// + /// this.olv1.CheckedObjectsEnumerable = this.olv1.Objects; + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable CheckedObjectsEnumerable { + get { + return this.CheckedObjects; + } + set { + this.CheckedObjects = ObjectListView.EnumerableToArray(value, true); + } + } + + /// + /// Gets Columns for this list. We hide the original so we can associate + /// a specialised editor with it. + /// + [Editor("BrightIdeasSoftware.Design.OLVColumnCollectionEditor", "System.Drawing.Design.UITypeEditor")] + public new ListView.ColumnHeaderCollection Columns { + get { + return base.Columns; + } + } + + /// + /// Get/set the list of columns that should be used when the list switches to tile view. + /// + [Browsable(false), + Obsolete("Use GetFilteredColumns() and OLVColumn.IsTileViewColumn instead"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public List ColumnsForTileView { + get { return this.GetFilteredColumns(View.Tile); } + } + + /// + /// Return the visible columns in the order they are displayed to the user + /// + [Browsable(false)] + public virtual List ColumnsInDisplayOrder { + get { + OLVColumn[] columnsInDisplayOrder = new OLVColumn[this.Columns.Count]; + foreach (OLVColumn col in this.Columns) { + columnsInDisplayOrder[col.DisplayIndex] = col; + } + return new List(columnsInDisplayOrder); + } + } + + + /// + /// Get the area of the control that shows the list, minus any header control + /// + [Browsable(false)] + public Rectangle ContentRectangle { + get { + Rectangle r = this.ClientRectangle; + + // If the listview has a header control, remove the header from the control area + if ((this.View == View.Details || this.ShowHeaderInAllViews) && this.HeaderControl != null) { + Rectangle hdrBounds = new Rectangle(); + NativeMethods.GetClientRect(this.HeaderControl.Handle, ref hdrBounds); + r.Y = hdrBounds.Height; + r.Height = r.Height - hdrBounds.Height; + } + + return r; + } + } + + /// + /// Gets or sets if the selected rows should be copied to the clipboard when the user presses Ctrl-C + /// + [Category("ObjectListView"), + Description("Should the control copy the selection to the clipboard when the user presses Ctrl-C?"), + DefaultValue(true)] + public virtual bool CopySelectionOnControlC { + get { return copySelectionOnControlC; } + set { copySelectionOnControlC = value; } + } + private bool copySelectionOnControlC = true; + + + /// + /// Gets or sets whether the Control-C copy to clipboard functionality should use + /// the installed DragSource to create the data object that is placed onto the clipboard. + /// + /// This is normally what is desired, unless a custom DragSource is installed + /// that does some very specialized drag-drop behaviour. + [Category("ObjectListView"), + Description("Should the Ctrl-C copy process use the DragSource to create the Clipboard data object?"), + DefaultValue(true)] + public bool CopySelectionOnControlCUsesDragSource { + get { return this.copySelectionOnControlCUsesDragSource; } + set { this.copySelectionOnControlCUsesDragSource = value; } + } + private bool copySelectionOnControlCUsesDragSource = true; + + /// + /// Gets the list of decorations that will be drawn the ListView + /// + /// + /// + /// Do not modify the contents of this list directly. Use the AddDecoration() and RemoveDecoration() methods. + /// + /// + /// A decoration scrolls with the list contents. An overlay is fixed in place. + /// + /// + [Browsable(false)] + protected IList Decorations { + get { return this.decorations; } + } + private readonly List decorations = new List(); + + /// + /// When owner drawing, this renderer will draw columns that do not have specific renderer + /// given to them + /// + /// If you try to set this to null, it will revert to a HighlightTextRenderer + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IRenderer DefaultRenderer { + get { return this.defaultRenderer; } + set { this.defaultRenderer = value ?? new HighlightTextRenderer(); } + } + private IRenderer defaultRenderer = new HighlightTextRenderer(); + + /// + /// Get the renderer to be used to draw the given cell. + /// + /// The row model for the row + /// The column to be drawn + /// The renderer used for drawing a cell. Must not return null. + public IRenderer GetCellRenderer(object model, OLVColumn column) { + IRenderer renderer = this.CellRendererGetter == null ? null : this.CellRendererGetter(model, column); + return renderer ?? column.Renderer ?? this.DefaultRenderer; + } + + /// + /// Gets or sets the style that will be applied to disabled items. + /// + /// If this is not set explicitly, will be used. + [Category("ObjectListView"), + Description("The style that will be applied to disabled items"), + DefaultValue(null)] + public SimpleItemStyle DisabledItemStyle + { + get { return disabledItemStyle; } + set { disabledItemStyle = value; } + } + private SimpleItemStyle disabledItemStyle; + + /// + /// Gets or sets the list of model objects that are disabled. + /// Disabled objects cannot be selected or activated. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable DisabledObjects + { + get + { + return disabledObjects.Keys; + } + set + { + this.disabledObjects.Clear(); + DisableObjects(value); + } + } + private readonly Hashtable disabledObjects = new Hashtable(); + + /// + /// Is this given model object disabled? + /// + /// + /// + public bool IsDisabled(object model) + { + return model != null && this.disabledObjects.ContainsKey(model); + } + + /// + /// Disable the given model object. + /// Disabled objects cannot be selected or activated. + /// + /// Must not be null + public void DisableObject(object model) { + ArrayList list = new ArrayList(); + list.Add(model); + this.DisableObjects(list); + } + + /// + /// Disable all the given model objects + /// + /// + public void DisableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model == null) + continue; + + this.disabledObjects[model] = true; + int modelIndex = this.IndexOf(model); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + this.RefreshObjects(list); + } + + /// + /// Enable the given model object, so it can be selected and activated again. + /// + /// Must not be null + public void EnableObject(object model) + { + this.disabledObjects.Remove(model); + this.RefreshObject(model); + } + + /// + /// Enable all the given model objects + /// + /// + public void EnableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model != null) + this.disabledObjects.Remove(model); + } + this.RefreshObjects(list); + } + + /// + /// Forget all disabled objects. This does not trigger a redraw or rebuild + /// + protected void ClearDisabledObjects() + { + this.disabledObjects.Clear(); + } + + /// + /// Gets or sets the object that controls how drags start from this control + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDragSource DragSource { + get { return this.dragSource; } + set { this.dragSource = value; } + } + private IDragSource dragSource; + + /// + /// Gets or sets the object that controls how drops are accepted and processed + /// by this ListView. + /// + /// + /// + /// If the given sink is an instance of SimpleDropSink, then events from the drop sink + /// will be automatically forwarded to the ObjectListView (which means that handlers + /// for those event can be configured within the IDE). + /// + /// If this is set to null, the control will not accept drops. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDropSink DropSink { + get { return this.dropSink; } + set { + if (this.dropSink == value) + return; + + // Stop listening for events on the old sink + SimpleDropSink oldSink = this.dropSink as SimpleDropSink; + if (oldSink != null) { + oldSink.CanDrop -= new EventHandler(this.DropSinkCanDrop); + oldSink.Dropped -= new EventHandler(this.DropSinkDropped); + oldSink.ModelCanDrop -= new EventHandler(this.DropSinkModelCanDrop); + oldSink.ModelDropped -= new EventHandler(this.DropSinkModelDropped); + } + + this.dropSink = value; + this.AllowDrop = (value != null); + if (this.dropSink != null) + this.dropSink.ListView = this; + + // Start listening for events on the new sink + SimpleDropSink newSink = value as SimpleDropSink; + if (newSink != null) { + newSink.CanDrop += new EventHandler(this.DropSinkCanDrop); + newSink.Dropped += new EventHandler(this.DropSinkDropped); + newSink.ModelCanDrop += new EventHandler(this.DropSinkModelCanDrop); + newSink.ModelDropped += new EventHandler(this.DropSinkModelDropped); + } + } + } + private IDropSink dropSink; + + // Forward events from the drop sink to the control itself + void DropSinkCanDrop(object sender, OlvDropEventArgs e) { this.OnCanDrop(e); } + void DropSinkDropped(object sender, OlvDropEventArgs e) { this.OnDropped(e); } + void DropSinkModelCanDrop(object sender, ModelDropEventArgs e) { this.OnModelCanDrop(e); } + void DropSinkModelDropped(object sender, ModelDropEventArgs e) { this.OnModelDropped(e); } + + /// + /// This registry decides what control should be used to edit what cells, based + /// on the type of the value in the cell. + /// + /// + /// All instances of ObjectListView share the same editor registry. +// ReSharper disable FieldCanBeMadeReadOnly.Global + public static EditorRegistry EditorRegistry = new EditorRegistry(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + + /// + /// Gets or sets the text that should be shown when there are no items in this list view. + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("When the list has no items, show this message in the control"), + DefaultValue(null), + Localizable(true)] + public virtual String EmptyListMsg { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Text; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) { + overlay.Text = value; + this.Invalidate(); + } + } + } + + /// + /// Gets or sets the font in which the List Empty message should be drawn + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("What font should the 'list empty' message be drawn in?"), + DefaultValue(null)] + public virtual Font EmptyListMsgFont { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Font; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) + overlay.Font = value; + } + } + + /// + /// Return the font for the 'list empty' message or a reasonable default + /// + [Browsable(false)] + public virtual Font EmptyListMsgFontOrDefault { + get { + return this.EmptyListMsgFont ?? new Font("Tahoma", 14); + } + } + + /// + /// Gets or sets the overlay responsible for drawing the List Empty msg. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IOverlay EmptyListMsgOverlay { + get { return this.emptyListMsgOverlay; } + set { + if (this.emptyListMsgOverlay != value) { + this.emptyListMsgOverlay = value; + this.Invalidate(); + } + } + } + private IOverlay emptyListMsgOverlay; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + /// + /// + /// This collection is the result of filtering the current list of objects. + /// It is not a snapshot of the filtered list that was last used to build the control. + /// + /// + /// Normal warnings apply when using this with virtual lists. It will work, but it + /// may take a while. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable FilteredObjects { + get { + if (this.UseFiltering) + return this.FilterObjects(this.Objects, this.ModelFilter, this.ListFilter); + + return this.Objects; + } + } + + /// + /// Gets or sets the strategy object that will be used to build the Filter menu + /// + /// If this is null, no filter menu will be built. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public FilterMenuBuilder FilterMenuBuildStrategy { + get { return filterMenuBuilder; } + set { filterMenuBuilder = value; } + } + private FilterMenuBuilder filterMenuBuilder = new FilterMenuBuilder(); + + /// + /// Gets or sets the row that has keyboard focus + /// + /// + /// + /// Setting an object to be focused does *not* select it. If you want to select and focus a row, + /// use . + /// + /// + /// This property is not generally used and is only useful in specialized situations. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object FocusedObject { + get { return this.FocusedItem == null ? null : ((OLVListItem)this.FocusedItem).RowObject; } + set { + OLVListItem item = this.ModelToItem(value); + if (item != null) + item.Focused = true; + } + } + + /// + /// Hide the Groups collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewGroupCollection Groups { + get { return base.Groups; } + } + + /// + /// Gets or sets the image list from which group header will take their images + /// + /// If this is not set, then group headers will not show any images. + [Category("ObjectListView"), + Description("The image list from which group header will take their images"), + DefaultValue(null)] + public ImageList GroupImageList { + get { return this.groupImageList; } + set { + this.groupImageList = value; + if (this.Created) { + NativeMethods.SetGroupImageList(this, value); + } + } + } + private ImageList groupImageList; + + /// + /// Gets how the group label should be formatted when a group is empty or + /// contains more than one item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Return this.GroupWithItemCountFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountFormat) ? "{0} [{1} items]" : this.GroupWithItemCountFormat; + } + } + + /// + /// Gets how the group label should be formatted when a group contains only a single item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Gets GroupWithItemCountSingularFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountSingularFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat) ? "{0} [{1} item]" : this.GroupWithItemCountSingularFormat; + } + } + + /// + /// Gets or sets whether or not the groups in this ObjectListView should be collapsible. + /// + /// + /// This feature only works under Vista and later. + /// + [Browsable(true), + Category("ObjectListView"), + Description("Should the groups in this control be collapsible (Vista and later only)."), + DefaultValue(true)] + public bool HasCollapsibleGroups { + get { return hasCollapsibleGroups; } + set { hasCollapsibleGroups = value; } + } + private bool hasCollapsibleGroups = true; + + /// + /// Does this listview have a message that should be drawn when the list is empty? + /// + [Browsable(false)] + public virtual bool HasEmptyListMsg { + get { return !String.IsNullOrEmpty(this.EmptyListMsg); } + } + + /// + /// Get whether there are any overlays to be drawn + /// + [Browsable(false)] + public bool HasOverlays { + get { + return (this.Overlays.Count > 2 || + this.imageOverlay.Image != null || + !String.IsNullOrEmpty(this.textOverlay.Text)); + } + } + + /// + /// Gets the header control for the ListView + /// + [Browsable(false)] + public HeaderControl HeaderControl { + get { return this.headerControl ?? (this.headerControl = new HeaderControl(this)); } + } + private HeaderControl headerControl; + + /// + /// Gets or sets the font in which the text of the column headers will be drawn + /// + /// Individual columns can override this through their HeaderFormatStyle property. + [DefaultValue(null)] + [Browsable(false)] + [Obsolete("Use a HeaderFormatStyle instead", false)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the style that will be used to draw the column headers of the listview + /// + /// + /// + /// This is only used when HeaderUsesThemes is false. + /// + /// + /// Individual columns can override this through their HeaderFormatStyle property. + /// + /// + [Category("ObjectListView"), + Description("What style will be used to draw the control's header"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the maximum height of the header. -1 means no maximum. + /// + [Category("ObjectListView"), + Description("What is the maximum height of the header? -1 means no maximum"), + DefaultValue(-1)] + public int HeaderMaximumHeight + { + get { return headerMaximumHeight; } + set { headerMaximumHeight = value; } + } + private int headerMaximumHeight = -1; + + /// + /// Gets or sets the minimum height of the header. -1 means no minimum. + /// + [Category("ObjectListView"), + Description("What is the minimum height of the header? -1 means no minimum"), + DefaultValue(-1)] + public int HeaderMinimumHeight + { + get { return headerMinimumHeight; } + set { headerMinimumHeight = value; } + } + private int headerMinimumHeight = -1; + + /// + /// Gets or sets whether the header will be drawn strictly according to the OS's theme. + /// + /// + /// + /// If this is set to true, the header will be rendered completely by the system, without + /// any of ObjectListViews fancy processing -- no images in header, no filter indicators, + /// no word wrapping, no header styling, no checkboxes. + /// + /// If this is set to false, ObjectListView will render the header as it thinks best. + /// If no special features are required, then ObjectListView will delegate rendering to the OS. + /// Otherwise, ObjectListView will draw the header according to the configuration settings. + /// + /// + /// The effect of not being themed will be different from OS to OS. At + /// very least, the sort indicator will not be standard. + /// + /// + [Category("ObjectListView"), + Description("Will the column headers be drawn strictly according to OS theme?"), + DefaultValue(false)] + public bool HeaderUsesThemes { + get { return this.headerUsesThemes; } + set { this.headerUsesThemes = value; } + } + private bool headerUsesThemes; + + /// + /// Gets or sets the whether the text in the header will be word wrapped. + /// + /// + /// Line breaks will be applied between words. Words that are too long + /// will still be ellipsed. + /// + /// As with all settings that make the header look different, HeaderUsesThemes must be set to false, otherwise + /// the OS will be responsible for drawing the header, and it does not allow word wrapped text. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the column headers be word wrapped?"), + DefaultValue(false)] + public bool HeaderWordWrap { + get { return this.headerWordWrap; } + set { + this.headerWordWrap = value; + if (this.headerControl != null) + this.headerControl.WordWrap = value; + } + } + private bool headerWordWrap; + + /// + /// Gets the tool tip that shows tips for the column headers + /// + [Browsable(false)] + public ToolTipControl HeaderToolTip { + get { + return this.HeaderControl.ToolTip; + } + } + + /// + /// Gets the index of the row that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotRowIndex { + get { return this.hotRowIndex; } + protected set { this.hotRowIndex = value; } + } + private int hotRowIndex; + + /// + /// Gets the index of the subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotColumnIndex { + get { return this.hotColumnIndex; } + protected set { this.hotColumnIndex = value; } + } + private int hotColumnIndex; + + /// + /// Gets the part of the item/subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocation HotCellHitLocation { + get { return this.hotCellHitLocation; } + protected set { this.hotCellHitLocation = value; } + } + private HitTestLocation hotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocationEx HotCellHitLocationEx + { + get { return this.hotCellHitLocationEx; } + protected set { this.hotCellHitLocationEx = value; } + } + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the group that the mouse is over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVGroup HotGroup + { + get { return hotGroup; } + internal set { hotGroup = value; } + } + private OLVGroup hotGroup; + + /// + /// The index of the item that is 'hot', i.e. under the cursor. -1 means no item. + /// + [Browsable(false), + Obsolete("Use HotRowIndex instead", false)] + public virtual int HotItemIndex { + get { return this.HotRowIndex; } + } + + /// + /// What sort of formatting should be applied to the row under the cursor? + /// + /// + /// + /// This only takes effect when UseHotItem is true. + /// + /// If the style has an overlay, it must be set + /// *before* assigning it to this property. Adding it afterwards will be ignored. + /// + [Category("ObjectListView"), + Description("How should the row under the cursor be highlighted"), + DefaultValue(null)] + public virtual HotItemStyle HotItemStyle { + get { return this.hotItemStyle; } + set { + if (this.HotItemStyle != null) + this.RemoveOverlay(this.HotItemStyle.Overlay); + this.hotItemStyle = value; + if (this.HotItemStyle != null) + this.AddOverlay(this.HotItemStyle.Overlay); + } + } + private HotItemStyle hotItemStyle; + + /// + /// Gets the installed hot item style or a reasonable default. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HotItemStyle HotItemStyleOrDefault { + get { return this.HotItemStyle ?? ObjectListView.DefaultHotItemStyle; } + } + + /// + /// What sort of formatting should be applied to hyperlinks? + /// + [Category("ObjectListView"), + Description("How should hyperlinks be drawn"), + DefaultValue(null)] + public virtual HyperlinkStyle HyperlinkStyle { + get { return this.hyperlinkStyle; } + set { this.hyperlinkStyle = value; } + } + private HyperlinkStyle hyperlinkStyle; + + /// + /// What color should be used for the background of selected rows? + /// + [Category("ObjectListView"), + Description("The background of selected rows when the control is owner drawn"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color selectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedBackColorOrDefault { + get { + return this.SelectedBackColor.IsEmpty ? SystemColors.Highlight : this.SelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows (when the control is owner drawn)"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedForeColor { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color selectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedForeColorOrDefault { + get { + return this.SelectedForeColor.IsEmpty ? SystemColors.HighlightText : this.SelectedForeColor; + } + } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedBackColor instead")] + public virtual Color HighlightBackgroundColor { get { return this.SelectedBackColor; } set { this.SelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedBackColorOrDefault instead")] + public virtual Color HighlightBackgroundColorOrDefault { get { return this.SelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedForeColor instead")] + public virtual Color HighlightForegroundColor { get { return this.SelectedForeColor; } set { this.SelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedForeColorOrDefault instead")] + public virtual Color HighlightForegroundColorOrDefault { get { return this.SelectedForeColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedBackColor instead")] + public virtual Color UnfocusedHighlightBackgroundColor { get { return this.UnfocusedSelectedBackColor; } set { this.UnfocusedSelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedBackColorOrDefault instead")] + public virtual Color UnfocusedHighlightBackgroundColorOrDefault { get { return this.UnfocusedSelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedForeColor instead")] + public virtual Color UnfocusedHighlightForegroundColor { get { return this.UnfocusedSelectedForeColor; } set { this.UnfocusedSelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedForeColorOrDefault instead")] + public virtual Color UnfocusedHighlightForegroundColorOrDefault { get { return this.UnfocusedSelectedForeColorOrDefault; } } + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied or dragged, will data in hidden columns be included in the text? If this is false, only visible columns will be included."), + DefaultValue(false)] + public virtual bool IncludeHiddenColumnsInDataTransfer + { + get { return includeHiddenColumnsInDataTransfer; } + set { includeHiddenColumnsInDataTransfer = value; } + } + private bool includeHiddenColumnsInDataTransfer; + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied, will column headers be in the text?."), + DefaultValue(false)] + public virtual bool IncludeColumnHeadersInCopy + { + get { return includeColumnHeadersInCopy; } + set { includeColumnHeadersInCopy = value; } + } + private bool includeColumnHeadersInCopy; + + /// + /// Return true if a cell edit operation is currently happening + /// + [Browsable(false)] + public virtual bool IsCellEditing { + get { return this.cellEditor != null; } + } + + /// + /// Return true if the ObjectListView is being used within the development environment. + /// + [Browsable(false)] + public virtual bool IsDesignMode { + get { return this.DesignMode; } + } + + /// + /// Gets whether or not the current list is filtering its contents + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool IsFiltering { + get { return this.UseFiltering && (this.ModelFilter != null || this.ListFilter != null); } + } + + /// + /// When the user types into a list, should the values in the current sort column be searched to find a match? + /// If this is false, the primary column will always be used regardless of the sort column. + /// + /// When this is true, the behavior is like that of ITunes. + [Category("ObjectListView"), + Description("When the user types into a list, should the values in the current sort column be searched to find a match?"), + DefaultValue(true)] + public virtual bool IsSearchOnSortColumn { + get { return isSearchOnSortColumn; } + set { isSearchOnSortColumn = value; } + } + private bool isSearchOnSortColumn = true; + + /// + /// Gets or sets if this control will use a SimpleDropSink to receive drops + /// + /// + /// + /// Setting this replaces any previous DropSink. + /// + /// + /// After setting this to true, the SimpleDropSink will still need to be configured + /// to say when it can accept drops and what should happen when something is dropped. + /// The need to do these things makes this property mostly useless :( + /// + /// + [Category("ObjectListView"), + Description("Should this control will use a SimpleDropSink to receive drops."), + DefaultValue(false)] + public virtual bool IsSimpleDropSink { + get { return this.DropSink != null; } + set { + this.DropSink = value ? new SimpleDropSink() : null; + } + } + + /// + /// Gets or sets if this control will use a SimpleDragSource to initiate drags + /// + /// Setting this replaces any previous DragSource + [Category("ObjectListView"), + Description("Should this control use a SimpleDragSource to initiate drags out from this control"), + DefaultValue(false)] + public virtual bool IsSimpleDragSource { + get { return this.DragSource != null; } + set { + this.DragSource = value ? new SimpleDragSource() : null; + } + } + + /// + /// Hide the Items collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewItemCollection Items { + get { return base.Items; } + } + + /// + /// This renderer draws the items when in the list is in non-details view. + /// In details view, the renderers for the individuals columns are responsible. + /// + [Category("ObjectListView"), + Description("The owner drawn renderer that draws items when the list is in non-Details view."), + DefaultValue(null)] + public IRenderer ItemRenderer { + get { return itemRenderer; } + set { itemRenderer = value; } + } + private IRenderer itemRenderer; + + /// + /// Which column did we last sort by + /// + /// This is an alias for PrimarySortColumn + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn LastSortColumn { + get { return this.PrimarySortColumn; } + set { this.PrimarySortColumn = value; } + } + + /// + /// Which direction did we last sort + /// + /// This is an alias for PrimarySortOrder + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder LastSortOrder { + get { return this.PrimarySortOrder; } + set { this.PrimarySortOrder = value; } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// + /// + /// The list is updated immediately to reflect this filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IListFilter ListFilter { + get { return listFilter; } + set { + listFilter = value; + if (this.UseFiltering) + this.UpdateFiltering(); + } + } + private IListFilter listFilter; + + /// + /// Gets or sets the filter that is applied to each model objects in the list + /// + /// + /// You may want to consider using instead of this property, + /// since AdditionalFilter combines with column filtering at runtime. Setting this property simply + /// replaces any column filter the user may have given. + /// + /// The list is updated immediately to reflect this filter. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter ModelFilter { + get { return modelFilter; } + set { + modelFilter = value; + this.NotifyNewModelFilter(); + if (this.UseFiltering) { + this.UpdateFiltering(); + + // When the filter changes, it's likely/possible that the selection has also changed. + // It's expensive to see if the selection has actually changed (for large virtual lists), + // so we just fake a selection changed event, just in case. SF #144 + this.OnSelectedIndexChanged(EventArgs.Empty); + } + } + } + private IModelFilter modelFilter; + + /// + /// Gets the hit test info last time the mouse was moved. + /// + /// Useful for hot item processing. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OlvListViewHitTestInfo MouseMoveHitTest { + get { return mouseMoveHitTest; } + private set { mouseMoveHitTest = value; } + } + private OlvListViewHitTestInfo mouseMoveHitTest; + + /// + /// Gets or sets the list of groups shown by the listview. + /// + /// + /// This property does not work like the .NET Groups property. It should + /// be treated as a read-only property. + /// Changes made to the list are NOT reflected in the ListView itself -- it is pointless to add + /// or remove groups to/from this list. Such modifications will do nothing. + /// To do such things, you must listen for + /// BeforeCreatingGroups or AboutToCreateGroups events, and change the list of + /// groups in those events. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList OLVGroups { + get { return this.olvGroups; } + set { this.olvGroups = value; } + } + private IList olvGroups; + + /// + /// Gets or sets the collection of OLVGroups that are collapsed. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable CollapsedGroups { + get + { + if (this.OLVGroups != null) + { + foreach (OLVGroup group in this.OLVGroups) + { + if (group.Collapsed) + yield return group; + } + } + } + set + { + if (this.OLVGroups == null) + return; + + Hashtable shouldCollapse = new Hashtable(); + if (value != null) + { + foreach (OLVGroup group in value) + shouldCollapse[group.Key] = true; + } + foreach (OLVGroup group in this.OLVGroups) + { + group.Collapsed = shouldCollapse.ContainsKey(group.Key); + } + + } + } + + /// + /// Gets or sets whether the user wants to owner draw the header control + /// themselves. If this is false (the default), ObjectListView will use + /// custom drawing to render the header, if needed. + /// + /// + /// If you listen for the DrawColumnHeader event, you need to set this to true, + /// otherwise your event handler will not be called. + /// + [Category("ObjectListView"), + Description("Should the DrawColumnHeader event be triggered"), + DefaultValue(false)] + public bool OwnerDrawnHeader { + get { return ownerDrawnHeader; } + set { ownerDrawnHeader = value; } + } + private bool ownerDrawnHeader; + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists: setting is problem-free, but if you try to get it + /// and the list has 10 million objects, it may take some time to return. + /// This collection is unfiltered. Use to access just those objects + /// that survive any installed filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Objects { + get { return this.objects; } + set { this.SetObjects(value, true); } + } + private IEnumerable objects; + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable ObjectsForClustering { + get { return this.Objects; } + } + + /// + /// Gets or sets the image that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The image that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public ImageOverlay OverlayImage { + get { return this.imageOverlay; } + set { + if (this.imageOverlay == value) + return; + + this.RemoveOverlay(this.imageOverlay); + this.imageOverlay = value; + this.AddOverlay(this.imageOverlay); + } + } + private ImageOverlay imageOverlay; + + /// + /// Gets or sets the text that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public TextOverlay OverlayText { + get { return this.textOverlay; } + set { + if (this.textOverlay == value) + return; + + this.RemoveOverlay(this.textOverlay); + this.textOverlay = value; + this.AddOverlay(this.textOverlay); + } + } + private TextOverlay textOverlay; + + /// + /// Gets or sets the transparency of all the overlays. + /// 0 is completely transparent, 255 is completely opaque. + /// + /// + /// This is obsolete. Use Transparency on each overlay. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int OverlayTransparency { + get { return this.overlayTransparency; } + set { this.overlayTransparency = Math.Min(255, Math.Max(0, value)); } + } + private int overlayTransparency = 128; + + /// + /// Gets the list of overlays that will be drawn on top of the ListView + /// + /// + /// You can add new overlays and remove overlays that you have added, but + /// don't mess with the overlays that you didn't create. + /// + [Browsable(false)] + protected IList Overlays { + get { return this.overlays; } + } + private readonly List overlays = new List(); + + /// + /// Gets or sets whether the ObjectListView will be owner drawn. Defaults to true. + /// + /// + /// + /// When this is true, all of ObjectListView's neat features are available. + /// + /// We have to reimplement this property, even though we just call the base + /// property, in order to change the [DefaultValue] to true. + /// + /// + [Category("Appearance"), + Description("Should the ListView do its own rendering"), + DefaultValue(true)] + public new bool OwnerDraw { + get { return base.OwnerDraw; } + set { base.OwnerDraw = value; } + } + + /// + /// Gets or sets whether or not primary checkboxes will persistent their values across list rebuild + /// and filtering operations. + /// + /// + /// + /// This property is only useful when you don't explicitly set CheckStateGetter/Putter. + /// If you use CheckStateGetter/Putter, the checkedness of a row will already be persisted + /// by those methods. + /// + /// This defaults to true. If this is false, checkboxes will lose their values when the + /// list if rebuild or filtered. + /// If you set it to false on virtual lists, + /// you have to install CheckStateGetter/Putters. + /// + [Category("ObjectListView"), + Description("Will primary checkboxes persistent their values across list rebuilds"), + DefaultValue(true)] + public virtual bool PersistentCheckBoxes { + get { return persistentCheckBoxes; } + set { + if (persistentCheckBoxes == value) + return; + persistentCheckBoxes = value; + this.ClearPersistentCheckState(); + } + } + private bool persistentCheckBoxes = true; + + /// + /// Gets or sets a dictionary that remembers the check state of model objects + /// + /// This is used when PersistentCheckBoxes is true and for virtual lists. + protected Dictionary CheckStateMap { + get { return checkStateMap ?? (checkStateMap = new Dictionary()); } + set { checkStateMap = value; } + } + private Dictionary checkStateMap; + + /// + /// Which column did we last sort by + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn PrimarySortColumn { + get { return this.primarySortColumn; } + set { + this.primarySortColumn = value; + if (this.TintSortColumn) + this.SelectedColumn = value; + } + } + private OLVColumn primarySortColumn; + + /// + /// Which direction did we last sort + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder PrimarySortOrder { + get { return primarySortOrder; } + set { primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets if non-editable checkboxes are drawn as disabled. Default is false. + /// + /// + /// This only has effect in owner drawn mode. + /// + [Category("ObjectListView"), + Description("Should non-editable checkboxes be drawn as disabled?"), + DefaultValue(false)] + public virtual bool RenderNonEditableCheckboxesAsDisabled { + get { return renderNonEditableCheckboxesAsDisabled; } + set { renderNonEditableCheckboxesAsDisabled = value; } + } + private bool renderNonEditableCheckboxesAsDisabled; + + /// + /// Specify the height of each row in the control in pixels. + /// + /// The row height in a listview is normally determined by the font size and the small image list size. + /// This setting allows that calculation to be overridden (within reason: you still cannot set the line height to be + /// less than the line height of the font used in the control). + /// Setting it to -1 means use the normal calculation method. + /// This feature is experimental! Strange things may happen to your program, + /// your spouse or your pet if you use it. + /// + [Category("ObjectListView"), + Description("Specify the height of each row in pixels. -1 indicates default height"), + DefaultValue(-1)] + public virtual int RowHeight { + get { return rowHeight; } + set { + if (value < 1) + rowHeight = -1; + else + rowHeight = value; + if (this.DesignMode) + return; + this.SetupBaseImageList(); + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + } + private int rowHeight = -1; + + /// + /// How many pixels high is each row? + /// + [Browsable(false)] + public virtual int RowHeightEffective { + get { + switch (this.View) { + case View.List: + case View.SmallIcon: + case View.Details: + return Math.Max(this.SmallImageSize.Height, this.Font.Height); + + case View.Tile: + return this.TileSize.Height; + + case View.LargeIcon: + if (this.LargeImageList == null) + return this.Font.Height; + + return Math.Max(this.LargeImageList.ImageSize.Height, this.Font.Height); + + default: + // This should never happen + return 0; + } + } + } + + /// + /// How many rows appear on each page of this control + /// + [Browsable(false)] + public virtual int RowsPerPage { + get { + return NativeMethods.GetCountPerPage(this); + } + } + + /// + /// Get/set the column that will be used to resolve comparisons that are equal when sorting. + /// + /// There is no user interface for this setting. It must be set programmatically. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn SecondarySortColumn { + get { return this.secondarySortColumn; } + set { this.secondarySortColumn = value; } + } + private OLVColumn secondarySortColumn; + + /// + /// When the SecondarySortColumn is used, in what order will it compare results? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder = SortOrder.None; + + /// + /// Gets or sets if all rows should be selected when the user presses Ctrl-A + /// + [Category("ObjectListView"), + Description("Should the control select all rows when the user presses Ctrl-A?"), + DefaultValue(true)] + public virtual bool SelectAllOnControlA { + get { return selectAllOnControlA; } + set { selectAllOnControlA = value; } + } + private bool selectAllOnControlA = true; + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose which columns will be shown in the view? + /// + /// This is just a compatibility wrapper for the SelectColumnsOnRightClickBehaviour + /// property. + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to choose which columns will be shown in the view?"), + DefaultValue(true)] + public virtual bool SelectColumnsOnRightClick { + get { return this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None; } + set { + if (value) { + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.None) + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + } else { + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.None; + } + } + } + + /// + /// Gets or sets how the user will be able to select columns when the header is right clicked + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, how will the user be able to select columns?"), + DefaultValue(ColumnSelectBehaviour.InlineMenu)] + public virtual ColumnSelectBehaviour SelectColumnsOnRightClickBehaviour { + get { return selectColumnsOnRightClickBehaviour; } + set { selectColumnsOnRightClickBehaviour = value; } + } + private ColumnSelectBehaviour selectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + + /// + /// When the column select menu is open, should it stay open after an item is selected? + /// Staying open allows the user to turn more than one column on or off at a time. + /// + /// This only works when SelectColumnsOnRightClickBehaviour is set to InlineMenu. + /// It has no effect when the behaviour is set to SubMenu. + [Category("ObjectListView"), + Description("When the column select inline menu is open, should it stay open after an item is selected?"), + DefaultValue(true)] + public virtual bool SelectColumnsMenuStaysOpen { + get { return selectColumnsMenuStaysOpen; } + set { selectColumnsMenuStaysOpen = value; } + } + private bool selectColumnsMenuStaysOpen = true; + + /// + /// Gets or sets the column that is drawn with a slight tint. + /// + /// + /// + /// If TintSortColumn is true, the sort column will automatically + /// be made the selected column. + /// + /// + /// The colour of the tint is controlled by SelectedColumnTint. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn SelectedColumn { + get { return this.selectedColumn; } + set { + this.selectedColumn = value; + if (value == null) { + this.RemoveDecoration(this.selectedColumnDecoration); + } else { + if (!this.HasDecoration(this.selectedColumnDecoration)) + this.AddDecoration(this.selectedColumnDecoration); + } + } + } + private OLVColumn selectedColumn; + private readonly TintedColumnDecoration selectedColumnDecoration = new TintedColumnDecoration(); + + /// + /// Gets or sets the decoration that will be drawn on all selected rows + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IDecoration SelectedRowDecoration { + get { return this.selectedRowDecoration; } + set { this.selectedRowDecoration = value; } + } + private IDecoration selectedRowDecoration; + + /// + /// What color should be used to tint the selected column? + /// + /// + /// The tint color must be alpha-blendable, so if the given color is solid + /// (i.e. alpha = 255), it will be changed to have a reasonable alpha value. + /// + [Category("ObjectListView"), + Description("The color that will be used to tint the selected column"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedColumnTint { + get { return selectedColumnTint; } + set { + this.selectedColumnTint = value.A == 255 ? Color.FromArgb(15, value) : value; + this.selectedColumnDecoration.Tint = this.selectedColumnTint; + } + } + private Color selectedColumnTint = Color.Empty; + + /// + /// Gets or sets the index of the row that is currently selected. + /// When getting the index, if no row is selected,or more than one is selected, return -1. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int SelectedIndex { + get { return this.SelectedIndices.Count == 1 ? this.SelectedIndices[0] : -1; } + set { + this.SelectedIndices.Clear(); + if (value >= 0 && value < this.Items.Count) + this.SelectedIndices.Add(value); + } + } + + /// + /// Gets or sets the ListViewItem that is currently selected . If no row is selected, or more than one is selected, return null. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVListItem SelectedItem { + get { + return this.SelectedIndices.Count == 1 ? this.GetItem(this.SelectedIndices[0]) : null; + } + set { + this.SelectedIndices.Clear(); + if (value != null) + this.SelectedIndices.Add(value.Index); + } + } + + /// + /// Gets the model object from the currently selected row, if there is only one row selected. + /// If no row is selected, or more than one is selected, returns null. + /// When setting, this will select the row that is displaying the given model object and focus on it. + /// All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object SelectedObject { + get { + return this.SelectedIndices.Count == 1 ? this.GetModelObject(this.SelectedIndices[0]) : null; + } + set { + // If the given model is already selected, don't do anything else (prevents an flicker) + object selectedObject = this.SelectedObject; + if (selectedObject != null && selectedObject.Equals(value)) + return; + + this.SelectedIndices.Clear(); + this.SelectObject(value, true); + } + } + + /// + /// Get the model objects from the currently selected rows. If no row is selected, the returned List will be empty. + /// When setting this value, select the rows that is displaying the given model objects. All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList SelectedObjects { + get { + ArrayList list = new ArrayList(); + foreach (int index in this.SelectedIndices) + list.Add(this.GetModelObject(index)); + return list; + } + set { + this.SelectedIndices.Clear(); + this.SelectObjects(value); + } + } + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose common tasks to perform on the listview? + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to perform common tasks on the listview?"), + DefaultValue(false)] + public virtual bool ShowCommandMenuOnRightClick { + get { return showCommandMenuOnRightClick; } + set { showCommandMenuOnRightClick = value; } + } + private bool showCommandMenuOnRightClick; + + /// + /// Gets or sets whether this ObjectListView will show Excel like filtering + /// menus when the header control is right clicked + /// + [Category("ObjectListView"), + Description("If this is true, right clicking on a column header will show a Filter menu option"), + DefaultValue(true)] + public bool ShowFilterMenuOnRightClick { + get { return showFilterMenuOnRightClick; } + set { showFilterMenuOnRightClick = value; } + } + private bool showFilterMenuOnRightClick = true; + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + public new virtual bool ShowGroups { + get { return base.ShowGroups; } + set { + this.GroupImageList = this.GroupImageList; + base.ShowGroups = value; + } + } + + /// + /// Should the list view show a bitmap in the column header to show the sort direction? + /// + /// + /// The only reason for not wanting to have sort indicators is that, on pre-XP versions of + /// Windows, having sort indicators required the ListView to have a small image list, and + /// as soon as you give a ListView a SmallImageList, the text of column 0 is bumped 16 + /// pixels to the right, even if you never used an image. + /// + [Category("ObjectListView"), + Description("Should the list view show sort indicators in the column headers?"), + DefaultValue(true)] + public virtual bool ShowSortIndicators { + get { return showSortIndicators; } + set { showSortIndicators = value; } + } + private bool showSortIndicators; + + /// + /// Should the list view show images on subitems? + /// + /// + /// Virtual lists have to be owner drawn in order to show images on subitems + /// + [Category("ObjectListView"), + Description("Should the list view show images on subitems?"), + DefaultValue(false)] + public virtual bool ShowImagesOnSubItems { + get { return showImagesOnSubItems; } + set { + showImagesOnSubItems = value; + if (this.Created) + this.ApplyExtendedStyles(); + if (value && this.VirtualMode) + this.OwnerDraw = true; + } + } + private bool showImagesOnSubItems; + + /// + /// This property controls whether group labels will be suffixed with a count of items. + /// + /// + /// The format of the suffix is controlled by GroupWithItemCountFormat/GroupWithItemCountSingularFormat properties + /// + [Category("ObjectListView"), + Description("Will group titles be suffixed with a count of the items in the group?"), + DefaultValue(false)] + public virtual bool ShowItemCountOnGroups { + get { return showItemCountOnGroups; } + set { showItemCountOnGroups = value; } + } + private bool showItemCountOnGroups; + + /// + /// Gets or sets whether the control will show column headers in all + /// views (true), or only in Details view (false) + /// + /// + /// + /// This property is not working correctly. JPP 2010/04/06. + /// It works fine if it is set before the control is created. + /// But if it turned off once the control is created, the control + /// loses its checkboxes (weird!) + /// + /// + /// To changed this setting after the control is created, things + /// are complicated. If it is off and we want it on, we have + /// to change the View and the header will appear. If it is currently + /// on and we want to turn it off, we have to both change the view + /// AND recreate the handle. Recreating the handle is a problem + /// since it makes our checkbox style disappear. + /// + /// + /// This property doesn't work on XP. + /// + [Category("ObjectListView"), + Description("Will the control will show column headers in all views?"), + DefaultValue(true)] + public bool ShowHeaderInAllViews { + get { return ObjectListView.IsVistaOrLater && showHeaderInAllViews; } + set { + if (showHeaderInAllViews == value) + return; + + showHeaderInAllViews = value; + + // If the control isn't already created, everything is fine. + if (!this.Created) + return; + + // If the header is being hidden, we have to recreate the control + // to remove the style (not sure why this is) + if (showHeaderInAllViews) + this.ApplyExtendedStyles(); + else + this.RecreateHandle(); + + // Still more complications. The change doesn't become visible until the View is changed + if (this.View != View.Details) { + View temp = this.View; + this.View = View.Details; + this.View = temp; + } + } + } + private bool showHeaderInAllViews = true; + + /// + /// Override the SmallImageList property so we can correctly shadow its operations. + /// + /// If you use the RowHeight property to specify the row height, the SmallImageList + /// must be fully initialised before setting/changing the RowHeight. If you add new images to the image + /// list after setting the RowHeight, you must assign the imagelist to the control again. Something as simple + /// as this will work: + /// listView1.SmallImageList = listView1.SmallImageList; + /// + public new ImageList SmallImageList { + get { return this.shadowedImageList; } + set { + this.shadowedImageList = value; + if (this.UseSubItemCheckBoxes) + this.SetupSubItemCheckBoxes(); + this.SetupBaseImageList(); + } + } + private ImageList shadowedImageList; + + /// + /// Return the size of the images in the small image list or a reasonable default + /// + [Browsable(false)] + public virtual Size SmallImageSize { + get { + return this.BaseSmallImageList == null ? new Size(16, 16) : this.BaseSmallImageList.ImageSize; + } + } + + /// + /// When the listview is grouped, should the items be sorted by the primary column? + /// If this is false, the items will be sorted by the same column as they are grouped. + /// + /// + /// + /// The primary column is always column 0 and is unrelated to the PrimarySort column. + /// + /// + [Category("ObjectListView"), + Description("When the listview is grouped, should the items be sorted by the primary column? If this is false, the items will be sorted by the same column as they are grouped."), + DefaultValue(true)] + public virtual bool SortGroupItemsByPrimaryColumn { + get { return this.sortGroupItemsByPrimaryColumn; } + set { this.sortGroupItemsByPrimaryColumn = value; } + } + private bool sortGroupItemsByPrimaryColumn = true; + + /// + /// When the listview is grouped, how many pixels should exist between the end of one group and the + /// beginning of the next? + /// + [Category("ObjectListView"), + Description("How many pixels of space will be between groups"), + DefaultValue(0)] + public virtual int SpaceBetweenGroups { + get { return this.spaceBetweenGroups; } + set { + if (this.spaceBetweenGroups == value) + return; + + this.spaceBetweenGroups = value; + this.SetGroupSpacing(); + } + } + private int spaceBetweenGroups; + + private void SetGroupSpacing() { + if (!this.IsHandleCreated) + return; + + NativeMethods.LVGROUPMETRICS metrics = new NativeMethods.LVGROUPMETRICS(); + metrics.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUPMETRICS))); + metrics.mask = (uint)GroupMetricsMask.LVGMF_BORDERSIZE; + metrics.Bottom = (uint)this.SpaceBetweenGroups; + NativeMethods.SetGroupMetrics(this, metrics); + } + + /// + /// Should the sort column show a slight tinge? + /// + [Category("ObjectListView"), + Description("Should the sort column show a slight tinting?"), + DefaultValue(false)] + public virtual bool TintSortColumn { + get { return this.tintSortColumn; } + set { + this.tintSortColumn = value; + if (value && this.PrimarySortColumn != null) + this.SelectedColumn = this.PrimarySortColumn; + else + this.SelectedColumn = null; + } + } + private bool tintSortColumn; + + /// + /// Should each row have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). Otherwise, user clicks + /// alternate between checked and unchecked. CheckStateGetter can still return Indeterminate when this + /// setting is false. + /// + [Category("ObjectListView"), + Description("Should the primary column have a checkbox that behaves as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + this.InitializeStateImageList(); + } + } + private bool triStateCheckBoxes; + + /// + /// Get or set the index of the top item of this listview + /// + /// + /// + /// This property only works when the listview is in Details view and not showing groups. + /// + /// + /// The reason that it does not work when showing groups is that, when groups are enabled, + /// the Windows msg LVM_GETTOPINDEX always returns 0, regardless of the + /// scroll position. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int TopItemIndex { + get { + if (this.View == View.Details && this.IsHandleCreated) + return NativeMethods.GetTopIndex(this); + + return -1; + } + set { + int newTopIndex = Math.Min(value, this.GetItemCount() - 1); + if (this.View != View.Details || newTopIndex < 0) + return; + + try { + this.TopItem = this.Items[newTopIndex]; + + // Setting the TopItem sometimes gives off by one errors, + // that (bizarrely) are correct on a second attempt + if (this.TopItem != null && this.TopItem.Index != newTopIndex) + this.TopItem = this.GetItem(newTopIndex); + } + catch (NullReferenceException) { + // There is a bug in the .NET code where setting the TopItem + // will sometimes throw null reference exceptions + // There is nothing we can do to get around it. + } + } + } + + /// + /// Gets or sets whether moving the mouse over the header will trigger CellOver events. + /// Defaults to true. + /// + /// + /// Moving the mouse over the header did not previously trigger CellOver events, since the + /// header is considered a separate control. + /// If this change in behaviour causes your application problems, set this to false. + /// If you are interested in knowing when the mouse moves over the header, set this property to true (the default). + /// + [Category("ObjectListView"), + Description("Should moving the mouse over the header trigger CellOver events?"), + DefaultValue(true)] + public bool TriggerCellOverEventsWhenOverHeader + { + get { return triggerCellOverEventsWhenOverHeader; } + set { triggerCellOverEventsWhenOverHeader = value; } + } + private bool triggerCellOverEventsWhenOverHeader = true; + + /// + /// When resizing a column by dragging its divider, should any space filling columns be + /// resized at each mouse move? If this is false, the filling columns will be + /// updated when the mouse is released. + /// + /// + /// + /// If you have a space filling column + /// is in the left of the column that is being resized, this will look odd: + /// the right edge of the column will be dragged, but + /// its left edge will move since the space filling column is shrinking. + /// + /// This is logical behaviour -- it just looks wrong. + /// + /// + /// Given the above behavior is probably best to turn this property off if your space filling + /// columns aren't the right-most columns. + /// + [Category("ObjectListView"), + Description("When resizing a column by dragging its divider, should any space filling columns be resized at each mouse move?"), + DefaultValue(true)] + public virtual bool UpdateSpaceFillingColumnsWhenDraggingColumnDivider { + get { return updateSpaceFillingColumnsWhenDraggingColumnDivider; } + set { updateSpaceFillingColumnsWhenDraggingColumnDivider = value; } + } + private bool updateSpaceFillingColumnsWhenDraggingColumnDivider = true; + + /// + /// What color should be used for the background of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The background color of selected rows when the control doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedBackColor { + get { return this.unfocusedSelectedBackColor; } + set { this.unfocusedSelectedBackColor = value; } + } + private Color unfocusedSelectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedBackColorOrDefault { + get { + return this.UnfocusedSelectedBackColor.IsEmpty ? SystemColors.Control : this.UnfocusedSelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows when the control is owner drawn and doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedForeColor { + get { return this.unfocusedSelectedForeColor; } + set { this.unfocusedSelectedForeColor = value; } + } + private Color unfocusedSelectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedForeColorOrDefault { + get { + return this.UnfocusedSelectedForeColor.IsEmpty ? SystemColors.ControlText : this.UnfocusedSelectedForeColor; + } + } + + /// + /// Gets or sets whether the list give a different background color to every second row? Defaults to false. + /// + /// The color of the alternate rows is given by AlternateRowBackColor. + /// There is a "feature" in .NET for listviews in non-full-row-select mode, where + /// selected rows are not drawn with their correct background color. + [Category("ObjectListView"), + Description("Should the list view use a different backcolor to alternate rows?"), + DefaultValue(false)] + public virtual bool UseAlternatingBackColors { + get { return useAlternatingBackColors; } + set { useAlternatingBackColors = value; } + } + private bool useAlternatingBackColors; + + /// + /// Should FormatCell events be called for each cell in the control? + /// + /// + /// In many situations, no cell level formatting is performed. ObjectListView + /// can run somewhat faster if it does not trigger a format cell event for every cell + /// unless it is required. So, by default, it does not raise an event for each cell. + /// + /// ObjectListView *does* raise a FormatRow event every time a row is rebuilt. + /// Individual rows can decide whether to raise FormatCell + /// events for every cell in row. + /// + /// + /// Regardless of this setting, FormatCell events are only raised when the ObjectListView + /// is in Details view. + /// + [Category("ObjectListView"), + Description("Should FormatCell events be triggered to every cell that is built?"), + DefaultValue(false)] + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + private bool useCellFormatEvents; + + /// + /// Should the selected row be drawn with non-standard foreground and background colors? + /// + /// v2.9 This property is no longer required + [Category("ObjectListView"), + Description("Should the selected row be drawn with non-standard foreground and background colors?"), + DefaultValue(false)] + public bool UseCustomSelectionColors { + get { return false; } + // ReSharper disable once ValueParameterNotUsed + set { } + } + + /// + /// Gets or sets whether this ObjectListView will use the same hot item and selection + /// mechanism that Vista Explorer does. + /// + /// + /// + /// This property has many imperfections: + /// + /// This only works on Vista and later + /// It does not work well with AlternateRowBackColors. + /// It does not play well with HotItemStyles. + /// It looks a little bit silly is FullRowSelect is false. + /// It doesn't work at all when the list is owner drawn (since the renderers + /// do all the drawing). As such, it won't work with TreeListView's since they *have to be* + /// owner drawn. You can still set it, but it's just not going to be happy. + /// + /// But if you absolutely have to look like Vista/Win7, this is your property. + /// Do not complain if settings this messes up other things. + /// + /// + /// When this property is set to true, the ObjectListView will be not owner drawn. This will + /// disable many of the pretty drawing-based features of ObjectListView. + /// + /// Because of the above, this property should never be set to true for TreeListViews, + /// since they *require* owner drawing to be rendered correctly. + /// + [Category("ObjectListView"), + Description("Should the list use the same hot item and selection mechanism as Vista?"), + DefaultValue(false)] + public bool UseExplorerTheme { + get { return useExplorerTheme; } + set { + useExplorerTheme = value; + if (this.Created) + NativeMethods.SetWindowTheme(this.Handle, value ? "explorer" : "", null); + + this.OwnerDraw = !value; + } + } + private bool useExplorerTheme; + + /// + /// Gets or sets whether the list should enable filtering + /// + [Category("ObjectListView"), + Description("Should the list enable filtering?"), + DefaultValue(false)] + public virtual bool UseFiltering { + get { return useFiltering; } + set { + if (useFiltering == value) + return; + useFiltering = value; + this.UpdateFiltering(); + } + } + private bool useFiltering; + + /// + /// Gets or sets whether the list should put an indicator into a column's header to show that + /// it is filtering on that column + /// + /// If you set this to true, HeaderUsesThemes is automatically set to false, since + /// we can only draw a filter indicator when not using a themed header. + [Category("ObjectListView"), + Description("Should an image be drawn in a column's header when that column is being used for filtering?"), + DefaultValue(false)] + public virtual bool UseFilterIndicator { + get { return useFilterIndicator; } + set { + if (this.useFilterIndicator == value) + return; + useFilterIndicator = value; + if (this.useFilterIndicator) + this.HeaderUsesThemes = false; + this.Invalidate(); + } + } + private bool useFilterIndicator; + + /// + /// Should controls (checkboxes or buttons) that are under the mouse be drawn "hot"? + /// + /// + /// If this is false, control will not be drawn differently when the mouse is over them. + /// + /// If this is false AND UseHotItem is false AND UseHyperlinks is false, then the ObjectListView + /// can skip some processing on mouse move. This make mouse move processing use almost no CPU. + /// + /// + [Category("ObjectListView"), + Description("Should controls (checkboxes or buttons) that are under the mouse be drawn hot?"), + DefaultValue(true)] + public bool UseHotControls { + get { return this.useHotControls; } + set { this.useHotControls = value; } + } + private bool useHotControls = true; + + /// + /// Should the item under the cursor be formatted in a special way? + /// + [Category("ObjectListView"), + Description("Should HotTracking be used? Hot tracking applies special formatting to the row under the cursor"), + DefaultValue(false)] + public bool UseHotItem { + get { return this.useHotItem; } + set { + this.useHotItem = value; + if (value) + this.AddOverlay(this.HotItemStyleOrDefault.Overlay); + else + this.RemoveOverlay(this.HotItemStyleOrDefault.Overlay); + } + } + private bool useHotItem; + + /// + /// Gets or sets whether this listview should show hyperlinks in the cells. + /// + [Category("ObjectListView"), + Description("Should hyperlinks be shown on this control?"), + DefaultValue(false)] + public bool UseHyperlinks { + get { return this.useHyperlinks; } + set { + this.useHyperlinks = value; + if (value && this.HyperlinkStyle == null) + this.HyperlinkStyle = new HyperlinkStyle(); + } + } + private bool useHyperlinks; + + /// + /// Should this control show overlays + /// + /// Overlays are enabled by default and would only need to be disabled + /// if they were causing problems in your development environment. + [Category("ObjectListView"), + Description("Should this control show overlays"), + DefaultValue(true)] + public bool UseOverlays { + get { return this.useOverlays; } + set { this.useOverlays = value; } + } + private bool useOverlays = true; + + /// + /// Should this control be configured to show check boxes on subitems? + /// + /// If this is set to True, the control will be given a SmallImageList if it + /// doesn't already have one. Also, if it is a virtual list, it will be set to owner + /// drawn, since virtual lists can't draw check boxes without being owner drawn. + [Category("ObjectListView"), + Description("Should this control be configured to show check boxes on subitems."), + DefaultValue(false)] + public bool UseSubItemCheckBoxes { + get { return this.useSubItemCheckBoxes; } + set { + this.useSubItemCheckBoxes = value; + if (value) + this.SetupSubItemCheckBoxes(); + } + } + private bool useSubItemCheckBoxes; + + /// + /// Gets or sets if the ObjectListView will use a translucent selection mechanism like Vista. + /// + /// + /// + /// Unlike UseExplorerTheme, this Vista-like scheme works on XP and for both + /// owner and non-owner drawn lists. + /// + /// + /// This will replace any SelectedRowDecoration that has been installed. + /// + /// + /// If you don't like the colours used for the selection, ignore this property and + /// just create your own RowBorderDecoration and assigned it to SelectedRowDecoration, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent selection mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentSelection { + get { return useTranslucentSelection; } + set { + useTranslucentSelection = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.FillBrush = new SolidBrush(Color.FromArgb(48, 163, 217, 225)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + this.SelectedRowDecoration = rbd; + } else + this.SelectedRowDecoration = null; + } + } + private bool useTranslucentSelection; + + /// + /// Gets or sets if the ObjectListView will use a translucent hot row highlighting mechanism like Vista. + /// + /// + /// + /// Setting this will replace any HotItemStyle that has been installed. + /// + /// + /// If you don't like the colours used for the hot item, ignore this property and + /// just create your own HotItemStyle, fill in the values you want, and assigned it to HotItemStyle property, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent hot row highlighting mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentHotItem { + get { return useTranslucentHotItem; } + set { + useTranslucentHotItem = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + rbd.FillGradientFrom = Color.FromArgb(0, 255, 255, 255); + rbd.FillGradientTo = Color.FromArgb(64, 183, 237, 240); + HotItemStyle his = new HotItemStyle(); + his.Decoration = rbd; + this.HotItemStyle = his; + } else + this.HotItemStyle = null; + this.UseHotItem = value; + } + } + private bool useTranslucentHotItem; + + /// + /// Get/set the style of view that this listview is using + /// + /// Switching to tile or details view installs the columns appropriate to that view. + /// Confusingly, in tile view, every column is shown as a row of information. + [Category("Appearance"), + Description("Select the layout of the items within this control)"), + DefaultValue(null)] + public new View View + { + get { return base.View; } + set { + if (base.View == value) + return; + + if (this.Frozen) { + base.View = value; + this.SetupBaseImageList(); + } else { + this.Freeze(); + + if (value == View.Tile) + this.CalculateReasonableTileSize(); + + base.View = value; + this.SetupBaseImageList(); + this.Unfreeze(); + } + } + } + + #endregion + + #region Callbacks + + /// + /// This delegate fetches the checkedness of an object as a boolean only. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStateGetter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.CheckStateGetter = null; + else + this.CheckStateGetter = delegate(Object x) { + return value(x) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// This delegate sets the checkedness of an object as a boolean only. It must return + /// true or false indicating if the object was checked or not. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStatePutter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.CheckStatePutter = null; + else + this.CheckStatePutter = delegate(Object x, CheckState state) { + bool isChecked = (state == CheckState.Checked); + return value(x, isChecked) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public virtual bool CanShowGroups { + get { + return true; + } + } + + /// + /// Gets or sets whether ObjectListView can rely on Application.Idle events + /// being raised. + /// + /// In some host environments (e.g. when running as an extension within + /// VisualStudio and possibly Office), Application.Idle events are never raised. + /// Set this to false when Idle events will not be raised, and ObjectListView will + /// raise those events itself. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CanUseApplicationIdle { + get { return this.canUseApplicationIdle; } + set { this.canUseApplicationIdle = value; } + } + private bool canUseApplicationIdle = true; + + /// + /// This delegate fetches the renderer for a particular cell. + /// + /// + /// + /// If this returns null (or is not installed), the renderer for the column will be used. + /// If the column renderer is null, then will be used. + /// + /// + /// This is called every time any cell is drawn. It must be efficient! + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellRendererGetterDelegate CellRendererGetter + { + get { return this.cellRendererGetter; } + set { this.cellRendererGetter = value; } + } + private CellRendererGetterDelegate cellRendererGetter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular cell. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to show the full text of truncated cell values). + /// + /// + /// Displaying the full text of truncated cell values only work for FullRowSelect listviews. + /// This is MS's behavior, not mine. Don't complain to me :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellToolTipGetterDelegate CellToolTipGetter { + get { return cellToolTipGetter; } + set { cellToolTipGetter = value; } + } + private CellToolTipGetterDelegate cellToolTipGetter; + + /// + /// The name of the property (or field) that holds whether or not a model is checked. + /// + /// + /// The property be modifiable. It must have a return type of bool (or of bool? if + /// TriStateCheckBoxes is true). + /// Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed. + /// Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence + /// over the behavior of this property. + /// + [Category("ObjectListView"), + Description("The name of the property or field that holds the 'checkedness' of the model"), + DefaultValue(null)] + public virtual string CheckedAspectName { + get { return checkedAspectName; } + set { + checkedAspectName = value; + if (String.IsNullOrEmpty(checkedAspectName)) { + this.checkedAspectMunger = null; + this.CheckStateGetter = null; + this.CheckStatePutter = null; + } else { + this.checkedAspectMunger = new Munger(checkedAspectName); + this.CheckStateGetter = delegate(Object modelObject) { + bool? result = this.checkedAspectMunger.GetValue(modelObject) as bool?; + if (result.HasValue) + return result.Value ? CheckState.Checked : CheckState.Unchecked; + return this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + }; + this.CheckStatePutter = delegate(Object modelObject, CheckState newValue) { + if (this.TriStateCheckBoxes && newValue == CheckState.Indeterminate) + this.checkedAspectMunger.PutValue(modelObject, null); + else + this.checkedAspectMunger.PutValue(modelObject, newValue == CheckState.Checked); + return this.CheckStateGetter(modelObject); + }; + } + } + } + private string checkedAspectName; + private Munger checkedAspectMunger; + + /// + /// This delegate will be called whenever the ObjectListView needs to know the check state + /// of the row associated with a given model object. + /// + /// + /// .NET has no support for indeterminate values, but as of v2.0, this class allows + /// indeterminate values. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { checkStateGetter = value; } + } + private CheckStateGetterDelegate checkStateGetter; + + /// + /// This delegate will be called whenever the user tries to change the check state of a row. + /// The delegate should return the state that was actually set, which may be different + /// to the state given. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { checkStatePutter = value; } + } + private CheckStatePutterDelegate checkStatePutter; + + /// + /// This delegate can be used to sort the table in a custom fashion. + /// + /// + /// + /// The delegate must install a ListViewItemSorter on the ObjectListView. + /// Installing the ItemSorter does the actual work of sorting the ListViewItems. + /// See ColumnComparer in the code for an example of what an ItemSorter has to do. + /// + /// + /// Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects() + /// method of the IVirtualListDataSource instead. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortDelegate CustomSorter { + get { return customSorter; } + set { customSorter = value; } + } + private SortDelegate customSorter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular header. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to not show any tooltip). + /// + /// + /// Installing a HeaderToolTipGetter takes precedence over any text in OLVColumn.ToolTipText. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return headerToolTipGetter; } + set { headerToolTipGetter = value; } + } + private HeaderToolTipGetterDelegate headerToolTipGetter; + + /// + /// This delegate can be used to format a OLVListItem before it is added to the control. + /// + /// + /// The model object for the row can be found through the RowObject property of the OLVListItem object. + /// All subitems normally have the same style as list item, so setting the forecolor on one + /// subitem changes the forecolor of all subitems. + /// To allow subitems to have different attributes, do this: + /// myListViewItem.UseItemStyleForSubItems = false;. + /// + /// If UseAlternatingBackColors is true, the backcolor of the listitem will be calculated + /// by the control and cannot be controlled by the RowFormatter delegate. + /// In general, trying to use a RowFormatter + /// when UseAlternatingBackColors is true does not work well. + /// As it says in the summary, this is called before the item is added to the control. + /// Many properties of the OLVListItem itself are not available at that point, including: + /// Index, Selected, Focused, Bounds, Checked, DisplayIndex. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowFormatterDelegate RowFormatter { + get { return rowFormatter; } + set { rowFormatter = value; } + } + private RowFormatterDelegate rowFormatter; + + #endregion + + #region List commands + + /// + /// Add the given model object to this control. + /// + /// The model object to be displayed + /// See AddObjects() for more details + public virtual void AddObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.AddObject(modelObject); }); + else + this.AddObjects(new object[] { modelObject }); + } + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public virtual void AddObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.AddObjects(modelObjects); }); + return; + } + this.InsertObjects(ObjectListView.EnumerableCount(this.Objects), modelObjects); + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Resize the columns to the maximum of the header width and the data. + /// + public virtual void AutoResizeColumns() { + foreach (OLVColumn c in this.Columns) { + this.AutoResizeColumn(c.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + } + } + + /// + /// Set up any automatically initialized column widths (columns that + /// have a width of 0 or -1 will be resized to the width of their + /// contents or header respectively). + /// + /// + /// Obviously, this will only work once. Once it runs, the columns widths will + /// be changed to something else (other than 0 or -1), so it wont do anything the + /// second time through. Use to force all columns + /// to change their size. + /// + public virtual void AutoSizeColumns() { + // If we are supposed to resize to content, but if there is no content, + // resize to the header size instead. + ColumnHeaderAutoResizeStyle resizeToContentStyle = this.GetItemCount() == 0 ? + ColumnHeaderAutoResizeStyle.HeaderSize : + ColumnHeaderAutoResizeStyle.ColumnContent; + foreach (ColumnHeader column in this.Columns) { + switch (column.Width) { + case 0: + this.AutoResizeColumn(column.Index, resizeToContentStyle); + break; + case -1: + this.AutoResizeColumn(column.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + break; + } + } + } + + /// + /// Organise the view items into groups, based on the last sort column or the first column + /// if there is no last sort column + /// + public virtual void BuildGroups() { + this.BuildGroups(this.PrimarySortColumn, this.PrimarySortOrder == SortOrder.None ? SortOrder.Ascending : this.PrimarySortOrder); + } + + /// + /// Organise the view items into groups, based on the given column + /// + /// + /// + /// If the AlwaysGroupByColumn property is not null, + /// the list view items will be organised by that column, + /// and the 'column' parameter will be ignored. + /// + /// This method triggers sorting events: BeforeSorting and AfterSorting. + /// + /// The column whose values should be used for sorting. + /// + public virtual void BuildGroups(OLVColumn column, SortOrder order) { + // Sanity + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(column, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, + args.ColumnToSort, args.SortOrder, args.SecondaryColumnToSort, args.SecondarySortOrder); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + private BeforeSortingEventArgs BuildBeforeSortingEventArgs(OLVColumn column, SortOrder order) { + OLVColumn groupBy = this.AlwaysGroupByColumn ?? column ?? this.GetColumn(0); + SortOrder groupByOrder = this.AlwaysGroupBySortOrder; + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + if (groupByOrder == SortOrder.None) + groupByOrder = order; + + BeforeSortingEventArgs args = new BeforeSortingEventArgs( + groupBy, groupByOrder, + column, order, + this.SecondarySortColumn ?? this.GetColumn(0), + this.SecondarySortOrder == SortOrder.None ? order : this.SecondarySortOrder); + if (column != null) + args.Canceled = !column.Sortable; + return args; + } + + /// + /// Organise the view items into groups, based on the given columns + /// + /// What column will be used for grouping + /// What ordering will be used for groups + /// The column whose values should be used for sorting. Cannot be null + /// The order in which the values from column will be sorted + /// When the values from 'column' are equal, use the values provided by this column + /// How will the secondary values be sorted + /// This method does not trigger sorting events. Use BuildGroups() to do that + public virtual void BuildGroups(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + // Sanity checks + if (groupByColumn == null) + return; + + // Getting the Count forces any internal cache of the ListView to be flushed. Without + // this, iterating over the Items will not work correctly if the ListView handle + // has not yet been created. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int dummy = this.Items.Count; +#pragma warning restore 168 + + // Collect all the information that governs the creation of groups + GroupingParameters parms = this.CollectGroupingParameters(groupByColumn, groupByOrder, + column, order, secondaryColumn, secondaryOrder); + + // Trigger an event to let the world create groups if they want + CreateGroupsEventArgs args = new CreateGroupsEventArgs(parms); + if (parms.GroupByColumn != null) + args.Canceled = !parms.GroupByColumn.Groupable; + this.OnBeforeCreatingGroups(args); + if (args.Canceled) + return; + + // If the event didn't create them for us, use our default strategy + if (args.Groups == null) + args.Groups = this.MakeGroups(parms); + + // Give the world a chance to munge the groups before they are created + this.OnAboutToCreateGroups(args); + if (args.Canceled) + return; + + // Create the groups now + this.OLVGroups = args.Groups; + this.CreateGroups(args.Groups); + + // Tell the world that new groups have been created + this.OnAfterCreatingGroups(args); + lastGroupingParameters = args.Parameters; + } + private GroupingParameters lastGroupingParameters; + + /// + /// Collect and return all the variables that influence the creation of groups + /// + /// + protected virtual GroupingParameters CollectGroupingParameters(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn sortByColumn, SortOrder sortByOrder, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + + // If the user tries to group by a non-groupable column, keep the current group by + // settings, but use the non-groupable column for sorting + if (!groupByColumn.Groupable && lastGroupingParameters != null) { + sortByColumn = groupByColumn; + sortByOrder = groupByOrder; + groupByColumn = lastGroupingParameters.GroupByColumn; + groupByOrder = lastGroupingParameters.GroupByOrder; + } + + string titleFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountFormatOrDefault : null; + string titleSingularFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountSingularFormatOrDefault : null; + GroupingParameters parms = new GroupingParameters(this, groupByColumn, groupByOrder, + sortByColumn, sortByOrder, secondaryColumn, secondaryOrder, + titleFormat, titleSingularFormat, + this.SortGroupItemsByPrimaryColumn && this.AlwaysGroupByColumn == null); + return parms; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// The list of groups to be created + /// This should not change the state of the control. It is possible that the + /// groups created will not be used. They may simply be discarded. + protected virtual IList MakeGroups(GroupingParameters parms) { + + // There is a lot of overlap between this method and FastListGroupingStrategy.MakeGroups() + // Any changes made here may need to be reflected there + + // Separate the list view items into groups, using the group key as the descrimanent + NullableDictionary> map = new NullableDictionary>(); + foreach (OLVListItem olvi in parms.ListView.Items) { + object key = parms.GroupByColumn.GetGroupKey(olvi.RowObject); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(olvi); + } + + // Sort the items within each group (unless specifically turned off) + OLVColumn sortColumn = parms.SortItemsByPrimaryColumn ? parms.ListView.GetColumn(0) : parms.PrimarySort; + if (sortColumn != null && parms.PrimarySortOrder != SortOrder.None) { + IComparer itemSorter = parms.ItemComparer ?? + new ColumnComparer(sortColumn, parms.PrimarySortOrder, parms.SecondarySort, parms.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(itemSorter); + } + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parms.CreateGroup(key, map[key].Count, HasCollapsibleGroups); + lvg.Items = map[key]; + if (parms.GroupByColumn.GroupFormatter != null) + parms.GroupByColumn.GroupFormatter(lvg, parms); + groups.Add(lvg); + } + + // Sort the groups + if (parms.GroupByOrder != SortOrder.None) + groups.Sort(parms.GroupComparer ?? new OLVGroupComparer(parms.GroupByOrder)); + + return groups; + } + + /// + /// Build/rebuild all the list view items in the list, preserving as much state as is possible + /// + public virtual void BuildList() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.BuildList)); + else + this.BuildList(true); + } + + /// + /// Build/rebuild all the list view items in the list + /// + /// If this is true, the control will try to preserve the selection, + /// focused item, and the scroll position (see Remarks) + /// + /// + /// + /// Use this method in situations were the contents of the list is basically the same + /// as previously. + /// + /// + public virtual void BuildList(bool shouldPreserveState) { + if (this.Frozen) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + this.ApplyExtendedStyles(); + this.ClearHotItem(); + int previousTopIndex = this.TopItemIndex; + Point currentScrollPosition = this.LowLevelScrollPosition; + + IList previousSelection = new ArrayList(); + Object previousFocus = null; + if (shouldPreserveState && this.objects != null) { + previousSelection = this.SelectedObjects; + OLVListItem focusedItem = this.FocusedItem as OLVListItem; + if (focusedItem != null) + previousFocus = focusedItem.RowObject; + } + + IEnumerable objectsToDisplay = this.FilteredObjects; + + this.BeginUpdate(); + try { + this.Items.Clear(); + this.ListViewItemSorter = null; + + if (objectsToDisplay != null) { + // Build a list of all our items and then display them. (Building + // a list and then doing one AddRange is about 10-15% faster than individual adds) + List itemList = new List(); // use ListViewItem to avoid co-variant conversion + foreach (object rowObject in objectsToDisplay) { + OLVListItem lvi = new OLVListItem(rowObject); + this.FillInValues(lvi, rowObject); + itemList.Add(lvi); + } + this.Items.AddRange(itemList.ToArray()); + this.Sort(); + + if (shouldPreserveState) { + this.SelectedObjects = previousSelection; + this.FocusedItem = this.ModelToItem(previousFocus); + } + } + } finally { + this.EndUpdate(); + } + + this.RefreshHotItem(); + + // We can only restore the scroll position after the EndUpdate() because + // of caching that the ListView does internally during a BeginUpdate/EndUpdate pair. + if (shouldPreserveState) { + // Restore the scroll position. TopItemIndex is best, but doesn't work + // when the control is grouped. + if (this.ShowGroups) + this.LowLevelScroll(currentScrollPosition.X, currentScrollPosition.Y); + else + this.TopItemIndex = previousTopIndex; + } + + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Building list for {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + /// + /// Clear any cached info this list may have been using + /// + public virtual void ClearCachedInfo() + { + // ObjectListView doesn't currently cache information but subclass do (or might) + } + + /// + /// Apply all required extended styles to our control. + /// + /// + /// + /// Whenever .NET code sets an extended style, it erases all other extended styles + /// that it doesn't use. So, we have to explicit reapply the styles that we have + /// added. + /// + /// + /// Normally, we would override CreateParms property and update + /// the ExStyle member, but ListView seems to ignore all ExStyles that + /// it doesn't already know about. Worse, when we set the LVS_EX_HEADERINALLVIEWS + /// value, bad things happen (the control crashes!). + /// + /// + protected virtual void ApplyExtendedStyles() { + const int LVS_EX_SUBITEMIMAGES = 0x00000002; + //const int LVS_EX_TRANSPARENTBKGND = 0x00400000; + const int LVS_EX_HEADERINALLVIEWS = 0x02000000; + + const int STYLE_MASK = LVS_EX_SUBITEMIMAGES | LVS_EX_HEADERINALLVIEWS; + int style = 0; + + if (this.ShowImagesOnSubItems && !this.VirtualMode) + style ^= LVS_EX_SUBITEMIMAGES; + + if (this.ShowHeaderInAllViews) + style ^= LVS_EX_HEADERINALLVIEWS; + + NativeMethods.SetExtendedStyle(this, style, STYLE_MASK); + } + + /// + /// Give the listview a reasonable size of its tiles, based on the number of lines of + /// information that each tile is going to display. + /// + public virtual void CalculateReasonableTileSize() { + if (this.Columns.Count <= 0) + return; + + List columns = this.AllColumns.FindAll(delegate(OLVColumn x) { + return (x.Index == 0) || x.IsTileViewColumn; + }); + + int imageHeight = (this.LargeImageList == null ? 16 : this.LargeImageList.ImageSize.Height); + int dataHeight = (this.Font.Height + 1) * columns.Count; + int tileWidth = (this.TileSize.Width == 0 ? 200 : this.TileSize.Width); + int tileHeight = Math.Max(this.TileSize.Height, Math.Max(imageHeight, dataHeight)); + this.TileSize = new Size(tileWidth, tileHeight); + } + + /// + /// Rebuild this list for the given view + /// + /// + public virtual void ChangeToFilteredColumns(View view) { + // Store the state + this.SuspendSelectionEvents(); + IList previousSelection = this.SelectedObjects; + int previousTopIndex = this.TopItemIndex; + + this.Freeze(); + this.Clear(); + List columns = this.GetFilteredColumns(view); + if (view == View.Details || this.ShowHeaderInAllViews) { + // Make sure all columns have a reasonable LastDisplayIndex + for (int index = 0; index < columns.Count; index++) + { + if (columns[index].LastDisplayIndex == -1) + columns[index].LastDisplayIndex = index; + } + // ListView will ignore DisplayIndex FOR ALL COLUMNS if there are any errors, + // e.g. duplicates (two columns with the same DisplayIndex) or gaps. + // LastDisplayIndex isn't guaranteed to be unique, so we just sort the columns by + // the last position they were displayed and use that to generate a sequence + // we can use for the DisplayIndex values. + List columnsInDisplayOrder = new List(columns); + columnsInDisplayOrder.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + int i = 0; + foreach (OLVColumn col in columnsInDisplayOrder) + col.DisplayIndex = i++; + } + +// ReSharper disable once CoVariantArrayConversion + this.Columns.AddRange(columns.ToArray()); + if (view == View.Details || this.ShowHeaderInAllViews) + this.ShowSortIndicator(); + this.UpdateFiltering(); + this.Unfreeze(); + + // Restore the state + this.SelectedObjects = previousSelection; + this.TopItemIndex = previousTopIndex; + this.ResumeSelectionEvents(); + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public virtual void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else + this.SetObjects(null); + } + + /// + /// Reset the memory of which URLs have been visited + /// + public virtual void ClearUrlVisited() { + this.visitedUrlMap = new Dictionary(); + } + + /// + /// Copy a text and html representation of the selected rows onto the clipboard. + /// + /// Be careful when using this with virtual lists. If the user has selected + /// 10,000,000 rows, this method will faithfully try to copy all of them to the clipboard. + /// From the user's point of view, your program will appear to have hung. + public virtual void CopySelectionToClipboard() { + IList selection = this.SelectedObjects; + if (selection.Count == 0) + return; + + // Use the DragSource object to create the data object, if so configured. + // This relies on the assumption that DragSource will handle the selected objects only. + // It is legal for StartDrag to return null. + object data = null; + if (this.CopySelectionOnControlCUsesDragSource && this.DragSource != null) + data = this.DragSource.StartDrag(this, MouseButtons.Left, this.ModelToItem(selection[0])); + + Clipboard.SetDataObject(data ?? new OLVDataObject(this, selection)); + } + + /// + /// Copy a text and html representation of the given objects onto the clipboard. + /// + public virtual void CopyObjectsToClipboard(IList objectsToCopy) { + if (objectsToCopy.Count == 0) + return; + + // We don't know where these objects came from, so we can't use the DragSource to create + // the data object, like we do with CopySelectionToClipboard() above. + OLVDataObject dataObject = new OLVDataObject(this, objectsToCopy); + dataObject.CreateTextFormats(); + Clipboard.SetDataObject(dataObject); + } + + /// + /// Return a html representation of the given objects + /// + public virtual string ObjectsToHtml(IList objectsToConvert) { + if (objectsToConvert.Count == 0) + return String.Empty; + + OLVExporter exporter = new OLVExporter(this, objectsToConvert); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Deselect all rows in the listview + /// + public virtual void DeselectAll() { + NativeMethods.DeselectAllItems(this); + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A ListViewItem + public virtual OLVListItem GetNextItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + bool isFound = (itemToFind == null); + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + if (isFound) + return olvi; + isFound = (itemToFind == olvi); + } + } + return null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(0); + if (itemToFind.Index == this.GetItemCount() - 1) + return null; + return this.GetItem(itemToFind.Index + 1); + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public virtual OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return this.GetItem(this.GetItemCount() - 1); + + if (this.Groups.Count > 0) { + ListViewGroup lastGroup = this.Groups[this.Groups.Count - 1]; + if (lastGroup.Items.Count > 0) + return (OLVListItem)lastGroup.Items[lastGroup.Items.Count - 1]; + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.Groups.Count == 0) + return this.GetItem(n); + + foreach (ListViewGroup group in this.Groups) { + if (n < group.Items.Count) + return (OLVListItem)group.Items[n]; + + n -= group.Items.Count; + } + + return null; + } + + /// + /// Return the display index of the given listviewitem index. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups || this.Groups.Count == 0) + return itemIndex; + + // TODO: This could be optimized + int i = 0; + foreach (ListViewGroup lvg in this.Groups) { + foreach (ListViewItem lvi in lvg.Items) { + if (lvi.Index == itemIndex) + return i; + i++; + } + } + + return -1; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public virtual OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + OLVListItem previousItem = null; + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem lvi in group.Items) { + if (lvi == itemToFind) + return previousItem; + + previousItem = lvi; + } + } + return itemToFind == null ? previousItem : null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(this.GetItemCount() - 1); + if (itemToFind.Index == 0) + return null; + return this.GetItem(itemToFind.Index - 1); + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// + /// + /// This operation only makes sense of non-sorted, non-grouped + /// lists, since any subsequent sort/group operation will rearrange + /// the list. + /// + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { + this.InsertObjects(index, modelObjects); + }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToAdd; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + // If we are filtering the list, there is no way to efficiently + // insert the objects, so just put them into our collection and rebuild. + // Sigh -- yet another ListView anomoly. In every view except Details, an item + // inserted into the Items collection always appear at the end regardless of + // their actual insertion index. + if (this.IsFiltering || this.View != View.Details) { + index = Math.Max(0, Math.Min(index, ourObjects.Count)); + ourObjects.InsertRange(index, modelObjects); + this.BuildList(true); + } else { + this.ListViewItemSorter = null; + index = Math.Max(0, Math.Min(index, this.GetItemCount())); + int i = index; + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + ourObjects.Insert(i, modelObject); + OLVListItem lvi = new OLVListItem(modelObject); + this.FillInValues(lvi, modelObject); + this.Items.Insert(i, lvi); + i++; + } + } + + for (i = index; i < this.GetItemCount(); i++) { + OLVListItem lvi = this.GetItem(i); + this.SetSubItemImages(lvi.Index, lvi); + } + + this.PostProcessRows(); + } + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Return true if the row representing the given model is selected + /// + /// The model object to look for + /// Is the row selected + public bool IsSelected(object model) { + OLVListItem item = this.ModelToItem(model); + return item != null && item.Selected; + } + + /// + /// Has the given URL been visited? + /// + /// The string to be consider + /// Has it been visited + public virtual bool IsUrlVisited(string url) { + return this.visitedUrlMap.ContainsKey(url); + } + + /// + /// Scroll the ListView by the given deltas. + /// + /// Horizontal delta + /// Vertical delta + public void LowLevelScroll(int dx, int dy) { + NativeMethods.Scroll(this, dx, dy); + } + + /// + /// Return a point that represents the current horizontal and vertical scroll positions + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Point LowLevelScrollPosition + { + get { + return new Point(NativeMethods.GetScrollPosition(this, true), NativeMethods.GetScrollPosition(this, false)); + } + } + + /// + /// Remember that the given URL has been visited + /// + /// The url to be remembered + /// This does not cause the control be redrawn + public virtual void MarkUrlVisited(string url) { + this.visitedUrlMap[url] = true; + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public virtual void MoveObjects(int index, ICollection modelObjects) { + + // We are going to remove all the given objects from our list + // and then insert them at the given location + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = this.IndexOf(modelObject); + if (i >= 0) { + indicesToRemove.Add(i); + ourObjects.Remove(modelObject); + if (i <= index) + index--; + } + } + } + + // Remove the objects in reverse order so earlier + // deletes don't change the index of later ones + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + try { + this.BeginUpdate(); + foreach (int i in indicesToRemove) { + this.Items.RemoveAt(i); + } + this.InsertObjects(index, modelObjects); + } finally { + this.EndUpdate(); + } + } + + /// + /// Calculate what item is under the given point? + /// + /// + /// + /// + public new ListViewHitTestInfo HitTest(int x, int y) { + // Everything costs something. Playing with the layout of the header can cause problems + // with the hit testing. If the header shrinks, the underlying control can throw a tantrum. + try { + return base.HitTest(x, y); + } catch (ArgumentOutOfRangeException) { + return new ListViewHitTestInfo(null, null, ListViewHitTestLocations.None); + } + } + + /// + /// Perform a hit test using the Windows control's SUBITEMHITTEST message. + /// This provides information about group hits that the standard ListView.HitTest() does not. + /// + /// + /// + /// + protected OlvListViewHitTestInfo LowLevelHitTest(int x, int y) { + + // If it's not even in the control, don't bother with anything else + if (!this.ClientRectangle.Contains(x, y)) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // If there are no columns, also don't bother with anything else + if (this.Columns.Count == 0) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // Is the point over the header? + OlvListViewHitTestInfo.HeaderHitTestInfo headerHitTestInfo = this.HeaderControl.HitTest(x, y); + if (headerHitTestInfo != null) + return new OlvListViewHitTestInfo(this, headerHitTestInfo.ColumnIndex, headerHitTestInfo.IsOverCheckBox, headerHitTestInfo.OverDividerIndex); + + // Call the native hit test method, which is a little confusing. + NativeMethods.LVHITTESTINFO lParam = new NativeMethods.LVHITTESTINFO(); + lParam.pt_x = x; + lParam.pt_y = y; + int index = NativeMethods.HitTest(this, ref lParam); + + // Setup the various values we need to make our hit test structure + bool isGroupHit = (lParam.flags & (int)HitTestLocationEx.LVHT_EX_GROUP) != 0; + OLVListItem hitItem = isGroupHit || index == -1 ? null : this.GetItem(index); + OLVListSubItem subItem = (this.View == View.Details && hitItem != null) ? hitItem.GetSubItem(lParam.iSubItem) : null; + + // Figure out which group is involved in the hit test. This is a little complicated: + // If the list is virtual: + // - the returned value is list view item index + // - iGroup is the *index* of the hit group. + // If the list is not virtual: + // - iGroup is always -1. + // - if the point is over a group, the returned value is the *id* of the hit group. + // - if the point is not over a group, the returned value is list view item index. + OLVGroup group = null; + if (this.ShowGroups && this.OLVGroups != null) { + if (this.VirtualMode) { + group = lParam.iGroup >= 0 && lParam.iGroup < this.OLVGroups.Count ? this.OLVGroups[lParam.iGroup] : null; + } else { + if (isGroupHit) { + foreach (OLVGroup olvGroup in this.OLVGroups) { + if (olvGroup.GroupId == index) { + group = olvGroup; + break; + } + } + } + } + } + OlvListViewHitTestInfo olvListViewHitTest = new OlvListViewHitTestInfo(hitItem, subItem, lParam.flags, group, lParam.iSubItem); + // System.Diagnostics.Debug.WriteLine(String.Format("HitTest({0}, {1})=>{2}", x, y, olvListViewHitTest)); + return olvListViewHitTest; + } + + /// + /// What is under the given point? This takes the various parts of a cell into account, including + /// any custom parts that a custom renderer might use + /// + /// + /// + /// An information block about what is under the point + public virtual OlvListViewHitTestInfo OlvHitTest(int x, int y) { + OlvListViewHitTestInfo hti = this.LowLevelHitTest(x, y); + + // There is a bug/"feature" of the ListView concerning hit testing. + // If FullRowSelect is false and the point is over cell 0 but not on + // the text or icon, HitTest will not register a hit. We could turn + // FullRowSelect on, do the HitTest, and then turn it off again, but + // toggling FullRowSelect in that way messes up the tooltip in the + // underlying control. So we have to find another way. + // + // It's too hard to try to write the hit test from scratch. Grouping (for + // example) makes it just too complicated. So, we have to use HitTest + // but try to get around its limits. + // + // First step is to determine if the point was within column 0. + // If it was, then we only have to determine if there is an actual row + // under the point. If there is, then we know that the point is over cell 0. + // So we try a Battleship-style approach: is there a subcell to the right + // of cell 0? This will return a false negative if column 0 is the rightmost column, + // so we also check for a subcell to the left. But if only column 0 is visible, + // then that will fail too, so we check for something at the very left of the + // control. + // + // This will still fail under pathological conditions. If column 0 fills + // the whole listview and no part of the text column 0 is visible + // (because it is horizontally scrolled offscreen), then the hit test will fail. + + // Are we in the buggy context? Details view, not full row select, and + // failing to find anything + if (hti.Item == null && !this.FullRowSelect && this.View == View.Details) { + // Is the point within the column 0? If it is, maybe it should have been a hit. + // Let's test slightly to the right and then to left of column 0. Hopefully one + // of those will hit a subitem + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + if (x >= sides.X && x <= sides.Y) { + // We look for: + // - any subitem to the right of cell 0? + // - any subitem to the left of cell 0? + // - cell 0 at the left edge of the screen + hti = this.LowLevelHitTest(sides.Y + 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(sides.X - 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(4, y); + + if (hti.Item != null) { + // We hit something! So, the original point must have been in cell 0 + hti.ColumnIndex = 0; + hti.SubItem = hti.Item.GetSubItem(0); + hti.Location = ListViewHitTestLocations.None; + hti.HitTestLocation = HitTestLocation.InCell; + } + } + } + + if (this.OwnerDraw) + this.CalculateOwnerDrawnHitTest(hti, x, y); + else + this.CalculateStandardHitTest(hti, x, y); + + return hti; + } + + /// + /// Perform a hit test when the control is not owner drawn + /// + /// + /// + /// + protected virtual void CalculateStandardHitTest(OlvListViewHitTestInfo hti, int x, int y) { + + // Standard hit test works fine for the primary column + if (this.View != View.Details || hti.ColumnIndex == 0 || + hti.SubItem == null || hti.Column == null) + return; + + Rectangle cellBounds = hti.SubItem.Bounds; + bool hasImage = (this.GetActualImageIndex(hti.SubItem.ImageSelector) != -1); + + // Unless we say otherwise, it was an general incell hit + hti.HitTestLocation = HitTestLocation.InCell; + + // Check if the point is over where an image should be. + // If there is a checkbox or image there, tag it and exit. + Rectangle r = cellBounds; + r.Width = this.SmallImageSize.Width; + if (r.Contains(x, y)) { + if (hti.Column.CheckBoxes) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + if (hasImage) { + hti.HitTestLocation = HitTestLocation.Image; + return; + } + } + + // Figure out where the text actually is and if the point is in it + // The standard HitTest assumes that any point inside a subitem is + // a hit on Text -- which is clearly not true. + Rectangle textBounds = cellBounds; + textBounds.X += 4; + if (hasImage) + textBounds.X += this.SmallImageSize.Width; + + Size proposedSize = new Size(textBounds.Width, textBounds.Height); + Size textSize = TextRenderer.MeasureText(hti.SubItem.Text, this.Font, proposedSize, TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix); + textBounds.Width = textSize.Width; + + switch (hti.Column.TextAlign) { + case HorizontalAlignment.Center: + textBounds.X += (cellBounds.Right - cellBounds.Left - textSize.Width) / 2; + break; + case HorizontalAlignment.Right: + textBounds.X = cellBounds.Right - textSize.Width; + break; + } + if (textBounds.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + } + } + + /// + /// Perform a hit test when the control is owner drawn. This hands off responsibility + /// to the renderer. + /// + /// + /// + /// + protected virtual void CalculateOwnerDrawnHitTest(OlvListViewHitTestInfo hti, int x, int y) { + // If the click wasn't on an item, give up + if (hti.Item == null) + return; + + // If the list is showing column, but they clicked outside the columns, also give up + if (this.View == View.Details && hti.Column == null) + return; + + // Which renderer was responsible for drawing that point + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(hti.RowObject, hti.Column) + : this.ItemRenderer; + + // We can't decide who was responsible. Give up + if (renderer == null) + return; + + // Ask the responsible renderer what is at that point + renderer.HitTest(hti, x, y); + } + + /// + /// Pause (or unpause) all animations in the list + /// + /// true to pause, false to unpause + public virtual void PauseAnimations(bool isPause) { + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + ImageRenderer renderer = col.Renderer as ImageRenderer; + if (renderer != null) { + renderer.ListView = this; + renderer.Paused = isPause; + } + } + } + + /// + /// Rebuild the columns based upon its current view and column visibility settings + /// + public virtual void RebuildColumns() { + this.ChangeToFilteredColumns(this.View); + } + + /// + /// Remove the given model object from the ListView + /// + /// The model to be removed + /// See RemoveObjects() for more details + /// This method is thread-safe. + /// + public virtual void RemoveObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.RemoveObject(modelObject); }); + else + this.RemoveObjects(new object[] { modelObject }); + } + + /// + /// Remove all of the given objects from the control. + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// This method is thread-safe. + /// + public virtual void RemoveObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.RemoveObjects(modelObjects); }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToRemove; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { +// ReSharper disable PossibleMultipleEnumeration + int i = ourObjects.IndexOf(modelObject); + if (i >= 0) + ourObjects.RemoveAt(i); +// ReSharper restore PossibleMultipleEnumeration + i = this.IndexOf(modelObject); + if (i >= 0) + this.Items.RemoveAt(i); + } + } + this.PostProcessRows(); + + // Tell the world that the list has changed + this.UnsubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Select all rows in the listview + /// + public virtual void SelectAll() { + NativeMethods.SelectAllItems(this); + } + + /// + /// Set the given image to be fixed in the bottom right of the list view. + /// This image will not scroll when the list view scrolls. + /// + /// + /// + /// This method uses ListView's native ability to display a background image. + /// It has a few limitations: + /// + /// + /// It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself, + /// including its background, which covers the background image. + /// It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image. + /// It does not work at all on XP. + /// Obviously, it doesn't look good when alternate row background colors are enabled. + /// + /// + /// If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not + /// translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that + /// they work correctly even in MDI applications. + /// + /// Setting this clears any background image. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundWatermark(Image image) { + NativeMethods.SetBackgroundImage(this, image, true, false, 0, 0); + } + + /// + /// Set the given image to be background of the ListView so that it appears at the given + /// percentage offsets within the list. + /// + /// + /// This has the same limitations as described in . Make sure those limitations + /// are understood before using the method. + /// This is very similar to setting the property of the standard .NET ListView, except that the standard + /// BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This + /// method does not have that problem. + /// Setting this clears any background watermark. + /// + /// The image to be drawn. If null, any existing image will be removed. + /// The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// The vertical percentage where the image will be placed. + public void SetNativeBackgroundImage(Image image, int xOffset, int yOffset) { + NativeMethods.SetBackgroundImage(this, image, false, false, xOffset, yOffset); + } + + /// + /// Set the given image to be the tiled background of the ListView. + /// + /// + /// This has the same limitations as described in and . + /// Make sure those limitations + /// are understood before using the method. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundTiledImage(Image image) { + NativeMethods.SetBackgroundImage(this, image, false, true, 0, 0); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + public virtual void SetObjects(IEnumerable collection) { + this.SetObjects(collection, false); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + /// Should the state of the list be preserved as far as is possible. + public virtual void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(this.objects, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + collection = args.NewObjects; + + // If we own the current list and they change to another list, we don't own it any more + if (this.isOwnerOfObjects && !ReferenceEquals(this.objects, collection)) + this.isOwnerOfObjects = false; + this.objects = collection; + this.BuildList(preserveState); + + // Tell the world that the list has changed + this.UpdateNotificationSubscriptions(this.objects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + + /// + /// Update the given model object into the ListView. The model will be added if it doesn't already exist. + /// + /// The model to be updated + /// + /// + /// See for more details + /// + /// This method is thread-safe. + /// This method will cause the list to be resorted. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.UpdateObject(modelObject); }); + else + this.UpdateObjects(new object[] { modelObject }); + } + + /// + /// Update the pre-existing models that are equal to the given objects. If any of the model doesn't + /// already exist in the control, they will be added. + /// + /// Collection of objects to be updated/added + /// + /// This method will cause the list to be resorted. + /// Nulls are silently ignored. + /// This method is thread-safe. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.UpdateObjects(modelObjects); }); + return; + } + if (modelObjects == null || modelObjects.Count == 0) + return; + + this.BeginUpdate(); + try { + this.UnsubscribeNotifications(modelObjects); + + ArrayList objectsToAdd = new ArrayList(); + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = ourObjects.IndexOf(modelObject); + if (i < 0) + objectsToAdd.Add(modelObject); + else { + ourObjects[i] = modelObject; + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + olvi.RowObject = modelObject; + this.RefreshItem(olvi); + } + } + } + } + this.PostProcessRows(); + + this.AddObjects(objectsToAdd); + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change any subscriptions to INotifyPropertyChanged events on our current + /// model objects so that we no longer listen for events on the old models + /// and do listen for events on the given collection. + /// + /// This does nothing if UseNotifyPropertyChanged is false. + /// + protected virtual void UpdateNotificationSubscriptions(IEnumerable collection) { + if (!this.UseNotifyPropertyChanged) + return; + + // We could calculate a symmetric difference between the old models and the new models + // except that we don't have the previous models at this point. + + this.UnsubscribeNotifications(null); + this.SubscribeNotifications(collection ?? this.Objects); + } + + /// + /// Gets or sets whether or not ObjectListView should subscribe to INotifyPropertyChanged + /// events on the model objects that it is given. + /// + /// + /// + /// This should be set before calling SetObjects(). If you set this to false, + /// ObjectListView will unsubscribe to all current model objects. + /// + /// If you set this to true on a virtual list, the ObjectListView will + /// walk all the objects in the list trying to subscribe to change notifications. + /// If you have 10,000,000 items in your virtual list, this may take some time. + /// + [Category("ObjectListView"), + Description("Should ObjectListView listen for property changed events on the model objects?"), + DefaultValue(false)] + public bool UseNotifyPropertyChanged { + get { return this.useNotifyPropertyChanged; } + set { + if (this.useNotifyPropertyChanged == value) + return; + this.useNotifyPropertyChanged = value; + if (value) + this.SubscribeNotifications(this.Objects); + else + this.UnsubscribeNotifications(null); + } + } + private bool useNotifyPropertyChanged; + + /// + /// Subscribe to INotifyPropertyChanges on the given collection of objects. + /// + /// + protected void SubscribeNotifications(IEnumerable models) { + if (!this.UseNotifyPropertyChanged || models == null) + return; + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null && !subscribedModels.ContainsKey(notifier)) { + notifier.PropertyChanged += HandleModelOnPropertyChanged; + subscribedModels[notifier] = notifier; + } + } + } + + /// + /// Unsubscribe from INotifyPropertyChanges on the given collection of objects. + /// If the given collection is null, unsubscribe from all current subscriptions + /// + /// + protected void UnsubscribeNotifications(IEnumerable models) { + if (models == null) { + foreach (INotifyPropertyChanged notifier in this.subscribedModels.Keys) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + } + subscribedModels = new Hashtable(); + } else { + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + subscribedModels.Remove(notifier); + } + } + } + } + + private void HandleModelOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { + // System.Diagnostics.Debug.WriteLine(String.Format("PropertyChanged: '{0}' on '{1}", propertyChangedEventArgs.PropertyName, sender)); + this.RefreshObject(sender); + } + + private Hashtable subscribedModels = new Hashtable(); + + #endregion + + #region Save/Restore State + + /// + /// Return a byte array that represents the current state of the ObjectListView, such + /// that the state can be restored by RestoreState() + /// + /// + /// The state of an ObjectListView includes the attributes that the user can modify: + /// + /// current view (i.e. Details, Tile, Large Icon...) + /// sort column and direction + /// column order + /// column widths + /// column visibility + /// + /// + /// + /// It does not include selection or the scroll position. + /// + /// + /// A byte array representing the state of the ObjectListView + public virtual byte[] SaveState() { + ObjectListViewState olvState = new ObjectListViewState(); + olvState.VersionNumber = 1; + olvState.NumberOfColumns = this.AllColumns.Count; + olvState.CurrentView = this.View; + + // If we have a sort column, it is possible that it is not currently being shown, in which + // case, it's Index will be -1. So we calculate its index directly. Technically, the sort + // column does not even have to a member of AllColumns, in which case IndexOf will return -1, + // which is works fine since we have no way of restoring such a column anyway. + if (this.PrimarySortColumn != null) + olvState.SortColumn = this.AllColumns.IndexOf(this.PrimarySortColumn); + olvState.LastSortOrder = this.PrimarySortOrder; + olvState.IsShowingGroups = this.ShowGroups; + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + foreach (OLVColumn column in this.AllColumns) { + olvState.ColumnIsVisible.Add(column.IsVisible); + olvState.ColumnDisplayIndicies.Add(column.LastDisplayIndex); + olvState.ColumnWidths.Add(column.Width); + } + + // Now that we have stored our state, convert it to a byte array + using (MemoryStream ms = new MemoryStream()) { + BinaryFormatter serializer = new BinaryFormatter(); + serializer.AssemblyFormat = FormatterAssemblyStyle.Simple; + serializer.Serialize(ms, olvState); + return ms.ToArray(); + } + } + + /// + /// Restore the state of the control from the given string, which must have been + /// produced by SaveState() + /// + /// A byte array returned from SaveState() + /// Returns true if the state was restored + public virtual bool RestoreState(byte[] state) { + using (MemoryStream ms = new MemoryStream(state)) { + BinaryFormatter deserializer = new BinaryFormatter(); + ObjectListViewState olvState; + try { + olvState = deserializer.Deserialize(ms) as ObjectListViewState; + } catch (System.Runtime.Serialization.SerializationException) { + return false; + } + // The number of columns has changed. We have no way to match old + // columns to the new ones, so we just give up. + if (olvState == null || olvState.NumberOfColumns != this.AllColumns.Count) + return false; + if (olvState.SortColumn == -1) { + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + } else { + this.PrimarySortColumn = this.AllColumns[olvState.SortColumn]; + this.PrimarySortOrder = olvState.LastSortOrder; + } + for (int i = 0; i < olvState.NumberOfColumns; i++) { + OLVColumn column = this.AllColumns[i]; + column.Width = (int)olvState.ColumnWidths[i]; + column.IsVisible = (bool)olvState.ColumnIsVisible[i]; + column.LastDisplayIndex = (int)olvState.ColumnDisplayIndicies[i]; + } +// ReSharper disable RedundantCheckBeforeAssignment + if (olvState.IsShowingGroups != this.ShowGroups) +// ReSharper restore RedundantCheckBeforeAssignment + this.ShowGroups = olvState.IsShowingGroups; + if (this.View == olvState.CurrentView) + this.RebuildColumns(); + else + this.View = olvState.CurrentView; + } + + return true; + } + + /// + /// Instances of this class are used to store the state of an ObjectListView. + /// + [Serializable] + internal class ObjectListViewState + { +// ReSharper disable NotAccessedField.Global + public int VersionNumber = 1; +// ReSharper restore NotAccessedField.Global + public int NumberOfColumns = 1; + public View CurrentView; + public int SortColumn = -1; + public bool IsShowingGroups; + public SortOrder LastSortOrder = SortOrder.None; +// ReSharper disable FieldCanBeMadeReadOnly.Global + public ArrayList ColumnIsVisible = new ArrayList(); + public ArrayList ColumnDisplayIndicies = new ArrayList(); + public ArrayList ColumnWidths = new ArrayList(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + } + + #endregion + + #region Event handlers + + /// + /// The application is idle. Trigger a SelectionChanged event. + /// + /// + /// + protected virtual void HandleApplicationIdle(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(HandleApplicationIdle); + this.hasIdleHandler = false; + + this.OnSelectionChanged(new EventArgs()); + } + + /// + /// The application is idle. Handle the column resizing event. + /// + /// + /// + protected virtual void HandleApplicationIdleResizeColumns(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(this.HandleApplicationIdleResizeColumns); + this.hasResizeColumnsHandler = false; + + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// Handle the BeginScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleBeginScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + NativeMethods.NMLVSCROLL nmlvscroll = (NativeMethods.NMLVSCROLL)m.GetLParam(typeof(NativeMethods.NMLVSCROLL)); + if (nmlvscroll.dx != 0) { + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionH - nmlvscroll.dx, scrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + + // Force any empty list msg to redraw when the list is scrolled horizontally + if (this.GetItemCount() == 0) + this.Invalidate(); + } + if (nmlvscroll.dy != 0) { + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionV - nmlvscroll.dy, scrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + return false; + } + + /// + /// Handle the EndScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleEndScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + // There is a bug in ListView under XP that causes the gridlines to be incorrectly scrolled + // when the left button is clicked to scroll. This is supposedly documented at + // KB 813791, but I couldn't find it anywhere. You can follow this thread to see the discussion + // http://www.ureader.com/msg/1484143.aspx + + if (!ObjectListView.IsVistaOrLater && ObjectListView.IsLeftMouseDown && this.GridLines) { + this.Invalidate(); + this.Update(); + } + + return false; + } + + /// + /// Handle the LinkClick listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleLinkClick(ref Message m) { + //System.Diagnostics.Debug.WriteLine("HandleLinkClick"); + + NativeMethods.NMLVLINK nmlvlink = (NativeMethods.NMLVLINK)m.GetLParam(typeof(NativeMethods.NMLVLINK)); + + // Find the group that was clicked and trigger an event + foreach (OLVGroup x in this.OLVGroups) { + if (x.GroupId == nmlvlink.iSubItem) { + this.OnGroupTaskClicked(new GroupTaskClickedEventArgs(x)); + return true; + } + } + + return false; + } + + /// + /// The cell tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleCellToolTipShowing(object sender, ToolTipShowingEventArgs e) { + this.BuildCellEvent(e, this.PointToClient(Cursor.Position)); + if (e.Item != null) { + e.Text = this.GetCellToolTip(e.ColumnIndex, e.RowIndex); + this.OnCellToolTip(e); + } + } + + /// + /// Allow the HeaderControl to call back into HandleHeaderToolTipShowing without making that method public + /// + /// + /// + internal void HeaderToolTipShowingCallback(object sender, ToolTipShowingEventArgs e) { + this.HandleHeaderToolTipShowing(sender, e); + } + + /// + /// The header tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleHeaderToolTipShowing(object sender, ToolTipShowingEventArgs e) { + e.ColumnIndex = this.HeaderControl.ColumnIndexUnderCursor; + if (e.ColumnIndex < 0) + return; + + e.RowIndex = -1; + e.Model = null; + e.Column = this.GetColumn(e.ColumnIndex); + e.Text = this.GetHeaderToolTip(e.ColumnIndex); + e.ListView = this; + this.OnHeaderToolTip(e); + } + + /// + /// Event handler for the column click event + /// + protected virtual void HandleColumnClick(object sender, ColumnClickEventArgs e) { + if (!this.PossibleFinishCellEditing()) + return; + + // Toggle the sorting direction on successive clicks on the same column + if (this.PrimarySortColumn != null && e.Column == this.PrimarySortColumn.Index) + this.PrimarySortOrder = (this.PrimarySortOrder == SortOrder.Descending ? SortOrder.Ascending : SortOrder.Descending); + else + this.PrimarySortOrder = SortOrder.Ascending; + + this.BeginUpdate(); + try { + this.Sort(e.Column); + } finally { + this.EndUpdate(); + } + } + + #endregion + + #region Low level Windows Message handling + + /// + /// Override the basic message pump for this control + /// + /// + protected override void WndProc(ref Message m) + { + + // System.Diagnostics.Debug.WriteLine(m.Msg); + switch (m.Msg) { + case 2: // WM_DESTROY + if (!this.HandleDestroy(ref m)) + base.WndProc(ref m); + break; + //case 0x14: // WM_ERASEBKGND + // Can't do anything here since, when the control is double buffered, anything + // done here is immediately over-drawn + // break; + case 0x0F: // WM_PAINT + if (!this.HandlePaint(ref m)) + base.WndProc(ref m); + break; + case 0x46: // WM_WINDOWPOSCHANGING + if (this.PossibleFinishCellEditing() && !this.HandleWindowPosChanging(ref m)) + base.WndProc(ref m); + break; + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref m)) + base.WndProc(ref m); + break; + case 0x0100: // WM_KEY_DOWN + if (!this.HandleKeyDown(ref m)) + base.WndProc(ref m); + break; + case 0x0102: // WM_CHAR + if (!this.HandleChar(ref m)) + base.WndProc(ref m); + break; + case 0x0200: // WM_MOUSEMOVE + if (!this.HandleMouseMove(ref m)) + base.WndProc(ref m); + break; + case 0x0201: // WM_LBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x202: // WM_LBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonUp(ref m)) + base.WndProc(ref m); + break; + case 0x0203: // WM_LBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x0204: // WM_RBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x0205: // WM_RBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONUP"); + base.WndProc(ref m); + break; + case 0x0206: // WM_RBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref m)) + base.WndProc(ref m); + break; + case 0x114: // WM_HSCROLL: + case 0x115: // WM_VSCROLL: + //System.Diagnostics.Debug.WriteLine("WM_VSCROLL"); + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x20A: // WM_MOUSEWHEEL: + case 0x20E: // WM_MOUSEHWHEEL: + if (this.AllowCellEditorsToProcessMouseWheel && this.IsCellEditing) + break; + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x7B: // WM_CONTEXTMENU + if (!this.HandleContextMenu(ref m)) + base.WndProc(ref m); + break; + case 0x1000 + 18: // LVM_HITTEST: + //System.Diagnostics.Debug.WriteLine("LVM_HITTEST"); + if (this.skipNextHitTest) { + //System.Diagnostics.Debug.WriteLine("SKIPPING LVM_HITTEST"); + this.skipNextHitTest = false; + } else { + base.WndProc(ref m); + } + break; + default: + base.WndProc(ref m); + break; + } + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleChar(ref Message m) { + + // Trigger a normal KeyPress event, which listeners can handle if they want. + // Handling the event stops ObjectListView's fancy search-by-typing. + if (this.ProcessKeyEventArgs(ref m)) + return true; + + const int MILLISECONDS_BETWEEN_KEYPRESSES = 1000; + + // What character did the user type and was it part of a longer string? + char character = (char)m.WParam.ToInt32(); //TODO: Will this work on 64 bit or MBCS? + if (character == (char)Keys.Back) { + // Backspace forces the next key to be considered the start of a new search + this.timeLastCharEvent = 0; + return true; + } + + if (System.Environment.TickCount < (this.timeLastCharEvent + MILLISECONDS_BETWEEN_KEYPRESSES)) + this.lastSearchString += character; + else + this.lastSearchString = character.ToString(CultureInfo.InvariantCulture); + + // If this control is showing checkboxes, we want to ignore single space presses, + // since they are used to toggle the selected checkboxes. + if (this.CheckBoxes && this.lastSearchString == " ") { + this.timeLastCharEvent = 0; + return true; + } + + // Where should the search start? + int start = 0; + ListViewItem focused = this.FocusedItem; + if (focused != null) { + start = this.GetDisplayOrderOfItemIndex(focused.Index); + + // If the user presses a single key, we search from after the focused item, + // being careful not to march past the end of the list + if (this.lastSearchString.Length == 1) { + start += 1; + if (start == this.GetItemCount()) + start = 0; + } + } + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(this.lastSearchString, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return true; + + // The parameters of the search may have been changed + string searchString = args.StringToFind; + start = args.StartSearchFrom; + + // Do the actual search + int found = this.FindMatchingRow(searchString, start, SearchDirectionHint.Down); + if (found >= 0) { + // Select and focus on the found item + this.BeginUpdate(); + try { + this.SelectedIndices.Clear(); + OLVListItem lvi = this.GetNthItemInDisplayOrder(found); + if (lvi != null) { + if (lvi.Enabled) + lvi.Selected = true; + lvi.Focused = true; + this.EnsureVisible(lvi.Index); + } + } finally { + this.EndUpdate(); + } + } + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(searchString, found); + this.OnAfterSearching(args2); + if (!args2.Handled) { + if (found < 0) + System.Media.SystemSounds.Beep.Play(); + } + + // When did this event occur? + this.timeLastCharEvent = System.Environment.TickCount; + return true; + } + private int timeLastCharEvent; + private string lastSearchString; + + /// + /// The user wants to see the context menu. + /// + /// The windows m + /// A bool indicating if this m has been handled + /// + /// We want to ignore context menu requests that are triggered by right clicks on the header + /// + protected virtual bool HandleContextMenu(ref Message m) { + // Don't try to handle context menu commands at design time. + if (this.DesignMode) + return false; + + // If the context menu command was generated by the keyboard, LParam will be -1. + // We don't want to process these. + if (m.LParam == this.minusOne) + return false; + + // If the context menu came from somewhere other than the header control, + // we also don't want to ignore it + if (m.WParam != this.HeaderControl.Handle) + return false; + + // OK. Looks like a right click in the header + if (!this.PossibleFinishCellEditing()) + return true; + + int columnIndex = this.HeaderControl.ColumnIndexUnderCursor; + return this.HandleHeaderRightClick(columnIndex); + } + readonly IntPtr minusOne = new IntPtr(-1); + + /// + /// Handle the Custom draw series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleCustomDraw(ref Message m) { + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_PREERASE = 3; + const int CDDS_POSTERASE = 4; + //const int CDRF_NEWFONT = 2; + //const int CDRF_SKIPDEFAULT = 4; + const int CDDS_ITEM = 0x00010000; + const int CDDS_SUBITEM = 0x00020000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + const int CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE); + const int CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE); + const int CDDS_SUBITEMPREPAINT = (CDDS_SUBITEM | CDDS_ITEMPREPAINT); + const int CDDS_SUBITEMPOSTPAINT = (CDDS_SUBITEM | CDDS_ITEMPOSTPAINT); + const int CDRF_NOTIFYPOSTPAINT = 0x10; + //const int CDRF_NOTIFYITEMDRAW = 0x20; + //const int CDRF_NOTIFYSUBITEMDRAW = 0x20; // same value as above! + const int CDRF_NOTIFYPOSTERASE = 0x40; + + // There is a bug in owner drawn virtual lists which causes lots of custom draw messages + // to be sent to the control *outside* of a WmPaint event. AFAIK, these custom draw events + // are spurious and only serve to make the control flicker annoyingly. + // So, we ignore messages that are outside of a paint event. + if (!this.isInWmPaintEvent) + return true; + + // One more complication! Sometimes with owner drawn virtual lists, the act of drawing + // the overlays triggers a second attempt to paint the control -- which makes an annoying + // flicker. So, we only do the custom drawing once per WmPaint event. + if (!this.shouldDoCustomDrawing) + return true; + + NativeMethods.NMLVCUSTOMDRAW nmcustomdraw = (NativeMethods.NMLVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMLVCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("cd: {0:x}, {1}, {2}", nmcustomdraw.nmcd.dwDrawStage, nmcustomdraw.dwItemType, nmcustomdraw.nmcd.dwItemSpec)); + + // Ignore drawing of group items + if (nmcustomdraw.dwItemType == 1) { + // This is the basis of an idea about how to owner draw group headers + + //nmcustomdraw.clrText = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrFace = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrTextBk = ColorTranslator.ToWin32(Color.DeepPink); + //Marshal.StructureToPtr(nmcustomdraw, m.LParam, false); + //using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + // g.DrawRectangle(Pens.Red, Rectangle.FromLTRB(nmcustomdraw.rcText.left, nmcustomdraw.rcText.top, nmcustomdraw.rcText.right, nmcustomdraw.rcText.bottom)); + //} + //m.Result = (IntPtr)((int)m.Result | CDRF_SKIPDEFAULT); + return true; + } + + switch (nmcustomdraw.nmcd.dwDrawStage) { + case CDDS_PREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_PREPAINT"); + // Remember which items were drawn during this paint cycle + if (this.prePaintLevel == 0) + this.drawnItems = new List(); + + // If there are any items, we have to wait until at least one has been painted + // before we draw the overlays. If there aren't any items, there will never be any + // item paint events, so we can draw the overlays whenever + this.isAfterItemPaint = (this.GetItemCount() == 0); + this.prePaintLevel++; + base.WndProc(ref m); + + // Make sure that we get postpaint notifications + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_POSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTPAINT"); + this.prePaintLevel--; + + // When in group view, we have two problems. On XP, the control sends + // a whole heap of PREPAINT/POSTPAINT messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays. + // On Vista, we have a different problem. On Vista, the control nests calls + // to PREPAINT and POSTPAINT. We only want to draw overlays on the outermost + // POSTPAINT. + if (this.prePaintLevel == 0 && (this.isMarqueSelecting || this.isAfterItemPaint)) { + this.shouldDoCustomDrawing = false; + + // Draw our overlays after everything has been drawn + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + this.DrawAllDecorations(g, this.drawnItems); + } + } + break; + + case CDDS_ITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREPAINT"); + + // When in group view on XP, the control send a whole heap of PREPAINT/POSTPAINT + // messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays + this.isAfterItemPaint = true; + + // This scheme of catching custom draw msgs works fine, except + // for Tile view. Something in .NET's handling of Tile view causes lots + // of invalidates and erases. So, we just ignore completely + // .NET's handling of Tile view and let the underlying control + // do its stuff. Strangely, if the Tile view is + // completely owner drawn, those erasures don't happen. + if (this.View == View.Tile) { + if (this.OwnerDraw && this.ItemRenderer != null) + base.WndProc(ref m); + } else { + base.WndProc(ref m); + } + + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_ITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTPAINT"); + // Remember which items have been drawn so we can draw any decorations for them + // once all other painting is finished + if (this.Columns.Count > 0) { + OLVListItem olvi = this.GetItem((int)nmcustomdraw.nmcd.dwItemSpec); + if (olvi != null) + this.drawnItems.Add(olvi); + } + break; + + case CDDS_SUBITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine(String.Format("CDDS_SUBITEMPREPAINT ({0},{1})", (int)nmcustomdraw.nmcd.dwItemSpec, nmcustomdraw.iSubItem)); + + // There is a bug in the .NET framework which appears when column 0 of an owner drawn listview + // is dragged to another column position. + // The bounds calculation always returns the left edge of column 0 as being 0. + // The effects of this bug become apparent + // when the listview is scrolled horizontally: the control can think that column 0 + // is no longer visible (the horizontal scroll position is subtracted from the bounds, giving a + // rectangle that is offscreen). In those circumstances, column 0 is not redraw because + // the control thinks it is not visible and so does not trigger a DrawSubItem event. + + // To fix this problem, we have to detected the situation -- owner drawing column 0 in any column except 0 -- + // trigger our own DrawSubItem, and then prevent the default processing from occurring. + + // Are we owner drawing column 0 when it's in any column except 0? + if (!this.OwnerDraw) + return false; + + int columnIndex = nmcustomdraw.iSubItem; + if (columnIndex != 0) + return false; + + int displayIndex = this.Columns[0].DisplayIndex; + if (displayIndex == 0) + return false; + + int rowIndex = (int)nmcustomdraw.nmcd.dwItemSpec; + OLVListItem item = this.GetItem(rowIndex); + if (item == null) + return false; + + // OK. We have the error condition, so lets do what the .NET framework should do. + // Trigger an event to draw column 0 when it is not at display index 0 + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + + // Correctly calculate the bounds of cell 0 + Rectangle r = item.GetSubItemBounds(0); + + // We can hardcode "0" here since we know we are only doing this for column 0 + DrawListViewSubItemEventArgs args = new DrawListViewSubItemEventArgs(g, r, item, item.SubItems[0], rowIndex, 0, + this.Columns[0], (ListViewItemStates)nmcustomdraw.nmcd.uItemState); + this.OnDrawSubItem(args); + + // If the event handler wants to do the default processing (i.e. DrawDefault = true), we are stuck. + // There is no way we can force the default drawing because of the bug in .NET we are trying to get around. + System.Diagnostics.Trace.Assert(!args.DrawDefault, "Default drawing is impossible in this situation"); + } + m.Result = (IntPtr)4; + + return true; + + case CDDS_SUBITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_SUBITEMPOSTPAINT"); + break; + + // I have included these stages, but it doesn't seem that they are sent for ListViews. + // http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-08/msg00220.html + + case CDDS_PREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_PREERASE"); + break; + + case CDDS_POSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTERASE"); + break; + + case CDDS_ITEMPREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREERASE"); + break; + + case CDDS_ITEMPOSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTERASE"); + break; + } + + return false; + } + bool isAfterItemPaint; + List drawnItems; + + /// + /// Handle the underlying control being destroyed + /// + /// + /// + protected virtual bool HandleDestroy(ref Message m) { + //System.Diagnostics.Debug.WriteLine(String.Format("WM_DESTROY: Disposing={0}, IsDisposed={1}, VirtualMode={2}", Disposing, IsDisposed, VirtualMode)); + + // Recreate the header control when the listview control is destroyed + this.headerControl = null; + + // When the underlying control is destroyed, we need to recreate and reconfigure its tooltip + if (this.cellToolTip != null) { + this.cellToolTip.PushSettings(); + this.BeginInvoke((MethodInvoker)delegate { + this.UpdateCellToolTipHandle(); + this.cellToolTip.PopSettings(); + }); + } + + return false; + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleFindItem(ref Message m) { + // NOTE: As far as I can see, this message is never actually sent to the control, making this + // method redundant! + + const int LVFI_STRING = 0x0002; + + NativeMethods.LVFINDINFO findInfo = (NativeMethods.LVFINDINFO)m.GetLParam(typeof(NativeMethods.LVFINDINFO)); + + // We can only handle string searches + if ((findInfo.flags & LVFI_STRING) != LVFI_STRING) + return false; + + int start = m.WParam.ToInt32(); + m.Result = (IntPtr)this.FindMatchingRow(findInfo.psz, start, SearchDirectionHint.Down); + return true; + } + + /// + /// Find the first row after the given start in which the text value in the + /// comparison column begins with the given text. The comparison column is column 0, + /// unless IsSearchOnSortColumn is true, in which case the current sort column is used. + /// + /// The text to be prefix matched + /// The index of the first row to consider + /// Which direction should be searched? + /// The index of the first row that matched, or -1 + /// The text comparison is a case-insensitive, prefix match. The search will + /// search the every row until a match is found, wrapping at the end if needed. + public virtual int FindMatchingRow(string text, int start, SearchDirectionHint direction) { + // We also can't do anything if we don't have data + if (this.Columns.Count == 0) + return -1; + int rowCount = this.GetItemCount(); + if (rowCount == 0) + return -1; + + // Which column are we going to use for our comparing? + OLVColumn column = this.GetColumn(0); + if (this.IsSearchOnSortColumn && this.View == View.Details && this.PrimarySortColumn != null) + column = this.PrimarySortColumn; + + // Do two searches if necessary to find a match. The second search is the wrap-around part of searching + int i; + if (direction == SearchDirectionHint.Down) { + i = this.FindMatchInRange(text, start, rowCount - 1, column); + if (i == -1 && start > 0) + i = this.FindMatchInRange(text, 0, start - 1, column); + } else { + i = this.FindMatchInRange(text, start, 0, column); + if (i == -1 && start != rowCount) + i = this.FindMatchInRange(text, rowCount - 1, start + 1, column); + } + + return i; + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected virtual int FindMatchInRange(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// Handle the Group Info series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleGroupInfo(ref Message m) + { + NativeMethods.NMLVGROUP nmlvgroup = (NativeMethods.NMLVGROUP)m.GetLParam(typeof(NativeMethods.NMLVGROUP)); + + //System.Diagnostics.Debug.WriteLine(String.Format("group: {0}, old state: {1}, new state: {2}", + // nmlvgroup.iGroupId, StateToString(nmlvgroup.uOldState), StateToString(nmlvgroup.uNewState))); + + // Ignore state changes that aren't related to selection, focus or collapsedness + const uint INTERESTING_STATES = (uint) (GroupState.LVGS_COLLAPSED | GroupState.LVGS_FOCUSED | GroupState.LVGS_SELECTED); + if ((nmlvgroup.uOldState & INTERESTING_STATES) == (nmlvgroup.uNewState & INTERESTING_STATES)) + return false; + + foreach (OLVGroup group in this.OLVGroups) { + if (group.GroupId == nmlvgroup.iGroupId) { + GroupStateChangedEventArgs args = new GroupStateChangedEventArgs(group, (GroupState)nmlvgroup.uOldState, (GroupState)nmlvgroup.uNewState); + this.OnGroupStateChanged(args); + break; + } + } + + return false; + } + + //private static string StateToString(uint state) + //{ + // if (state == 0) + // return Enum.GetName(typeof(GroupState), 0); + // + // List names = new List(); + // foreach (int value in Enum.GetValues(typeof(GroupState))) + // { + // if (value != 0 && (state & value) == value) + // { + // names.Add(Enum.GetName(typeof(GroupState), value)); + // } + // } + // return names.Count == 0 ? state.ToString("x") : String.Join("|", names.ToArray()); + //} + + /// + /// Handle a key down message + /// + /// + /// True if the msg has been handled + protected virtual bool HandleKeyDown(ref Message m) { + + // If this is a checkbox list, toggle the selected rows when the user presses Space + if (this.CheckBoxes && m.WParam.ToInt32() == (int)Keys.Space && this.SelectedIndices.Count > 0) { + this.ToggleSelectedRowCheckBoxes(); + return true; + } + + // Remember the scroll position so we can decide if the listview has scrolled in the + // handling of the event. + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + + base.WndProc(ref m); + + // It's possible that the processing in base.WndProc has actually destroyed this control + if (this.IsDisposed) + return true; + + // If the keydown processing changed the scroll position, trigger a Scroll event + int newScrollPositionH = NativeMethods.GetScrollPosition(this, true); + int newScrollPositionV = NativeMethods.GetScrollPosition(this, false); + + if (scrollPositionH != newScrollPositionH) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionH, newScrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + } + if (scrollPositionV != newScrollPositionV) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionV, newScrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + if (scrollPositionH != newScrollPositionH || scrollPositionV != newScrollPositionV) + this.RefreshHotItem(); + + return true; + } + + /// + /// Toggle the checkedness of the selected rows + /// + /// + /// + /// Actually, this doesn't actually toggle all rows. It toggles the first row, and + /// all other rows get the check state of that first row. This is actually a much + /// more useful behaviour. + /// + /// + /// If no rows are selected, this method does nothing. + /// + /// + public void ToggleSelectedRowCheckBoxes() { + if (this.SelectedIndices.Count == 0) + return; + Object primaryModel = this.GetItem(this.SelectedIndices[0]).RowObject; + this.ToggleCheckObject(primaryModel); + CheckState? state = this.GetCheckState(primaryModel); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + /// + /// Catch the Left Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + // We have to intercept this low level message rather than the more natural + // overridding of OnMouseDown, since ListCtrl's internal mouse down behavior + // is to select (or deselect) rows when the mouse is released. We don't + // want the selection to change when the user checks or unchecks a checkbox, so if the + // mouse down event was to check/uncheck, we have to hide this mouse + // down event from the control. + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + + if (hti.Item == null) + return false; + + // If the click occurs on a button, ignore it so the row isn't selected + if (hti.HitTestLocation == HitTestLocation.Button) { + this.Invalidate(); + + return true; + } + + // If they didn't click checkbox, we can just return + if (hti.HitTestLocation != HitTestLocation.CheckBox) + return false; + + // Disabled rows cannot change checkboxes + if (!hti.Item.Enabled) + return true; + + // Did they click a sub item checkbox? + if (hti.Column != null && hti.Column.Index > 0) { + if (hti.Column.IsEditable && hti.Item.Enabled) + this.ToggleSubItemCheckBox(hti.RowObject, hti.Column); + return true; + } + + // They must have clicked the primary checkbox + this.ToggleCheckObject(hti.RowObject); + + // If they change the checkbox of a selected row, all the rows in the selection + // should be given the same state + if (hti.Item.Selected) { + CheckState? state = this.GetCheckState(hti.RowObject); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + return true; + } + + /// + /// Catch the Left Button up event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonUp(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + if (this.MouseMoveHitTest == null) + return false; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + // Did they click an enabled, non-empty button? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.Button) { + // If a button was hit, Item and Column must be non-null + if (this.MouseMoveHitTest.Item.Enabled || this.MouseMoveHitTest.Column.EnableButtonWhenItemIsDisabled) { + string buttonText = this.MouseMoveHitTest.Column.GetStringValue(this.MouseMoveHitTest.RowObject); + if (!String.IsNullOrEmpty(buttonText)) { + this.Invalidate(); + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, new Point(x, y), this.MouseMoveHitTest); + this.OnButtonClick(args); + return true; + } + } + } + + // Are they trying to expand/collapse a group? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.GroupExpander) { + if (this.TriggerGroupExpandCollapse(this.MouseMoveHitTest.Group)) + return true; + } + + if (ObjectListView.IsVistaOrLater && this.HasCollapsibleGroups) + base.DefWndProc(ref m); + + return false; + } + + /// + /// Trigger a GroupExpandCollapse event and return true if the action was cancelled + /// + /// + /// + protected virtual bool TriggerGroupExpandCollapse(OLVGroup group) + { + GroupExpandingCollapsingEventArgs args = new GroupExpandingCollapsingEventArgs(group); + this.OnGroupExpandingCollapsing(args); + return args.Canceled; + } + + /// + /// Catch the Right Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDown(OlvListViewHitTestInfo hti) { + if (hti.Item == null) + return false; + + // Ignore clicks on checkboxes + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the Left Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDoubleClick(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDoubleClick(OlvListViewHitTestInfo hti) { + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the right Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDoubleClick(ref Message m) { + + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a right mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDoubleClick(OlvListViewHitTestInfo hti) { + + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the MouseMove event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleMouseMove(ref Message m) + { + //int x = m.LParam.ToInt32() & 0xFFFF; + //int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + //this.lastMouseMoveX = x; + //this.lastMouseMoveY = y; + + return false; + } + //private int lastMouseMoveX = -1; + //private int lastMouseMoveY = -1; + + /// + /// Handle notifications that have been reflected back from the parent window + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleReflectNotify(ref Message m) { + const int NM_CLICK = -2; + const int NM_DBLCLK = -3; + const int NM_RDBLCLK = -6; + const int NM_CUSTOMDRAW = -12; + const int NM_RELEASEDCAPTURE = -16; + const int LVN_FIRST = -100; + const int LVN_ITEMCHANGED = LVN_FIRST - 1; + const int LVN_ITEMCHANGING = LVN_FIRST - 0; + const int LVN_HOTTRACK = LVN_FIRST - 21; + const int LVN_MARQUEEBEGIN = LVN_FIRST - 56; + const int LVN_GETINFOTIP = LVN_FIRST - 58; + const int LVN_GETDISPINFO = LVN_FIRST - 77; + const int LVN_BEGINSCROLL = LVN_FIRST - 80; + const int LVN_ENDSCROLL = LVN_FIRST - 81; + const int LVN_LINKCLICK = LVN_FIRST - 84; + const int LVN_GROUPINFO = LVN_FIRST - 88; // undocumented + const int LVIF_STATE = 8; + //const int LVIS_FOCUSED = 1; + const int LVIS_SELECTED = 2; + + bool isMsgHandled = false; + + // TODO: Don't do any logic in this method. Create separate methods for each message + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + //System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr->code)); + + switch (nmhdr.code) { + case NM_CLICK: + // The standard ListView does some strange stuff here when the list has checkboxes. + // If you shift click on non-primary columns when FullRowSelect is true, the + // checkedness of the selected rows changes. + // We can't just not do the base class stuff because it sets up state that is used to + // determine mouse up events later on. + // So, we sabotage the base class's process of the click event. The base class does a HITTEST + // in order to determine which row was clicked -- if that fails, the base class does nothing. + // So when we get a CLICK, we know that the base class is going to send a HITTEST very soon, + // so we ignore the next HITTEST message, which will cause the click processing to fail. + //System.Diagnostics.Debug.WriteLine("NM_CLICK"); + this.skipNextHitTest = true; + break; + + case LVN_BEGINSCROLL: + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + isMsgHandled = this.HandleBeginScroll(ref m); + break; + + case LVN_ENDSCROLL: + isMsgHandled = this.HandleEndScroll(ref m); + break; + + case LVN_LINKCLICK: + isMsgHandled = this.HandleLinkClick(ref m); + break; + + case LVN_MARQUEEBEGIN: + //System.Diagnostics.Debug.WriteLine("LVN_MARQUEEBEGIN"); + this.isMarqueSelecting = true; + break; + + case LVN_GETINFOTIP: + //System.Diagnostics.Debug.WriteLine("LVN_GETINFOTIP"); + // When virtual lists are in SmallIcon view, they generates tooltip message with invalid item indices. + NativeMethods.NMLVGETINFOTIP nmGetInfoTip = (NativeMethods.NMLVGETINFOTIP)m.GetLParam(typeof(NativeMethods.NMLVGETINFOTIP)); + isMsgHandled = nmGetInfoTip.iItem >= this.GetItemCount() || this.Columns.Count == 0; + break; + + case NM_RELEASEDCAPTURE: + //System.Diagnostics.Debug.WriteLine("NM_RELEASEDCAPTURE"); + this.isMarqueSelecting = false; + this.Invalidate(); + break; + + case NM_CUSTOMDRAW: + //System.Diagnostics.Debug.WriteLine("NM_CUSTOMDRAW"); + isMsgHandled = this.HandleCustomDraw(ref m); + break; + + case NM_DBLCLK: + // The default behavior of a .NET ListView with checkboxes is to toggle the checkbox on + // double-click. That's just silly, if you ask me :) + if (this.CheckBoxes) { + // How do we make ListView not do that silliness? We could just ignore the message + // but the last part of the base code sets up state information, and without that + // state, the ListView doesn't trigger MouseDoubleClick events. So we fake a + // right button double click event, which sets up the same state, but without + // toggling the checkbox. + nmhdr.code = NM_RDBLCLK; + Marshal.StructureToPtr(nmhdr, m.LParam, false); + } + break; + + case LVN_ITEMCHANGED: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGED"); + NativeMethods.NMLISTVIEW nmlistviewPtr2 = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr2.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr2.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr2.uNewState); + if (currentValue != newCheckValue) + { + // Remove the state indices so that we don't trigger the OnItemChecked method + // when we call our base method after exiting this method + nmlistviewPtr2.uOldState = (nmlistviewPtr2.uOldState & 0x0FFF); + nmlistviewPtr2.uNewState = (nmlistviewPtr2.uNewState & 0x0FFF); + Marshal.StructureToPtr(nmlistviewPtr2, m.LParam, false); + } + else + { + bool isSelected = (nmlistviewPtr2.uNewState & LVIS_SELECTED) == LVIS_SELECTED; + + if (isSelected) + { + // System.Diagnostics.Debug.WriteLine(String.Format("Selected: {0}", nmlistviewPtr2.iItem)); + bool isShiftDown = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + + // -1 indicates that all rows are to be selected -- in fact, they already have been. + // We now have to deselect all the disabled objects. + if (nmlistviewPtr2.iItem == -1 || isShiftDown) { + Stopwatch sw = Stopwatch.StartNew(); + foreach (object disabledModel in this.DisabledObjects) + { + int modelIndex = this.IndexOf(disabledModel); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Deselecting took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks)); + } + else + { + // If the object just selected is disabled, explicitly de-select it + OLVListItem olvi = this.GetItem(nmlistviewPtr2.iItem); + if (olvi != null && !olvi.Enabled) + NativeMethods.DeselectOneItem(this, nmlistviewPtr2.iItem); + } + } + } + } + break; + + case LVN_ITEMCHANGING: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGING"); + NativeMethods.NMLISTVIEW nmlistviewPtr = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr.uNewState); + + if (currentValue != newCheckValue) { + // Prevent the base method from seeing the state change, + // since we handled it elsewhere + nmlistviewPtr.uChanged &= ~LVIF_STATE; + Marshal.StructureToPtr(nmlistviewPtr, m.LParam, false); + } + } + break; + + case LVN_HOTTRACK: + break; + + case LVN_GETDISPINFO: + break; + + case LVN_GROUPINFO: + //System.Diagnostics.Debug.WriteLine("reflect notify: GROUP INFO"); + isMsgHandled = this.HandleGroupInfo(ref m); + break; + + //default: + //System.Diagnostics.Debug.WriteLine(String.Format("reflect notify: {0}", nmhdr.code)); + //break; + } + + return isMsgHandled; + } + private bool skipNextHitTest; + + private CheckState CalculateCheckState(int state) { + switch ((state & 0xf000) >> 12) { + case 1: + return CheckState.Unchecked; + case 2: + return CheckState.Checked; + case 3: + return CheckState.Indeterminate; + default: + return CheckState.Checked; + } + } + + /// + /// In the notification messages, we handle attempts to change the width of our columns + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected bool HandleNotify(ref Message m) { + bool isMsgHandled = false; + + const int NM_CUSTOMDRAW = -12; + + const int HDN_FIRST = (0 - 300); + const int HDN_ITEMCHANGINGA = (HDN_FIRST - 0); + const int HDN_ITEMCHANGINGW = (HDN_FIRST - 20); + const int HDN_ITEMCLICKA = (HDN_FIRST - 2); + const int HDN_ITEMCLICKW = (HDN_FIRST - 22); + const int HDN_DIVIDERDBLCLICKA = (HDN_FIRST - 5); + const int HDN_DIVIDERDBLCLICKW = (HDN_FIRST - 25); + const int HDN_BEGINTRACKA = (HDN_FIRST - 6); + const int HDN_BEGINTRACKW = (HDN_FIRST - 26); + const int HDN_ENDTRACKA = (HDN_FIRST - 7); + const int HDN_ENDTRACKW = (HDN_FIRST - 27); + const int HDN_TRACKA = (HDN_FIRST - 8); + const int HDN_TRACKW = (HDN_FIRST - 28); + + // Handle the notification, remembering to handle both ANSI and Unicode versions + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Debug.WriteLine(String.Format("not: {0}", nmhdr->code)); + + //if (nmhdr.code < HDN_FIRST) + // System.Diagnostics.Debug.WriteLine(nmhdr.code); + + // In KB Article #183258, MS states that when a header control has the HDS_FULLDRAG style, it will receive + // ITEMCHANGING events rather than TRACK events. Under XP SP2 (at least) this is not always true, which may be + // why MS has withdrawn that particular KB article. It is true that the header is always given the HDS_FULLDRAG + // style. But even while window style set, the control doesn't always received ITEMCHANGING events. + // The controlling setting seems to be the Explorer option "Show Window Contents While Dragging"! + // In the category of "truly bizarre side effects", if the this option is turned on, we will receive + // ITEMCHANGING events instead of TRACK events. But if it is turned off, we receive lots of TRACK events and + // only one ITEMCHANGING event at the very end of the process. + // If we receive HDN_TRACK messages, it's harder to control the resizing process. If we return a result of 1, we + // cancel the whole drag operation, not just that particular track event, which is clearly not what we want. + // If we are willing to compile with unsafe code enabled, we can modify the size of the column in place, using the + // commented out code below. But without unsafe code, the best we can do is allow the user to drag the column to + // any width, and then spring it back to within bounds once they release the mouse button. UI-wise it's very ugly. + switch (nmheader.nhdr.code) { + + case NM_CUSTOMDRAW: + if (!this.OwnerDrawnHeader) + isMsgHandled = this.HeaderControl.HandleHeaderCustomDraw(ref m); + break; + + case HDN_ITEMCLICKA: + case HDN_ITEMCLICKW: + if (!this.PossibleFinishCellEditing()) + { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + break; + + case HDN_DIVIDERDBLCLICKA: + case HDN_DIVIDERDBLCLICKW: + case HDN_BEGINTRACKA: + case HDN_BEGINTRACKW: + if (!this.PossibleFinishCellEditing()) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + break; + } + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + OLVColumn column = this.GetColumn(nmheader.iItem); + // Space filling columns can't be dragged or double-click resized + if (column.FillsFreeSpace) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + break; + case HDN_ENDTRACKA: + case HDN_ENDTRACKW: + //if (this.ShowGroups) + // this.ResizeLastGroup(); + break; + case HDN_TRACKA: + case HDN_TRACKW: + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + if (hditem.cxy < column.MinimumWidth) + hditem.cxy = column.MinimumWidth; + else if (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth) + hditem.cxy = column.MaximumWidth; + Marshal.StructureToPtr(hditem, nmheader.pHDITEM, false); + } + break; + + case HDN_ITEMCHANGINGA: + case HDN_ITEMCHANGINGW: + nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + // Check the mask to see if the width field is valid, and if it is, make sure it's within range + if ((hditem.mask & 1) == 1) { + if (hditem.cxy < column.MinimumWidth || + (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth)) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + } + break; + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("olv TTN_SHOW"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleShow(ref m); + break; + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("olv TTN_POP"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandlePop(ref m); + break; + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("olv TTN_GETDISPINFO"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleGetDispInfo(ref m); + break; + +// default: +// System.Diagnostics.Debug.WriteLine(String.Format("notify: {0}", nmheader.nhdr.code)); +// break; + } + + return isMsgHandled; + } + + /// + /// Create a ToolTipControl to manage the tooltip control used by the listview control + /// + protected virtual void CreateCellToolTip() { + this.cellToolTip = new ToolTipControl(); + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + this.cellToolTip.Showing += new EventHandler(HandleCellToolTipShowing); + this.cellToolTip.SetMaxWidth(); + NativeMethods.MakeTopMost(this.cellToolTip); + } + + /// + /// Update the handle used by our cell tooltip to be the tooltip used by + /// the underlying Windows listview control. + /// + protected virtual void UpdateCellToolTipHandle() { + if (this.cellToolTip != null && this.cellToolTip.Handle == IntPtr.Zero) + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + } + + /// + /// Handle the WM_PAINT event + /// + /// + /// Return true if the msg has been handled and nothing further should be done + protected virtual bool HandlePaint(ref Message m) { + //System.Diagnostics.Debug.WriteLine("> WMPAINT"); + + // We only want to custom draw the control within WmPaint message and only + // once per paint event. We use these bools to insure this. + this.isInWmPaintEvent = true; + this.shouldDoCustomDrawing = true; + this.prePaintLevel = 0; + + this.ShowOverlays(); + + this.HandlePrePaint(); + base.WndProc(ref m); + this.HandlePostPaint(); + this.isInWmPaintEvent = false; + //System.Diagnostics.Debug.WriteLine("< WMPAINT"); + return true; + } + private int prePaintLevel; + + /// + /// Perform any steps needed before painting the control + /// + protected virtual void HandlePrePaint() { + // When we get a WM_PAINT msg, remember the rectangle that is being updated. + // We can't get this information later, since the BeginPaint call wipes it out. + // this.lastUpdateRectangle = NativeMethods.GetUpdateRect(this); // we no longer need this, but keep the code so we can see it later + + //// When the list is empty, we want to handle the drawing of the control by ourselves. + //// Unfortunately, there is no easy way to tell our superclass that we want to do this. + //// So we resort to guile and deception. We validate the list area of the control, which + //// effectively tells our superclass that this area does not need to be painted. + //// Our superclass will then not paint the control, leaving us free to do so ourselves. + //// Without doing this trickery, the superclass will draw the list as empty, + //// and then moments later, we will draw the empty list msg, giving a nasty flicker + //if (this.GetItemCount() == 0 && this.HasEmptyListMsg) + // NativeMethods.ValidateRect(this, this.ClientRectangle); + } + + /// + /// Perform any steps needed after painting the control + /// + protected virtual void HandlePostPaint() { + // This message is no longer necessary, but we keep it for compatibility + } + + /// + /// Handle the window position changing. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleWindowPosChanging(ref Message m) { + const int SWP_NOSIZE = 1; + + NativeMethods.WINDOWPOS pos = (NativeMethods.WINDOWPOS)m.GetLParam(typeof(NativeMethods.WINDOWPOS)); + if ((pos.flags & SWP_NOSIZE) == 0) { + if (pos.cx < this.Bounds.Width) // only when shrinking + // pos.cx is the window width, not the client area width, so we have to subtract the border widths + this.ResizeFreeSpaceFillingColumns(pos.cx - (this.Bounds.Width - this.ClientSize.Width)); + } + + return false; + } + + #endregion + + #region Column header clicking, column hiding and resizing + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + protected virtual bool HandleHeaderRightClick(int columnIndex) { + ToolStripDropDown menu = this.MakeHeaderRightClickMenu(columnIndex); + ColumnRightClickEventArgs eventArgs = new ColumnRightClickEventArgs(columnIndex, menu, Cursor.Position); + this.OnColumnRightClick(eventArgs); + + // Did the event handler stop any further processing? + if (eventArgs.Cancel) + return false; + + return this.ShowHeaderRightClickMenu(columnIndex, eventArgs.MenuStrip, eventArgs.Location); + } + + /// + /// Show a menu that is appropriate when the given column header is clicked. + /// + /// The index of the header that was clicked. This + /// can be -1, indicating that the header was clicked outside of a column + /// Where should the menu be shown + /// True if a menu was displayed + protected virtual bool ShowHeaderRightClickMenu(int columnIndex, ToolStripDropDown menu, Point pt) { + if (menu.Items.Count > 0) { + menu.Show(pt); + return true; + } + + return false; + } + + /// + /// Create the menu that should be displayed when the user right clicks + /// on the given column header. + /// + /// Index of the column that was right clicked. + /// This can be negative, which indicates a click outside of any header. + /// The toolstrip that should be displayed + protected virtual ToolStripDropDown MakeHeaderRightClickMenu(int columnIndex) { + ToolStripDropDown m = new ContextMenuStrip(); + + if (columnIndex >= 0 && this.UseFiltering && this.ShowFilterMenuOnRightClick) + m = this.MakeFilteringMenu(m, columnIndex); + + if (columnIndex >= 0 && this.ShowCommandMenuOnRightClick) + m = this.MakeColumnCommandMenu(m, columnIndex); + + if (this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None) { + m = this.MakeColumnSelectMenu(m); + } + + return m; + } + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + [Obsolete("Use HandleHeaderRightClick(int) instead")] + protected virtual bool HandleHeaderRightClick() { + return false; + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnSelectMenu(Point pt) { + ToolStripDropDown m = this.MakeColumnSelectMenu(new ContextMenuStrip()); + m.Show(pt); + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnCommandMenu(int columnIndex, Point pt) { + ToolStripDropDown m = this.MakeColumnCommandMenu(new ContextMenuStrip(), columnIndex); + if (this.SelectColumnsOnRightClick) { + if (m.Items.Count > 0) + m.Items.Add(new ToolStripSeparator()); + this.MakeColumnSelectMenu(m); + } + m.Show(pt); + } + + /// + /// Gets or set the text to be used for the sorting ascending command + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort ascending by '{0}'"), Localizable(true)] + public string MenuLabelSortAscending { + get { return this.menuLabelSortAscending; } + set { this.menuLabelSortAscending = value; } + } + private string menuLabelSortAscending = "Sort ascending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort descending by '{0}'"), Localizable(true)] + public string MenuLabelSortDescending { + get { return this.menuLabelSortDescending; } + set { this.menuLabelSortDescending = value; } + } + private string menuLabelSortDescending = "Sort descending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Group by '{0}'"), Localizable(true)] + public string MenuLabelGroupBy { + get { return this.menuLabelGroupBy; } + set { this.menuLabelGroupBy = value; } + } + private string menuLabelGroupBy = "Group by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Lock grouping on '{0}'"), Localizable(true)] + public string MenuLabelLockGroupingOn { + get { return this.menuLabelLockGroupingOn; } + set { this.menuLabelLockGroupingOn = value; } + } + private string menuLabelLockGroupingOn = "Lock grouping on '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unlock grouping from '{0}'"), Localizable(true)] + public string MenuLabelUnlockGroupingOn { + get { return this.menuLabelUnlockGroupingOn; } + set { this.menuLabelUnlockGroupingOn = value; } + } + private string menuLabelUnlockGroupingOn = "Unlock grouping from '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Turn off groups"), Localizable(true)] + public string MenuLabelTurnOffGroups { + get { return this.menuLabelTurnOffGroups; } + set { this.menuLabelTurnOffGroups = value; } + } + private string menuLabelTurnOffGroups = "Turn off groups"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unsort"), Localizable(true)] + public string MenuLabelUnsort { + get { return this.menuLabelUnsort; } + set { this.menuLabelUnsort = value; } + } + private string menuLabelUnsort = "Unsort"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Columns"), Localizable(true)] + public string MenuLabelColumns { + get { return this.menuLabelColumns; } + set { this.menuLabelColumns = value; } + } + private string menuLabelColumns = "Columns"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Select Columns..."), Localizable(true)] + public string MenuLabelSelectColumns { + get { return this.menuLabelSelectColumns; } + set { this.menuLabelSelectColumns = value; } + } + private string menuLabelSelectColumns = "Select Columns..."; + + /// + /// Gets or sets the image that will be place next to the Sort Ascending command + /// + public static Bitmap SortAscendingImage = BrightIdeasSoftware.Properties.Resources.SortAscending; + + /// + /// Gets or sets the image that will be placed next to the Sort Descending command + /// + public static Bitmap SortDescendingImage = BrightIdeasSoftware.Properties.Resources.SortDescending; + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnCommandMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + if (strip.Items.Count > 0) + strip.Items.Add(new ToolStripSeparator()); + + string label = String.Format(this.MenuLabelSortAscending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortAscendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Ascending); + }); + } + label = String.Format(this.MenuLabelSortDescending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortDescendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Descending); + }); + } + if (this.CanShowGroups) { + label = String.Format(this.MenuLabelGroupBy, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.PrimarySortColumn = column; + this.PrimarySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + if (this.ShowGroups) { + if (this.AlwaysGroupByColumn == column) { + label = String.Format(this.MenuLabelUnlockGroupingOn, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.AlwaysGroupByColumn = null; + this.AlwaysGroupBySortOrder = SortOrder.None; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelLockGroupingOn, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.AlwaysGroupByColumn = column; + this.AlwaysGroupBySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + label = String.Format(this.MenuLabelTurnOffGroups, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = false; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelUnsort, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label) && this.PrimarySortOrder != SortOrder.None) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.Unsort(); + }); + } + } + + return strip; + } + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnSelectMenu(ToolStripDropDown strip) { + + System.Diagnostics.Debug.Assert(this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None); + + // Append a separator if the menu isn't empty and the last item isn't already a separator + if (strip.Items.Count > 0 && (!(strip.Items[strip.Items.Count-1] is ToolStripSeparator))) + strip.Items.Add(new ToolStripSeparator()); + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.ModelDialog) { + strip.Items.Add(this.MenuLabelSelectColumns, null, delegate(object sender, EventArgs args) { + (new ColumnSelectionForm()).OpenOn(this); + }); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.Submenu) { + ToolStripMenuItem menu = new ToolStripMenuItem(this.MenuLabelColumns); + menu.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Items.Add(menu); + this.AddItemsToColumnSelectMenu(menu.DropDownItems); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.InlineMenu) { + strip.ItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Closing += new ToolStripDropDownClosingEventHandler(this.ColumnSelectMenuClosing); + this.AddItemsToColumnSelectMenu(strip.Items); + } + + return strip; + } + + /// + /// Create the menu items that will allow columns to be choosen and add them to the + /// given collection + /// + /// + protected void AddItemsToColumnSelectMenu(ToolStripItemCollection items) { + + // Sort columns by display order + List columns = new List(this.AllColumns); + columns.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + + // Build menu from sorted columns + foreach (OLVColumn col in columns) { + ToolStripMenuItem mi = new ToolStripMenuItem(col.Text); + mi.Checked = col.IsVisible; + mi.Tag = col; + + // The 'Index' property returns -1 when the column is not visible, so if the + // column isn't visible we have to enable the item. Also the first column can't be turned off + mi.Enabled = !col.IsVisible || col.CanBeHidden; + items.Add(mi); + } + } + + private void ColumnSelectMenuItemClicked(object sender, ToolStripItemClickedEventArgs e) { + this.contextMenuStaysOpen = false; + ToolStripMenuItem menuItemClicked = e.ClickedItem as ToolStripMenuItem; + if (menuItemClicked == null) + return; + OLVColumn col = menuItemClicked.Tag as OLVColumn; + if (col == null) + return; + menuItemClicked.Checked = !menuItemClicked.Checked; + col.IsVisible = menuItemClicked.Checked; + this.contextMenuStaysOpen = this.SelectColumnsMenuStaysOpen; + this.BeginInvoke(new MethodInvoker(this.RebuildColumns)); + } + private bool contextMenuStaysOpen; + + private void ColumnSelectMenuClosing(object sender, ToolStripDropDownClosingEventArgs e) { + e.Cancel = this.contextMenuStaysOpen && e.CloseReason == ToolStripDropDownCloseReason.ItemClicked; + this.contextMenuStaysOpen = false; + } + + /// + /// Create a Filtering menu + /// + /// + /// + /// + public virtual ToolStripDropDown MakeFilteringMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + FilterMenuBuilder strategy = this.FilterMenuBuildStrategy; + if (strategy == null) + return strip; + + return strategy.MakeFilterMenu(strip, this, column); + } + + /// + /// Override the OnColumnReordered method to do what we want + /// + /// + protected override void OnColumnReordered(ColumnReorderedEventArgs e) { + base.OnColumnReordered(e); + + // The internal logic of the .NET code behind a ENDDRAG event means that, + // at this point, the DisplayIndex's of the columns are not yet as they are + // going to be. So we have to invoke a method to run later that will remember + // what the real DisplayIndex's are. + this.BeginInvoke(new MethodInvoker(this.RememberDisplayIndicies)); + } + + private void RememberDisplayIndicies() { + // Remember the display indexes so we can put them back at a later date + foreach (OLVColumn x in this.AllColumns) + x.LastDisplayIndex = x.DisplayIndex; + } + + /// + /// When the column widths are changing, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) { + if (this.UpdateSpaceFillingColumnsWhenDraggingColumnDivider && !this.GetColumn(e.ColumnIndex).FillsFreeSpace) { + // If the width of a column is increasing, resize any space filling columns allowing the extra + // space that the new column width is going to consume + int oldWidth = this.GetColumn(e.ColumnIndex).Width; + if (e.NewWidth > oldWidth) + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width - (e.NewWidth - oldWidth)); + else + this.ResizeFreeSpaceFillingColumns(); + } + } + + /// + /// When the column widths change, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { + if (!this.GetColumn(e.ColumnIndex).FillsFreeSpace) + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// When the size of the control changes, we have to resize our space filling columns. + /// + /// + /// + protected virtual void HandleLayout(object sender, LayoutEventArgs e) { + // We have to delay executing the recalculation of the columns, since virtual lists + // get terribly confused if we resize the column widths during this event. + if (!this.hasResizeColumnsHandler) { + this.hasResizeColumnsHandler = true; + this.RunWhenIdle(this.HandleApplicationIdleResizeColumns); + } + } + + private void RunWhenIdle(EventHandler eventHandler) { + Application.Idle += eventHandler; + if (!this.CanUseApplicationIdle) { + SynchronizationContext.Current.Post(delegate(object x) { Application.RaiseIdle(EventArgs.Empty); }, null); + } + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns() { + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width); + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns(int freeSpace) { + // It's too confusing to dynamically resize columns at design time. + if (this.DesignMode) + return; + + if (this.Frozen) + return; + + this.BeginUpdate(); + + // Calculate the free space available + int totalProportion = 0; + List spaceFillingColumns = new List(); + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + if (col.FillsFreeSpace) { + spaceFillingColumns.Add(col); + totalProportion += col.FreeSpaceProportion; + } else + freeSpace -= col.Width; + } + freeSpace = Math.Max(0, freeSpace); + + // Any space filling column that would hit it's Minimum or Maximum + // width must be treated as a fixed column. + foreach (OLVColumn col in spaceFillingColumns.ToArray()) { + int newWidth = (freeSpace * col.FreeSpaceProportion) / totalProportion; + + if (col.MinimumWidth != -1 && newWidth < col.MinimumWidth) + newWidth = col.MinimumWidth; + else if (col.MaximumWidth != -1 && newWidth > col.MaximumWidth) + newWidth = col.MaximumWidth; + else + newWidth = 0; + + if (newWidth > 0) { + col.Width = newWidth; + freeSpace -= newWidth; + totalProportion -= col.FreeSpaceProportion; + spaceFillingColumns.Remove(col); + } + } + + // Distribute the free space between the columns + foreach (OLVColumn col in spaceFillingColumns) { + col.Width = (freeSpace*col.FreeSpaceProportion)/totalProportion; + } + + this.EndUpdate(); + } + + #endregion + + #region Checkboxes + + /// + /// Check all rows + /// + public virtual void CheckAll() + { + this.CheckedObjects = EnumerableToArray(this.Objects, false); + } + + /// + /// Check the checkbox in the given column header + /// + /// If the given columns header check box is linked to the cell check boxes, + /// then checkboxes in all cells will also be checked. + /// + public virtual void CheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Checked); + } + + /// + /// Mark the checkbox in the given column header as having an indeterminate value + /// + /// + public virtual void CheckIndeterminateHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Indeterminate); + } + + /// + /// Mark the given object as indeterminate check state + /// + /// The model object to be marked indeterminate + public virtual void CheckIndeterminateObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Indeterminate); + } + + /// + /// Mark the given object as checked in the list + /// + /// The model object to be checked + public virtual void CheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Checked); + } + + /// + /// Mark the given objects as checked in the list + /// + /// The model object to be checked + public virtual void CheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.CheckObject(model); + } + + /// + /// Put a check into the check box at the given cell + /// + /// + /// + public virtual void CheckSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Checked); + this.RefreshObject(rowObject); + } + + /// + /// Put an indeterminate check into the check box at the given cell + /// + /// + /// + public virtual void CheckIndeterminateSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Indeterminate); + this.RefreshObject(rowObject); + } + + /// + /// Return true of the given object is checked + /// + /// The model object whose checkedness is returned + /// Is the given object checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsChecked(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Checked; + } + + /// + /// Return true of the given object is indeterminately checked + /// + /// The model object whose checkedness is returned + /// Is the given object indeterminately checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsCheckedIndeterminate(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Indeterminate; + } + + /// + /// Is there a check at the check box at the given cell + /// + /// + /// + public virtual bool IsSubItemChecked(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return false; + return (column.GetCheckState(rowObject) == CheckState.Checked); + } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does not know and the value from the control will be used. + /// + /// + /// + protected virtual CheckState? GetCheckState(Object modelObject) { + if (this.CheckStateGetter != null) + return this.CheckStateGetter(modelObject); + return this.PersistentCheckBoxes ? this.GetPersistentCheckState(modelObject) : (CheckState?)null; + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected virtual CheckState PutCheckState(Object modelObject, CheckState state) { + if (this.CheckStatePutter != null) + return this.CheckStatePutter(modelObject, state); + return this.PersistentCheckBoxes ? this.SetPersistentCheckState(modelObject, state) : state; + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected virtual bool SetObjectCheckedness(object modelObject, CheckState state) { + + if (GetCheckState(modelObject) == state) + return false; + + OLVListItem olvi = this.ModelToItem(modelObject); + + // If we didn't find the given, we still try to record the check state. + if (olvi == null) { + this.PutCheckState(modelObject, state); + return true; + } + + // Trigger checkbox changing event + ItemCheckEventArgs ice = new ItemCheckEventArgs(olvi.Index, state, olvi.CheckState); + this.OnItemCheck(ice); + if (ice.NewValue == olvi.CheckState) + return false; + + olvi.CheckState = this.PutCheckState(modelObject, state); + this.RefreshItem(olvi); + + // Trigger check changed event + this.OnItemChecked(new ItemCheckedEventArgs(olvi)); + return true; + } + + /// + /// Toggle the checkedness of the given object. A checked object becomes + /// unchecked; an unchecked or indeterminate object becomes checked. + /// If the list has tristate checkboxes, the order is: + /// unchecked -> checked -> indeterminate -> unchecked ... + /// + /// The model object to be checked + public virtual void ToggleCheckObject(object modelObject) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi == null) + return; + + CheckState newState = CheckState.Checked; + + if (olvi.CheckState == CheckState.Checked) { + newState = this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + } else { + if (olvi.CheckState == CheckState.Indeterminate && this.TriStateCheckBoxes) + newState = CheckState.Unchecked; + } + this.SetObjectCheckedness(modelObject, newState); + } + + /// + /// Toggle the checkbox in the header of the given column + /// + /// Obviously, this is only useful if the column actually has a header checkbox. + /// + public virtual void ToggleHeaderCheckBox(OLVColumn column) { + if (column == null) + return; + + CheckState newState = CalculateToggledCheckState(column.HeaderCheckState, column.HeaderTriStateCheckBox, column.HeaderCheckBoxDisabled); + ChangeHeaderCheckBoxState(column, newState); + } + + private void ChangeHeaderCheckBoxState(OLVColumn column, CheckState newState) { + // Tell the world the checkbox was clicked + HeaderCheckBoxChangingEventArgs args = new HeaderCheckBoxChangingEventArgs(); + args.Column = column; + args.NewCheckState = newState; + + this.OnHeaderCheckBoxChanging(args); + if (args.Cancel || column.HeaderCheckState == args.NewCheckState) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + column.HeaderCheckState = args.NewCheckState; + this.HeaderControl.Invalidate(column); + + if (column.HeaderCheckBoxUpdatesRowCheckBoxes) { + if (column.Index == 0) + this.UpdateAllPrimaryCheckBoxes(column); + else + this.UpdateAllSubItemCheckBoxes(column); + } + + // Debug.WriteLine(String.Format("PERF - Changing row checkboxes on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + private void UpdateAllPrimaryCheckBoxes(OLVColumn column) { + if (!this.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + if (column.HeaderCheckState == CheckState.Checked) + CheckAll(); + else + UncheckAll(); + } + + private void UpdateAllSubItemCheckBoxes(OLVColumn column) { + if (!column.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + foreach (object model in this.Objects) + column.PutCheckState(model, column.HeaderCheckState); + this.BuildList(true); + } + + /// + /// Toggle the check at the check box of the given cell + /// + /// + /// + public virtual void ToggleSubItemCheckBox(object rowObject, OLVColumn column) { + CheckState currentState = column.GetCheckState(rowObject); + CheckState newState = CalculateToggledCheckState(currentState, column.TriStateCheckBoxes, false); + + SubItemCheckingEventArgs args = new SubItemCheckingEventArgs(column, this.ModelToItem(rowObject), column.Index, currentState, newState); + this.OnSubItemChecking(args); + if (args.Canceled) + return; + + switch (args.NewValue) { + case CheckState.Checked: + this.CheckSubItem(rowObject, column); + break; + case CheckState.Indeterminate: + this.CheckIndeterminateSubItem(rowObject, column); + break; + case CheckState.Unchecked: + this.UncheckSubItem(rowObject, column); + break; + } + } + + /// + /// Uncheck all rows + /// + public virtual void UncheckAll() + { + this.CheckedObjects = null; + } + + /// + /// Mark the given object as unchecked in the list + /// + /// The model object to be unchecked + public virtual void UncheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Unchecked); + } + + /// + /// Mark the given objects as unchecked in the list + /// + /// The model object to be checked + public virtual void UncheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.UncheckObject(model); + } + + /// + /// Uncheck the checkbox in the given column header + /// + /// + public virtual void UncheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Unchecked); + } + + /// + /// Uncheck the check at the given cell + /// + /// + /// + public virtual void UncheckSubItem(object rowObject, OLVColumn column) + { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Unchecked); + this.RefreshObject(rowObject); + } + + #endregion + + #region OLV accessing + + /// + /// Return the column at the given index + /// + /// Index of the column to be returned + /// An OLVColumn, or null if the index is out of bounds + public virtual OLVColumn GetColumn(int index) { + return (index >=0 && index < this.Columns.Count) ? (OLVColumn)this.Columns[index] : null; + } + + /// + /// Return the column at the given title. + /// + /// Name of the column to be returned + /// An OLVColumn + public virtual OLVColumn GetColumn(string name) { + foreach (ColumnHeader column in this.Columns) { + if (column.Text == name) + return (OLVColumn)column; + } + return null; + } + + /// + /// Return a collection of columns that are visible to the given view. + /// Only Tile and Details have columns; all other views have 0 columns. + /// + /// Which view are the columns being calculate for? + /// A list of columns + public virtual List GetFilteredColumns(View view) { + // For both detail and tile view, the first column must be included. Normally, we would + // use the ColumnHeader.Index property, but if the header is not currently part of a ListView + // that property returns -1. So, we track the index of + // the column header, and always include the first header. + + int index = 0; + return this.AllColumns.FindAll(delegate(OLVColumn x) { + return (index++ == 0) || x.IsVisible; + }); + } + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + /// If a filter is installed, this will return the number of items that match the filter. + public virtual int GetItemCount() { + return this.Items.Count; + } + + /// + /// Return the item at the given index + /// + /// Index of the item to be returned + /// An OLVListItem + public virtual OLVListItem GetItem(int index) { + if (index < 0 || index >= this.GetItemCount()) + return null; + + return (OLVListItem)this.Items[index]; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public virtual object GetModelObject(int index) { + OLVListItem item = this.GetItem(index); + return item == null ? null : item.RowObject; + } + + /// + /// Find the item and column that are under the given co-ords + /// + /// X co-ord + /// Y co-ord + /// The column under the given point + /// The item under the given point. Can be null. + public virtual OLVListItem GetItemAt(int x, int y, out OLVColumn hitColumn) { + hitColumn = null; + ListViewHitTestInfo info = this.HitTest(x, y); + if (info.Item == null) + return null; + + if (info.SubItem != null) { + int subItemIndex = info.Item.SubItems.IndexOf(info.SubItem); + hitColumn = this.GetColumn(subItemIndex); + } + + return (OLVListItem)info.Item; + } + + /// + /// Return the sub item at the given index/column + /// + /// Index of the item to be returned + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index, int columnIndex) { + OLVListItem olvi = this.GetItem(index); + return olvi == null ? null : olvi.GetSubItem(columnIndex); + } + + #endregion + + #region Object manipulation + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// This does not work on virtual lists, since virtual lists don't use ListViewGroups + /// for grouping. Use instead. + /// + public virtual void EnsureGroupVisible(ListViewGroup lvg) { + if (!this.ShowGroups || lvg == null) + return; + + int groupIndex = this.Groups.IndexOf(lvg); + if (groupIndex <= 0) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + ListViewGroup previousGroup = this.Groups[groupIndex - 1]; + ListViewItem lastItemInGroup = previousGroup.Items[previousGroup.Items.Count - 1]; + Rectangle r = this.GetItemRect(lastItemInGroup.Index); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Ensure that the given model object is visible + /// + /// The model object to be revealed + public virtual void EnsureModelVisible(Object modelObject) { + int index = this.IndexOf(modelObject); + if (index >= 0) + this.EnsureVisible(index); + } + + /// + /// Return the model object of the row that is selected or null if there is no selection or more than one selection + /// + /// Model object or null + [Obsolete("Use SelectedObject property instead of this method")] + public virtual object GetSelectedObject() { + return this.SelectedObject; + } + + /// + /// Return the model objects of the rows that are selected or an empty collection if there is no selection + /// + /// ArrayList + [Obsolete("Use SelectedObjects property instead of this method")] + public virtual ArrayList GetSelectedObjects() { + return ObjectListView.EnumerableToArray(this.SelectedObjects, false); + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + /// Model object or null + /// Use CheckedObject property instead of this method + [Obsolete("Use CheckedObject property instead of this method")] + public virtual object GetCheckedObject() { + return this.CheckedObject; + } + + /// + /// Get the collection of model objects that are checked. + /// + /// Use CheckedObjects property instead of this method + [Obsolete("Use CheckedObjects property instead of this method")] + public virtual ArrayList GetCheckedObjects() { + return ObjectListView.EnumerableToArray(this.CheckedObjects, false); + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public virtual int IndexOf(Object modelObject) { + for (int i = 0; i < this.GetItemCount(); i++) { + if (this.GetModelObject(i).Equals(modelObject)) + return i; + } + return -1; + } + + /// + /// Rebuild the given ListViewItem with the data from its associated model. + /// + /// This method does not resort or regroup the view. It simply updates + /// the displayed data of the given item + public virtual void RefreshItem(OLVListItem olvi) { + olvi.UseItemStyleForSubItems = true; + olvi.SubItems.Clear(); + this.FillInValues(olvi, olvi.RowObject); + this.PostProcessOneRow(olvi.Index, this.GetDisplayOrderOfItemIndex(olvi.Index), olvi); + } + + /// + /// Rebuild the data on the row that is showing the given object. + /// + /// + /// + /// This method does not resort or regroup the view. + /// + /// + /// The given object is *not* used as the source of data for the rebuild. + /// It is only used to locate the matching model in the collection, + /// then that matching model is used as the data source. This distinction is + /// only important in model classes that have overridden the Equals() method. + /// + /// + /// If you want the given model object to replace the pre-existing model, + /// use . + /// + /// + public virtual void RefreshObject(object modelObject) { + this.RefreshObjects(new object[] { modelObject }); + } + + /// + /// Update the rows that are showing the given objects + /// + /// + /// This method does not resort or regroup the view. + /// This method can safely be called from background threads. + /// + public virtual void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + this.ReplaceModel(olvi, modelObject); + this.RefreshItem(olvi); + } + } + } + + private void ReplaceModel(OLVListItem olvi, object newModel) { + if (ReferenceEquals(olvi.RowObject, newModel)) + return; + + this.TakeOwnershipOfObjects(); + ArrayList array = ObjectListView.EnumerableToArray(this.Objects, false); + int i = array.IndexOf(olvi.RowObject); + if (i >= 0) + array[i] = newModel; + + olvi.RowObject = newModel; + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public virtual void RefreshSelectedObjects() { + foreach (ListViewItem lvi in this.SelectedItems) + this.RefreshItem((OLVListItem)lvi); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject) { + this.SelectObject(modelObject, false); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Should the object be focused as well? + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject, bool setFocus) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) { + olvi.Selected = true; + if (setFocus) + olvi.Focused = true; + } + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + public virtual void SelectObjects(IList modelObjects) { + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) + olvi.Selected = true; + } + } + + #endregion + + #region Freezing/Suspending + + /// + /// Get or set whether or not the listview is frozen. When the listview is + /// frozen, it will not update itself. + /// + /// The Frozen property is similar to the methods Freeze()/Unfreeze() + /// except that setting Frozen property to false immediately unfreezes the control + /// regardless of the number of Freeze() calls outstanding. + /// objectListView1.Frozen = false; // unfreeze the control now! + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool Frozen { + get { return freezeCount > 0; } + set { + if (value) + Freeze(); + else if (freezeCount > 0) { + freezeCount = 1; + Unfreeze(); + } + } + } + private int freezeCount; + + /// + /// Freeze the listview so that it no longer updates itself. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Freeze() { + if (freezeCount == 0) + DoFreeze(); + + freezeCount++; + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Unfreeze the listview. If this call is the outermost Unfreeze(), + /// the contents of the listview will be rebuilt. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Unfreeze() { + if (freezeCount <= 0) + return; + + freezeCount--; + if (freezeCount == 0) + DoUnfreeze(); + + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Do the actual work required when the listview is frozen + /// + protected virtual void DoFreeze() { + this.BeginUpdate(); + } + + /// + /// Do the actual work required when the listview is unfrozen + /// + protected virtual void DoUnfreeze() + { + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + this.BuildList(); + } + + /// + /// Returns true if selection events are currently suspended. + /// While selection events are suspended, neither SelectedIndexChanged + /// or SelectionChanged events will be raised. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected bool SelectionEventsSuspended { + get { return this.suspendSelectionEventCount > 0; } + } + + /// + /// Suspend selection events until a matching ResumeSelectionEvents() + /// is called. + /// + /// Calls to this method nest correctly. Every call to SuspendSelectionEvents() + /// must have a matching ResumeSelectionEvents(). + protected void SuspendSelectionEvents() { + this.suspendSelectionEventCount++; + } + + /// + /// Resume raising selection events. + /// + protected void ResumeSelectionEvents() { + Debug.Assert(this.SelectionEventsSuspended, "Mismatched called to ResumeSelectionEvents()"); + this.suspendSelectionEventCount--; + } + + /// + /// Returns a disposable that will disable selection events + /// during a using() block. + /// + /// + protected IDisposable SuspendSelectionEventsDuring() { + return new SuspendSelectionDisposable(this); + } + + /// + /// Implementation only class that suspends and resumes selection + /// events on instance creation and disposal. + /// + private class SuspendSelectionDisposable : IDisposable { + public SuspendSelectionDisposable(ObjectListView objectListView) { + this.objectListView = objectListView; + this.objectListView.SuspendSelectionEvents(); + } + + public void Dispose() { + this.objectListView.ResumeSelectionEvents(); + } + + private readonly ObjectListView objectListView; + } + + #endregion + + #region Column sorting + + /// + /// Sort the items by the last sort column and order + /// + public new void Sort() { + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The name of the column whose values will be used for the sorting + public virtual void Sort(string columnToSortName) { + this.Sort(this.GetColumn(columnToSortName), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The index of the column whose values will be used for the sorting + public virtual void Sort(int columnToSortIndex) { + if (columnToSortIndex >= 0 && columnToSortIndex < this.Columns.Count) + this.Sort(this.GetColumn(columnToSortIndex), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The column whose values will be used for the sorting + public virtual void Sort(OLVColumn columnToSort) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort); }); + } else { + this.Sort(columnToSort, this.PrimarySortOrder); + } + } + + /// + /// Sort the items in the list view by the values in the given column and by the given order. + /// + /// The column whose values will be used for the sorting. + /// If null, the first column will be used. + /// The ordering to be used for sorting. If this is None, + /// this.Sorting and then SortOrder.Ascending will be used + /// If ShowGroups is true, the rows will be grouped by the given column. + /// If AlwaysGroupsByColumn is not null, the rows will be grouped by that column, + /// and the rows within each group will be sorted by the given column. + public virtual void Sort(OLVColumn columnToSort, SortOrder order) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort, order); }); + } else { + this.DoSort(columnToSort, order); + this.PostProcessRows(); + } + } + + private void DoSort(OLVColumn columnToSort, SortOrder order) { + // Sanity checks + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + // Fill in default values, if the parameters don't make sense + if (this.ShowGroups) { + columnToSort = columnToSort ?? this.GetColumn(0); + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + } + + // Give the world a chance to fiddle with or completely avoid the sorting process + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(columnToSort, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + // Virtual lists don't preserve selection, so we have to do it specifically + // THINK: Do we need to preserve focus too? + IList selection = this.VirtualMode ? this.SelectedObjects : null; + this.SuspendSelectionEvents(); + + this.ClearHotItem(); + + // Finally, do the work of sorting, unless an event handler has already done the sorting for us + if (!args.Handled) { + // Sanity checks + if (args.ColumnToSort != null && args.SortOrder != SortOrder.None) { + if (this.ShowGroups) + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + else if (this.CustomSorter != null) + this.CustomSorter(args.ColumnToSort, args.SortOrder); + else + this.ListViewItemSorter = new ColumnComparer(args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + } + } + + if (this.ShowSortIndicators) + this.ShowSortIndicator(args.ColumnToSort, args.SortOrder); + + this.PrimarySortColumn = args.ColumnToSort; + this.PrimarySortOrder = args.SortOrder; + + if (selection != null && selection.Count > 0) + this.SelectedObjects = selection; + this.ResumeSelectionEvents(); + + this.RefreshHotItem(); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + /// + /// Put a sort indicator next to the text of the sort column + /// + public virtual void ShowSortIndicator() { + if (this.ShowSortIndicators && this.PrimarySortOrder != SortOrder.None) + this.ShowSortIndicator(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Put a sort indicator next to the text of the given column + /// + /// The column to be marked + /// The sort order in effect on that column + protected virtual void ShowSortIndicator(OLVColumn columnToSort, SortOrder sortOrder) { + int imageIndex = -1; + + if (!NativeMethods.HasBuiltinSortIndicators()) { + // If we can't use builtin image, we have to make and then locate the index of the + // sort indicator we want to use. SortOrder.None doesn't show an image. + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(SORT_INDICATOR_UP_KEY)) + MakeSortIndicatorImages(); + + if (this.SmallImageList != null) + { + string key = sortOrder == SortOrder.Ascending ? SORT_INDICATOR_UP_KEY : SORT_INDICATOR_DOWN_KEY; + imageIndex = this.SmallImageList.Images.IndexOfKey(key); + } + } + + // Set the image for each column + for (int i = 0; i < this.Columns.Count; i++) { + if (columnToSort != null && i == columnToSort.Index) + NativeMethods.SetColumnImage(this, i, sortOrder, imageIndex); + else + NativeMethods.SetColumnImage(this, i, SortOrder.None, -1); + } + } + + /// + /// The name of the image used when a column is sorted ascending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_UP_KEY = "sort-indicator-up"; + + /// + /// The name of the image used when a column is sorted descending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_DOWN_KEY = "sort-indicator-down"; + + /// + /// If the sort indicator images don't already exist, this method will make and install them + /// + protected virtual void MakeSortIndicatorImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + // This arrangement of points works well with (16,16) images, and OK with others + int midX = il.ImageSize.Width / 2; + int midY = (il.ImageSize.Height / 2) - 1; + int deltaX = midX - 2; + int deltaY = deltaX / 2; + + if (il.Images.IndexOfKey(SORT_INDICATOR_UP_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY + deltaY); + Point pt2 = new Point(midX, midY - deltaY - 1); + Point pt3 = new Point(midX + deltaX, midY + deltaY); + il.Images.Add(SORT_INDICATOR_UP_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + if (il.Images.IndexOfKey(SORT_INDICATOR_DOWN_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY - deltaY); + Point pt2 = new Point(midX, midY + deltaY); + Point pt3 = new Point(midX + deltaX, midY - deltaY); + il.Images.Add(SORT_INDICATOR_DOWN_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + this.SmallImageList = il; + } + + private Bitmap MakeTriangleBitmap(Size sz, Point[] pts) { + Bitmap bm = new Bitmap(sz.Width, sz.Height); + Graphics g = Graphics.FromImage(bm); + g.FillPolygon(new SolidBrush(Color.Gray), pts); + return bm; + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + public virtual void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.BuildList(); + } + + #endregion + + #region Utilities + + private static CheckState CalculateToggledCheckState(CheckState currentState, bool isTriState, bool isDisabled) + { + if (isDisabled) + return currentState; + switch (currentState) + { + case CheckState.Checked: return isTriState ? CheckState.Indeterminate : CheckState.Unchecked; + case CheckState.Indeterminate: return CheckState.Unchecked; + default: return CheckState.Checked; + } + } + + /// + /// Do the actual work of creating the given list of groups + /// + /// + protected virtual void CreateGroups(IEnumerable groups) { + this.Groups.Clear(); + // The group must be added before it is given items, otherwise an exception is thrown (is this documented?) + foreach (OLVGroup group in groups) { + group.InsertGroupOldStyle(this); + group.SetItemsOldStyle(); + } + } + + /// + /// For some reason, UseItemStyleForSubItems doesn't work for the colors + /// when owner drawing the list, so we have to specifically give each subitem + /// the desired colors + /// + /// The item whose subitems are to be corrected + /// Cells drawn via BaseRenderer don't need this, but it is needed + /// when an owner drawn cell uses DrawDefault=true + protected virtual void CorrectSubItemColors(ListViewItem olvi) { + } + + /// + /// Fill in the given OLVListItem with values of the given row + /// + /// the OLVListItem that is to be stuff with values + /// the model object from which values will be taken + protected virtual void FillInValues(OLVListItem lvi, object rowObject) { + if (this.Columns.Count == 0) + return; + + OLVListSubItem subItem = this.MakeSubItem(rowObject, this.GetColumn(0)); + lvi.SubItems[0] = subItem; + lvi.ImageSelector = subItem.ImageSelector; + + // Give the item the same font/colors as the control + lvi.Font = this.Font; + lvi.BackColor = this.BackColor; + lvi.ForeColor = this.ForeColor; + + // Should the row be selectable? + lvi.Enabled = !this.IsDisabled(rowObject); + + // Only Details and Tile views have subitems + switch (this.View) { + case View.Details: + for (int i = 1; i < this.Columns.Count; i++) { + lvi.SubItems.Add(this.MakeSubItem(rowObject, this.GetColumn(i))); + } + break; + case View.Tile: + for (int i = 1; i < this.Columns.Count; i++) { + OLVColumn column = this.GetColumn(i); + if (column.IsTileViewColumn) + lvi.SubItems.Add(this.MakeSubItem(rowObject, column)); + } + break; + } + + // Should the row be selectable? + if (!lvi.Enabled) { + lvi.UseItemStyleForSubItems = false; + ApplyRowStyle(lvi, this.DisabledItemStyle ?? ObjectListView.DefaultDisabledItemStyle); + } + + // Set the check state of the row, if we are showing check boxes + if (this.CheckBoxes) { + CheckState? state = this.GetCheckState(lvi.RowObject); + if (state.HasValue) + lvi.CheckState = state.Value; + } + + // Give the RowFormatter a chance to mess with the item + if (this.RowFormatter != null) { + this.RowFormatter(lvi); + } + } + + private OLVListSubItem MakeSubItem(object rowObject, OLVColumn column) { + object cellValue = column.GetValue(rowObject); + OLVListSubItem subItem = new OLVListSubItem(cellValue, + column.ValueToString(cellValue), + column.GetImage(rowObject)); + if (this.UseHyperlinks && column.Hyperlink) { + IsHyperlinkEventArgs args = new IsHyperlinkEventArgs(); + args.ListView = this; + args.Model = rowObject; + args.Column = column; + args.Text = subItem.Text; + args.Url = subItem.Text; + args.IsHyperlink = !this.IsDisabled(rowObject); + this.OnIsHyperlink(args); + subItem.Url = args.IsHyperlink ? args.Url : null; + } + + return subItem; + } + + private void ApplyHyperlinkStyle(OLVListItem olvi) { + + for (int i = 0; i < this.Columns.Count; i++) { + OLVListSubItem subItem = olvi.GetSubItem(i); + if (subItem == null) + continue; + OLVColumn column = this.GetColumn(i); + if (column.Hyperlink && !String.IsNullOrEmpty(subItem.Url)) + this.ApplyCellStyle(olvi, i, this.IsUrlVisited(subItem.Url) ? this.HyperlinkStyle.Visited : this.HyperlinkStyle.Normal); + } + } + + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + protected virtual void ForceSubItemImagesExStyle() { + // Virtual lists can't show subitem images natively, so don't turn on this flag + if (!this.VirtualMode) + NativeMethods.ForceSubItemImagesExStyle(this); + } + + /// + /// Convert the given image selector to an index into our image list. + /// Return -1 if that's not possible + /// + /// + /// Index of the image in the imageList, or -1 + protected virtual int GetActualImageIndex(Object imageSelector) { + if (imageSelector == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null && this.SmallImageList != null) + return this.SmallImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given column + /// + /// The column index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetHeaderToolTip(int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return null; + String tooltip = column.ToolTipText; + if (this.HeaderToolTipGetter != null) + tooltip = this.HeaderToolTipGetter(column); + return tooltip; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given cell + /// + /// The column index whose tool tip is to be fetched + /// The row index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetCellToolTip(int columnIndex, int rowIndex) { + if (this.CellToolTipGetter != null) + return this.CellToolTipGetter(this.GetColumn(columnIndex), this.GetModelObject(rowIndex)); + + // Show the URL in the tooltip if it's different to the text + if (columnIndex >= 0) { + OLVListSubItem subItem = this.GetSubItem(rowIndex, columnIndex); + if (subItem != null && !String.IsNullOrEmpty(subItem.Url) && subItem.Url != subItem.Text && + this.HotCellHitLocation == HitTestLocation.Text) + return subItem.Url; + } + + return null; + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public virtual OLVListItem ModelToItem(object modelObject) { + if (modelObject == null) + return null; + + foreach (OLVListItem olvi in this.Items) { + if (olvi.RowObject != null && olvi.RowObject.Equals(modelObject)) + return olvi; + } + return null; + } + + /// + /// Do the work required after the items in a listview have been created + /// + protected virtual void PostProcessRows() { + // If this method is called during a BeginUpdate/EndUpdate pair, changes to the + // Items collection are cached. Getting the Count flushes that cache. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int count = this.Items.Count; +#pragma warning restore 168 + + int i = 0; + if (this.ShowGroups) { + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } else { + foreach (OLVListItem olvi in this.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } + + /// + /// Do the work required after one item in a listview have been created + /// + protected virtual void PostProcessOneRow(int rowIndex, int displayIndex, OLVListItem olvi) { + if (this.Columns.Count == 0) + return; + if (this.UseAlternatingBackColors && this.View == View.Details && olvi.Enabled) { + olvi.UseItemStyleForSubItems = true; + olvi.BackColor = displayIndex % 2 == 1 ? this.AlternateRowBackColorOrDefault : this.BackColor; + } + if (this.ShowImagesOnSubItems && !this.VirtualMode) + this.SetSubItemImages(rowIndex, olvi); + + bool needToTriggerFormatCellEvents = this.TriggerFormatRowEvent(rowIndex, displayIndex, olvi); + + // We only need cell level events if we are in details view + if (this.View != View.Details) + return; + + // If we're going to have per cell formatting, we need to copy the formatting + // of the item into each cell, before triggering the cell format events + if (needToTriggerFormatCellEvents) { + PropagateFormatFromRowToCells(olvi); + this.TriggerFormatCellEvents(rowIndex, displayIndex, olvi); + } + + // Similarly, if any cell in the row has hyperlinks, we have to copy formatting + // from the item into each cell before applying the hyperlink style + if (this.UseHyperlinks && olvi.HasAnyHyperlinks) { + PropagateFormatFromRowToCells(olvi); + this.ApplyHyperlinkStyle(olvi); + } + } + + /// + /// Prepare the listview to show alternate row backcolors + /// + /// We cannot rely on lvi.Index in this method. + /// In a straight list, lvi.Index is the display index, and can be used to determine + /// whether the row should be colored. But when organised by groups, lvi.Index is not + /// usable because it still refers to the position in the overall list, not the display order. + /// + [Obsolete("This method is no longer used. Override PostProcessOneRow() to achieve a similar result")] + protected virtual void PrepareAlternateBackColors() { + } + + /// + /// Setup all subitem images on all rows + /// + [Obsolete("This method is not longer maintained and will be removed", false)] + protected virtual void SetAllSubItemImages() { + //if (!this.ShowImagesOnSubItems || this.OwnerDraw) + // return; + + //this.ForceSubItemImagesExStyle(); + + //for (int rowIndex = 0; rowIndex < this.GetItemCount(); rowIndex++) + // SetSubItemImages(rowIndex, this.GetItem(rowIndex)); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item) { + this.SetSubItemImages(rowIndex, item, false); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + /// will existing images be cleared if no new image is provided? + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item, bool shouldClearImages) { + if (!this.ShowImagesOnSubItems || this.OwnerDraw) + return; + + for (int i = 1; i < item.SubItems.Count; i++) { + this.SetSubItemImage(rowIndex, i, item.GetSubItem(i), shouldClearImages); + } + } + + /// + /// Set the subitem image natively + /// + /// + /// + /// + /// + public virtual void SetSubItemImage(int rowIndex, int subItemIndex, OLVListSubItem subItem, bool shouldClearImages) { + int imageIndex = this.GetActualImageIndex(subItem.ImageSelector); + if (shouldClearImages || imageIndex != -1) + NativeMethods.SetSubItemImage(this, rowIndex, subItemIndex, imageIndex); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// This method has the intentional side-effect of converting our list of objects to an ArrayList. + /// + /// + protected virtual void TakeOwnershipOfObjects() { + if (this.isOwnerOfObjects) + return; + + this.isOwnerOfObjects = true; + + this.objects = ObjectListView.EnumerableToArray(this.objects, true); + } + + /// + /// Trigger FormatRow and possibly FormatCell events for the given item + /// + /// + /// + /// + protected virtual bool TriggerFormatRowEvent(int rowIndex, int displayIndex, OLVListItem olvi) { + FormatRowEventArgs args = new FormatRowEventArgs(); + args.ListView = this; + args.RowIndex = rowIndex; + args.DisplayIndex = displayIndex; + args.Item = olvi; + args.UseCellFormatEvents = this.UseCellFormatEvents; + this.OnFormatRow(args); + return args.UseCellFormatEvents; + } + + /// + /// Trigger FormatCell events for the given item + /// + /// + /// + /// + protected virtual void TriggerFormatCellEvents(int rowIndex, int displayIndex, OLVListItem olvi) { + + PropagateFormatFromRowToCells(olvi); + + // Fire one event per cell + FormatCellEventArgs args2 = new FormatCellEventArgs(); + args2.ListView = this; + args2.RowIndex = rowIndex; + args2.DisplayIndex = displayIndex; + args2.Item = olvi; + for (int i = 0; i < this.Columns.Count; i++) { + args2.ColumnIndex = i; + args2.Column = this.GetColumn(i); + args2.SubItem = olvi.GetSubItem(i); + this.OnFormatCell(args2); + } + } + + private static void PropagateFormatFromRowToCells(OLVListItem olvi) { + // If a cell isn't given its own colors, it *should* use the colors of the item. + // However, there is a bug in the .NET framework where the cell are given + // the colors of the ListView instead of the colors of the row. + + // If we've already done this, don't do it again + if (olvi.UseItemStyleForSubItems == false) + return; + + // So we have to explicitly give each cell the fore and back colors and the font that it should have. + olvi.UseItemStyleForSubItems = false; + Color backColor = olvi.BackColor; + Color foreColor = olvi.ForeColor; + Font font = olvi.Font; + foreach (ListViewItem.ListViewSubItem subitem in olvi.SubItems) { + subitem.BackColor = backColor; + subitem.ForeColor = foreColor; + subitem.Font = font; + } + } + + /// + /// Make the list forget everything -- all rows and all columns + /// + /// Use if you want to remove just the rows. + public virtual void Reset() { + this.Clear(); + this.AllColumns.Clear(); + this.ClearObjects(); + this.PrimarySortColumn = null; + this.SecondarySortColumn = null; + this.ClearDisabledObjects(); + this.ClearPersistentCheckState(); + this.ClearUrlVisited(); + this.ClearHotItem(); + } + + + #endregion + + #region ISupportInitialize Members + + void ISupportInitialize.BeginInit() { + this.Frozen = true; + } + + void ISupportInitialize.EndInit() { + if (this.RowHeight != -1) { + this.SmallImageList = this.SmallImageList; + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + + if (this.UseSubItemCheckBoxes || (this.VirtualMode && this.CheckBoxes)) + this.SetupSubItemCheckBoxes(); + + this.Frozen = false; + } + + #endregion + + #region Image list manipulation + + /// + /// Update our externally visible image list so it holds the same images as our shadow list, but sized correctly + /// + private void SetupBaseImageList() { + // If a row height hasn't been set, or an image list has been give which is the required size, just assign it + if (rowHeight == -1 || + this.View != View.Details || + (this.shadowedImageList != null && this.shadowedImageList.ImageSize.Height == rowHeight)) + this.BaseSmallImageList = this.shadowedImageList; + else { + int width = (this.shadowedImageList == null ? 16 : this.shadowedImageList.ImageSize.Width); + this.BaseSmallImageList = this.MakeResizedImageList(width, rowHeight, shadowedImageList); + } + } + + /// + /// Return a copy of the given source image list, where each image has been resized to be height x height in size. + /// If source is null, an empty image list of the given size is returned + /// + /// Height and width of the new images + /// Height and width of the new images + /// Source of the images (can be null) + /// A new image list + private ImageList MakeResizedImageList(int width, int height, ImageList source) { + ImageList il = new ImageList(); + il.ImageSize = new Size(width, height); + + // If there's nothing to copy, just return the new list + if (source == null) + return il; + + il.TransparentColor = source.TransparentColor; + il.ColorDepth = source.ColorDepth; + + // Fill the imagelist with resized copies from the source + for (int i = 0; i < source.Images.Count; i++) { + Bitmap bm = this.MakeResizedImage(width, height, source.Images[i], source.TransparentColor); + il.Images.Add(bm); + } + + // Give each image the same key it has in the original + foreach (String key in source.Images.Keys) { + il.Images.SetKeyName(source.Images.IndexOfKey(key), key); + } + + return il; + } + + /// + /// Return a bitmap of the given height x height, which shows the given image, centred. + /// + /// Height and width of new bitmap + /// Height and width of new bitmap + /// Image to be centred + /// The background color + /// A new bitmap + private Bitmap MakeResizedImage(int width, int height, Image image, Color transparent) { + Bitmap bm = new Bitmap(width, height); + Graphics g = Graphics.FromImage(bm); + g.Clear(transparent); + int x = Math.Max(0, (bm.Size.Width - image.Size.Width) / 2); + int y = Math.Max(0, (bm.Size.Height - image.Size.Height) / 2); + g.DrawImage(image, x, y, image.Size.Width, image.Size.Height); + return bm; + } + + /// + /// Initialize the state image list with the required checkbox images + /// + protected virtual void InitializeStateImageList() { + if (this.DesignMode) + return; + + if (!this.CheckBoxes) + return; + + if (this.StateImageList == null) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight == -1 ? 16 : this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + if (this.RowHeight != -1 && + this.View == View.Details && + this.StateImageList.ImageSize.Height != this.RowHeight) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + // The internal logic of ListView cycles through the state images when the primary + // checkbox is clicked. So we have to get exactly the right number of images in the + // image list. + if (this.StateImageList.Images.Count == 0) + this.AddCheckStateBitmap(this.StateImageList, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + if (this.StateImageList.Images.Count <= 1) + this.AddCheckStateBitmap(this.StateImageList, CHECKED_KEY, CheckBoxState.CheckedNormal); + if (this.TriStateCheckBoxes && this.StateImageList.Images.Count <= 2) + this.AddCheckStateBitmap(this.StateImageList, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + else { + if (this.StateImageList.Images.ContainsKey(INDETERMINATE_KEY)) + this.StateImageList.Images.RemoveByKey(INDETERMINATE_KEY); + } + } + + /// + /// The name of the image used when a check box is checked + /// + public const string CHECKED_KEY = "checkbox-checked"; + + /// + /// The name of the image used when a check box is unchecked + /// + public const string UNCHECKED_KEY = "checkbox-unchecked"; + + /// + /// The name of the image used when a check box is Indeterminate + /// + public const string INDETERMINATE_KEY = "checkbox-indeterminate"; + + /// + /// Setup this control so it can display check boxes on subitems + /// (or primary checkboxes in virtual mode) + /// + /// This gives the ListView a small image list, if it doesn't already have one. + public virtual void SetupSubItemCheckBoxes() { + this.ShowImagesOnSubItems = true; + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(CHECKED_KEY)) + this.InitializeSubItemCheckBoxImages(); + } + + /// + /// Make sure the small image list for this control has checkbox images + /// (used for sub-item checkboxes). + /// + /// + /// + /// This gives the ListView a small image list, if it doesn't already have one. + /// + /// + /// ObjectListView has to manage checkboxes on subitems separate from the checkboxes on each row. + /// The underlying ListView knows about the per-row checkboxes, and to make them work, OLV has to + /// correctly configure the StateImageList. However, the ListView cannot do checkboxes in subitems, + /// so ObjectListView has to handle them in a different fashion. So, per-row checkboxes are controlled + /// by images in the StateImageList, but per-cell checkboxes are handled by images in the SmallImageList. + /// + /// + protected virtual void InitializeSubItemCheckBoxImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + this.AddCheckStateBitmap(il, CHECKED_KEY, CheckBoxState.CheckedNormal); + this.AddCheckStateBitmap(il, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + this.AddCheckStateBitmap(il, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + + this.SmallImageList = il; + } + + private void AddCheckStateBitmap(ImageList il, string key, CheckBoxState boxState) { + Bitmap b = new Bitmap(il.ImageSize.Width, il.ImageSize.Height); + Graphics g = Graphics.FromImage(b); + g.Clear(il.TransparentColor); + Point location = new Point(b.Width / 2 - 5, b.Height / 2 - 6); + CheckBoxRenderer.DrawCheckBox(g, location, boxState); + il.Images.Add(key, b); + } + + #endregion + + #region Owner drawing + + /// + /// Owner draw the column header + /// + /// + protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { + e.DrawDefault = true; + base.OnDrawColumnHeader(e); + } + + /// + /// Owner draw the item + /// + /// + protected override void OnDrawItem(DrawListViewItemEventArgs e) { + if (this.View == View.Details) + e.DrawDefault = false; + else { + if (this.ItemRenderer == null) + e.DrawDefault = true; + else { + Object row = ((OLVListItem)e.Item).RowObject; + e.DrawDefault = !this.ItemRenderer.RenderItem(e, e.Graphics, e.Bounds, row); + } + } + + if (e.DrawDefault) + base.OnDrawItem(e); + } + + /// + /// Owner draw a single subitem + /// + /// + protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnDrawSubItem ({0}, {1})", e.ItemIndex, e.ColumnIndex)); + // Don't try to do owner drawing at design time + if (this.DesignMode) { + e.DrawDefault = true; + return; + } + + object rowObject = ((OLVListItem)e.Item).RowObject; + + // Calculate where the subitem should be drawn + Rectangle r = e.Bounds; + + // Get the special renderer for this column. If there isn't one, use the default draw mechanism. + OLVColumn column = this.GetColumn(e.ColumnIndex); + IRenderer renderer = this.GetCellRenderer(rowObject, column); + + // Get a graphics context for the renderer to use. + // But we have more complications. Virtual lists have a nasty habit of drawing column 0 + // whenever there is any mouse move events over a row, and doing it in an un-double-buffered manner, + // which results in nasty flickers! There are also some unbuffered draw when a mouse is first + // hovered over column 0 of a normal row. So, to avoid all complications, + // we always manually double-buffer the drawing. + // Except with Mono, which doesn't seem to handle double buffering at all :-( + BufferedGraphics buffer = BufferedGraphicsManager.Current.Allocate(e.Graphics, r); + Graphics g = buffer.Graphics; + + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + // Finally, give the renderer a chance to draw something + e.DrawDefault = !renderer.RenderSubItem(e, g, r, rowObject); + + if (!e.DrawDefault) + buffer.Render(); + buffer.Dispose(); + } + + #endregion + + #region OnEvent Handling + + /// + /// We need the click count in the mouse up event, but that is always 1. + /// So we have to remember the click count from the preceding mouse down event. + /// + /// + protected override void OnMouseDown(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseDown: {0}, {1}", e.Button, e.Clicks)); + this.lastMouseDownClickCount = e.Clicks; + this.lastMouseDownButton = e.Button; + base.OnMouseDown(e); + } + private int lastMouseDownClickCount; + private MouseButtons lastMouseDownButton; + + /// + /// When the mouse leaves the control, remove any hot item highlighting + /// + /// + protected override void OnMouseLeave(EventArgs e) { + base.OnMouseLeave(e); + + if (!this.Created) + return; + + this.UpdateHotItem(new Point(-1,-1)); + } + + // We could change the hot item on the mouse hover event, but it looks wrong. + + //protected override void OnMouseHover(EventArgs e) { + // System.Diagnostics.Debug.WriteLine(String.Format("OnMouseHover")); + // base.OnMouseHover(e); + // this.UpdateHotItem(this.PointToClient(Cursor.Position)); + //} + + /// + /// When the mouse moves, we might need to change the hot item. + /// + /// + protected override void OnMouseMove(MouseEventArgs e) { + base.OnMouseMove(e); + + if (this.Created) + HandleMouseMove(e.Location); + } + + internal void HandleMouseMove(Point pt) { + //System.Diagnostics.Debug.WriteLine(String.Format("HandleMouseMove: {0}", pt)); + + CellOverEventArgs args = new CellOverEventArgs(); + this.BuildCellEvent(args, pt); + this.OnCellOver(args); + this.MouseMoveHitTest = args.HitTest; + + if (!args.Handled) + this.UpdateHotItem(args.HitTest); + } + + /// + /// Check to see if we need to start editing a cell + /// + /// + protected override void OnMouseUp(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseUp: {0}, {1}", e.Button, e.Clicks)); + + base.OnMouseUp(e); + + if (!this.Created) + return; + + // Sigh! More complexity. e.Button is not reliable when clicking on group headers. + // The mouse up event for first click on a group header always reports e.Button as None. + // Subsequent mouse up events report the button from the previous event. + // However, mouse down events are correctly reported, so we use the button value from + // the last mouse down event. + if (this.lastMouseDownButton == MouseButtons.Right) { + this.OnRightMouseUp(e); + return; + } + + // What event should we listen for to start cell editing? + // ------------------------------------------------------ + // + // We can't use OnMouseClick, OnMouseDoubleClick, OnClick, or OnDoubleClick + // since they are not triggered for clicks on subitems without Full Row Select. + // + // We could use OnMouseDown, but selecting rows is done in OnMouseUp. This means + // that if we start the editing during OnMouseDown, the editor will automatically + // lose focus when mouse up happens. + // + + // Tell the world about a cell click. If someone handles it, don't do anything else + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, e.Location); + args.ClickCount = this.lastMouseDownClickCount; + this.OnCellClick(args); + if (args.Handled) + return; + + // Did the user click a hyperlink? + if (this.UseHyperlinks && + args.HitTest.HitTestLocation == HitTestLocation.Text && + args.SubItem != null && + !String.IsNullOrEmpty(args.SubItem.Url)) { + // We have to delay the running of this process otherwise we can generate + // a series of MouseUp events (don't ask me why) + this.BeginInvoke((MethodInvoker)delegate { this.ProcessHyperlinkClicked(args); }); + } + + // No one handled it so check to see if we should start editing. + if (!this.ShouldStartCellEdit(e)) + return; + + // We only start the edit if the user clicked on the image or text. + if (args.HitTest.HitTestLocation == HitTestLocation.Nothing) + return; + + // We don't edit the primary column by single clicks -- only subitems. + if (this.CellEditActivation == CellEditActivateMode.SingleClick && args.ColumnIndex <= 0) + return; + + // Don't start a cell edit operation when the user clicks on the background of a checkbox column -- it just looks wrong. + // If the user clicks on the actual checkbox, changing the checkbox state is handled elsewhere. + if (args.Column != null && args.Column.CheckBoxes) + return; + + this.EditSubItem(args.Item, args.ColumnIndex); + } + + /// + /// Tell the world that a hyperlink was clicked and if the event isn't handled, + /// do the default processing. + /// + /// + protected virtual void ProcessHyperlinkClicked(CellClickEventArgs e) { + HyperlinkClickedEventArgs args = new HyperlinkClickedEventArgs(); + args.HitTest = e.HitTest; + args.ListView = this; + args.Location = new Point(-1, -1); + args.Item = e.Item; + args.SubItem = e.SubItem; + args.Model = e.Model; + args.ColumnIndex = e.ColumnIndex; + args.Column = e.Column; + args.RowIndex = e.RowIndex; + args.ModifierKeys = Control.ModifierKeys; + args.Url = e.SubItem.Url; + this.OnHyperlinkClicked(args); + if (!args.Handled) { + this.StandardHyperlinkClickedProcessing(args); + } + } + + /// + /// Do the default processing for a hyperlink clicked event, which + /// is to try and open the url. + /// + /// + protected virtual void StandardHyperlinkClickedProcessing(HyperlinkClickedEventArgs args) { + Cursor originalCursor = this.Cursor; + try { + this.Cursor = Cursors.WaitCursor; + System.Diagnostics.Process.Start(args.Url); + } catch (Win32Exception) { + System.Media.SystemSounds.Beep.Play(); + // ignore it + } finally { + this.Cursor = originalCursor; + } + this.MarkUrlVisited(args.Url); + this.RefreshHotItem(); + } + + /// + /// The user right clicked on the control + /// + /// + protected virtual void OnRightMouseUp(MouseEventArgs e) { + CellRightClickEventArgs args = new CellRightClickEventArgs(); + this.BuildCellEvent(args, e.Location); + this.OnCellRightClick(args); + if (!args.Handled) { + if (args.MenuStrip != null) { + args.MenuStrip.Show(this, args.Location); + } + } + } + + internal void BuildCellEvent(CellEventArgs args, Point location) { + BuildCellEvent(args, location, this.OlvHitTest(location.X, location.Y)); + } + + internal void BuildCellEvent(CellEventArgs args, Point location, OlvListViewHitTestInfo hitTest) { + args.HitTest = hitTest; + args.ListView = this; + args.Location = location; + args.Item = hitTest.Item; + args.SubItem = hitTest.SubItem; + args.Model = hitTest.RowObject; + args.ColumnIndex = hitTest.ColumnIndex; + args.Column = hitTest.Column; + if (hitTest.Item != null) + args.RowIndex = hitTest.Item.Index; + args.ModifierKeys = Control.ModifierKeys; + + // In non-details view, we want any hit on an item to act as if it was a hit + // on column 0 -- which, effectively, it was. + if (args.Item != null && args.ListView.View != View.Details) { + args.ColumnIndex = 0; + args.Column = args.ListView.GetColumn(0); + args.SubItem = args.Item.GetSubItem(0); + } + } + + /// + /// This method is called every time a row is selected or deselected. This can be + /// a pain if the user shift-clicks 100 rows. We override this method so we can + /// trigger one event for any number of select/deselects that come from one user action + /// + /// + protected override void OnSelectedIndexChanged(EventArgs e) { + if (this.SelectionEventsSuspended) + return; + + base.OnSelectedIndexChanged(e); + + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Schedule a SelectionChanged event to happen after the next idle event, + /// unless we've already scheduled that to happen. + /// + protected virtual void TriggerDeferredSelectionChangedEvent() { + if (this.SelectionEventsSuspended) + return; + + // If we haven't already scheduled an event, schedule it to be triggered + // By using idle time, we will wait until all select events for the same + // user action have finished before triggering the event. + if (!this.hasIdleHandler) { + this.hasIdleHandler = true; + this.RunWhenIdle(HandleApplicationIdle); + } + } + + /// + /// Called when the handle of the underlying control is created + /// + /// + protected override void OnHandleCreated(EventArgs e) { + //Debug.WriteLine("OnHandleCreated"); + base.OnHandleCreated(e); + + this.Invoke((MethodInvoker)this.OnControlCreated); + } + + /// + /// This method is called after the control has been fully created. + /// + protected virtual void OnControlCreated() { + + //Debug.WriteLine("OnControlCreated"); + + // Force the header control to be created when the listview handle is + HeaderControl hc = this.HeaderControl; + hc.WordWrap = this.HeaderWordWrap; + + // Make sure any overlays that are set on the hot item style take effect + this.HotItemStyle = this.HotItemStyle; + + // Arrange for any group images to be installed after the control is created + NativeMethods.SetGroupImageList(this, this.GroupImageList); + + this.UseExplorerTheme = this.UseExplorerTheme; + + this.RememberDisplayIndicies(); + this.SetGroupSpacing(); + + if (this.VirtualMode) + this.ApplyExtendedStyles(); + } + + #endregion + + #region Cell editing + + /// + /// Should we start editing the cell in response to the given mouse button event? + /// + /// + /// + protected virtual bool ShouldStartCellEdit(MouseEventArgs e) { + if (this.IsCellEditing) + return false; + + if (e.Button != MouseButtons.Left && e.Button != MouseButtons.Right) + return false; + + if ((Control.ModifierKeys & (Keys.Shift | Keys.Control | Keys.Alt)) != 0) + return false; + + if (this.lastMouseDownClickCount == 1 && ( + this.CellEditActivation == CellEditActivateMode.SingleClick || + this.CellEditActivation == CellEditActivateMode.SingleClickAlways)) + return true; + + return (this.lastMouseDownClickCount == 2 && this.CellEditActivation == CellEditActivateMode.DoubleClick); + } + + /// + /// Handle a key press on this control. We specifically look for F2 which edits the primary column, + /// or a Tab character during an edit operation, which tries to start editing on the next (or previous) cell. + /// + /// + /// + protected override bool ProcessDialogKey(Keys keyData) { + + if (this.IsCellEditing) + return this.CellEditKeyEngine.HandleKey(this, keyData); + + // Treat F2 as a request to edit the primary column + if (keyData == Keys.F2) { + this.EditSubItem((OLVListItem)this.FocusedItem, 0); + return base.ProcessDialogKey(keyData); + } + + // Treat Ctrl-C as Copy To Clipboard. + if (this.CopySelectionOnControlC && keyData == (Keys.C | Keys.Control)) { + this.CopySelectionToClipboard(); + return true; + } + + // Treat Ctrl-A as Select All. + if (this.SelectAllOnControlA && keyData == (Keys.A | Keys.Control)) { + this.SelectAll(); + return true; + } + + return base.ProcessDialogKey(keyData); + } + + /// + /// Start an editing operation on the first editable column of the given model. + /// + /// + /// + /// + /// If the model doesn't exist, or there are no editable columns, this method + /// will do nothing. + /// + /// This will start an edit operation regardless of CellActivationMode. + /// + /// + public virtual void EditModel(object rowModel) { + OLVListItem olvItem = this.ModelToItem(rowModel); + if (olvItem == null) + return; + + for (int i = 0; i < olvItem.SubItems.Count; i++) { + var olvColumn = this.GetColumn(i); + if (olvColumn != null && olvColumn.IsEditable) { + this.StartCellEdit(olvItem, i); + return; + } + } + } + + /// + /// Begin an edit operation on the given cell. + /// + /// This performs various sanity checks and passes off the real work to StartCellEdit(). + /// The row to be edited + /// The index of the cell to be edited + public virtual void EditSubItem(OLVListItem item, int subItemIndex) { + if (item == null) + return; + + if (this.CellEditActivation == CellEditActivateMode.None) + return; + + OLVColumn olvColumn = this.GetColumn(subItemIndex); + if (olvColumn == null || !olvColumn.IsEditable) + return; + + if (!item.Enabled) + return; + + this.StartCellEdit(item, subItemIndex); + } + + /// + /// Really start an edit operation on a given cell. The parameters are assumed to be sane. + /// + /// The row to be edited + /// The index of the cell to be edited + public virtual void StartCellEdit(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + if (column == null) + return; + Control c = this.GetCellEditor(item, subItemIndex); + Rectangle cellBounds = this.CalculateCellBounds(item, subItemIndex); + c.Bounds = this.CalculateCellEditorBounds(item, subItemIndex, c.PreferredSize); + + // Try to align the control as the column is aligned. Not all controls support this property + Munger.PutProperty(c, "TextAlign", column.TextAlign); + + // Give the control the value from the model + this.SetControlValue(c, column.GetValue(item.RowObject), column.GetStringValue(item.RowObject)); + + // Give the outside world the chance to munge with the process + this.CellEditEventArgs = new CellEditEventArgs(column, c, cellBounds, item, subItemIndex); + this.OnCellEditStarting(this.CellEditEventArgs); + if (this.CellEditEventArgs.Cancel) + return; + + // The event handler may have completely changed the control, so we need to remember it + this.cellEditor = this.CellEditEventArgs.Control; + + this.Invalidate(); + this.Controls.Add(this.cellEditor); + this.ConfigureControl(); + this.PauseAnimations(true); + } + private Control cellEditor; + internal CellEditEventArgs CellEditEventArgs; + + /// + /// Calculate the bounds of the edit control for the given item/column + /// + /// + /// + /// + /// + public Rectangle CalculateCellEditorBounds(OLVListItem item, int subItemIndex, Size preferredSize) { + Rectangle r = CalculateCellBounds(item, subItemIndex); + + // Calculate the width of the cell's current contents + return this.OwnerDraw + ? CalculateCellEditorBoundsOwnerDrawn(item, subItemIndex, r, preferredSize) + : CalculateCellEditorBoundsStandard(item, subItemIndex, r, preferredSize); + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsOwnerDrawn(OLVListItem item, int subItemIndex, Rectangle r, Size preferredSize) { + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(item.RowObject, this.GetColumn(subItemIndex)) + : this.ItemRenderer; + + if (renderer == null) + return r; + + using (Graphics g = this.CreateGraphics()) { + return renderer.GetEditRectangle(g, r, item, subItemIndex, preferredSize); + } + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is not being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsStandard(OLVListItem item, int subItemIndex, Rectangle cellBounds, Size preferredSize) { + if (this.View == View.Tile) + return cellBounds; + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + // Only Details view needs more processing + if (this.View != View.Details) + return cellBounds; + + // Allow for image (if there is one). + int offset = 0; + object imageSelector = null; + if (subItemIndex == 0) + imageSelector = item.ImageSelector; + else { + // We only check for subitem images if we are owner drawn or showing subitem images + if (this.OwnerDraw || this.ShowImagesOnSubItems) + imageSelector = item.GetSubItem(subItemIndex).ImageSelector; + } + if (this.GetActualImageIndex(imageSelector) != -1) { + offset += this.SmallImageSize.Width + 2; + } + + // Allow for checkbox + if (this.CheckBoxes && this.StateImageList != null && subItemIndex == 0) { + offset += this.StateImageList.ImageSize.Width + 2; + } + + // Allow for indent (first column only) + if (subItemIndex == 0 && item.IndentCount > 0) { + offset += (this.SmallImageSize.Width * item.IndentCount); + } + + // Do the adjustment + if (offset > 0) { + cellBounds.X += offset; + cellBounds.Width -= offset; + } + + return cellBounds; + } + + /// + /// Try to give the given value to the provided control. Fall back to assigning a string + /// if the value assignment fails. + /// + /// A control + /// The value to be given to the control + /// The string to be given if the value doesn't work + protected virtual void SetControlValue(Control control, Object value, String stringValue) { + // Does the control implement our custom interface? + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) { + olvEditor.Value = value; + return; + } + + // Handle combobox explicitly + ComboBox cb = control as ComboBox; + if (cb != null) { + if (cb.Created) + cb.SelectedValue = value; + else + this.BeginInvoke(new MethodInvoker(delegate { + cb.SelectedValue = value; + })); + return; + } + + if (Munger.PutProperty(control, "Value", value)) + return; + + // There wasn't a Value property, or we couldn't set it, so set the text instead + try + { + String valueAsString = value as String; + control.Text = valueAsString ?? stringValue; + } + catch (ArgumentOutOfRangeException) { + // The value couldn't be set via the Text property. + } + } + + /// + /// Setup the given control to be a cell editor + /// + protected virtual void ConfigureControl() { + this.cellEditor.Validating += new CancelEventHandler(CellEditor_Validating); + this.cellEditor.Select(); + } + + /// + /// Return the value that the given control is showing + /// + /// + /// + protected virtual Object GetControlValue(Control control) { + if (control == null) + return null; + + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) + return olvEditor.Value; + + TextBox box = control as TextBox; + if (box != null) + return box.Text; + + ComboBox comboBox = control as ComboBox; + if (comboBox != null) + return comboBox.SelectedValue; + + CheckBox checkBox = control as CheckBox; + if (checkBox != null) + return checkBox.Checked; + + try { + return control.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, control, null); + } catch (MissingMethodException) { // Microsoft throws this + return control.Text; + } catch (MissingFieldException) { // Mono throws this + return control.Text; + } + } + + /// + /// Called when the cell editor could be about to lose focus. Time to commit the change + /// + /// + /// + protected virtual void CellEditor_Validating(object sender, CancelEventArgs e) { + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Control.Select(); + e.Cancel = true; + } else + FinishCellEdit(); + } + + /// + /// Return the bounds of the given cell + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex) { + + // It seems on Win7, GetSubItemBounds() does not have the same problems with + // column 0 that it did previously. + + // TODO - Check on XP + + if (this.View != View.Details) + return this.GetItemRect(item.Index, ItemBoundsPortion.Label); + + Rectangle r = item.GetSubItemBounds(subItemIndex); + r.Width -= 1; + r.Height -= 1; + return r; + + // We use ItemBoundsPortion.Label rather than ItemBoundsPortion.Item + // since Label extends to the right edge of the cell, whereas Item gives just the + // current text width. + //return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.Label); + } + + /// + /// Return the bounds of the given cell only until the edge of the current text + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellTextBounds(OLVListItem item, int subItemIndex) { + return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.ItemOnly); + } + + private Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex, ItemBoundsPortion portion) { + // SubItem.Bounds works for every subitem, except the first. + if (subItemIndex > 0) + return item.GetSubItemBounds(subItemIndex); + + // For non detail views, we just use the requested portion + Rectangle r = this.GetItemRect(item.Index, portion); + if (r.Y < -10000000 || r.Y > 10000000) { + r.Y = item.Bounds.Y; + } + if (this.View != View.Details) + return r; + + // Finding the bounds of cell 0 should not be a difficult task, but it is. Problems: + // 1) item.SubItem[0].Bounds is always the full bounds of the entire row, not just cell 0. + // 2) if column 0 has been dragged to some other position, the bounds always has a left edge of 0. + + // We avoid both these problems by using the position of sides the column header to calculate + // the sides of the cell + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + r.X = sides.X + 4; + r.Width = sides.Y - sides.X - 5; + + return r; + } + + /// + /// Calculate the visible bounds of the given column. The column's bottom edge is + /// either the bottom of the last row or the bottom of the control. + /// + /// The bounds of the control itself + /// The column + /// A Rectangle + /// This returns an empty rectangle if the control isn't in Details mode, + /// OR has doesn't have any rows, OR if the given column is hidden. + public virtual Rectangle CalculateColumnVisibleBounds(Rectangle bounds, OLVColumn column) + { + // Sanity checks + if (column == null || + this.View != System.Windows.Forms.View.Details || + this.GetItemCount() == 0 || + !column.IsVisible) + return Rectangle.Empty; + + Point sides = NativeMethods.GetScrolledColumnSides(this, column.Index); + if (sides.X == -1) + return Rectangle.Empty; + + Rectangle columnBounds = new Rectangle(sides.X, bounds.Top, sides.Y - sides.X, bounds.Bottom); + + // Find the bottom of the last item. The column only extends to there. + OLVListItem lastItem = this.GetLastItemInDisplayOrder(); + if (lastItem != null) + { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + return columnBounds; + } + + /// + /// Return a control that can be used to edit the value of the given cell. + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Control to edit the given cell + protected virtual Control GetCellEditor(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + Object value = column.GetValue(item.RowObject); + + // Does the column have its own special way of creating cell editors? + if (column.EditorCreator != null) { + Control customEditor = column.EditorCreator(item.RowObject, column, value); + if (customEditor != null) + return customEditor; + } + + // Ask the registry for an instance of the appropriate editor. + // Use a default editor if the registry can't create one for us. + Control editor = ObjectListView.EditorRegistry.GetEditor(item.RowObject, column, value ?? this.GetFirstNonNullValue(column)); + return editor ?? this.MakeDefaultCellEditor(column); + } + + /// + /// Get the first non-null value of the given column. + /// At most 1000 rows will be considered. + /// + /// + /// The first non-null value, or null if no non-null values were found + internal object GetFirstNonNullValue(OLVColumn column) { + for (int i = 0; i < Math.Min(this.GetItemCount(), 1000); i++) { + object value = column.GetValue(this.GetModelObject(i)); + if (value != null) + return value; + } + return null; + } + + /// + /// Return a TextBox that can be used as a default cell editor. + /// + /// What column does the cell belong to? + /// + protected virtual Control MakeDefaultCellEditor(OLVColumn column) { + TextBox tb = new TextBox(); + if (column.AutoCompleteEditor) + this.ConfigureAutoComplete(tb, column); + return tb; + } + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + public void ConfigureAutoComplete(TextBox tb, OLVColumn column) { + this.ConfigureAutoComplete(tb, column, 1000); + } + + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + /// Consider only this many rows + public void ConfigureAutoComplete(TextBox tb, OLVColumn column, int maxRows) { + // Don't consider more rows than we actually have + maxRows = Math.Min(this.GetItemCount(), maxRows); + + // Reset any existing autocomplete + tb.AutoCompleteCustomSource.Clear(); + + // CONSIDER: Should we use ClusteringStrategy here? + + // Build a list of unique values, to be used as autocomplete on the editor + Dictionary alreadySeen = new Dictionary(); + List values = new List(); + for (int i = 0; i < maxRows; i++) { + string valueAsString = column.GetStringValue(this.GetModelObject(i)); + if (!String.IsNullOrEmpty(valueAsString) && !alreadySeen.ContainsKey(valueAsString)) { + values.Add(valueAsString); + alreadySeen[valueAsString] = true; + } + } + + tb.AutoCompleteCustomSource.AddRange(values.ToArray()); + tb.AutoCompleteSource = AutoCompleteSource.CustomSource; + tb.AutoCompleteMode = column.AutoCompleteEditorMode; + } + + /// + /// Stop editing a cell and throw away any changes. + /// + public virtual void CancelCellEdit() { + if (!this.IsCellEditing) + return; + + // Let the world know that the user has cancelled the edit operation + this.CellEditEventArgs.Cancel = true; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // Now cleanup the editing process + this.CleanupCellEdit(false, this.CellEditEventArgs.AutoDispose); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + public virtual bool PossibleFinishCellEditing() { + return this.PossibleFinishCellEditing(false); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual bool PossibleFinishCellEditing(bool expectingCellEdit) { + if (!this.IsCellEditing) + return true; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) + return false; + + this.FinishCellEdit(expectingCellEdit); + + return true; + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + public virtual void FinishCellEdit() { + this.FinishCellEdit(false); + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual void FinishCellEdit(bool expectingCellEdit) { + if (!this.IsCellEditing) + return; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // If someone doesn't cancel the editing process, write the value back into the model + if (!this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Column.PutValue(this.CellEditEventArgs.RowObject, this.CellEditEventArgs.NewValue); + this.RefreshItem(this.CellEditEventArgs.ListViewItem); + } + + this.CleanupCellEdit(expectingCellEdit, this.CellEditEventArgs.AutoDispose); + + // Tell the world that the cell has been edited + this.OnCellEditFinished(this.CellEditEventArgs); + } + + /// + /// Remove all trace of any existing cell edit operation + /// + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + /// True if the cell editor should be disposed + protected virtual void CleanupCellEdit(bool expectingCellEdit, bool disposeOfCellEditor) { + if (this.cellEditor == null) + return; + + this.cellEditor.Validating -= new CancelEventHandler(CellEditor_Validating); + + Control soonToBeOldCellEditor = this.cellEditor; + this.cellEditor = null; + + // Delay cleaning up the cell editor so that if we are immediately going to + // start a new cell edit (because the user pressed Tab) the new cell editor + // has a chance to grab the focus. Without this, the ListView gains focus + // momentarily (after the cell editor is remove and before the new one is created) + // causing the list's selection to flash momentarily. + EventHandler toBeRun = null; + toBeRun = delegate(object sender, EventArgs e) { + Application.Idle -= toBeRun; + this.Controls.Remove(soonToBeOldCellEditor); + if (disposeOfCellEditor) + soonToBeOldCellEditor.Dispose(); + this.Invalidate(); + + if (!this.IsCellEditing) { + if (this.Focused) + this.Select(); + this.PauseAnimations(false); + } + }; + + // We only want to delay the removal of the control if we are expecting another cell + // to be edited. Otherwise, we remove the control immediately. + if (expectingCellEdit) + this.RunWhenIdle(toBeRun); + else + toBeRun(null, null); + } + + #endregion + + #region Hot row and cell handling + + /// + /// Force the hot item to be recalculated + /// + public virtual void ClearHotItem() { + this.UpdateHotItem(new Point(-1, -1)); + } + + /// + /// Force the hot item to be recalculated + /// + public virtual void RefreshHotItem() { + this.UpdateHotItem(this.PointToClient(Cursor.Position)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// Where is the mouse? + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(Point pt) { + this.UpdateHotItem(this.OlvHitTest(pt.X, pt.Y)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(OlvListViewHitTestInfo hti) { + + // We only need to do the work of this method when the list has hot parts + // (i.e. some element whose visual appearance changes when under the mouse)? + // Hot item decorations and hyperlinks are obvious, but if we have checkboxes + // or buttons, those are also "hot". It's difficult to quickly detect if there are any + // columns that have checkboxes or buttons, so we just abdicate responsibility and + // provide a property (UseHotControls) which lets the programmer say whether to do + // the hot processing or not. + if (!this.UseHotItem && !this.UseHyperlinks && !this.UseHotControls) + return; + + int newHotRow = hti.RowIndex; + int newHotColumn = hti.ColumnIndex; + HitTestLocation newHotCellHitLocation = hti.HitTestLocation; + HitTestLocationEx newHotCellHitLocationEx = hti.HitTestLocationEx; + OLVGroup newHotGroup = hti.Group; + + // In non-details view, we treat any hit on a row as if it were a hit + // on column 0 -- which (effectively) it is! + if (newHotRow >= 0 && this.View != View.Details) + newHotColumn = 0; + + if (this.HotRowIndex == newHotRow && + this.HotColumnIndex == newHotColumn && + this.HotCellHitLocation == newHotCellHitLocation && + this.HotCellHitLocationEx == newHotCellHitLocationEx && + this.HotGroup == newHotGroup) { + return; + } + + // Trigger the hotitem changed event + HotItemChangedEventArgs args = new HotItemChangedEventArgs(); + args.HotCellHitLocation = newHotCellHitLocation; + args.HotCellHitLocationEx = newHotCellHitLocationEx; + args.HotColumnIndex = newHotColumn; + args.HotRowIndex = newHotRow; + args.HotGroup = newHotGroup; + args.OldHotCellHitLocation = this.HotCellHitLocation; + args.OldHotCellHitLocationEx = this.HotCellHitLocationEx; + args.OldHotColumnIndex = this.HotColumnIndex; + args.OldHotRowIndex = this.HotRowIndex; + args.OldHotGroup = this.HotGroup; + this.OnHotItemChanged(args); + + // Update the state of the control + this.HotRowIndex = newHotRow; + this.HotColumnIndex = newHotColumn; + this.HotCellHitLocation = newHotCellHitLocation; + this.HotCellHitLocationEx = newHotCellHitLocationEx; + this.HotGroup = newHotGroup; + + // If the event handler handled it complete, don't do anything else + if (args.Handled) + return; + +// System.Diagnostics.Debug.WriteLine(String.Format("Changed hot item: {0}", args)); + + this.BeginUpdate(); + try { + this.Invalidate(); + if (args.OldHotRowIndex != -1) + this.UnapplyHotItem(args.OldHotRowIndex); + + if (this.HotRowIndex != -1) { + // Virtual lists apply hot item style when fetching their rows + if (this.VirtualMode) { + this.ClearCachedInfo(); + this.RedrawItems(this.HotRowIndex, this.HotRowIndex, true); + } else { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, hti.Item); + } + } + + if (this.UseHotItem && this.HotItemStyleOrDefault.Overlay != null) { + this.RefreshOverlays(); + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the given row using the current hot item information + /// + /// + protected virtual void UpdateHotRow(OLVListItem olvi) { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, olvi); + } + + /// + /// Update the given row using the given hot item information + /// + /// + /// + /// + /// + protected virtual void UpdateHotRow(int rowIndex, int columnIndex, HitTestLocation hitLocation, OLVListItem olvi) { + if (rowIndex < 0 || columnIndex < 0) + return; + + // System.Diagnostics.Debug.WriteLine(String.Format("UpdateHotRow: {0}, {1}, {2}", rowIndex, columnIndex, hitLocation)); + + if (this.UseHyperlinks) { + OLVColumn column = this.GetColumn(columnIndex); + OLVListSubItem subItem = olvi.GetSubItem(columnIndex); + if (column != null && column.Hyperlink && hitLocation == HitTestLocation.Text && !String.IsNullOrEmpty(subItem.Url)) { + this.ApplyCellStyle(olvi, columnIndex, this.HyperlinkStyle.Over); + this.Cursor = this.HyperlinkStyle.OverCursor ?? Cursors.Default; + } else { + this.Cursor = Cursors.Default; + } + } + + if (this.UseHotItem) { + if (!olvi.Selected && olvi.Enabled) { + this.ApplyRowStyle(olvi, this.HotItemStyleOrDefault); + } + } + } + + /// + /// Apply a style to the given row + /// + /// + /// + public virtual void ApplyRowStyle(OLVListItem olvi, IItemStyle style) { + if (style == null) + return; + + Font font = style.Font ?? olvi.Font; + + if (style.FontStyle != FontStyle.Regular) + font = new Font(font ?? this.Font, style.FontStyle); + + if (!Equals(font, olvi.Font)) { + if (olvi.UseItemStyleForSubItems) + olvi.Font = font; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.Font = font; + } + } + + if (!style.ForeColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.ForeColor = style.ForeColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.ForeColor = style.ForeColor; + } + } + + if (!style.BackColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.BackColor = style.BackColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.BackColor = style.BackColor; + } + } + } + + /// + /// Apply a style to a cell + /// + /// + /// + /// + protected virtual void ApplyCellStyle(OLVListItem olvi, int columnIndex, IItemStyle style) { + if (style == null) + return; + + // Don't apply formatting to subitems when not in Details view + if (this.View != View.Details && columnIndex > 0) + return; + + olvi.UseItemStyleForSubItems = false; + + ListViewItem.ListViewSubItem subItem = olvi.SubItems[columnIndex]; + if (style.Font != null) + subItem.Font = style.Font; + + if (style.FontStyle != FontStyle.Regular) + subItem.Font = new Font(subItem.Font ?? olvi.Font ?? this.Font, style.FontStyle); + + if (!style.ForeColor.IsEmpty) + subItem.ForeColor = style.ForeColor; + + if (!style.BackColor.IsEmpty) + subItem.BackColor = style.BackColor; + } + + /// + /// Remove hot item styling from the given row + /// + /// + protected virtual void UnapplyHotItem(int index) { + this.Cursor = Cursors.Default; + // Virtual lists will apply the appropriate formatting when the row is fetched + if (this.VirtualMode) { + if (index < this.VirtualListSize) + this.RedrawItems(index, index, true); + } else { + OLVListItem olvi = this.GetItem(index); + if (olvi != null) { + //this.PostProcessOneRow(index, index, olvi); + this.RefreshItem(olvi); + } + } + } + + + #endregion + + #region Drag and drop + + /// + /// + /// + /// + protected override void OnItemDrag(ItemDragEventArgs e) { + base.OnItemDrag(e); + + if (this.DragSource == null) + return; + + Object data = this.DragSource.StartDrag(this, e.Button, (OLVListItem)e.Item); + if (data != null) { + DragDropEffects effect = this.DoDragDrop(data, this.DragSource.GetAllowedEffects(data)); + this.DragSource.EndDrag(data, effect); + } + } + + /// + /// + /// + /// + protected override void OnDragEnter(DragEventArgs args) { + base.OnDragEnter(args); + + if (this.DropSink != null) + this.DropSink.Enter(args); + } + + /// + /// + /// + /// + protected override void OnDragOver(DragEventArgs args) { + base.OnDragOver(args); + + if (this.DropSink != null) + this.DropSink.Over(args); + } + + /// + /// + /// + /// + protected override void OnDragDrop(DragEventArgs args) { + base.OnDragDrop(args); + + this.lastMouseDownClickCount = 0; // prevent drop events from becoming cell edits + + if (this.DropSink != null) + this.DropSink.Drop(args); + } + + /// + /// + /// + /// + protected override void OnDragLeave(EventArgs e) { + base.OnDragLeave(e); + + if (this.DropSink != null) + this.DropSink.Leave(); + } + + /// + /// + /// + /// + protected override void OnGiveFeedback(GiveFeedbackEventArgs args) { + base.OnGiveFeedback(args); + + if (this.DropSink != null) + this.DropSink.GiveFeedback(args); + } + + /// + /// + /// + /// + protected override void OnQueryContinueDrag(QueryContinueDragEventArgs args) { + base.OnQueryContinueDrag(args); + + if (this.DropSink != null) + this.DropSink.QueryContinue(args); + } + + #endregion + + #region Decorations and Overlays + + /// + /// Add the given decoration to those on this list and make it appear + /// + /// The decoration + /// + /// A decoration scrolls with the listview. An overlay stays fixed in place. + /// + public virtual void AddDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Add(decoration); + this.Invalidate(); + } + + /// + /// Add the given overlay to those on this list and make it appear + /// + /// The overlay + public virtual void AddOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Add(overlay); + this.Invalidate(); + } + + /// + /// Draw all the decorations + /// + /// A Graphics + /// The items that were redrawn and whose decorations should also be redrawn + protected virtual void DrawAllDecorations(Graphics g, List itemsThatWereRedrawn) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + Rectangle contentRectangle = this.ContentRectangle; + + if (this.HasEmptyListMsg && this.GetItemCount() == 0) { + this.EmptyListMsgOverlay.Draw(this, g, contentRectangle); + } + + // Let the drop sink draw whatever feedback it likes + if (this.DropSink != null) { + this.DropSink.DrawFeedback(g, contentRectangle); + } + + // Draw our item and subitem decorations + foreach (OLVListItem olvi in itemsThatWereRedrawn) { + if (olvi.HasDecoration) { + foreach (IDecoration d in olvi.Decorations) { + d.ListItem = olvi; + d.SubItem = null; + d.Draw(this, g, contentRectangle); + } + } + foreach (OLVListSubItem subItem in olvi.SubItems) { + if (subItem.HasDecoration) { + foreach (IDecoration d in subItem.Decorations) { + d.ListItem = olvi; + d.SubItem = subItem; + d.Draw(this, g, contentRectangle); + } + } + } + if (this.SelectedRowDecoration != null && olvi.Selected && olvi.Enabled) { + this.SelectedRowDecoration.ListItem = olvi; + this.SelectedRowDecoration.SubItem = null; + this.SelectedRowDecoration.Draw(this, g, contentRectangle); + } + } + + // Now draw the specifically registered decorations + foreach (IDecoration decoration in this.Decorations) { + decoration.ListItem = null; + decoration.SubItem = null; + decoration.Draw(this, g, contentRectangle); + } + + // Finally, draw any hot item decoration + if (this.UseHotItem) { + IDecoration hotItemDecoration = this.HotItemStyleOrDefault.Decoration; + if (hotItemDecoration != null) { + hotItemDecoration.ListItem = this.GetItem(this.HotRowIndex); + if (hotItemDecoration.ListItem == null || hotItemDecoration.ListItem.Enabled) { + hotItemDecoration.SubItem = hotItemDecoration.ListItem == null ? null : hotItemDecoration.ListItem.GetSubItem(this.HotColumnIndex); + hotItemDecoration.Draw(this, g, contentRectangle); + } + } + } + + // If we are in design mode, we don't want to use the glass panels, + // so we draw the background overlays here + if (this.DesignMode) { + foreach (IOverlay overlay in this.Overlays) { + overlay.Draw(this, g, contentRectangle); + } + } + } + + /// + /// Is the given decoration shown on this list + /// + /// The overlay + public virtual bool HasDecoration(IDecoration decoration) { + return this.Decorations.Contains(decoration); + } + + /// + /// Is the given overlay shown on this list? + /// + /// The overlay + public virtual bool HasOverlay(IOverlay overlay) { + return this.Overlays.Contains(overlay); + } + + /// + /// Hide any overlays. + /// + /// + /// This is only a temporary hiding -- the overlays will be shown + /// the next time the ObjectListView redraws. + /// + public virtual void HideOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.HideGlass(); + } + } + + /// + /// Create and configure the empty list msg overlay + /// + protected virtual void InitializeEmptyListMsgOverlay() { + TextOverlay overlay = new TextOverlay(); + overlay.Alignment = System.Drawing.ContentAlignment.MiddleCenter; + overlay.TextColor = SystemColors.ControlDarkDark; + overlay.BackColor = Color.BlanchedAlmond; + overlay.BorderColor = SystemColors.ControlDark; + overlay.BorderWidth = 2.0f; + this.EmptyListMsgOverlay = overlay; + } + + /// + /// Initialize the standard image and text overlays + /// + protected virtual void InitializeStandardOverlays() { + this.OverlayImage = new ImageOverlay(); + this.AddOverlay(this.OverlayImage); + this.OverlayText = new TextOverlay(); + this.AddOverlay(this.OverlayText); + } + + /// + /// Make sure that any overlays are visible. + /// + public virtual void ShowOverlays() { + // If we shouldn't show overlays, then don't create glass panels + if (!this.ShouldShowOverlays()) + return; + + // Make sure that each overlay has its own glass panels + if (this.Overlays.Count != this.glassPanels.Count) { + foreach (IOverlay overlay in this.Overlays) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel == null) { + glassPanel = new GlassPanelForm(); + glassPanel.Bind(this, overlay); + this.glassPanels.Add(glassPanel); + } + } + } + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.ShowGlass(); + } + } + + private bool ShouldShowOverlays() { + // If we are in design mode, we dont show the overlays + if (this.DesignMode) + return false; + + // If we are explicitly not using overlays, also don't show them + if (!this.UseOverlays) + return false; + + // If there are no overlays, guess... + if (!this.HasOverlays) + return false; + + // If we don't have 32-bit display, alpha blending doesn't work, so again, no overlays + // TODO: This should actually figure out which screen(s) the control is on, and make sure + // that each one is 32-bit. + if (Screen.PrimaryScreen.BitsPerPixel < 32) + return false; + + // Finally, we can show the overlays + return true; + } + + private GlassPanelForm FindGlassPanelForOverlay(IOverlay overlay) { + return this.glassPanels.Find(delegate(GlassPanelForm x) { return x.Overlay == overlay; }); + } + + /// + /// Refresh the display of the overlays + /// + public virtual void RefreshOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Invalidate(); + } + } + + /// + /// Refresh the display of just one overlays + /// + public virtual void RefreshOverlay(IOverlay overlay) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) + glassPanel.Invalidate(); + } + + /// + /// Remove the given decoration from this list + /// + /// The decoration to remove + public virtual void RemoveDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Remove(decoration); + this.Invalidate(); + } + + /// + /// Remove the given overlay to those on this list + /// + /// The overlay + public virtual void RemoveOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Remove(overlay); + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) { + this.glassPanels.Remove(glassPanel); + glassPanel.Unbind(); + glassPanel.Dispose(); + } + } + + #endregion + + #region Filtering + + /// + /// Create a filter that will enact all the filtering currently installed + /// on the visible columns. + /// + public virtual IModelFilter CreateColumnFilter() { + List filters = new List(); + foreach (OLVColumn column in this.Columns) { + IModelFilter filter = column.ValueBasedFilter; + if (filter != null) + filters.Add(filter); + } + return (filters.Count == 0) ? null : new CompositeAllFilter(filters); + } + + /// + /// Do the actual work of filtering + /// + /// + /// + /// + /// + protected virtual IEnumerable FilterObjects(IEnumerable originalObjects, IModelFilter aModelFilter, IListFilter aListFilter) { + // Being cautious + originalObjects = originalObjects ?? new ArrayList(); + + // Tell the world to filter the objects. If they do so, don't do anything else +// ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(originalObjects); + this.OnFilter(args); + if (args.FilteredObjects != null) + return args.FilteredObjects; + + // Apply a filter to the list as a whole + if (aListFilter != null) + originalObjects = aListFilter.Filter(originalObjects); + + // Apply the object filter if there is one + if (aModelFilter != null) { + ArrayList filteredObjects = new ArrayList(); + foreach (object model in originalObjects) { + if (aModelFilter.Filter(model)) + filteredObjects.Add(model); + } + originalObjects = filteredObjects; + } + + return originalObjects; +// ReSharper restore PossibleMultipleEnumeration + } + + /// + /// Remove all column filtering. + /// + public virtual void ResetColumnFiltering() { + foreach (OLVColumn column in this.Columns) { + column.ValuesChosenForFiltering.Clear(); + } + this.UpdateColumnFiltering(); + } + + /// + /// Update the filtering of this ObjectListView based on the value filtering + /// defined in each column + /// + public virtual void UpdateColumnFiltering() { + //List filters = new List(); + //IModelFilter columnFilter = this.CreateColumnFilter(); + //if (columnFilter != null) + // filters.Add(columnFilter); + //if (this.AdditionalFilter != null) + // filters.Add(this.AdditionalFilter); + //this.ModelFilter = filters.Count == 0 ? null : new CompositeAllFilter(filters); + + if (this.AdditionalFilter == null) + this.ModelFilter = this.CreateColumnFilter(); + else { + IModelFilter columnFilter = this.CreateColumnFilter(); + if (columnFilter == null) + this.ModelFilter = this.AdditionalFilter; + else { + List filters = new List(); + filters.Add(columnFilter); + filters.Add(this.AdditionalFilter); + this.ModelFilter = new CompositeAllFilter(filters); + } + } + } + + /// + /// When some setting related to filtering changes, this method is called. + /// + protected virtual void UpdateFiltering() { + this.BuildList(true); + } + + /// + /// Update all renderers with the currently installed model filter + /// + protected virtual void NotifyNewModelFilter() { + IFilterAwareRenderer filterAware = this.DefaultRenderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + + foreach (OLVColumn column in this.AllColumns) { + filterAware = column.Renderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + } + } + + #endregion + + #region Persistent check state + + /// + /// Gets the checkedness of the given model. + /// + /// The model + /// The checkedness of the model. Defaults to unchecked. + protected virtual CheckState GetPersistentCheckState(object model) { + CheckState state; + if (model != null && this.CheckStateMap.TryGetValue(model, out state)) + return state; + return CheckState.Unchecked; + } + + /// + /// Remember the check state of the given model object + /// + /// The model to be remembered + /// The model's checkedness + /// The state given to the method + protected virtual CheckState SetPersistentCheckState(object model, CheckState state) { + if (model == null) + return CheckState.Unchecked; + + this.CheckStateMap[model] = state; + return state; + } + + /// + /// Forget any persistent checkbox state + /// + protected virtual void ClearPersistentCheckState() { + this.CheckStateMap = null; + } + + #endregion + + #region Implementation variables + + private bool isOwnerOfObjects; // does this ObjectListView own the Objects collection? + private bool hasIdleHandler; // has an Idle handler already been installed? + private bool hasResizeColumnsHandler; // has an idle handler been installed which will handle column resizing? + private bool isInWmPaintEvent; // is a WmPaint event currently being handled? + private bool shouldDoCustomDrawing; // should the list do its custom drawing? + private bool isMarqueSelecting; // Is a marque selection in progress? + private int suspendSelectionEventCount; // How many unmatched SuspendSelectionEvents() calls have been made? + + private readonly List glassPanels = new List(); // The transparent panel that draws overlays + private Dictionary visitedUrlMap = new Dictionary(); // Which urls have been visited? + + // TODO + //private CheckBoxSettings checkBoxSettings = new CheckBoxSettings(); + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.shfb b/ObjectListView/ObjectListView.shfb new file mode 100644 index 0000000..514d58b --- /dev/null +++ b/ObjectListView/ObjectListView.shfb @@ -0,0 +1,47 @@ + + + + + + + All ObjectListView appears in this namespace + + + ObjectListViewDemo demonstrates helpful techniques when using an ObjectListView + Summary, Parameter, Returns, AutoDocumentCtors, Namespace + InheritedMembers, Protected, SealedProtected + + + .\Help\ + + + True + True + HtmlHelp1x + True + False + 2.0.50727 + True + False + True + False + + ObjectListView Reference + Documentation + en-US + + (c) Copyright 2006-2008 Phillip Piper All Rights Reserved + phillip.piper@gmail.com + + + Local + Msdn + Blank + Prototype + Guid + CSharp + False + AboveNamespaces + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.csproj b/ObjectListView/ObjectListView2019.csproj new file mode 100644 index 0000000..70e616b --- /dev/null +++ b/ObjectListView/ObjectListView2019.csproj @@ -0,0 +1,54 @@ + + + net6.0-windows + Library + BrightIdeasSoftware + ObjectListView + true + olv-keyfile.snk + %24/ObjectListView/trunk/ObjectListView + . + https://grammarian.visualstudio.com + {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} + false + true + true + + + 1 + bin\Debug\ObjectListView.XML + + + bin\Release\ObjectListView.XML + + + + + + + + + + + + + + Component + + + Component + + + + + + + Designer + + + + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.nuspec b/ObjectListView/ObjectListView2019.nuspec new file mode 100644 index 0000000..3e883c6 --- /dev/null +++ b/ObjectListView/ObjectListView2019.nuspec @@ -0,0 +1,22 @@ + + + + ObjectListView.Official + ObjectListView (Official) + 2.9.2-alpha2 + Phillip Piper + Phillip Piper + http://www.gnu.org/licenses/gpl.html + http://objectlistview.sourceforge.net + http://objectlistview.sourceforge.net/cs/_static/index-icon.png + true + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + More calmly, it is a C# wrapper around a .NET ListView, which makes the ListView much easier to use and teaches it lots of neat new tricks. + v2.9.2 Fixed cell edit bounds problem in TreeListView, plus other small issues. + v2.9.1 Added CellRendererGetter to allow each cell to have a different renderer, plus fixes a few small bugs. + v2.9 adds buttons to cells, fixed some formatting bugs, and completely rewrote the demo to be much easier to understand. + Copyright 2006-2016 Bright Ideas Software + .Net WinForms Net20 Net40 ListView Controls + + \ No newline at end of file diff --git a/ObjectListView/Properties/AssemblyInfo.cs b/ObjectListView/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..515899d --- /dev/null +++ b/ObjectListView/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// 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("ObjectListView")] +[assembly: AssemblyDescription("A much easier to use ListView and friends")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Bright Ideas Software")] +[assembly: AssemblyProduct("ObjectListView")] +[assembly: AssemblyCopyright("Copyright © 2006-2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ef28c7a8-77ae-442d-abc3-bb023fa31e57")] + +// 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 Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("2.9.1.*")] +[assembly: AssemblyFileVersion("2.9.1.0")] +[assembly: AssemblyInformationalVersion("2.9.1")] +[assembly: System.CLSCompliant(true)] diff --git a/ObjectListView/Properties/Resources.Designer.cs b/ObjectListView/Properties/Resources.Designer.cs new file mode 100644 index 0000000..1b86d07 --- /dev/null +++ b/ObjectListView/Properties/Resources.Designer.cs @@ -0,0 +1,113 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace BrightIdeasSoftware.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BrightIdeasSoftware.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ClearFiltering { + get { + object obj = ResourceManager.GetObject("ClearFiltering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ColumnFilterIndicator { + get { + object obj = ResourceManager.GetObject("ColumnFilterIndicator", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap Filtering { + get { + object obj = ResourceManager.GetObject("Filtering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortAscending { + get { + object obj = ResourceManager.GetObject("SortAscending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortDescending { + get { + object obj = ResourceManager.GetObject("SortDescending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/ObjectListView/Properties/Resources.resx b/ObjectListView/Properties/Resources.resx new file mode 100644 index 0000000..b017d6a --- /dev/null +++ b/ObjectListView/Properties/Resources.resx @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\clear-filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + + ..\Resources\filter-icons3.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-ascending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-descending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/ObjectListView/Rendering/Adornments.cs b/ObjectListView/Rendering/Adornments.cs new file mode 100644 index 0000000..a159cfa --- /dev/null +++ b/ObjectListView/Rendering/Adornments.cs @@ -0,0 +1,743 @@ +/* + * Adornments - Adornments are the basis for overlays and decorations -- things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 16/08/2009 1:02 AM + * + * Change log: + * v2.6 + * 2012-08-18 JPP - Correctly dispose of brush and pen resources + * v2.3 + * 2009-09-22 JPP - Added Wrap property to TextAdornment, to allow text wrapping to be disabled + * - Added ShrinkToWidth property to ImageAdornment + * 2009-08-17 JPP - Initial version + * + * To do: + * - Use IPointLocator rather than Corners + * - Add RotationCenter property rather than always using middle center + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// An adornment is the common base for overlays and decorations. + /// + public class GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the corner of the adornment that will be positioned at the reference corner + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment AdornmentCorner { + get { return this.adornmentCorner; } + set { this.adornmentCorner = value; } + } + private System.Drawing.ContentAlignment adornmentCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets location within the reference rectangle where the adornment will be drawn + /// + /// This is a simplified interface to ReferenceCorner and AdornmentCorner + [Category("ObjectListView"), + Description("How will the adornment be aligned"), + DefaultValue(System.Drawing.ContentAlignment.BottomRight), + NotifyParentProperty(true)] + public System.Drawing.ContentAlignment Alignment { + get { return this.alignment; } + set { + this.alignment = value; + this.ReferenceCorner = value; + this.AdornmentCorner = value; + } + } + private System.Drawing.ContentAlignment alignment = System.Drawing.ContentAlignment.BottomRight; + + /// + /// Gets or sets the offset by which the position of the adornment will be adjusted + /// + [Category("ObjectListView"), + Description("The offset by which the position of the adornment will be adjusted"), + DefaultValue(typeof(Size), "0,0")] + public Size Offset { + get { return this.offset; } + set { this.offset = value; } + } + private Size offset = new Size(); + + /// + /// Gets or sets the point of the reference rectangle to which the adornment will be aligned. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment ReferenceCorner { + get { return this.referenceCorner; } + set { this.referenceCorner = value; } + } + private System.Drawing.ContentAlignment referenceCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets the degree of rotation by which the adornment will be transformed. + /// The centre of rotation will be the center point of the adornment. + /// + [Category("ObjectListView"), + Description("The degree of rotation that will be applied to the adornment."), + DefaultValue(0), + NotifyParentProperty(true)] + public int Rotation { + get { return this.rotation; } + set { this.rotation = value; } + } + private int rotation; + + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + [Category("ObjectListView"), + Description("The transparency of this adornment. 0 is completely transparent, 255 is completely opaque."), + DefaultValue(128)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + + #region Calculations + + /// + /// Calculate the location of rectangle of the given size, + /// so that it's indicated corner would be at the given point. + /// + /// The point + /// + /// Which corner will be positioned at the reference point + /// + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.TopLeft) -> Point(50, 100) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.MiddleCenter) -> Point(45, 90) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.BottomRight) -> Point(40, 80) + public virtual Point CalculateAlignedPosition(Point pt, Size size, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return pt; + case System.Drawing.ContentAlignment.TopCenter: + return new Point(pt.X - (size.Width / 2), pt.Y); + case System.Drawing.ContentAlignment.TopRight: + return new Point(pt.X - size.Width, pt.Y); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(pt.X, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(pt.X - size.Width, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(pt.X, pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(pt.X - size.Width, pt.Y - size.Height); + } + + // Should never reach here + return pt; + } + + /// + /// Calculate a rectangle that has the given size which is positioned so that + /// its alignment point is at the reference location of the given rect. + /// + /// + /// + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz) { + return this.CreateAlignedRectangle(r, sz, this.ReferenceCorner, this.AdornmentCorner, this.Offset); + } + + /// + /// Create a rectangle of the given size which is positioned so that + /// its indicated corner is at the indicated corner of the reference rect. + /// + /// + /// + /// + /// + /// + /// + /// + /// Creates a rectangle so that its bottom left is at the centre of the reference: + /// corner=BottomLeft, referenceCorner=MiddleCenter + /// This is a powerful concept that takes some getting used to, but is + /// very neat once you understand it. + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz, + System.Drawing.ContentAlignment corner, System.Drawing.ContentAlignment referenceCorner, Size offset) { + Point referencePt = this.CalculateCorner(r, referenceCorner); + Point topLeft = this.CalculateAlignedPosition(referencePt, sz, corner); + return new Rectangle(topLeft + offset, sz); + } + + /// + /// Return the point at the indicated corner of the given rectangle (it doesn't + /// have to be a corner, but a named location) + /// + /// The reference rectangle + /// Which point of the rectangle should be returned? + /// A point + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.TopLeft) -> Point(0, 0) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.MiddleCenter) -> Point(25, 50) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.BottomRight) -> Point(50, 100) + public virtual Point CalculateCorner(Rectangle r, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return new Point(r.Left, r.Top); + case System.Drawing.ContentAlignment.TopCenter: + return new Point(r.X + (r.Width / 2), r.Top); + case System.Drawing.ContentAlignment.TopRight: + return new Point(r.Right, r.Top); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(r.Left, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(r.X + (r.Width / 2), r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(r.Right, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(r.Left, r.Bottom); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(r.X + (r.Width / 2), r.Bottom); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(r.Right, r.Bottom); + } + + // Should never reach here + return r.Location; + } + + /// + /// Given the item and the subitem, calculate its bounds. + /// + /// + /// + /// + public virtual Rectangle CalculateItemBounds(OLVListItem item, OLVListSubItem subItem) { + if (item == null) + return Rectangle.Empty; + + if (subItem == null) + return item.Bounds; + + return item.GetSubItemBounds(item.SubItems.IndexOf(subItem)); + } + + #endregion + + #region Commands + + /// + /// Apply any specified rotation to the Graphic content. + /// + /// The Graphics to be transformed + /// The rotation will be around the centre of this rect + protected virtual void ApplyRotation(Graphics g, Rectangle r) { + if (this.Rotation == 0) + return; + + // THINK: Do we want to reset the transform? I think we want to push a new transform + g.ResetTransform(); + Matrix m = new Matrix(); + m.RotateAt(this.Rotation, new Point(r.Left + r.Width / 2, r.Top + r.Height / 2)); + g.Transform = m; + } + + /// + /// Reverse the rotation created by ApplyRotation() + /// + /// + protected virtual void UnapplyRotation(Graphics g) { + if (this.Rotation != 0) + g.ResetTransform(); + } + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + public class ImageAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the image that will be drawn + /// + [Category("ObjectListView"), + Description("The image that will be drawn"), + DefaultValue(null), + NotifyParentProperty(true)] + public Image Image { + get { return this.image; } + set { this.image = value; } + } + private Image image; + + /// + /// Gets or sets if the image will be shrunk to fit with its horizontal bounds + /// + [Category("ObjectListView"), + Description("Will the image be shrunk to fit within its width?"), + DefaultValue(false)] + public bool ShrinkToWidth { + get { return this.shrinkToWidth; } + set { this.shrinkToWidth = value; } + } + private bool shrinkToWidth; + + #endregion + + #region Commands + + /// + /// Draw the image in its specified location + /// + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void DrawImage(Graphics g, Rectangle r) { + if (this.ShrinkToWidth) + this.DrawScaledImage(g, r, this.Image, this.Transparency); + else + this.DrawImage(g, r, this.Image, this.Transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image != null) + this.DrawImage(g, r, image, image.Size, transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How big should the image be? + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, Size sz, int transparency) { + if (image == null) + return; + + Rectangle adornmentBounds = this.CreateAlignedRectangle(r, sz); + try { + this.ApplyRotation(g, adornmentBounds); + this.DrawTransparentBitmap(g, adornmentBounds, image, transparency); + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Draw the image in its specified location, scaled so that it is not wider + /// than the given rectangle. Height is scaled proportional to the width. + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawScaledImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image == null) + return; + + // If the image is too wide to be drawn in the space provided, proportionally scale it down. + // Too tall images are not scaled. + Size size = image.Size; + if (image.Width > r.Width) { + float scaleRatio = (float)r.Width / (float)image.Width; + size.Height = (int)((float)image.Height * scaleRatio); + size.Width = r.Width - 1; + } + + this.DrawImage(g, r, image, size, transparency); + } + + /// + /// Utility to draw a bitmap transparently. + /// + /// + /// + /// + /// + protected virtual void DrawTransparentBitmap(Graphics g, Rectangle r, Image image, int transparency) { + ImageAttributes imageAttributes = null; + if (transparency != 255) { + imageAttributes = new ImageAttributes(); + float a = (float)transparency / 255.0f; + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 1, 0, 0}, + new float[] {0, 0, 0, a, 0}, + new float[] {0, 0, 0, 0, 1}}; + + imageAttributes.SetColorMatrix(new ColorMatrix(colorMatrixElements)); + } + + g.DrawImage(image, + r, // destination rectangle + 0, 0, image.Size.Width, image.Size.Height, // source rectangle + GraphicsUnit.Pixel, + imageAttributes); + } + + #endregion + } + + /// + /// An adornment that will draw text + /// + public class TextAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the background color of the text + /// Set this to Color.Empty to not draw a background + /// + [Category("ObjectListView"), + Description("The background color of the text"), + DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush BackgroundBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.BackColor)); + } + } + + /// + /// Gets or sets the color of the border around the billboard. + /// Set this to Color.Empty to remove the border + /// + [Category("ObjectListView"), + Description("The color of the border around the text"), + DefaultValue(typeof(Color), "")] + public Color BorderColor { + get { return this.borderColor; } + set { this.borderColor = value; } + } + private Color borderColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Pen BorderPen { + get { + return new Pen(Color.FromArgb(this.workingTransparency, this.BorderColor), this.BorderWidth); + } + } + + /// + /// Gets or sets the width of the border around the text + /// + [Category("ObjectListView"), + Description("The width of the border around the text"), + DefaultValue(0.0f)] + public float BorderWidth { + get { return this.borderWidth; } + set { this.borderWidth = value; } + } + private float borderWidth; + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + [Category("ObjectListView"), + Description("How rounded should the corners of the border be? 0 means no rounding."), + DefaultValue(16.0f), + NotifyParentProperty(true)] + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the font that will be used to draw the text + /// + [Category("ObjectListView"), + Description("The font that will be used to draw the text"), + DefaultValue(null), + NotifyParentProperty(true)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets the font that will be used to draw the text or a reasonable default + /// + [Browsable(false)] + public Font FontOrDefault { + get { + return this.Font ?? new Font("Tahoma", 16); + } + } + + /// + /// Does this text have a background? + /// + [Browsable(false)] + public bool HasBackground { + get { + return this.BackColor != Color.Empty; + } + } + + /// + /// Does this overlay have a border? + /// + [Browsable(false)] + public bool HasBorder { + get { + return this.BorderColor != Color.Empty && this.BorderWidth > 0; + } + } + + /// + /// Gets or sets the maximum width of the text. Text longer than this will wrap. + /// 0 means no maximum. + /// + [Category("ObjectListView"), + Description("The maximum width the text (0 means no maximum). Text longer than this will wrap"), + DefaultValue(0)] + public int MaximumTextWidth { + get { return this.maximumTextWidth; } + set { this.maximumTextWidth = value; } + } + private int maximumTextWidth; + + /// + /// Gets or sets the formatting that should be used on the text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual StringFormat StringFormat { + get { + if (this.stringFormat == null) { + this.stringFormat = new StringFormat(); + this.stringFormat.Alignment = StringAlignment.Center; + this.stringFormat.LineAlignment = StringAlignment.Center; + this.stringFormat.Trimming = StringTrimming.EllipsisCharacter; + if (!this.Wrap) + this.stringFormat.FormatFlags = StringFormatFlags.NoWrap; + } + return this.stringFormat; + } + set { this.stringFormat = value; } + } + private StringFormat stringFormat; + + /// + /// Gets or sets the text that will be drawn + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DefaultValue(null), + NotifyParentProperty(true), + Localizable(true)] + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush TextBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.TextColor)); + } + } + + /// + /// Gets or sets the color of the text + /// + [Category("ObjectListView"), + Description("The color of the text"), + DefaultValue(typeof(Color), "DarkBlue"), + NotifyParentProperty(true)] + public Color TextColor { + get { return this.textColor; } + set { this.textColor = value; } + } + private Color textColor = Color.DarkBlue; + + /// + /// Gets or sets whether the text will wrap when it exceeds its bounds + /// + [Category("ObjectListView"), + Description("Will the text wrap?"), + DefaultValue(true)] + public bool Wrap { + get { return this.wrap; } + set { this.wrap = value; } + } + private bool wrap = true; + + #endregion + + #region Implementation + + /// + /// Draw our text with our stored configuration in relation to the given + /// reference rectangle + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + public virtual void DrawText(Graphics g, Rectangle r) { + this.DrawText(g, r, this.Text, this.Transparency); + } + + /// + /// Draw the given text with our stored configuration + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + /// The text to draw + /// How opaque should be text be + public virtual void DrawText(Graphics g, Rectangle r, string s, int transparency) { + if (String.IsNullOrEmpty(s)) + return; + + Rectangle textRect = this.CalculateTextBounds(g, r, s); + this.DrawBorderedText(g, textRect, s, transparency); + } + + /// + /// Draw the text with a border + /// + /// The Graphics used for drawing + /// The bounds within which the text should be drawn + /// The text to draw + /// How opaque should be text be + protected virtual void DrawBorderedText(Graphics g, Rectangle textRect, string text, int transparency) { + Rectangle borderRect = textRect; + borderRect.Inflate((int)this.BorderWidth / 2, (int)this.BorderWidth / 2); + borderRect.Y -= 1; // Looker better a little higher + + try { + this.ApplyRotation(g, textRect); + using (GraphicsPath path = this.GetRoundedRect(borderRect, this.CornerRounding)) { + this.workingTransparency = transparency; + if (this.HasBackground) { + using (Brush b = this.BackgroundBrush) + g.FillPath(b, path); + } + + using (Brush b = this.TextBrush) + g.DrawString(text, this.FontOrDefault, b, textRect, this.StringFormat); + + if (this.HasBorder) { + using (Pen p = this.BorderPen) + g.DrawPath(p, path); + } + } + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Return the rectangle that will be the precise bounds of the displayed text + /// + /// + /// + /// + /// The bounds of the text + protected virtual Rectangle CalculateTextBounds(Graphics g, Rectangle r, string s) { + int maxWidth = this.MaximumTextWidth <= 0 ? r.Width : this.MaximumTextWidth; + SizeF sizeF = g.MeasureString(s, this.FontOrDefault, maxWidth, this.StringFormat); + Size size = new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + return this.CreateAlignedRectangle(r, size); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected virtual GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + + private int workingTransparency; + } +} diff --git a/ObjectListView/Rendering/Decorations.cs b/ObjectListView/Rendering/Decorations.cs new file mode 100644 index 0000000..91f21d6 --- /dev/null +++ b/ObjectListView/Rendering/Decorations.cs @@ -0,0 +1,973 @@ +/* + * Decorations - Images, text or other things that can be rendered onto an ObjectListView + * + * Author: Phillip Piper + * Date: 19/08/2009 10:56 PM + * + * Change log: + * 2018-04-30 JPP - Added ColumnEdgeDecoration. + * TintedColumnDecoration now uses common base class, ColumnDecoration. + * v2.5 + * 2011-04-04 JPP - Added ability to have a gradient background on BorderDecoration + * v2.4 + * 2010-04-15 JPP - Tweaked LightBoxDecoration a little + * v2.3 + * 2009-09-23 JPP - Added LeftColumn and RightColumn to RowBorderDecoration + * 2009-08-23 JPP - Added LightBoxDecoration + * 2009-08-19 JPP - Initial version. Separated from Overlays.cs + * + * To do: + * + * Copyright (C) 2009-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A decoration is an overlay that draws itself in relation to a given row or cell. + /// Decorations scroll when the listview scrolls. + /// + public interface IDecoration : IOverlay + { + /// + /// Gets or sets the row that is to be decorated + /// + OLVListItem ListItem { get; set; } + + /// + /// Gets or sets the subitem that is to be decorated + /// + OLVListSubItem SubItem { get; set; } + } + + /// + /// An AbstractDecoration is a safe do-nothing implementation of the IDecoration interface + /// + public class AbstractDecoration : IDecoration + { + #region IDecoration Members + + /// + /// Gets or sets the row that is to be decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the subitem that is to be decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Public properties + + /// + /// Gets the bounds of the decorations row + /// + public Rectangle RowBounds { + get { + if (this.ListItem == null) + return Rectangle.Empty; + else + return this.ListItem.Bounds; + } + } + + /// + /// Get the bounds of the decorations cell + /// + public Rectangle CellBounds { + get { + if (this.ListItem == null || this.SubItem == null) + return Rectangle.Empty; + else + return this.ListItem.GetSubItemBounds(this.ListItem.SubItems.IndexOf(this.SubItem)); + } + } + + #endregion + + #region IOverlay Members + + /// + /// Draw the decoration + /// + /// + /// + /// + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + } + + + /// + /// This decoration draws something over a given column. + /// Subclasses must override DrawDecoration() + /// + public class ColumnDecoration : AbstractDecoration { + #region Constructors + + /// + /// Create a ColumnDecoration + /// + public ColumnDecoration() { + } + + /// + /// Create a ColumnDecoration + /// + /// + public ColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column ?? throw new ArgumentNullException("column"); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the column that will be decorated + /// + public OLVColumn ColumnToDecorate { + get { return this.columnToDecorate; } + set { this.columnToDecorate = value; } + } + private OLVColumn columnToDecorate; + + /// + /// Gets or sets the pen that will be used to draw the column decoration + /// + public Pen Pen { + get { + return this.pen ?? Pens.DarkSlateBlue; + } + set { + if (this.pen == value) + return; + + if (this.pen != null) { + this.pen.Dispose(); + } + + this.pen = value; + } + } + private Pen pen; + + #endregion + + #region IOverlay Members + + /// + /// Draw a decoration over our column + /// + /// + /// This overlay only works when: + /// - the list is in Details view + /// - there is at least one row + /// - there is a selected column (or a specified tint column) + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + + if (olv.View != System.Windows.Forms.View.Details) + return; + + if (olv.GetItemCount() == 0) + return; + + if (this.ColumnToDecorate == null) + return; + + Point sides = NativeMethods.GetScrolledColumnSides(olv, this.ColumnToDecorate.Index); + if (sides.X == -1) + return; + + Rectangle columnBounds = new Rectangle(sides.X, r.Top, sides.Y - sides.X, r.Bottom); + + // Find the bottom of the last item. The decoration should extend only to there. + OLVListItem lastItem = olv.GetLastItemInDisplayOrder(); + if (lastItem != null) { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + // Delegate the drawing of the actual decoration + this.DrawDecoration(olv, g, r, columnBounds); + } + + /// + /// Subclasses should override this to draw exactly what they want + /// + /// + /// + /// + /// + public virtual void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.DrawRectangle(this.Pen, columnBounds); + } + + #endregion + } + + /// + /// This decoration draws a slight tint over a column of the + /// owning listview. If no column is explicitly set, the selected + /// column in the listview will be used. + /// The selected column is normally the sort column, but does not have to be. + /// + public class TintedColumnDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a TintedColumnDecoration + /// + public TintedColumnDecoration() { + this.Tint = Color.FromArgb(15, Color.Blue); + } + + /// + /// Create a TintedColumnDecoration + /// + /// + public TintedColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the color that will be 'tinted' over the selected column + /// + public Color Tint { + get { return this.tint; } + set { + if (this.tint == value) + return; + + if (this.tintBrush != null) { + this.tintBrush.Dispose(); + this.tintBrush = null; + } + + this.tint = value; + this.tintBrush = new SolidBrush(this.tint); + } + } + private Color tint; + private SolidBrush tintBrush; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.FillRectangle(this.tintBrush, columnBounds); + } + + #endregion + } + + /// + /// Specify on which side edge the decoration will be drawn + /// + public enum ColumnEdge { + Left, + Right + } + + /// + /// This decoration draws a line on the edge(s) of its given column + /// + /// + /// Like all decorations, this draws over the contents of list view. + /// If you set the Pen too wide enough, you may overwrite the contents + /// of the column (if alignment is Inside) or the surrounding columns (if alignment is Outside) + /// + public class ColumnEdgeDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a ColumnEdgeDecoration + /// + public ColumnEdgeDecoration() { + } + + /// + /// Create a ColumnEdgeDecoration which draws a line over the right edges of the column (by default) + /// + /// + /// + /// + /// + public ColumnEdgeDecoration(OLVColumn column, Pen pen = null, ColumnEdge edge = ColumnEdge.Right, float xOffset = 0) + : this() { + this.ColumnToDecorate = column; + this.Pen = pen; + this.Edge = edge; + this.XOffset = xOffset; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether this decoration will draw a line on the left or right edge of the column + /// + public ColumnEdge Edge { + get { return edge; } + set { edge = value; } + } + private ColumnEdge edge = ColumnEdge.Right; + + /// + /// Gets or sets the horizontal offset from centered at which the line will be drawn + /// + public float XOffset { + get { return xOffset; } + set { xOffset = value; } + } + private float xOffset; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + float left = CalculateEdge(columnBounds); + g.DrawLine(this.Pen, left, columnBounds.Top, left, columnBounds.Bottom); + + } + + private float CalculateEdge(Rectangle columnBounds) { + float tweak = this.XOffset + (this.Pen.Width <= 2 ? 0 : 1); + int x = this.Edge == ColumnEdge.Left ? columnBounds.Left : columnBounds.Right; + return tweak + x - this.Pen.Width / 2; + } + + #endregion + } + + /// + /// This decoration draws an optionally filled border around a rectangle. + /// Subclasses must override CalculateBounds(). + /// + public class BorderDecoration : AbstractDecoration + { + #region Constructors + + /// + /// Create a BorderDecoration + /// + public BorderDecoration() + : this(new Pen(Color.FromArgb(64, Color.Blue), 1)) { + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + public BorderDecoration(Pen borderPen) { + this.BorderPen = borderPen; + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + /// The brush used to fill the rectangle + public BorderDecoration(Pen borderPen, Brush fill) { + this.BorderPen = borderPen; + this.FillBrush = fill; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the pen that will be used to draw the border + /// + public Pen BorderPen { + get { return this.borderPen; } + set { this.borderPen = value; } + } + private Pen borderPen; + + /// + /// Gets or sets the padding that will be added to the bounds of the item + /// before drawing the border and fill. + /// + public Size BoundsPadding { + get { return this.boundsPadding; } + set { this.boundsPadding = value; } + } + private Size boundsPadding = new Size(-1, 2); + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the brush that will be used to fill the border + /// + /// This value is ignored when using gradient brush + public Brush FillBrush { + get { return this.fillBrush; } + set { this.fillBrush = value; } + } + private Brush fillBrush = new SolidBrush(Color.FromArgb(64, Color.Blue)); + + /// + /// Gets or sets the color that will be used as the start of a gradient fill. + /// + /// This and FillGradientTo must be given value to show a gradient + public Color? FillGradientFrom { + get { return this.fillGradientFrom; } + set { this.fillGradientFrom = value; } + } + private Color? fillGradientFrom; + + /// + /// Gets or sets the color that will be used as the end of a gradient fill. + /// + /// This and FillGradientFrom must be given value to show a gradient + public Color? FillGradientTo { + get { return this.fillGradientTo; } + set { this.fillGradientTo = value; } + } + private Color? fillGradientTo; + + /// + /// Gets or sets the fill mode that will be used for the gradient. + /// + public LinearGradientMode FillGradientMode { + get { return this.fillGradientMode; } + set { this.fillGradientMode = value; } + } + private LinearGradientMode fillGradientMode = LinearGradientMode.Vertical; + + #endregion + + #region IOverlay Members + + /// + /// Draw a filled border + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle bounds = this.CalculateBounds(); + if (!bounds.IsEmpty) + this.DrawFilledBorder(g, bounds); + } + + #endregion + + #region Subclass responsibility + + /// + /// Subclasses should override this to say where the border should be drawn + /// + /// + protected virtual Rectangle CalculateBounds() { + return Rectangle.Empty; + } + + #endregion + + #region Implementation utilities + + /// + /// Do the actual work of drawing the filled border + /// + /// + /// + protected void DrawFilledBorder(Graphics g, Rectangle bounds) { + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillGradientFrom != null && this.FillGradientTo != null) { + if (this.FillBrush != null) + this.FillBrush.Dispose(); + this.FillBrush = new LinearGradientBrush(bounds, this.FillGradientFrom.Value, this.FillGradientTo.Value, this.FillGradientMode); + } + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + /// + /// Create a GraphicsPath that represents a round cornered rectangle. + /// + /// + /// If this is 0 or less, the rectangle will not be rounded. + /// + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter <= 0.0f) { + path.AddRectangle(rect); + } else { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } + + return path; + } + + #endregion + } + + /// + /// Instances of this class draw a border around the decorated row + /// + public class RowBorderDecoration : BorderDecoration + { + /// + /// Gets or sets the index of the left most column to be used for the border + /// + public int LeftColumn { + get { return leftColumn; } + set { leftColumn = value; } + } + private int leftColumn = -1; + + /// + /// Gets or sets the index of the right most column to be used for the border + /// + public int RightColumn { + get { return rightColumn; } + set { rightColumn = value; } + } + private int rightColumn = -1; + + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + Rectangle bounds = this.RowBounds; + if (this.ListItem == null) + return bounds; + + if (this.LeftColumn >= 0) { + Rectangle leftCellBounds = this.ListItem.GetSubItemBounds(this.LeftColumn); + if (!leftCellBounds.IsEmpty) { + bounds.Width = bounds.Right - leftCellBounds.Left; + bounds.X = leftCellBounds.Left; + } + } + + if (this.RightColumn >= 0) { + Rectangle rightCellBounds = this.ListItem.GetSubItemBounds(this.RightColumn); + if (!rightCellBounds.IsEmpty) { + bounds.Width = rightCellBounds.Right - bounds.Left; + } + } + + return bounds; + } + } + + /// + /// Instances of this class draw a border around the decorated subitem. + /// + public class CellBorderDecoration : BorderDecoration + { + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + return this.CellBounds; + } + } + + /// + /// This decoration puts a border around the cell being edited and + /// optionally "lightboxes" the cell (makes the rest of the control dark). + /// + public class EditingCellBorderDecoration : BorderDecoration + { + #region Life and death + + /// + /// Create a EditingCellBorderDecoration + /// + public EditingCellBorderDecoration() { + this.FillBrush = null; + this.BorderPen = new Pen(Color.DarkBlue, 2); + this.CornerRounding = 8; + this.BoundsPadding = new Size(10, 8); + + } + + /// + /// Create a EditingCellBorderDecoration + /// + /// Should the decoration use a lighbox display style? + public EditingCellBorderDecoration(bool useLightBox) : this() + { + this.UseLightbox = useLightbox; + } + + #endregion + + #region Configuration properties + + /// + /// Gets or set whether the decoration should make the rest of + /// the control dark when a cell is being edited + /// + /// If this is true, FillBrush is used to overpaint + /// the control. + public bool UseLightbox { + get { return this.useLightbox; } + set { + if (this.useLightbox == value) + return; + this.useLightbox = value; + if (this.useLightbox) { + if (this.FillBrush == null) + this.FillBrush = new SolidBrush(Color.FromArgb(64, Color.Black)); + } + } + } + private bool useLightbox; + + #endregion + + #region Implementation + + /// + /// Draw the decoration + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!olv.IsCellEditing) + return; + + Rectangle bounds = olv.CellEditor.Bounds; + if (bounds.IsEmpty) + return; + + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillBrush != null) { + if (this.UseLightbox) { + using (Region newClip = new Region(r)) { + newClip.Exclude(path); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } else { + g.FillPath(this.FillBrush, path); + } + } + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + #endregion + } + + /// + /// This decoration causes everything *except* the row under the mouse to be overpainted + /// with a tint, making the row under the mouse stand out in comparison. + /// The darker and more opaque the fill color, the more obvious the + /// decorated row becomes. + /// + public class LightBoxDecoration : BorderDecoration + { + /// + /// Create a LightBoxDecoration + /// + public LightBoxDecoration() { + this.BoundsPadding = new Size(-1, 4); + this.CornerRounding = 8.0f; + this.FillBrush = new SolidBrush(Color.FromArgb(72, Color.Black)); + } + + /// + /// Draw a tint over everything in the ObjectListView except the + /// row under the mouse. + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!r.Contains(olv.PointToClient(Cursor.Position))) + return; + + Rectangle bounds = this.RowBounds; + if (bounds.IsEmpty) { + if (olv.View == View.Tile) + g.FillRectangle(this.FillBrush, r); + return; + } + + using (Region newClip = new Region(r)) { + bounds.Inflate(this.BoundsPadding); + newClip.Exclude(this.GetRoundedRect(bounds, this.CornerRounding)); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } + } + + /// + /// Instances of this class put an Image over the row/cell that it is decorating + /// + public class ImageDecoration : ImageAdornment, IDecoration + { + #region Constructors + + /// + /// Create an image decoration + /// + public ImageDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create an image decoration + /// + /// + public ImageDecoration(Image image) + : this() { + this.Image = image; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, int transparency) + : this() { + this.Image = image; + this.Transparency = transparency; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, ContentAlignment alignment) + : this() { + this.Image = image; + this.Alignment = alignment; + } + + /// + /// Create an image decoration + /// + /// + /// + /// + public ImageDecoration(Image image, int transparency, ContentAlignment alignment) + : this() { + this.Image = image; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawImage(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } + + /// + /// Instances of this class draw some text over the row/cell that they are decorating + /// + public class TextDecoration : TextAdornment, IDecoration + { + #region Constructors + + /// + /// Create a TextDecoration + /// + public TextDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create a TextDecoration + /// + /// + public TextDecoration(string text) + : this() { + this.Text = text; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, int transparency) + : this() { + this.Text = text; + this.Transparency = transparency; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, ContentAlignment alignment) + : this() { + this.Text = text; + this.Alignment = alignment; + } + + /// + /// Create a TextDecoration + /// + /// + /// + /// + public TextDecoration(string text, int transparency, ContentAlignment alignment) + : this() { + this.Text = text; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawText(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Overlays.cs b/ObjectListView/Rendering/Overlays.cs new file mode 100644 index 0000000..d103601 --- /dev/null +++ b/ObjectListView/Rendering/Overlays.cs @@ -0,0 +1,302 @@ +/* + * Overlays - Images, text or other things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * v2.3 + * 2009-08-17 JPP - Overlays now use Adornments + * - Added ITransparentOverlay interface. Overlays can now have separate transparency levels + * 2009-08-10 JPP - Moved decoration related code to new file + * v2.2.1 + * 200-07-24 JPP - TintedColumnDecoration now works when last item is a member of a collapsed + * group (well, it no longer crashes). + * v2.2 + * 2009-06-01 JPP - Make sure that TintedColumnDecoration reaches to the last item in group view + * 2009-05-05 JPP - Unified BillboardOverlay text rendering with that of TextOverlay + * 2009-04-30 JPP - Added TintedColumnDecoration + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// The interface for an object which can draw itself over the top of + /// an ObjectListView. + /// + public interface IOverlay + { + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + void Draw(ObjectListView olv, Graphics g, Rectangle r); + } + + /// + /// An interface for an overlay that supports variable levels of transparency + /// + public interface ITransparentOverlay : IOverlay + { + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + int Transparency { get; set; } + } + + /// + /// A null implementation of the IOverlay interface + /// + public class AbstractOverlay : ITransparentOverlay + { + #region IOverlay Members + + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + + #region ITransparentOverlay Members + + /// + /// How transparent should this overlay be? + /// + [Category("ObjectListView"), + Description("How transparent should this overlay be"), + DefaultValue(128), + NotifyParentProperty(true)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class ImageOverlay : ImageAdornment, ITransparentOverlay + { + /// + /// Create an ImageOverlay + /// + public ImageOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawImage(g, insetRect, this.Image, 255); + } + + #endregion + } + + /// + /// An overlay that will draw text over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class TextOverlay : TextAdornment, ITransparentOverlay + { + /// + /// Create a TextOverlay + /// + public TextOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + /// + /// Gets or sets whether the border will be drawn with rounded corners + /// + [Browsable(false), + Obsolete("Use CornerRounding instead", false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool RoundCorneredBorder { + get { return this.CornerRounding > 0; } + set { + if (value) + this.CornerRounding = 16.0f; + else + this.CornerRounding = 0.0f; + } + } + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawText(g, insetRect, this.Text, 255); + } + + #endregion + } + + /// + /// A Billboard overlay is a TextOverlay positioned at an absolute point + /// + public class BillboardOverlay : TextOverlay + { + /// + /// Create a BillboardOverlay + /// + public BillboardOverlay() { + this.Transparency = 255; + this.BackColor = Color.PeachPuff; + this.TextColor = Color.Black; + this.BorderColor = Color.Empty; + this.Font = new Font("Tahoma", 10); + } + + /// + /// Gets or sets where should the top left of the billboard be placed + /// + public Point Location { + get { return this.location; } + set { this.location = value; } + } + private Point location; + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + // Calculate the bounds of the text, and then move it to where it should be + Rectangle textRect = this.CalculateTextBounds(g, r, this.Text); + textRect.Location = this.Location; + + // Make sure the billboard is within the bounds of the List, as far as is possible + if (textRect.Right > r.Width) + textRect.X = Math.Max(r.Left, r.Width - textRect.Width); + if (textRect.Bottom > r.Height) + textRect.Y = Math.Max(r.Top, r.Height - textRect.Height); + + this.DrawBorderedText(g, textRect, this.Text, 255); + } + } +} diff --git a/ObjectListView/Rendering/Renderers.cs b/ObjectListView/Rendering/Renderers.cs new file mode 100644 index 0000000..dac6a62 --- /dev/null +++ b/ObjectListView/Rendering/Renderers.cs @@ -0,0 +1,3887 @@ +/* + * Renderers - A collection of useful renderers that are used to owner draw a cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2018-10-06 JPP - Fix rendering so that OLVColumn.WordWrap works when using customised Renderers + * 2018-05-01 JPP - Use ITextMatchFilter interface rather than TextMatchFilter concrete class. + * v2.9.2 + * 2016-06-02 JPP - CalculateImageWidth() no longer adds 2 to the image width + * 2016-05-29 JPP - Fix calculation of cell edit boundaries on TreeListView controls + * v2.9 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * 2015-06-23 JPP - Added ColumnButtonRenderer plus general support for Buttons + * 2015-06-22 JPP - Added BaseRenderer.ConfigureItem() and ConfigureSubItem() to easily allow + * other renderers to be chained for use within a primary renderer. + * - Lots of tightening of hit tests and edit rectangles + * 2015-05-15 JPP - Handle rendering an Image when that Image is returned as an aspect. + * v2.8 + * 2014-09-26 JPP - Dispose of animation timer in a more robust fashion. + * 2014-05-20 JPP - Handle rendering disabled rows + * v2.7 + * 2013-04-29 JPP - Fixed bug where Images were not vertically aligned + * v2.6 + * 2012-10-26 JPP - Hit detection will no longer report check box hits on columns without checkboxes. + * 2012-07-13 JPP - [Breaking change] Added preferedSize parameter to IRenderer.GetEditRectangle(). + * v2.5.1 + * 2012-07-14 JPP - Added CellPadding to various places. Replaced DescribedTaskRenderer.CellPadding. + * 2012-07-11 JPP - Added CellVerticalAlignment to various places allow cell contents to be vertically + * aligned (rather than always being centered). + * v2.5 + * 2010-08-24 JPP - CheckBoxRenderer handles hot boxes and correctly vertically centers the box. + * 2010-06-23 JPP - Major rework of HighlightTextRenderer. Now uses TextMatchFilter directly. + * Draw highlighting underneath text to improve legibility. Works with new + * TextMatchFilter capabilities. + * v2.4 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * v2.3 + * 2009-09-28 JPP - Added DescribedTaskRenderer + * 2009-09-01 JPP - Correctly handle an ImageRenderer's handling of an aspect that holds + * the image to be displayed at Byte[]. + * 2009-08-29 JPP - Fixed bug where some of a cell's background was not erased. + * 2009-08-15 JPP - Correctly MeasureText() using the appropriate graphic context + * - Handle translucent selection setting + * v2.2.1 + * 2009-07-24 JPP - Try to honour CanWrap setting when GDI rendering text. + * 2009-07-11 JPP - Correctly calculate edit rectangle for subitems of a tree view + * (previously subitems were indented in the same way as the primary column) + * v2.2 + * 2009-06-06 JPP - Tweaked text rendering so that column 0 isn't ellipsed unnecessarily. + * 2009-05-05 JPP - Added Unfocused foreground and background colors + * (thanks to Christophe Hosten) + * 2009-04-21 JPP - Fixed off-by-1 error when calculating text widths. This caused + * middle and right aligned columns to always wrap one character + * when printed using ListViewPrinter (SF#2776634). + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-06 JPP - Allow for item indent when calculating edit rectangle + * v2.1 + * 2009-02-24 JPP - Work properly with ListViewPrinter again + * 2009-01-26 JPP - AUSTRALIA DAY (why aren't I on holidays!) + * - Major overhaul of renderers. Now uses IRenderer interface. + * - ImagesRenderer and FlagsRenderer are now defunct. + * The names are retained for backward compatibility. + * 2009-01-23 JPP - Align bitmap AND text according to column alignment (previously + * only text was aligned and bitmap was always to the left). + * 2009-01-21 JPP - Changed to use TextRenderer rather than native GDI routines. + * 2009-01-20 JPP - Draw images directly from image list if possible. 30% faster! + * - Tweaked some spacings to look more like native ListView + * - Text highlight for non FullRowSelect is now the right color + * when the control doesn't have focus. + * - Commented out experimental animations. Still needs work. + * 2009-01-19 JPP - Changed to draw text using GDI routines. Looks more like + * native control this way. Set UseGdiTextRendering to false to + * revert to previous behavior. + * 2009-01-15 JPP - Draw background correctly when control is disabled + * - Render checkboxes using CheckBoxRenderer + * v2.0.1 + * 2008-12-29 JPP - Render text correctly when HideSelection is true. + * 2008-12-26 JPP - BaseRenderer now works correctly in all Views + * 2008-12-23 JPP - Fixed two small bugs in BarRenderer + * v2.0 + * 2008-10-26 JPP - Don't owner draw when in Design mode + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2018 Phillip Piper + * + * TO DO: + * - Hit detection on renderers doesn't change the controls standard selection behavior + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using Timer = System.Threading.Timer; + +namespace BrightIdeasSoftware { + /// + /// Renderers are the mechanism used for owner drawing cells. As such, they can also handle + /// hit detection and positioning of cell editing rectangles. + /// + public interface IRenderer { + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, Object rowObject); + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, Object rowObject); + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + void HitTest(OlvListViewHitTestInfo hti, int x, int y); + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize); + } + + /// + /// Renderers that implement this interface will have the filter property updated, + /// each time the filter on the ObjectListView is updated. + /// + public interface IFilterAwareRenderer + { + /// + /// Gets or sets the filter that is currently active + /// + IModelFilter Filter { get; set; } + } + + /// + /// An AbstractRenderer is a do-nothing implementation of the IRenderer interface. + /// + [Browsable(true), + ToolboxItem(false)] + public class AbstractRenderer : Component, IRenderer { + #region IRenderer Members + + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject) { + return true; + } + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + return false; + } + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + public virtual void HitTest(OlvListViewHitTestInfo hti, int x, int y) {} + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + public virtual Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return cellBounds; + } + + #endregion + } + + /// + /// This class provides compatibility for v1 RendererDelegates + /// + [ToolboxItem(false)] + internal class Version1Renderer : AbstractRenderer { + public Version1Renderer(RenderDelegate renderDelegate) { + this.RenderDelegate = renderDelegate; + } + + /// + /// The renderer delegate that this renderer wraps + /// + public RenderDelegate RenderDelegate; + + #region IRenderer Members + + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + if (this.RenderDelegate == null) + return base.RenderSubItem(e, g, cellBounds, rowObject); + else + return this.RenderDelegate(e, g, cellBounds, rowObject); + } + + #endregion + } + + /// + /// A BaseRenderer provides useful base level functionality for any custom renderer. + /// + /// + /// Subclasses will normally override the Render or OptionalRender method, and use the other + /// methods as helper functions. + /// + [Browsable(true), + ToolboxItem(true)] + public class BaseRenderer : AbstractRenderer { + internal const TextFormatFlags NormalTextFormatFlags = TextFormatFlags.NoPrefix | + TextFormatFlags.EndEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + + #region Configuration Properties + + /// + /// Can the renderer wrap lines that do not fit completely within the cell? + /// + /// + /// If this is not set specifically, the value will be taken from Column.WordWrap + /// + /// Wrapping text doesn't work with the GDI renderer, so if this set to true, GDI+ rendering will used. + /// The difference between GDI and GDI+ rendering can give word wrapped columns a slight different appearance. + /// + /// + [Category("Appearance"), + Description("Can the renderer wrap text that does not fit completely within the cell"), + DefaultValue(null)] + public bool? CanWrap { + get { return canWrap; } + set { canWrap = value; } + } + + private bool? canWrap; + + /// + /// Get the actual value that should be used right now for CanWrap + /// + [Browsable(false)] + protected bool CanWrapOrDefault { + get { + return this.CanWrap ?? this.Column != null && this.Column.WordWrap; + } + } + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// for more details. + /// + [Category("ObjectListView"), + Description("The number of pixels that renderer will leave empty around the edge of the cell"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets the horizontal alignment of the column + /// + [Browsable(false)] + public HorizontalAlignment CellHorizontalAlignment + { + get { return this.Column == null ? HorizontalAlignment.Left : this.Column.TextAlign; } + } + + /// + /// Gets or sets how cells drawn by this renderer will be vertically aligned. + /// + /// + /// + /// If this is not set, the value from the column or control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets the optional padding that this renderer should apply before drawing. + /// This property considers all possible sources of padding + /// + [Browsable(false)] + protected virtual Rectangle? EffectiveCellPadding { + get { + if (this.cellPadding.HasValue) + return this.cellPadding.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellPadding.HasValue) + return this.OLVSubItem.CellPadding.Value; + + if (this.ListItem != null && this.ListItem.CellPadding.HasValue) + return this.ListItem.CellPadding.Value; + + if (this.Column != null && this.Column.CellPadding.HasValue) + return this.Column.CellPadding.Value; + + if (this.ListView != null && this.ListView.CellPadding.HasValue) + return this.ListView.CellPadding.Value; + + return null; + } + } + + /// + /// Gets the vertical cell alignment that should govern the rendering. + /// This property considers all possible sources. + /// + [Browsable(false)] + protected virtual StringAlignment EffectiveCellVerticalAlignment { + get { + if (this.cellVerticalAlignment.HasValue) + return this.cellVerticalAlignment.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellVerticalAlignment.HasValue) + return this.OLVSubItem.CellVerticalAlignment.Value; + + if (this.ListItem != null && this.ListItem.CellVerticalAlignment.HasValue) + return this.ListItem.CellVerticalAlignment.Value; + + if (this.Column != null && this.Column.CellVerticalAlignment.HasValue) + return this.Column.CellVerticalAlignment.Value; + + if (this.ListView != null) + return this.ListView.CellVerticalAlignment; + + return StringAlignment.Center; + } + } + + /// + /// Gets or sets the image list from which keyed images will be fetched + /// + [Category("Appearance"), + Description("The image list from which keyed images will be fetched for drawing. If this is not given, the small ImageList from the ObjectListView will be used"), + DefaultValue(null)] + public ImageList ImageList { + get { return imageList; } + set { imageList = value; } + } + + private ImageList imageList; + + /// + /// When rendering multiple images, how many pixels should be between each image? + /// + [Category("Appearance"), + Description("When rendering multiple images, how many pixels should be between each image?"), + DefaultValue(1)] + public int Spacing { + get { return spacing; } + set { spacing = value; } + } + + private int spacing = 1; + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + /// Even if this is set to true, it will return false if the renderer + /// is set to word wrap, since GDI doesn't handle wrapping. + [Category("Appearance"), + Description("Should text be rendered using GDI routines?"), + DefaultValue(true)] + public virtual bool UseGdiTextRendering { + get { + // Can't use GDI routines on a GDI+ printer context or when word wrapping is required + return !this.IsPrinting && !this.CanWrapOrDefault && useGdiTextRendering; + } + set { useGdiTextRendering = value; } + } + private bool useGdiTextRendering = true; + + #endregion + + #region State Properties + + /// + /// Get or set the aspect of the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object Aspect { + get { + if (aspect == null) + aspect = column.GetValue(this.rowObject); + return aspect; + } + set { aspect = value; } + } + + private Object aspect; + + /// + /// What are the bounds of the cell that is being drawn? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Rectangle Bounds { + get { return bounds; } + set { bounds = value; } + } + + private Rectangle bounds; + + /// + /// Get or set the OLVColumn that this renderer will draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn Column { + get { return column; } + set { column = value; } + } + + private OLVColumn column; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewItemEventArgs DrawItemEvent { + get { return drawItemEventArgs; } + set { drawItemEventArgs = value; } + } + + private DrawListViewItemEventArgs drawItemEventArgs; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewSubItemEventArgs Event { + get { return eventArgs; } + set { eventArgs = value; } + } + + private DrawListViewSubItemEventArgs eventArgs; + + /// + /// Gets or sets the font to be used for text in this cell + /// + /// + /// + /// In general, this property should be treated as internal. + /// If you do set this, the given font will be used without any other consideration. + /// All other factors -- selection state, hot item, hyperlinks -- will be ignored. + /// + /// + /// A better way to set the font is to change either ListItem.Font or SubItem.Font + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Font Font { + get { + if (this.font != null || this.ListItem == null) + return this.font; + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.Font; + + return this.SubItem.Font; + } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets the image list from which keyed images will be fetched + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageList ImageListOrDefault { + get { return this.ImageList ?? this.ListView.SmallImageList; } + } + + /// + /// Should this renderer fill in the background before drawing? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDrawBackground { + get { return !this.IsPrinting; } + } + + /// + /// Cache whether or not our item is selected + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsItemSelected { + get { return isItemSelected; } + set { isItemSelected = value; } + } + + private bool isItemSelected; + + /// + /// Is this renderer being used on a printer context? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrinting { + get { return isPrinting; } + set { isPrinting = value; } + } + + private bool isPrinting; + + /// + /// Get or set the listitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + + private OLVListItem listItem; + + /// + /// Get/set the listview for which the drawing is to be done + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + + private ObjectListView objectListView; + + /// + /// Get the specialized OLVSubItem that this renderer is drawing + /// + /// This returns null for column 0. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem OLVSubItem { + get { return listSubItem as OLVListSubItem; } + } + + /// + /// Get or set the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + + private Object rowObject; + + /// + /// Get or set the list subitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem SubItem { + get { return listSubItem; } + set { listSubItem = value; } + } + + private OLVListSubItem listSubItem; + + /// + /// The brush that will be used to paint the text + /// + /// + /// + /// In general, this property should be treated as internal. It will be reset after each render. + /// + /// + /// + /// In particular, don't set it to configure the color of the text on the control. That should be done via SubItem.ForeColor + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush TextBrush { + get { + if (textBrush == null) + return new SolidBrush(this.GetForegroundColor()); + else + return this.textBrush; + } + set { textBrush = value; } + } + + private Brush textBrush; + + /// + /// Will this renderer use the custom images from the parent ObjectListView + /// to draw the checkbox images. + /// + /// + /// + /// If this is true, the renderer will use the images from the + /// StateImageList to represent checkboxes. 0 - unchecked, 1 - checked, 2 - indeterminate. + /// + /// If this is false (the default), then the renderer will use .NET's standard + /// CheckBoxRenderer. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool UseCustomCheckboxImages { + get { return useCustomCheckboxImages; } + set { useCustomCheckboxImages = value; } + } + + private bool useCustomCheckboxImages; + + private void ClearState() { + this.Event = null; + this.DrawItemEvent = null; + this.Aspect = null; + this.TextBrush = null; + } + + #endregion + + #region Utilities + + /// + /// Align the second rectangle with the first rectangle, + /// according to the alignment of the column + /// + /// The cell's bounds + /// The rectangle to be aligned within the bounds + /// An aligned rectangle + protected virtual Rectangle AlignRectangle(Rectangle outer, Rectangle inner) { + Rectangle r = new Rectangle(outer.Location, inner.Size); + + // Align horizontally depending on the column alignment + if (inner.Width < outer.Width) { + r.X = AlignHorizontally(outer, inner); + } + + // Align vertically too + if (inner.Height < outer.Height) { + r.Y = AlignVertically(outer, inner); + } + + return r; + } + + /// + /// Calculate the left edge of the rectangle that aligns the outer rectangle with the inner one + /// according to this renderer's horizontal alignment + /// + /// + /// + /// + protected int AlignHorizontally(Rectangle outer, Rectangle inner) { + HorizontalAlignment alignment = this.CellHorizontalAlignment; + switch (alignment) { + case HorizontalAlignment.Left: + return outer.Left + 1; + case HorizontalAlignment.Center: + return outer.Left + ((outer.Width - inner.Width) / 2); + case HorizontalAlignment.Right: + return outer.Right - inner.Width - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with the inner rectangle + /// according to this renders vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, Rectangle inner) { + return AlignVertically(outer, inner.Height); + } + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with a rectangle of the given height + /// according to this renderer's vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, int innerHeight) { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return outer.Top + 1; + case StringAlignment.Center: + return outer.Top + ((outer.Height - innerHeight) / 2); + case StringAlignment.Far: + return outer.Bottom - innerHeight - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + /// + /// Calculate the space that our rendering will occupy and then align that space + /// with the given rectangle, according to the Column alignment + /// + /// + /// Pre-padded bounds of the cell + /// + protected virtual Rectangle CalculateAlignedRectangle(Graphics g, Rectangle r) { + if (this.Column == null) + return r; + + Rectangle contentRectangle = new Rectangle(Point.Empty, this.CalculateContentSize(g, r)); + return this.AlignRectangle(r, contentRectangle); + } + + /// + /// Calculate the size of the content of this cell. + /// + /// + /// Pre-padded bounds of the cell + /// The width and height of the content + protected virtual Size CalculateContentSize(Graphics g, Rectangle r) + { + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + Size imageSize = this.CalculateImageSize(g, this.GetImageSelector()); + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width - (checkBoxSize.Width + imageSize.Width)); + + // If the combined width is greater than the whole cell, we just use the cell itself + + int width = Math.Min(r.Width, checkBoxSize.Width + imageSize.Width + textSize.Width); + int componentMaxHeight = Math.Max(checkBoxSize.Height, Math.Max(imageSize.Height, textSize.Height)); + int height = Math.Min(r.Height, componentMaxHeight); + + return new Size(width, height); + } + + /// + /// Calculate the bounds of a checkbox given the (pre-padded) cell bounds + /// + /// + /// Pre-padded cell bounds + /// + protected Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + return this.AlignRectangle(cellBounds, new Rectangle(0, 0, checkBoxSize.Width, checkBoxSize.Height)); + } + + + /// + /// How much space will the check box for this cell occupy? + /// + /// Only column 0 can have check boxes. Sub item checkboxes are + /// treated as images + /// + /// + protected virtual Size CalculateCheckBoxSize(Graphics g) + { + if (UseCustomCheckboxImages && this.ListView.StateImageList != null) + return this.ListView.StateImageList.ImageSize; + + return CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); + } + + /// + /// How much space will the check box for this row occupy? + /// If the list doesn't have checkboxes, or this isn't the primary column, + /// this returns an empty size. + /// + /// + /// + protected virtual Size CalculatePrimaryCheckBoxSize(Graphics g) { + if (!this.ListView.CheckBoxes || !this.ColumnIsPrimary) + return Size.Empty; + + Size size = this.CalculateCheckBoxSize(g); + size.Width += 6; + return size; + } + + /// + /// How much horizontal space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageWidth(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Width; + } + + /// + /// How much vertical space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageHeight(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Height; + } + + /// + /// How much space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual Size CalculateImageSize(Graphics g, object imageSelector) + { + if (imageSelector == null || imageSelector == DBNull.Value) + return Size.Empty; + + // Check for the image in the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) + { + int selectorAsInt = -1; + + if (imageSelector is Int32) + selectorAsInt = (Int32)imageSelector; + else + { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + if (selectorAsInt >= 0) + return il.ImageSize; + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image != null) + return image.Size; + + return Size.Empty; + } + + /// + /// How much horizontal space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual int CalculateTextWidth(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return 0; + + return CalculateTextSize(g, txt, width).Width; + } + + /// + /// How much space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual Size CalculateTextSize(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return Size.Empty; + + if (this.UseGdiTextRendering) + { + Size proposedSize = new Size(width, Int32.MaxValue); + return TextRenderer.MeasureText(g, txt, this.Font, proposedSize, NormalTextFormatFlags); + } + + // Using GDI+ rendering + using (StringFormat fmt = new StringFormat()) { + fmt.Trimming = StringTrimming.EllipsisCharacter; + SizeF sizeF = g.MeasureString(txt, this.Font, width, fmt); + return new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + } + } + + /// + /// Return the Color that is the background color for this item's cell + /// + /// The background color of the subitem + public virtual Color GetBackgroundColor() { + if (!this.ListView.Enabled) + return SystemColors.Control; + + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection && this.ListView.FullRowSelect) + return this.GetSelectedBackgroundColor(); + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.BackColor; + + return this.SubItem.BackColor; + } + + /// + /// Return the color of the background color when the item is selected + /// + /// The background color of the subitem + public virtual Color GetSelectedBackgroundColor() { + if (this.ListView.Focused) + return this.ListItem.SelectedBackColor ?? this.ListView.SelectedBackColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedBackColorOrDefault; + + return this.ListItem.BackColor; + } + + /// + /// Return the color to be used for text in this cell + /// + /// The text color of the subitem + public virtual Color GetForegroundColor() { + if (this.IsItemSelected && + !this.ListView.UseTranslucentSelection && + (this.ColumnIsPrimary || this.ListView.FullRowSelect)) + return this.GetSelectedForegroundColor(); + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the color of the foreground color when the item is selected + /// + /// The foreground color of the subitem + public virtual Color GetSelectedForegroundColor() + { + if (this.ListView.Focused) + return this.ListItem.SelectedForeColor ?? this.ListView.SelectedForeColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedForeColorOrDefault; + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the image that should be drawn against this subitem + /// + /// An Image or null if no image should be drawn. + protected virtual Image GetImage() { + return this.GetImage(this.GetImageSelector()); + } + + /// + /// Return the actual image that should be drawn when keyed by the given image selector. + /// An image selector can be: + /// an int, giving the index into the image list + /// a string, giving the image key into the image list + /// an Image, being the image itself + /// + /// + /// The value that indicates the image to be used + /// An Image or null + protected virtual Image GetImage(Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return null; + + ImageList il = this.ImageListOrDefault; + if (il != null) { + if (imageSelector is Int32) { + Int32 index = (Int32) imageSelector; + if (index < 0 || index >= il.Images.Count) + return null; + + return il.Images[index]; + } + + String str = imageSelector as String; + if (str != null) { + if (il.Images.ContainsKey(str)) + return il.Images[str]; + + return null; + } + } + + return imageSelector as Image; + } + + /// + /// + protected virtual Object GetImageSelector() { + return this.ColumnIsPrimary ? this.ListItem.ImageSelector : this.OLVSubItem.ImageSelector; + } + + /// + /// Return the string that should be drawn within this + /// + /// + protected virtual string GetText() { + return this.SubItem == null ? this.ListItem.Text : this.SubItem.Text; + } + + /// + /// Return the Color that is the background color for this item's text + /// + /// The background color of the subitem's text + [Obsolete("Use GetBackgroundColor() instead")] + protected virtual Color GetTextBackgroundColor() { + return Color.Red; // just so it shows up if it is used + } + + #endregion + + #region IRenderer members + + /// + /// Render the whole item in a non-details view. + /// + /// + /// + /// + /// + /// + public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object model) { + this.ConfigureItem(e, itemBounds, model); + return this.OptionalRender(g, itemBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureItem(DrawListViewItemEventArgs e, Rectangle itemBounds, object model) + { + this.ClearState(); + + this.DrawItemEvent = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = null; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = this.ListView.GetColumn(0); + this.RowObject = model; + this.Bounds = itemBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Render one cell + /// + /// + /// + /// + /// + /// + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object model) { + this.ConfigureSubItem(e, cellBounds, model); + return this.OptionalRender(g, cellBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + this.ClearState(); + + this.Event = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = (OLVListSubItem)e.SubItem; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = (OLVColumn)e.Header; + this.RowObject = model; + this.Bounds = cellBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Calculate which part of this cell was hit + /// + /// + /// + /// + public override void HitTest(OlvListViewHitTestInfo hti, int x, int y) { + this.ClearState(); + + this.ListView = hti.ListView; + this.ListItem = hti.Item; + this.SubItem = hti.SubItem; + this.Column = hti.Column; + this.RowObject = hti.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + if (this.SubItem == null) + this.Bounds = this.ListItem.Bounds; + else + this.Bounds = this.ListItem.GetSubItemBounds(this.Column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) { + this.HandleHitTest(g, hti, x, y); + } + } + + /// + /// Calculate the edit rectangle + /// + /// + /// + /// + /// + /// + /// + public override Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + this.ClearState(); + + this.ListView = (ObjectListView) item.ListView; + this.ListItem = item; + this.SubItem = item.GetSubItem(subItemIndex); + this.Column = this.ListView.GetColumn(subItemIndex); + this.RowObject = item.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + this.Bounds = cellBounds; + + return this.HandleGetEditRectangle(g, cellBounds, item, subItemIndex, preferredSize); + } + + #endregion + + #region IRenderer implementation + + // Subclasses will probably want to override these methods rather than the IRenderer + // interface methods. + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method. + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + /// Returns whether the rendering has already taken place. + /// If this returns false, the default processing will take over. + /// + public virtual bool OptionalRender(Graphics g, Rectangle r) { + if (this.ListView.View != View.Details) + return false; + + this.Render(g, r); + return true; + } + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method if they never want + /// to fall back on the default processing + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + public virtual void Render(Graphics g, Rectangle r) { + this.StandardRender(g, r); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected virtual void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateAlignedRectangle(g, ApplyCellPadding(this.Bounds)); + this.StandardHitTest(g, hti, r, x, y); + } + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected virtual Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + // MAINTAINER NOTE: This type testing is wrong (design-wise). The base class should return cell bounds, + // and a more specialized class should return StandardGetEditRectangle(). But BaseRenderer is used directly + // to draw most normal cells, as well as being directly subclassed for user implemented renderers. And this + // method needs to return different bounds in each of those cases. We should have a StandardRenderer and make + // BaseRenderer into an ABC -- but that would break too much existing code. And so we have this hack :( + + // If we are a standard renderer, return the position of the text, otherwise, use the whole cell. + if (this.GetType() == typeof (BaseRenderer)) + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + return cellBounds; + } + + #endregion + + #region Standard IRenderer implementations + + /// + /// Draw the standard "[checkbox] [image] [text]" cell after the state properties have been initialized. + /// + /// + /// + protected void StandardRender(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + // Adjust the first columns rectangle to match the padding used by the native mode of the ListView + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left ) { + r.X += 3; + r.Width -= 1; + } + r = this.ApplyCellPadding(r); + this.DrawAlignedImageAndText(g, r); + + // Show where the bounds of the cell padding are (debugging) + if (ObjectListView.ShowCellPaddingBounds) + g.DrawRectangle(Pens.Purple, r); + } + + /// + /// Change the bounds of the given rectangle to take any cell padding into account + /// + /// + /// + public virtual Rectangle ApplyCellPadding(Rectangle r) { + Rectangle? padding = this.EffectiveCellPadding; + if (!padding.HasValue) + return r; + // The two subtractions below look wrong, but are correct! + Rectangle paddingRectangle = padding.Value; + r.Width -= paddingRectangle.Right; + r.Height -= paddingRectangle.Bottom; + r.Offset(paddingRectangle.Location); + return r; + } + + /// + /// Perform normal hit testing relative to the given aligned content bounds + /// + /// + /// + /// + /// + /// + protected virtual void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle alignedContentRectangle, int x, int y) { + Rectangle r = alignedContentRectangle; + + // Match tweaking from renderer + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left && !(this is TreeListView.TreeRenderer)) { + r.X += 3; + r.Width -= 1; + } + int width = 0; + + // Did they hit a check box on the primary column? + if (this.ColumnIsPrimary && this.ListView.CheckBoxes) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + int checkBoxTop = this.AlignVertically(r, checkBoxSize.Height); + Rectangle r3 = new Rectangle(r.X, checkBoxTop, checkBoxSize.Width, checkBoxSize.Height); + width = r3.Width + 6; + // g.DrawRectangle(Pens.DarkGreen, r3); + if (r3.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + } + + // Did they hit the image? If they hit the image of a + // non-primary column that has a checkbox, it counts as a + // checkbox hit + r.X += width; + r.Width -= width; + width = this.CalculateImageWidth(g, this.GetImageSelector()); + Rectangle rTwo = r; + rTwo.Width = width; + //g.DrawRectangle(Pens.Red, rTwo); + if (rTwo.Contains(x, y)) { + if (this.Column != null && (this.Column.Index > 0 && this.Column.CheckBoxes)) + hti.HitTestLocation = HitTestLocation.CheckBox; + else + hti.HitTestLocation = HitTestLocation.Image; + return; + } + + // Did they hit the text? + r.X += width; + r.Width -= width; + width = this.CalculateTextWidth(g, this.GetText(), r.Width); + rTwo = r; + rTwo.Width = width; + // g.DrawRectangle(Pens.Blue, rTwo); + if (rTwo.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + return; + } + + hti.HitTestLocation = HitTestLocation.InCell; + } + + /// + /// This method calculates the bounds of the text within a standard layout + /// (i.e. optional checkbox, optional image, text) + /// + /// This method only works correctly if the state of the renderer + /// has been fully initialized (see BaseRenderer.GetEditRectangle) + /// + /// + /// + /// + protected virtual Rectangle StandardGetEditRectangle(Graphics g, Rectangle cellBounds, Size preferredSize) { + + Size contentSize = this.CalculateContentSize(g, cellBounds); + int contentWidth = this.Column.CellEditUseWholeCellEffective ? cellBounds.Width : contentSize.Width; + Rectangle editControlBounds = this.CalculatePaddedAlignedBounds(g, cellBounds, new Size(contentWidth, preferredSize.Height)); + + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + int imageWidth = this.CalculateImageWidth(g, this.GetImageSelector()); + + int width = checkBoxSize.Width + imageWidth + 2; + + // Indent the primary column by the required amount + if (this.ColumnIsPrimary && this.ListItem.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * this.ListItem.IndentCount; + editControlBounds.X += indentWidth; + } + + editControlBounds.X += width; + editControlBounds.Width -= width; + + if (editControlBounds.Width < 50) + editControlBounds.Width = 50; + if (editControlBounds.Right > cellBounds.Right) + editControlBounds.Width = cellBounds.Right - editControlBounds.Left; + + return editControlBounds; + } + + /// + /// Apply any padding to the given bounds, and then align a rectangle of the given + /// size within that padded area. + /// + /// + /// + /// + /// + protected Rectangle CalculatePaddedAlignedBounds(Graphics g, Rectangle cellBounds, Size preferredSize) { + Rectangle r = ApplyCellPadding(cellBounds); + r = this.AlignRectangle(r, new Rectangle(Point.Empty, preferredSize)); + return r; + } + + #endregion + + #region Drawing routines + + /// + /// Draw the given image aligned horizontally within the column. + /// + /// + /// Over tall images are scaled to fit. Over-wide images are + /// truncated. This is by design! + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The image to be drawn + protected virtual void DrawAlignedImage(Graphics g, Rectangle r, Image image) { + if (image == null) + return; + + // By default, the image goes in the top left of the rectangle + Rectangle imageBounds = new Rectangle(r.Location, image.Size); + + // If the image is too tall to be drawn in the space provided, proportionally scale it down. + // Too wide images are not scaled. + if (image.Height > r.Height) { + float scaleRatio = (float) r.Height / (float) image.Height; + imageBounds.Width = (int) ((float) image.Width * scaleRatio); + imageBounds.Height = r.Height - 1; + } + + // Align and draw our (possibly scaled) image + Rectangle alignRectangle = this.AlignRectangle(r, imageBounds); + if (this.ListItem.Enabled) + g.DrawImage(image, alignRectangle); + else + ControlPaint.DrawImageDisabled(g, image, alignRectangle.X, alignRectangle.Y, GetBackgroundColor()); + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Pre-padded bounds of the cell + protected virtual void DrawAlignedImageAndText(Graphics g, Rectangle r) { + this.DrawImageAndText(g, this.CalculateAlignedRectangle(g, r)); + } + + /// + /// Fill in the background of this cell + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawBackground(Graphics g, Rectangle r) { + if (!this.IsDrawBackground) + return; + + Color backgroundColor = this.GetBackgroundColor(); + + using (Brush brush = new SolidBrush(backgroundColor)) { + g.FillRectangle(brush, r.X - 1, r.Y - 1, r.Width + 2, r.Height + 2); + } + } + + /// + /// Draw the primary check box of this row (checkboxes in other sub items use a different method) + /// + /// Graphics context to use for drawing + /// The pre-aligned and padded target rectangle + protected virtual int DrawCheckBox(Graphics g, Rectangle r) { + // The odd constants are to match checkbox placement in native mode (on XP at least) + // TODO: Unify this with CheckStateRenderer + + // The rectangle r is already horizontally aligned. We still need to align it vertically. + Size checkBoxSize = this.CalculateCheckBoxSize(g); + Point checkBoxLocation = new Point(r.X, this.AlignVertically(r, checkBoxSize.Height)); + + if (this.IsPrinting || this.UseCustomCheckboxImages) { + int imageIndex = this.ListItem.StateImageIndex; + if (this.ListView.StateImageList == null || imageIndex < 0 || imageIndex >= this.ListView.StateImageList.Images.Count) + return 0; + + return this.DrawImage(g, new Rectangle(checkBoxLocation, checkBoxSize), this.ListView.StateImageList.Images[imageIndex]) + 4; + } + + CheckBoxState boxState = this.GetCheckBoxState(this.ListItem.CheckState); + CheckBoxRenderer.DrawCheckBox(g, checkBoxLocation, boxState); + return checkBoxSize.Width; + } + + /// + /// Calculate the CheckBoxState we need to correctly draw the given state + /// + /// + /// + protected virtual CheckBoxState GetCheckBoxState(CheckState checkState) { + + // Should the checkbox be drawn as disabled? + if (this.IsCheckBoxDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the cursor currently over this checkbox? + if (this.IsCheckboxHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + + } + + /// + /// Should this checkbox be drawn as disabled? + /// + protected virtual bool IsCheckBoxDisabled { + get { + if (this.ListItem != null && !this.ListItem.Enabled) + return true; + + if (!this.ListView.RenderNonEditableCheckboxesAsDisabled) + return false; + + return (this.ListView.CellEditActivation == ObjectListView.CellEditActivateMode.None || + (this.Column != null && !this.Column.IsEditable)); + } + } + + /// + /// Is the current item hot (i.e. under the mouse)? + /// + protected bool IsCellHot { + get { + return this.ListView != null && + this.ListView.HotRowIndex == this.ListItem.Index && + this.ListView.HotColumnIndex == (this.Column == null ? 0 : this.Column.Index); + } + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsCheckboxHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.CheckBox; + } + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The optional image to be drawn + protected virtual int DrawImage(Graphics g, Rectangle r, Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return 0; + + // Draw from the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) { + + // Try to translate our imageSelector into a valid ImageList index + int selectorAsInt = -1; + if (imageSelector is Int32) { + selectorAsInt = (Int32) imageSelector; + if (selectorAsInt >= il.Images.Count) + selectorAsInt = -1; + } else { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + + // If we found a valid index into the ImageList, draw it. + // We want to draw using the native DrawImageList calls, since that let's us do some nice effects + // But the native call does not work on PrinterDCs, so if we're printing we have to skip this bit. + if (selectorAsInt >= 0) { + if (!this.IsPrinting) { + if (il.ImageSize.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, il.ImageSize)); + + // If we are not printing, it's probable that the given Graphics object is double buffered using a BufferedGraphics object. + // But the ImageList.Draw method doesn't honor the Translation matrix that's probably in effect on the buffered + // graphics. So we have to calculate our drawing rectangle, relative to the cells natural boundaries. + // This effectively simulates the Translation matrix. + + Rectangle r2 = new Rectangle(r.X - this.Bounds.X, r.Y - this.Bounds.Y, r.Width, r.Height); + NativeMethods.DrawImageList(g, il, selectorAsInt, r2.X, r2.Y, this.IsItemSelected, !this.ListItem.Enabled); + return il.ImageSize.Width; + } + + // For some reason, printing from an image list doesn't work onto a printer context + // So get the image from the list and FALL THROUGH to the "print an image" case + imageSelector = il.Images[selectorAsInt]; + } + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image == null) + return 0; // no, give up + + if (image.Size.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, image.Size)); + + if (this.ListItem.Enabled) + g.DrawImageUnscaled(image, r.X, r.Y); + else + ControlPaint.DrawImageDisabled(g, image, r.X, r.Y, GetBackgroundColor()); + + return image.Width; + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawImageAndText(Graphics g, Rectangle r) { + int offset = 0; + if (this.ListView.CheckBoxes && this.ColumnIsPrimary) { + offset = this.DrawCheckBox(g, r) + 6; + r.X += offset; + r.Width -= offset; + } + + offset = this.DrawImage(g, r, this.GetImageSelector()); + r.X += offset; + r.Width -= offset; + + this.DrawText(g, r, this.GetText()); + } + + /// + /// Draw the given collection of image selectors + /// + /// + /// + /// + protected virtual int DrawImages(Graphics g, Rectangle r, ICollection imageSelectors) { + // Collect the non-null images + List images = new List(); + foreach (Object selector in imageSelectors) { + Image image = this.GetImage(selector); + if (image != null) + images.Add(image); + } + + // Figure out how much space they will occupy + int width = 0; + int height = 0; + foreach (Image image in images) { + width += (image.Width + this.Spacing); + height = Math.Max(height, image.Height); + } + + // Align the collection of images within the cell + Rectangle r2 = this.AlignRectangle(r, new Rectangle(0, 0, width, height)); + + // Finally, draw all the images in their correct location + Color backgroundColor = GetBackgroundColor(); + Point pt = r2.Location; + foreach (Image image in images) { + if (this.ListItem.Enabled) + g.DrawImage(image, pt); + else + ControlPaint.DrawImageDisabled(g, image, pt.X, pt.Y, backgroundColor); + pt.X += (image.Width + this.Spacing); + } + + // Return the width that the images occupy + return width; + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The string to be drawn + public virtual void DrawText(Graphics g, Rectangle r, String txt) { + if (String.IsNullOrEmpty(txt)) + return; + + if (this.UseGdiTextRendering) + this.DrawTextGdi(g, r, txt); + else + this.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Print the given text in the given rectangle using only GDI routines + /// + /// + /// + /// + /// + /// The native list control uses GDI routines to do its drawing, so using them + /// here makes the owner drawn mode looks more natural. + /// This method doesn't honour the CanWrap setting on the renderer. All + /// text is single line + /// + protected virtual void DrawTextGdi(Graphics g, Rectangle r, String txt) { + Color backColor = Color.Transparent; + if (this.IsDrawBackground && this.IsItemSelected && ColumnIsPrimary && !this.ListView.FullRowSelect) + backColor = this.GetSelectedBackgroundColor(); + + TextFormatFlags flags = NormalTextFormatFlags | this.CellVerticalAlignmentAsTextFormatFlag; + + // I think there is a bug in the TextRenderer. Setting or not setting SingleLine doesn't make + // any difference -- it is always single line. + if (!this.CanWrapOrDefault) + flags |= TextFormatFlags.SingleLine; + TextRenderer.DrawText(g, txt, this.Font, r, this.GetForegroundColor(), backColor, flags); + } + + private bool ColumnIsPrimary { + get { return this.Column != null && this.Column.Index == 0; } + } + + /// + /// Gets the cell's vertical alignment as a TextFormatFlag + /// + /// + protected TextFormatFlags CellVerticalAlignmentAsTextFormatFlag { + get { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return TextFormatFlags.Top; + case StringAlignment.Center: + return TextFormatFlags.VerticalCenter; + case StringAlignment.Far: + return TextFormatFlags.Bottom; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + /// + /// Gets the StringFormat needed when drawing text using GDI+ + /// + protected virtual StringFormat StringFormatForGdiPlus { + get { + StringFormat fmt = new StringFormat(); + fmt.LineAlignment = this.EffectiveCellVerticalAlignment; + fmt.Trimming = StringTrimming.EllipsisCharacter; + fmt.Alignment = this.Column == null ? StringAlignment.Near : this.Column.TextStringAlign; + if (!this.CanWrapOrDefault) + fmt.FormatFlags = StringFormatFlags.NoWrap; + return fmt; + } + } + + /// + /// Print the given text in the given rectangle using normal GDI+ .NET methods + /// + /// Printing to a printer dc has to be done using this method. + protected virtual void DrawTextGdiPlus(Graphics g, Rectangle r, String txt) { + using (StringFormat fmt = this.StringFormatForGdiPlus) { + // Draw the background of the text as selected, if it's the primary column + // and it's selected and it's not in FullRowSelect mode. + Font f = this.Font; + if (this.IsDrawBackground && this.IsItemSelected && this.ColumnIsPrimary && !this.ListView.FullRowSelect) { + SizeF size = g.MeasureString(txt, f, r.Width, fmt); + Rectangle r2 = r; + r2.Width = (int) size.Width + 1; + using (Brush brush = new SolidBrush(this.GetSelectedBackgroundColor())) { + g.FillRectangle(brush, r2); + } + } + RectangleF rf = r; + g.DrawString(txt, f, this.TextBrush, rf, fmt); + } + + // We should put a focus rectangle around the column 0 text if it's selected -- + // but we don't because: + // - I really dislike this UI convention + // - we are using buffered graphics, so the DrawFocusRecatangle method of the event doesn't work + + //if (this.ColumnIsPrimary) { + // Size size = TextRenderer.MeasureText(this.SubItem.Text, this.ListView.ListFont); + // if (r.Width > size.Width) + // r.Width = size.Width; + // this.Event.DrawFocusRectangle(r); + //} + } + + #endregion + } + + /// + /// This renderer highlights substrings that match a given text filter. + /// + /// + /// Implementation note: + /// This renderer uses the functionality of BaseRenderer to draw the text, and + /// then draws a translucent frame over the top of the already rendered text glyphs. + /// There's no way to draw the matching text in a different font or color in this + /// implementation. + /// + public class HighlightTextRenderer : BaseRenderer, IFilterAwareRenderer { + #region Life and death + + /// + /// Create a HighlightTextRenderer + /// + public HighlightTextRenderer() { + this.FramePen = Pens.DarkGreen; + this.FillBrush = Brushes.Yellow; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + public HighlightTextRenderer(ITextMatchFilter filter) + : this() { + this.Filter = filter; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + [Obsolete("Use HighlightTextRenderer(TextMatchFilter) instead", true)] + public HighlightTextRenderer(string text) {} + + #endregion + + #region Configuration properties + + /// + /// Gets or set how rounded will be the corners of the text match frame + /// + [Category("Appearance"), + DefaultValue(3.0f), + Description("How rounded will be the corners of the text match frame?")] + public float CornerRoundness { + get { return cornerRoundness; } + set { cornerRoundness = value; } + } + + private float cornerRoundness = 3.0f; + + /// + /// Gets or set the brush will be used to paint behind the matched substrings. + /// Set this to null to not fill the frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush FillBrush { + get { return fillBrush; } + set { fillBrush = value; } + } + + private Brush fillBrush; + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter { + get { return filter; } + set { filter = value; } + } + private ITextMatchFilter filter; + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter + { + get { return filter; } + set { RegisterNewFilter(value); } + } + + internal void RegisterNewFilter(IModelFilter newFilter) { + TextMatchFilter textFilter = newFilter as TextMatchFilter; + if (textFilter != null) + { + Filter = textFilter; + return; + } + CompositeFilter composite = newFilter as CompositeFilter; + if (composite != null) + { + foreach (TextMatchFilter textSubFilter in composite.TextFilters) + { + Filter = textSubFilter; + return; + } + } + Filter = null; + } + + /// + /// Gets or set the pen will be used to frame the matched substrings. + /// Set this to null to not draw a frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen FramePen { + get { return framePen; } + set { framePen = value; } + } + + private Pen framePen; + + /// + /// Gets or sets whether the frame around a text match will have rounded corners + /// + [Category("Appearance"), + DefaultValue(true), + Description("Will the frame around a text match will have rounded corners?")] + public bool UseRoundedRectangle { + get { return useRoundedRectangle; } + set { useRoundedRectangle = value; } + } + + private bool useRoundedRectangle = true; + + #endregion + + #region Compatibility properties + + /// + /// Gets or set the text that will be highlighted + /// + [Obsolete("Set the Filter directly rather than just the text", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string TextToHighlight { + get { return String.Empty; } + set { } + } + + /// + /// Gets or sets the manner in which substring will be compared. + /// + /// + /// Use this to control if substring matches are case sensitive or insensitive. + [Obsolete("Set the Filter directly rather than just this setting", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public StringComparison StringComparison { + get { return StringComparison.CurrentCultureIgnoreCase; } + set { } + } + + #endregion + + #region IRenderer interface overrides + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + + #endregion + + #region Rendering + + // This class has two implement two highlighting schemes: one for GDI, another for GDI+. + // Naturally, GDI+ makes the task easier, but we have to provide something for GDI + // since that it is what is normally used. + + /// + /// Draw text using GDI + /// + /// + /// + /// + protected override void DrawTextGdi(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiTextHighlighting(g, r, txt); + + base.DrawTextGdi(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI + /// + /// + /// + /// + protected virtual void DrawGdiTextHighlighting(Graphics g, Rectangle r, string txt) { + + // TextRenderer puts horizontal padding around the strings, so we need to take + // that into account when measuring strings + const int paddingAdjustment = 6; + + // Cache the font + Font f = this.Font; + + foreach (CharacterRange range in this.Filter.FindAllMatchedRanges(txt)) { + // Measure the text that comes before our substring + Size precedingTextSize = Size.Empty; + if (range.First > 0) { + string precedingText = txt.Substring(0, range.First); + precedingTextSize = TextRenderer.MeasureText(g, precedingText, f, r.Size, NormalTextFormatFlags); + precedingTextSize.Width -= paddingAdjustment; + } + + // Measure the length of our substring (may be different each time due to case differences) + string highlightText = txt.Substring(range.First, range.Length); + Size textToHighlightSize = TextRenderer.MeasureText(g, highlightText, f, r.Size, NormalTextFormatFlags); + textToHighlightSize.Width -= paddingAdjustment; + + float textToHighlightLeft = r.X + precedingTextSize.Width + 1; + float textToHighlightTop = this.AlignVertically(r, textToHighlightSize.Height); + + // Draw a filled frame around our substring + this.DrawSubstringFrame(g, textToHighlightLeft, textToHighlightTop, textToHighlightSize.Width, textToHighlightSize.Height); + } + } + + /// + /// Draw an indication around the given frame that shows a text match + /// + /// + /// + /// + /// + /// + protected virtual void DrawSubstringFrame(Graphics g, float x, float y, float width, float height) { + if (this.UseRoundedRectangle) { + using (GraphicsPath path = this.GetRoundedRect(x, y, width, height, 3.0f)) { + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.FramePen != null) + g.DrawPath(this.FramePen, path); + } + } else { + if (this.FillBrush != null) + g.FillRectangle(this.FillBrush, x, y, width, height); + if (this.FramePen != null) + g.DrawRectangle(this.FramePen, x, y, width, height); + } + } + + /// + /// Draw the text using GDI+ + /// + /// + /// + /// + protected override void DrawTextGdiPlus(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiPlusTextHighlighting(g, r, txt); + + base.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI+ + /// + /// + /// + /// + protected virtual void DrawGdiPlusTextHighlighting(Graphics g, Rectangle r, string txt) { + // Find the substrings we want to highlight + List ranges = new List(this.Filter.FindAllMatchedRanges(txt)); + + if (ranges.Count == 0) + return; + + using (StringFormat fmt = this.StringFormatForGdiPlus) { + RectangleF rf = r; + fmt.SetMeasurableCharacterRanges(ranges.ToArray()); + Region[] stringRegions = g.MeasureCharacterRanges(txt, this.Font, rf, fmt); + + foreach (Region region in stringRegions) { + RectangleF bounds = region.GetBounds(g); + this.DrawSubstringFrame(g, bounds.X - 1, bounds.Y - 1, bounds.Width + 2, bounds.Height); + } + } + } + + #endregion + + #region Utilities + + /// + /// Gets whether the renderer should actually draw highlighting + /// + protected bool ShouldDrawHighlighting { + get { return this.Column == null || (this.Column.Searchable && this.Filter != null); } + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + /// + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(float x, float y, float width, float height, float diameter) { + return GetRoundedRect(new RectangleF(x, y, width, height), diameter); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + } + + /// + /// This class maps a data value to an image that should be drawn for that value. + /// + /// It is useful for drawing data that is represented as an enum or boolean. + public class MappedImageRenderer : BaseRenderer { + /// + /// Return a renderer that draw boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// A Renderer + public static MappedImageRenderer Boolean(Object trueImage, Object falseImage) { + return new MappedImageRenderer(true, trueImage, false, falseImage); + } + + /// + /// Return a renderer that draw tristate boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// Draw this when our data value is null + /// A Renderer + public static MappedImageRenderer TriState(Object trueImage, Object falseImage, Object nullImage) { + return new MappedImageRenderer(new Object[] {true, trueImage, false, falseImage, null, nullImage}); + } + + /// + /// Make a new empty renderer + /// + public MappedImageRenderer() { + map = new System.Collections.Hashtable(); + } + + /// + /// Make a new renderer that will show the given image when the given key is the aspect value + /// + /// The data value to be matched + /// The image to be shown when the key is matched + public MappedImageRenderer(Object key, Object image) + : this() { + this.Add(key, image); + } + + /// + /// Make a new renderer that will show the given images when it receives the given keys + /// + /// + /// + /// + /// + public MappedImageRenderer(Object key1, Object image1, Object key2, Object image2) + : this() { + this.Add(key1, image1); + this.Add(key2, image2); + } + + /// + /// Build a renderer from the given array of keys and their matching images + /// + /// An array of key/image pairs + public MappedImageRenderer(Object[] keysAndImages) + : this() { + if ((keysAndImages.GetLength(0) % 2) != 0) + throw new ArgumentException("Array must have key/image pairs"); + + for (int i = 0; i < keysAndImages.GetLength(0); i += 2) + this.Add(keysAndImages[i], keysAndImages[i + 1]); + } + + /// + /// Register the image that should be drawn when our Aspect has the data value. + /// + /// Value that the Aspect must match + /// An ImageSelector -- an int, string or image + public void Add(Object value, Object image) { + if (value == null) + this.nullImage = image; + else + map[value] = image; + } + + /// + /// Render our value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + ICollection aspectAsCollection = this.Aspect as ICollection; + if (aspectAsCollection == null) + this.RenderOne(g, r, this.Aspect); + else + this.RenderCollection(g, r, aspectAsCollection); + } + + /// + /// Draw a collection of images + /// + /// + /// + /// + protected void RenderCollection(Graphics g, Rectangle r, ICollection imageSelectors) { + ArrayList images = new ArrayList(); + Image image = null; + foreach (Object selector in imageSelectors) { + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + else + image = null; + + if (image != null) + images.Add(image); + } + + this.DrawImages(g, r, images); + } + + /// + /// Draw one image + /// + /// + /// + /// + protected void RenderOne(Graphics g, Rectangle r, Object selector) { + Image image = null; + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + + if (image != null) + this.DrawAlignedImage(g, r, image); + } + + #region Private variables + + private Hashtable map; // Track the association between values and images + private Object nullImage; // image to be drawn for null values (since null can't be a key) + + #endregion + } + + /// + /// This renderer draws just a checkbox to match the check state of our model object. + /// + public class CheckStateRenderer : BaseRenderer { + /// + /// Draw our cell + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + if (this.Column == null) + return; + r = this.ApplyCellPadding(r); + CheckState state = this.Column.GetCheckState(this.RowObject); + if (this.IsPrinting) { + // Renderers don't work onto printer DCs, so we have to draw the image ourselves + string key = ObjectListView.CHECKED_KEY; + if (state == CheckState.Unchecked) + key = ObjectListView.UNCHECKED_KEY; + if (state == CheckState.Indeterminate) + key = ObjectListView.INDETERMINATE_KEY; + this.DrawAlignedImage(g, r, this.ImageListOrDefault.Images[key]); + } else { + r = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, r.Location, this.GetCheckBoxState(state)); + } + } + + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateCheckBoxBounds(g, this.Bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.CheckBox; + } + } + + /// + /// Render an image that comes from our data source. + /// + /// The image can be sourced from: + /// + /// a byte-array (normally when the image to be shown is + /// stored as a value in a database) + /// an int, which is treated as an index into the image list + /// a string, which is treated first as a file name, and failing that as an index into the image list + /// an ICollection of ints or strings, which will be drawn as consecutive images + /// + /// If an image is an animated GIF, it's state is stored in the SubItem object. + /// By default, the image renderer does not render animations (it begins life with animations paused). + /// To enable animations, you must call Unpause(). + /// In the current implementation (2009-09), each column showing animated gifs must have a + /// different instance of ImageRenderer assigned to it. You cannot share the same instance of + /// an image renderer between two animated gif columns. If you do, only the last column will be + /// animated. + /// + public class ImageRenderer : BaseRenderer { + /// + /// Make an empty image renderer + /// + public ImageRenderer() { + this.stopwatch = new Stopwatch(); + } + + /// + /// Make an empty image renderer that begins life ready for animations + /// + public ImageRenderer(bool startAnimations) + : this() { + this.Paused = !startAnimations; + } + + /// + /// Finalizer + /// + protected override void Dispose(bool disposing) { + Paused = true; + base.Dispose(disposing); + } + + #region Properties + + /// + /// Should the animations in this renderer be paused? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool Paused { + get { return isPaused; } + set { + if (this.isPaused == value) + return; + + this.isPaused = value; + if (this.isPaused) { + this.StopTickler(); + this.stopwatch.Stop(); + } else { + this.Tickler.Change(1, Timeout.Infinite); + this.stopwatch.Start(); + } + } + } + + private bool isPaused = true; + + private void StopTickler() { + if (this.tickler == null) + return; + + this.tickler.Dispose(); + this.tickler = null; + } + + /// + /// Gets a timer that can be used to trigger redraws on animations + /// + protected Timer Tickler { + get { + if (this.tickler == null) + this.tickler = new System.Threading.Timer(new TimerCallback(this.OnTimer), null, Timeout.Infinite, Timeout.Infinite); + return this.tickler; + } + } + + #endregion + + #region Commands + + /// + /// Pause any animations + /// + public void Pause() { + this.Paused = true; + } + + /// + /// Unpause any animations + /// + public void Unpause() { + this.Paused = false; + } + + #endregion + + #region Drawing + + /// + /// Draw our image + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + if (this.Aspect == null || this.Aspect == System.DBNull.Value) + return; + r = this.ApplyCellPadding(r); + + if (this.Aspect is System.Byte[]) { + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + } else { + ICollection imageSelectors = this.Aspect as ICollection; + if (imageSelectors == null) + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + else + this.DrawImages(g, r, imageSelectors); + } + } + + /// + /// Translate our Aspect into an image. + /// + /// The strategy is: + /// If its a byte array, we treat it as an in-memory image + /// If it's an int, we use that as an index into our image list + /// If it's a string, we try to load a file by that name. If we can't, + /// we use the string as an index into our image list. + /// + /// An image + protected Image GetImageFromAspect() { + // If we've already figured out the image, don't do it again + if (this.OLVSubItem != null && this.OLVSubItem.ImageSelector is Image) { + if (this.OLVSubItem.AnimationState == null) + return (Image) this.OLVSubItem.ImageSelector; + else + return this.OLVSubItem.AnimationState.image; + } + + // Try to convert our Aspect into an Image + // If its a byte array, we treat it as an in-memory image + // If it's an int, we use that as an index into our image list + // If it's a string, we try to find a file by that name. + // If we can't, we use the string as an index into our image list. + Image image = this.Aspect as Image; + if (image != null) { + // Don't do anything else + } else if (this.Aspect is System.Byte[]) { + using (MemoryStream stream = new MemoryStream((System.Byte[]) this.Aspect)) { + try { + image = Image.FromStream(stream); + } + catch (ArgumentException) { + // ignore + } + } + } else if (this.Aspect is Int32) { + image = this.GetImage(this.Aspect); + } else { + String str = this.Aspect as String; + if (!String.IsNullOrEmpty(str)) { + try { + image = Image.FromFile(str); + } + catch (FileNotFoundException) { + image = this.GetImage(this.Aspect); + } + catch (OutOfMemoryException) { + image = this.GetImage(this.Aspect); + } + } + } + + // If this image is an animation, initialize the animation process + if (this.OLVSubItem != null && AnimationState.IsAnimation(image)) { + this.OLVSubItem.AnimationState = new AnimationState(image); + } + + // Cache the image so we don't repeat this dreary process + if (this.OLVSubItem != null) + this.OLVSubItem.ImageSelector = image; + + return image; + } + + #endregion + + #region Events + + /// + /// This is the method that is invoked by the timer. It basically switches control to the listview thread. + /// + /// not used + public void OnTimer(Object state) { + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + if (this.ListView.InvokeRequired) + this.ListView.Invoke((MethodInvoker) delegate { this.OnTimer(state); }); + else + this.OnTimerInThread(); + } + + private bool IsListViewDead { + get { + // Apply a whole heap of sanity checks, which basically ensure that the ListView is still alive + return this.ListView == null || + this.ListView.Disposing || + this.ListView.IsDisposed || + !this.ListView.IsHandleCreated; + } + } + + /// + /// This is the OnTimer callback, but invoked in the same thread as the creator of the ListView. + /// This method can use all of ListViews methods without creating a CrossThread exception. + /// + protected void OnTimerInThread() { + // MAINTAINER NOTE: This method must renew the tickler. If it doesn't the animations will stop. + + // If this listview has been destroyed, we can't do anything, so we return without + // renewing the tickler, effectively killing all animations on this renderer + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + // If we're not in Detail view or our column has been removed from the list, + // we can't do anything at the moment, but we still renew the tickler because the view may change later. + if (this.ListView.View != System.Windows.Forms.View.Details || this.Column == null || this.Column.Index < 0) { + this.Tickler.Change(1000, Timeout.Infinite); + return; + } + + long elapsedMilliseconds = this.stopwatch.ElapsedMilliseconds; + int subItemIndex = this.Column.Index; + long nextCheckAt = elapsedMilliseconds + 1000; // wait at most one second before checking again + Rectangle updateRect = new Rectangle(); // what part of the view must be updated to draw the changed gifs? + + // Run through all the subitems in the view for our column, and for each one that + // has an animation attached to it, see if the frame needs updating. + + for (int i = 0; i < this.ListView.GetItemCount(); i++) { + OLVListItem lvi = this.ListView.GetItem(i); + + // Get the animation state from the subitem. If there isn't an animation state, skip this row. + OLVListSubItem lvsi = lvi.GetSubItem(subItemIndex); + AnimationState state = lvsi.AnimationState; + if (state == null || !state.IsValid) + continue; + + // Has this frame of the animation expired? + if (elapsedMilliseconds >= state.currentFrameExpiresAt) { + state.AdvanceFrame(elapsedMilliseconds); + + // Track the area of the view that needs to be redrawn to show the changed images + if (updateRect.IsEmpty) + updateRect = lvsi.Bounds; + else + updateRect = Rectangle.Union(updateRect, lvsi.Bounds); + } + + // Remember the minimum time at which a frame is next due to change + nextCheckAt = Math.Min(nextCheckAt, state.currentFrameExpiresAt); + } + + // Update the part of the listview where frames have changed + if (!updateRect.IsEmpty) + this.ListView.Invalidate(updateRect); + + // Renew the tickler in time for the next frame change + this.Tickler.Change(nextCheckAt - elapsedMilliseconds, Timeout.Infinite); + } + + #endregion + + /// + /// Instances of this class kept track of the animation state of a single image. + /// + internal class AnimationState { + private const int PropertyTagTypeShort = 3; + private const int PropertyTagTypeLong = 4; + private const int PropertyTagFrameDelay = 0x5100; + private const int PropertyTagLoopCount = 0x5101; + + /// + /// Is the given image an animation + /// + /// The image to be tested + /// Is the image an animation? + public static bool IsAnimation(Image image) { + if (image == null) + return false; + else + return (new List(image.FrameDimensionsList)).Contains(FrameDimension.Time.Guid); + } + + /// + /// Create an AnimationState in a quiet state + /// + public AnimationState() { + this.imageDuration = new List(); + } + + /// + /// Create an animation state for the given image, which may or may not + /// be an animation + /// + /// The image to be rendered + public AnimationState(Image image) + : this() { + if (!AnimationState.IsAnimation(image)) + return; + + // How many frames in the animation? + this.image = image; + this.frameCount = this.image.GetFrameCount(FrameDimension.Time); + + // Find the delay between each frame. + // The delays are stored an array of 4-byte ints. Each int is the + // number of 1/100th of a second that should elapsed before the frame expires + foreach (PropertyItem pi in this.image.PropertyItems) { + if (pi.Id == PropertyTagFrameDelay) { + for (int i = 0; i < pi.Len; i += 4) { + //TODO: There must be a better way to convert 4-bytes to an int + int delay = (pi.Value[i + 3] << 24) + (pi.Value[i + 2] << 16) + (pi.Value[i + 1] << 8) + pi.Value[i]; + this.imageDuration.Add(delay * 10); // store delays as milliseconds + } + break; + } + } + + // There should be as many frame durations as frames + Debug.Assert(this.imageDuration.Count == this.frameCount, "There should be as many frame durations as there are frames."); + } + + /// + /// Does this state represent a valid animation + /// + public bool IsValid { + get { return (this.image != null && this.frameCount > 0); } + } + + /// + /// Advance our images current frame and calculate when it will expire + /// + public void AdvanceFrame(long millisecondsNow) { + this.currentFrame = (this.currentFrame + 1) % this.frameCount; + this.currentFrameExpiresAt = millisecondsNow + this.imageDuration[this.currentFrame]; + this.image.SelectActiveFrame(FrameDimension.Time, this.currentFrame); + } + + internal int currentFrame; + internal long currentFrameExpiresAt; + internal Image image; + internal List imageDuration; + internal int frameCount; + } + + #region Private variables + + private System.Threading.Timer tickler; // timer used to tickle the animations + private Stopwatch stopwatch; // clock used to time the animation frame changes + + #endregion + } + + /// + /// Render our Aspect as a progress bar + /// + public class BarRenderer : BaseRenderer { + #region Constructors + + /// + /// Make a BarRenderer + /// + public BarRenderer() + : base() {} + + /// + /// Make a BarRenderer for the given range of data values + /// + public BarRenderer(int minimum, int maximum) + : this() { + this.MinimumValue = minimum; + this.MaximumValue = maximum; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(Pen pen, Brush brush) + : this() { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(int minimum, int maximum, Pen pen, Brush brush) + : this(minimum, maximum) { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(Pen pen, Color start, Color end) + : this() { + this.Pen = pen; + this.SetGradient(start, end); + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(int minimum, int maximum, Pen pen, Color start, Color end) + : this(minimum, maximum) { + this.Pen = pen; + this.SetGradient(start, end); + } + + #endregion + + #region Configuration Properties + + /// + /// Should this bar be drawn in the system style? + /// + [Category("ObjectListView"), + Description("Should this bar be drawn in the system style?"), + DefaultValue(true)] + public bool UseStandardBar { + get { return useStandardBar; } + set { useStandardBar = value; } + } + + private bool useStandardBar = true; + + /// + /// How many pixels in from our cell border will this bar be drawn + /// + [Category("ObjectListView"), + Description("How many pixels in from our cell border will this bar be drawn"), + DefaultValue(2)] + public int Padding { + get { return padding; } + set { padding = value; } + } + + private int padding = 2; + + /// + /// What color will be used to fill the interior of the control before the + /// progress bar is drawn? + /// + [Category("ObjectListView"), + Description("The color of the interior of the bar"), + DefaultValue(typeof (Color), "AliceBlue")] + public Color BackgroundColor { + get { return backgroundColor; } + set { backgroundColor = value; } + } + + private Color backgroundColor = Color.AliceBlue; + + /// + /// What color should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("What color should the frame of the progress bar be"), + DefaultValue(typeof (Color), "Black")] + public Color FrameColor { + get { return frameColor; } + set { frameColor = value; } + } + + private Color frameColor = Color.Black; + + /// + /// How many pixels wide should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("How many pixels wide should the frame of the progress bar be"), + DefaultValue(1.0f)] + public float FrameWidth { + get { return frameWidth; } + set { frameWidth = value; } + } + + private float frameWidth = 1.0f; + + /// + /// What color should the 'filled in' part of the progress bar be? + /// + /// This is only used if GradientStartColor is Color.Empty + [Category("ObjectListView"), + Description("What color should the 'filled in' part of the progress bar be"), + DefaultValue(typeof (Color), "BlueViolet")] + public Color FillColor { + get { return fillColor; } + set { fillColor = value; } + } + + private Color fillColor = Color.BlueViolet; + + /// + /// Use a gradient to fill the progress bar starting with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar starting with this color"), + DefaultValue(typeof (Color), "CornflowerBlue")] + public Color GradientStartColor { + get { return startColor; } + set { startColor = value; } + } + + private Color startColor = Color.CornflowerBlue; + + /// + /// Use a gradient to fill the progress bar ending with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar ending with this color"), + DefaultValue(typeof (Color), "DarkBlue")] + public Color GradientEndColor { + get { return endColor; } + set { endColor = value; } + } + + private Color endColor = Color.DarkBlue; + + /// + /// Regardless of how wide the column become the progress bar will never be wider than this + /// + [Category("Behavior"), + Description("The progress bar will never be wider than this"), + DefaultValue(100)] + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + + private int maximumWidth = 100; + + /// + /// Regardless of how high the cell is the progress bar will never be taller than this + /// + [Category("Behavior"), + Description("The progress bar will never be taller than this"), + DefaultValue(16)] + public int MaximumHeight { + get { return maximumHeight; } + set { maximumHeight = value; } + } + + private int maximumHeight = 16; + + /// + /// The minimum data value expected. Values less than this will given an empty bar + /// + [Category("Behavior"), + Description("The minimum data value expected. Values less than this will given an empty bar"), + DefaultValue(0.0)] + public double MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private double minimumValue = 0.0; + + /// + /// The maximum value for the range. Values greater than this will give a full bar + /// + [Category("Behavior"), + Description("The maximum value for the range. Values greater than this will give a full bar"), + DefaultValue(100.0)] + public double MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private double maximumValue = 100.0; + + #endregion + + #region Public Properties (non-IDE) + + /// + /// The Pen that will draw the frame surrounding this bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen Pen { + get { + if (this.pen == null && !this.FrameColor.IsEmpty) + return new Pen(this.FrameColor, this.FrameWidth); + else + return this.pen; + } + set { this.pen = value; } + } + + private Pen pen; + + /// + /// The brush that will be used to fill the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush Brush { + get { + if (this.brush == null && !this.FillColor.IsEmpty) + return new SolidBrush(this.FillColor); + else + return this.brush; + } + set { this.brush = value; } + } + + private Brush brush; + + /// + /// The brush that will be used to fill the background of the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush BackgroundBrush { + get { + if (this.backgroundBrush == null && !this.BackgroundColor.IsEmpty) + return new SolidBrush(this.BackgroundColor); + else + return this.backgroundBrush; + } + set { this.backgroundBrush = value; } + } + + private Brush backgroundBrush; + + #endregion + + /// + /// Draw this progress bar using a gradient + /// + /// + /// + public void SetGradient(Color start, Color end) { + this.GradientStartColor = start; + this.GradientEndColor = end; + } + + /// + /// Draw our aspect + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + r = this.ApplyCellPadding(r); + + Rectangle frameRect = Rectangle.Inflate(r, 0 - this.Padding, 0 - this.Padding); + frameRect.Width = Math.Min(frameRect.Width, this.MaximumWidth); + frameRect.Height = Math.Min(frameRect.Height, this.MaximumHeight); + frameRect = this.AlignRectangle(r, frameRect); + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + Rectangle fillRect = Rectangle.Inflate(frameRect, -1, -1); + if (aspectValue <= this.MinimumValue) + fillRect.Width = 0; + else if (aspectValue < this.MaximumValue) + fillRect.Width = (int) (fillRect.Width * (aspectValue - this.MinimumValue) / this.MaximumValue); + + // MS-themed progress bars don't work when printing + if (this.UseStandardBar && ProgressBarRenderer.IsSupported && !this.IsPrinting) { + ProgressBarRenderer.DrawHorizontalBar(g, frameRect); + ProgressBarRenderer.DrawHorizontalChunks(g, fillRect); + } else { + g.FillRectangle(this.BackgroundBrush, frameRect); + if (fillRect.Width > 0) { + // FillRectangle fills inside the given rectangle, so expand it a little + fillRect.Width++; + fillRect.Height++; + if (this.GradientStartColor == Color.Empty) + g.FillRectangle(this.Brush, fillRect); + else { + using (LinearGradientBrush gradient = new LinearGradientBrush(frameRect, this.GradientStartColor, this.GradientEndColor, LinearGradientMode.Horizontal)) { + g.FillRectangle(gradient, fillRect); + } + } + } + g.DrawRectangle(this.Pen, frameRect); + } + } + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + } + + + /// + /// An ImagesRenderer draws zero or more images depending on the data returned by its Aspect. + /// + /// This renderer's Aspect must return a ICollection of ints, strings or Images, + /// each of which will be drawn horizontally one after the other. + /// As of v2.1, this functionality has been absorbed into ImageRenderer and this is now an + /// empty shell, solely for backwards compatibility. + /// + [ToolboxItem(false)] + public class ImagesRenderer : ImageRenderer {} + + /// + /// A MultiImageRenderer draws the same image a number of times based on our data value + /// + /// The stars in the Rating column of iTunes is a good example of this type of renderer. + public class MultiImageRenderer : BaseRenderer { + /// + /// Make a quiet renderer + /// + public MultiImageRenderer() + : base() {} + + /// + /// Make an image renderer that will draw the indicated image, at most maxImages times. + /// + /// + /// + /// + /// + public MultiImageRenderer(Object imageSelector, int maxImages, int minValue, int maxValue) + : this() { + this.ImageSelector = imageSelector; + this.MaxNumberImages = maxImages; + this.MinimumValue = minValue; + this.MaximumValue = maxValue; + } + + #region Configuration Properties + + /// + /// The index of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(-1)] + public int ImageIndex { + get { + if (imageSelector is Int32) + return (Int32) imageSelector; + else + return -1; + } + set { imageSelector = value; } + } + + /// + /// The name of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(null)] + public string ImageName { + get { return imageSelector as String; } + set { imageSelector = value; } + } + + /// + /// The image selector that will give the image to be drawn + /// + /// Like all image selectors, this can be an int, string or Image + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + + private Object imageSelector; + + /// + /// What is the maximum number of images that this renderer should draw? + /// + [Category("Behavior"), + Description("The maximum number of images that this renderer should draw"), + DefaultValue(10)] + public int MaxNumberImages { + get { return maxNumberImages; } + set { maxNumberImages = value; } + } + + private int maxNumberImages = 10; + + /// + /// Values less than or equal to this will have 0 images drawn + /// + [Category("Behavior"), + Description("Values less than or equal to this will have 0 images drawn"), + DefaultValue(0)] + public int MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private int minimumValue = 0; + + /// + /// Values greater than or equal to this will have MaxNumberImages images drawn + /// + [Category("Behavior"), + Description("Values greater than or equal to this will have MaxNumberImages images drawn"), + DefaultValue(100)] + public int MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private int maximumValue = 100; + + #endregion + + /// + /// Draw our data value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + Image image = this.GetImage(this.ImageSelector); + if (image == null) + return; + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + // Calculate how many images we need to draw to represent our aspect value + int numberOfImages; + if (aspectValue <= this.MinimumValue) + numberOfImages = 0; + else if (aspectValue < this.MaximumValue) + numberOfImages = 1 + (int) (this.MaxNumberImages * (aspectValue - this.MinimumValue) / this.MaximumValue); + else + numberOfImages = this.MaxNumberImages; + + // If we need to shrink the image, what will its on-screen dimensions be? + int imageScaledWidth = image.Width; + int imageScaledHeight = image.Height; + if (r.Height < image.Height) { + imageScaledWidth = (int) ((float) image.Width * (float) r.Height / (float) image.Height); + imageScaledHeight = r.Height; + } + // Calculate where the images should be drawn + Rectangle imageBounds = r; + imageBounds.Width = (this.MaxNumberImages * (imageScaledWidth + this.Spacing)) - this.Spacing; + imageBounds.Height = imageScaledHeight; + imageBounds = this.AlignRectangle(r, imageBounds); + + // Finally, draw the images + Rectangle singleImageRect = new Rectangle(imageBounds.X, imageBounds.Y, imageScaledWidth, imageScaledHeight); + Color backgroundColor = GetBackgroundColor(); + for (int i = 0; i < numberOfImages; i++) { + if (this.ListItem.Enabled) { + this.DrawImage(g, singleImageRect, this.ImageSelector); + } else + ControlPaint.DrawImageDisabled(g, image, singleImageRect.X, singleImageRect.Y, backgroundColor); + singleImageRect.X += (imageScaledWidth + this.Spacing); + } + } + } + + + /// + /// A class to render a value that contains a bitwise-OR'ed collection of values. + /// + public class FlagRenderer : BaseRenderer { + /// + /// Register the given image to the given value + /// + /// When this flag is present... + /// ...draw this image + public void Add(Object key, Object imageSelector) { + Int32 k2 = ((IConvertible) key).ToInt32(NumberFormatInfo.InvariantInfo); + + this.imageMap[k2] = imageSelector; + this.keysInOrder.Remove(k2); + this.keysInOrder.Add(k2); + } + + /// + /// Draw the flags + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + r = this.ApplyCellPadding(r); + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + ArrayList images = new ArrayList(); + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) + images.Add(image); + } + } + if (images.Count > 0) + this.DrawImages(g, r, images); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + + Point pt = this.Bounds.Location; + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) { + Rectangle imageRect = new Rectangle(pt, image.Size); + if (imageRect.Contains(x, y)) { + hti.UserData = key; + return; + } + pt.X += (image.Width + this.Spacing); + } + } + } + } + + private List keysInOrder = new List(); + private Dictionary imageMap = new Dictionary(); + } + + /// + /// This renderer draws an image, a single line title, and then multi-line description + /// under the title. + /// + /// + /// This class works best with FullRowSelect = true. + /// It's not designed to work with cell editing -- it will work but will look odd. + /// + /// It's not RightToLeft friendly. + /// + /// + public class DescribedTaskRenderer : BaseRenderer, IFilterAwareRenderer + { + private readonly StringFormat noWrapStringFormat; + private readonly HighlightTextRenderer highlightTextRenderer = new HighlightTextRenderer(); + + /// + /// Create a DescribedTaskRenderer + /// + public DescribedTaskRenderer() { + this.noWrapStringFormat = new StringFormat(StringFormatFlags.NoWrap); + this.noWrapStringFormat.Trimming = StringTrimming.EllipsisCharacter; + this.noWrapStringFormat.Alignment = StringAlignment.Near; + this.noWrapStringFormat.LineAlignment = StringAlignment.Near; + this.highlightTextRenderer.CellVerticalAlignment = StringAlignment.Near; + } + + #region Configuration properties + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + public override bool UseGdiTextRendering + { + get { return base.UseGdiTextRendering; } + set + { + base.UseGdiTextRendering = value; + this.highlightTextRenderer.UseGdiTextRendering = value; + } + } + + /// + /// Gets or set the font that will be used to draw the title of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the title of the task"), + DefaultValue(null)] + public Font TitleFont { + get { return titleFont; } + set { titleFont = value; } + } + + private Font titleFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font TitleFontOrDefault { + get { return this.TitleFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the title of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the title"), + DefaultValue(typeof (Color), "")] + public Color TitleColor { + get { return titleColor; } + set { titleColor = value; } + } + + private Color titleColor; + + /// + /// Return the color of the title of the task or a reasonable default + /// + [Browsable(false)] + public Color TitleColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected || this.TitleColor.IsEmpty) + return this.GetForegroundColor(); + + return this.TitleColor; + } + } + + /// + /// Gets or set the font that will be used to draw the description of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the description of the task"), + DefaultValue(null)] + public Font DescriptionFont { + get { return descriptionFont; } + set { descriptionFont = value; } + } + + private Font descriptionFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font DescriptionFontOrDefault { + get { return this.DescriptionFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the description of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the description"), + DefaultValue(typeof (Color), "")] + public Color DescriptionColor { + get { return descriptionColor; } + set { descriptionColor = value; } + } + private Color descriptionColor = Color.Empty; + + /// + /// Return the color of the description of the task or a reasonable default + /// + [Browsable(false)] + public Color DescriptionColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection) + return this.GetForegroundColor(); + return this.DescriptionColor.IsEmpty ? defaultDescriptionColor : this.DescriptionColor; + } + } + private static Color defaultDescriptionColor = Color.FromArgb(45, 46, 49); + + /// + /// Gets or sets the number of pixels that will be left between the image and the text + /// + [Category("ObjectListView"), + Description("The number of pixels that will be left between the image and the text"), + DefaultValue(4)] + public int ImageTextSpace + { + get { return imageTextSpace; } + set { imageTextSpace = value; } + } + private int imageTextSpace = 4; + + /// + /// Gets or sets the number of pixels that will be left between the title and the description + /// + [Category("ObjectListView"), + Description("The number of pixels that that will be left between the title and the description"), + DefaultValue(2)] + public int TitleDescriptionSpace + { + get { return titleDescriptionSpace; } + set { titleDescriptionSpace = value; } + } + private int titleDescriptionSpace = 2; + + /// + /// Gets or sets the name of the aspect of the model object that contains the task description + /// + [Category("ObjectListView"), + Description("The name of the aspect of the model object that contains the task description"), + DefaultValue(null)] + public string DescriptionAspectName { + get { return descriptionAspectName; } + set { descriptionAspectName = value; } + } + private string descriptionAspectName; + + #endregion + + #region Text highlighting + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter + { + get { return this.highlightTextRenderer.Filter; } + set { this.highlightTextRenderer.Filter = value; } + } + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter { + get { return this.Filter; } + set { this.highlightTextRenderer.RegisterNewFilter(value); } + } + + #endregion + + #region Calculating + + /// + /// Fetch the description from the model class + /// + /// + /// + public virtual string GetDescription(object model) { + if (String.IsNullOrEmpty(this.DescriptionAspectName)) + return String.Empty; + + if (this.descriptionGetter == null) + this.descriptionGetter = new Munger(this.DescriptionAspectName); + + return this.descriptionGetter.GetValue(model) as string; + } + private Munger descriptionGetter; + + #endregion + + #region Rendering + + /// + /// + /// + /// + /// + /// + public override void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + base.ConfigureSubItem(e, cellBounds, model); + this.highlightTextRenderer.ConfigureSubItem(e, cellBounds, model); + } + + /// + /// Draw our item + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + this.DrawDescribedTask(g, r, this.GetText(), this.GetDescription(this.RowObject), this.GetImageSelector()); + } + + /// + /// Draw the task + /// + /// + /// + /// + /// + /// + protected virtual void DrawDescribedTask(Graphics g, Rectangle r, string title, string description, object imageSelector) { + + //Debug.WriteLine(String.Format("DrawDescribedTask({0}, {1}, {2}, {3})", r, title, description, imageSelector)); + + // Draw the image if one's been given + Rectangle textBounds = r; + if (imageSelector != null) { + int imageWidth = this.DrawImage(g, r, imageSelector); + int gapToText = imageWidth + this.ImageTextSpace; + textBounds.X += gapToText; + textBounds.Width -= gapToText; + } + + // Draw the title + if (!String.IsNullOrEmpty(title)) { + using (SolidBrush b = new SolidBrush(this.TitleColorOrDefault)) { + this.highlightTextRenderer.CanWrap = false; + this.highlightTextRenderer.Font = this.TitleFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, title); + } + + // How tall was the title? + SizeF size = g.MeasureString(title, this.TitleFontOrDefault, textBounds.Width, this.noWrapStringFormat); + int pixelsToDescription = this.TitleDescriptionSpace + (int)size.Height; + textBounds.Y += pixelsToDescription; + textBounds.Height -= pixelsToDescription; + } + + // Draw the description + if (!String.IsNullOrEmpty(description)) { + using (SolidBrush b = new SolidBrush(this.DescriptionColorOrDefault)) { + this.highlightTextRenderer.CanWrap = true; + this.highlightTextRenderer.Font = this.DescriptionFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, description); + } + } + + //g.DrawRectangle(Pens.OrangeRed, r); + } + + #endregion + + #region Hit Testing + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + if (this.Bounds.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Text; + } + + #endregion + } + + /// + /// This renderer draws a functioning button in its cell + /// + public class ColumnButtonRenderer : BaseRenderer { + + #region Properties + + /// + /// Gets or sets how each button will be sized + /// + [Category("ObjectListView"), + Description("How each button will be sized"), + DefaultValue(OLVColumn.ButtonSizingMode.TextBounds)] + public OLVColumn.ButtonSizingMode SizingMode + { + get { return this.sizingMode; } + set { this.sizingMode = value; } + } + private OLVColumn.ButtonSizingMode sizingMode = OLVColumn.ButtonSizingMode.TextBounds; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize + { + get { return this.buttonSize; } + set { this.buttonSize = value; } + } + private Size? buttonSize; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds")] + public Size? ButtonPadding + { + get { return this.buttonPadding; } + set { this.buttonPadding = value; } + } + private Size? buttonPadding = new Size(10, 10); + + private Size ButtonPaddingOrDefault { + get { return this.ButtonPadding ?? new Size(10, 10); } + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MaxButtonWidth + { + get { return this.maxButtonWidth; } + set { this.maxButtonWidth = value; } + } + private int maxButtonWidth = -1; + + /// + /// Gets or sets the minimum width that a button can occupy. + /// -1 means there is no minimum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The minimum width that a button can be when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MinButtonWidth { + get { return this.minButtonWidth; } + set { this.minButtonWidth = value; } + } + private int minButtonWidth = -1; + + #endregion + + #region Rendering + + /// + /// Calculate the size of the contents + /// + /// + /// + /// + protected override Size CalculateContentSize(Graphics g, Rectangle r) { + if (this.SizingMode == OLVColumn.ButtonSizingMode.CellBounds) + return r.Size; + + if (this.SizingMode == OLVColumn.ButtonSizingMode.FixedBounds) + return this.ButtonSize ?? r.Size; + + // Ok, SizingMode must be TextBounds. So figure out the size of the text + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width); + + // Allow for padding and max width + textSize.Height += this.ButtonPaddingOrDefault.Height * 2; + textSize.Width += this.ButtonPaddingOrDefault.Width * 2; + if (this.MaxButtonWidth != -1 && textSize.Width > this.MaxButtonWidth) + textSize.Width = this.MaxButtonWidth; + if (textSize.Width < this.MinButtonWidth) + textSize.Width = this.MinButtonWidth; + + return textSize; + } + + /// + /// Draw the button + /// + /// + /// + protected override void DrawImageAndText(Graphics g, Rectangle r) { + TextFormatFlags textFormatFlags = TextFormatFlags.HorizontalCenter | + TextFormatFlags.VerticalCenter | + TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPadding | + TextFormatFlags.SingleLine | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.ListView.RightToLeftLayout) + textFormatFlags |= TextFormatFlags.RightToLeft; + + string buttonText = GetText(); + if (!String.IsNullOrEmpty(buttonText)) + ButtonRenderer.DrawButton(g, r, buttonText, this.Font, textFormatFlags, false, CalculatePushButtonState()); + } + + /// + /// What part of the control is under the given point? + /// + /// + /// + /// + /// + /// + protected override void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle bounds, int x, int y) { + Rectangle r = ApplyCellPadding(bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Button; + } + + /// + /// What is the state of the button? + /// + /// + protected PushButtonState CalculatePushButtonState() { + if (!this.ListItem.Enabled && !this.Column.EnableButtonWhenItemIsDisabled) + return PushButtonState.Disabled; + + if (this.IsButtonHot) + return ObjectListView.IsLeftMouseDown ? PushButtonState.Pressed : PushButtonState.Hot; + + return PushButtonState.Normal; + } + + /// + /// Is the mouse over the button? + /// + protected bool IsButtonHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.Button; + } + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Styles.cs b/ObjectListView/Rendering/Styles.cs new file mode 100644 index 0000000..bc1daa2 --- /dev/null +++ b/ObjectListView/Rendering/Styles.cs @@ -0,0 +1,400 @@ +/* + * Styles - A style is a group of formatting attributes that can be applied to a row or a cell + * + * Author: Phillip Piper + * Date: 29/07/2009 23:09 + * + * Change log: + * v2.4 + * 2010-03-23 JPP - Added HeaderFormatStyle and support + * v2.3 + * 2009-08-15 JPP - Added Decoration and Overlay properties to HotItemStyle + * 2009-07-29 JPP - Initial version + * + * To do: + * - These should be more generally available. It should be possible to do something like this: + * this.olv.GetItem(i).Style = new ItemStyle(); + * this.olv.GetItem(i).GetSubItem(j).Style = new CellStyle(); + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// The common interface supported by all style objects + /// + public interface IItemStyle + { + /// + /// Gets or set the font that will be used by this style + /// + Font Font { get; set; } + + /// + /// Gets or set the font style + /// + FontStyle FontStyle { get; set; } + + /// + /// Gets or sets the ForeColor + /// + Color ForeColor { get; set; } + + /// + /// Gets or sets the BackColor + /// + Color BackColor { get; set; } + } + + /// + /// Basic implementation of IItemStyle + /// + public class SimpleItemStyle : System.ComponentModel.Component, IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font + { + get { return this.font; } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle + { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color ForeColor + { + get { return this.foreColor; } + set { this.foreColor = value; } + } + + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color BackColor + { + get { return this.backColor; } + set { this.backColor = value; } + } + + private Color backColor; + } + + + /// + /// Instances of this class specify how should "hot items" (non-selected + /// rows under the cursor) be rendered. + /// + public class HotItemStyle : SimpleItemStyle + { + /// + /// Gets or sets the overlay that should be drawn as part of the hot item + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IOverlay Overlay { + get { return this.overlay; } + set { this.overlay = value; } + } + private IOverlay overlay; + + /// + /// Gets or sets the decoration that should be drawn as part of the hot item + /// + /// A decoration is different from an overlay in that an decoration + /// scrolls with the listview contents, whilst an overlay does not. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDecoration Decoration { + get { return this.decoration; } + set { this.decoration = value; } + } + private IDecoration decoration; + } + + /// + /// This class defines how a cell should be formatted + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class CellStyle : IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + } + + /// + /// Instances of this class describe how hyperlinks will appear + /// + public class HyperlinkStyle : System.ComponentModel.Component + { + /// + /// Create a HyperlinkStyle + /// + public HyperlinkStyle() { + this.Normal = new CellStyle(); + this.Normal.ForeColor = Color.Blue; + this.Over = new CellStyle(); + this.Over.FontStyle = FontStyle.Underline; + this.Visited = new CellStyle(); + this.Visited.ForeColor = Color.Purple; + this.OverCursor = Cursors.Hand; + } + + /// + /// What sort of formatting should be applied to hyperlinks in their normal state? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn")] + public CellStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private CellStyle normalStyle; + + /// + /// What sort of formatting should be applied to hyperlinks when the mouse is over them? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn when the mouse is over them?")] + public CellStyle Over { + get { return this.overStyle; } + set { this.overStyle = value; } + } + private CellStyle overStyle; + + /// + /// What sort of formatting should be applied to hyperlinks after they have been clicked? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn after they have been clicked")] + public CellStyle Visited { + get { return this.visitedStyle; } + set { this.visitedStyle = value; } + } + private CellStyle visitedStyle; + + /// + /// Gets or sets the cursor that should be shown when the mouse is over a hyperlink. + /// + [Category("Appearance"), + Description("What cursor should be shown when the mouse is over a link?")] + public Cursor OverCursor { + get { return this.overCursor; } + set { this.overCursor = value; } + } + private Cursor overCursor; + } + + /// + /// Instances of this class control one the styling of one particular state + /// (normal, hot, pressed) of a header control + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class HeaderStateStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + + /// + /// Gets or sets the color in which a frame will be drawn around the header for this column + /// + [DefaultValue(typeof(Color), "")] + public Color FrameColor { + get { return this.frameColor; } + set { this.frameColor = value; } + } + private Color frameColor; + + /// + /// Gets or sets the width of the frame that will be drawn around the header for this column + /// + [DefaultValue(0.0f)] + public float FrameWidth { + get { return this.frameWidth; } + set { this.frameWidth = value; } + } + private float frameWidth; + } + + /// + /// This class defines how a header should be formatted in its various states. + /// + public class HeaderFormatStyle : System.ComponentModel.Component + { + /// + /// Create a new HeaderFormatStyle + /// + public HeaderFormatStyle() { + this.Hot = new HeaderStateStyle(); + this.Normal = new HeaderStateStyle(); + this.Pressed = new HeaderStateStyle(); + } + + /// + /// What sort of formatting should be applied to a column header when the mouse is over it? + /// + [Category("Appearance"), + Description("How should the header be drawn when the mouse is over it?")] + public HeaderStateStyle Hot { + get { return this.hotStyle; } + set { this.hotStyle = value; } + } + private HeaderStateStyle hotStyle; + + /// + /// What sort of formatting should be applied to a column header in its normal state? + /// + [Category("Appearance"), + Description("How should a column header normally be drawn")] + public HeaderStateStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private HeaderStateStyle normalStyle; + + /// + /// What sort of formatting should be applied to a column header when pressed? + /// + [Category("Appearance"), + Description("How should a column header be drawn when it is pressed")] + public HeaderStateStyle Pressed { + get { return this.pressedStyle; } + set { this.pressedStyle = value; } + } + private HeaderStateStyle pressedStyle; + + /// + /// Set the font for all three states + /// + /// + public void SetFont(Font font) { + this.Normal.Font = font; + this.Hot.Font = font; + this.Pressed.Font = font; + } + + /// + /// Set the fore color for all three states + /// + /// + public void SetForeColor(Color color) { + this.Normal.ForeColor = color; + this.Hot.ForeColor = color; + this.Pressed.ForeColor = color; + } + + /// + /// Set the back color for all three states + /// + /// + public void SetBackColor(Color color) { + this.Normal.BackColor = color; + this.Hot.BackColor = color; + this.Pressed.BackColor = color; + } + } +} diff --git a/ObjectListView/Rendering/TreeRenderer.cs b/ObjectListView/Rendering/TreeRenderer.cs new file mode 100644 index 0000000..a3bef8a --- /dev/null +++ b/ObjectListView/Rendering/TreeRenderer.cs @@ -0,0 +1,309 @@ +/* + * TreeRenderer - Draw the major column in a TreeListView + * + * Author: Phillip Piper + * Date: 27/06/2015 + * + * Change log: + * 2016-07-17 JPP - Added TreeRenderer.UseTriangles and IsShowGlyphs + * 2015-06-27 JPP - Split out from TreeListView.cs + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware { + + public partial class TreeListView { + /// + /// This class handles drawing the tree structure of the primary column. + /// + public class TreeRenderer : HighlightTextRenderer { + /// + /// Create a TreeRenderer + /// + public TreeRenderer() { + this.LinePen = new Pen(Color.Blue, 1.0f); + this.LinePen.DashStyle = DashStyle.Dot; + } + + #region Configuration properties + + /// + /// Should the renderer draw glyphs at the expansion points? + /// + /// The expansion points will still function to expand/collapse even if this is false. + public bool IsShowGlyphs + { + get { return isShowGlyphs; } + set { isShowGlyphs = value; } + } + private bool isShowGlyphs = true; + + /// + /// Should the renderer draw lines connecting siblings? + /// + public bool IsShowLines + { + get { return isShowLines; } + set { isShowLines = value; } + } + private bool isShowLines = true; + + /// + /// Return the pen that will be used to draw the lines between branches + /// + public Pen LinePen + { + get { return linePen; } + set { linePen = value; } + } + private Pen linePen; + + /// + /// Should the renderer draw triangles as the expansion glyphs? + /// + /// + /// This looks best with ShowLines = false + /// + public bool UseTriangles + { + get { return useTriangles; } + set { useTriangles = value; } + } + private bool useTriangles = false; + + #endregion + + /// + /// Return the branch that the renderer is currently drawing. + /// + private Branch Branch { + get { + return this.TreeListView.TreeModel.GetBranch(this.RowObject); + } + } + + /// + /// Return the TreeListView for which the renderer is being used. + /// + public TreeListView TreeListView { + get { + return (TreeListView)this.ListView; + } + } + + /// + /// How many pixels will be reserved for each level of indentation? + /// + public static int PIXELS_PER_LEVEL = 16 + 1; + + /// + /// The real work of drawing the tree is done in this method + /// + /// + /// + public override void Render(System.Drawing.Graphics g, System.Drawing.Rectangle r) { + this.DrawBackground(g, r); + + Branch br = this.Branch; + + Rectangle paddedRectangle = this.ApplyCellPadding(r); + + Rectangle expandGlyphRectangle = paddedRectangle; + expandGlyphRectangle.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + expandGlyphRectangle.Width = PIXELS_PER_LEVEL; + expandGlyphRectangle.Height = PIXELS_PER_LEVEL; + expandGlyphRectangle.Y = this.AlignVertically(paddedRectangle, expandGlyphRectangle); + int expandGlyphRectangleMidVertical = expandGlyphRectangle.Y + (expandGlyphRectangle.Height/2); + + if (this.IsShowLines) + this.DrawLines(g, r, this.LinePen, br, expandGlyphRectangleMidVertical); + + if (br.CanExpand && this.IsShowGlyphs) + this.DrawExpansionGlyph(g, expandGlyphRectangle, br.IsExpanded); + + int indent = br.Level * PIXELS_PER_LEVEL; + paddedRectangle.Offset(indent, 0); + paddedRectangle.Width -= indent; + + this.DrawImageAndText(g, paddedRectangle); + } + + /// + /// Draw the expansion indicator + /// + /// + /// + /// + protected virtual void DrawExpansionGlyph(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseStyles) { + this.DrawExpansionGlyphStyled(g, r, isExpanded); + } else { + this.DrawExpansionGlyphManual(g, r, isExpanded); + } + } + + /// + /// Gets whether or not we should render using styles + /// + protected virtual bool UseStyles { + get { + return !this.IsPrinting && Application.RenderWithVisualStyles; + } + } + + /// + /// Draw the expansion indicator using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphStyled(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseTriangles && this.IsShowLines) { + using (SolidBrush b = new SolidBrush(GetBackgroundColor())) { + Rectangle r2 = r; + r2.Inflate(-2, -2); + g.FillRectangle(b, r2); + } + } + + VisualStyleRenderer renderer = new VisualStyleRenderer(DecideVisualElement(isExpanded)); + renderer.DrawBackground(g, r); + } + + private VisualStyleElement DecideVisualElement(bool isExpanded) { + string klass = this.UseTriangles ? "Explorer::TreeView" : "TREEVIEW"; + int part = this.UseTriangles && this.IsExpansionHot ? 4 : 2; + int state = isExpanded ? 2 : 1; + return VisualStyleElement.CreateElement(klass, part, state); + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsExpansionHot { + get { return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.ExpandButton; } + } + + /// + /// Draw the expansion indicator without using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphManual(Graphics g, Rectangle r, bool isExpanded) { + int h = 8; + int w = 8; + int x = r.X + 4; + int y = r.Y + (r.Height / 2) - 4; + + g.DrawRectangle(new Pen(SystemBrushes.ControlDark), x, y, w, h); + g.FillRectangle(Brushes.White, x + 1, y + 1, w - 1, h - 1); + g.DrawLine(Pens.Black, x + 2, y + 4, x + w - 2, y + 4); + + if (!isExpanded) + g.DrawLine(Pens.Black, x + 4, y + 2, x + 4, y + h - 2); + } + + /// + /// Draw the lines of the tree + /// + /// + /// + /// + /// + /// + protected virtual void DrawLines(Graphics g, Rectangle r, Pen p, Branch br, int glyphMidVertical) { + Rectangle r2 = r; + r2.Width = PIXELS_PER_LEVEL; + + // Vertical lines have to start on even points, otherwise the dotted line looks wrong. + // This is only needed if pen is dotted. + int top = r2.Top; + //if (p.DashStyle == DashStyle.Dot && (top & 1) == 0) + // top += 1; + + // Draw lines for ancestors + int midX; + IList ancestors = br.Ancestors; + foreach (Branch ancestor in ancestors) { + if (!ancestor.IsLastChild && !ancestor.IsOnlyBranch) { + midX = r2.Left + r2.Width / 2; + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + r2.Offset(PIXELS_PER_LEVEL, 0); + } + + // Draw lines for this branch + midX = r2.Left + r2.Width / 2; + + // Horizontal line first + g.DrawLine(p, midX, glyphMidVertical, r2.Right, glyphMidVertical); + + // Vertical line second + if (br.IsFirstBranch) { + if (!br.IsLastChild && !br.IsOnlyBranch) + g.DrawLine(p, midX, glyphMidVertical, midX, r2.Bottom); + } else { + if (br.IsLastChild) + g.DrawLine(p, midX, top, midX, glyphMidVertical); + else + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + } + + /// + /// Do the hit test + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Branch br = this.Branch; + + Rectangle r = this.ApplyCellPadding(this.Bounds); + if (br.CanExpand) { + r.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + r.Width = PIXELS_PER_LEVEL; + if (r.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.ExpandButton; + return; + } + } + + r = this.Bounds; + int indent = br.Level * PIXELS_PER_LEVEL; + r.X += indent; + r.Width -= indent; + + // Ignore events in the indent zone + if (x < r.Left) { + hti.HitTestLocation = HitTestLocation.Nothing; + } else { + this.StandardHitTest(g, hti, r, x, y); + } + } + + /// + /// Calculate the edit rect + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + } + } +} \ No newline at end of file diff --git a/ObjectListView/Resources/clear-filter.png b/ObjectListView/Resources/clear-filter.png new file mode 100644 index 0000000000000000000000000000000000000000..2ddf7073b0c3de5791448e7a8effdf05f2c25e77 GIT binary patch literal 1381 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu3$w13IYNSK;YpJ;1K`>2|$pMP*6~?L4aXGMZtoMfCCZ?4-^DGXfXWOVECXR@E?dQ z1pYfH{P$4!A7F4Hz~MoF!-oim{|OHNGaUXG1pKcE_)wAXABY+fK6DiP? zKrmy%f&~jUtk?hoJ2qU{vEjpnh7U6u{?BN50A#ON@L|J(4?8v-*m2;)feiRR|N(hXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr_kFdQ zoeld1Cq2lBJ3DomuG-I@|6fF&{HffzJymf>EyJTdrCUYrF&?;bSL@WRXdYXZ8L_8& z<{G4lv8T+tYq*RrCy!C_(dAdCziTk7Os_f-vdCUx*~%@3S$j_~ZHe|x2$B30aO11n q@yq4if(I79Qcsd^-jTfMt#}vzTCZ0dwIzWLW$<+Mb6Mw<&;$TKY4H>Q literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/coffee.jpg b/ObjectListView/Resources/coffee.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6032d83fc7a5e1db6b76067d8de98e2bce6619c4 GIT binary patch literal 73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k!{_*qLcp=b&S~KQDwda))^t9c(W#*v77eeug zdqyjU;}6c2v~v_C@`k)3^h8mf&hyFrnd$zsFZ%a){m-+<4m|u^m;>K zOVLAH zwqMUPvObT@b~-;Q{6Bpz7C+9@8hgTdK96qMrWwP>?eOq4NKl zxczybKf?jjqkcZxxDCR`NTJZs*gEz}&eiO%6&U?uP(Hm8&9515nCeje+=@8zDZFZCzP{>*a=dy$?G%>Nq@B0eCa7sd#J7IkJq zm!0f+-PaeoT3G()iv|47jiZ>>>!|Tjs!_^hsvDcmGmXrLhma$air4Pwtw&y@*TW!J z92IMU3%Q#;{TZUvNV&xE6sGWTcOMk8Arr7!U5B}ML-s_`t!wa*0)so)8?@@0?e$U7 zoZzmaPpL}$QSg)45*y=dbm@xm3&Ey$DAO~{cpgiQ|I(xWcQ1fq6;BUin661Sykgs5 ullEp5c{-Ly7?1km;*=ymtZauJUEbUWocnWm|MR!>f11Mohu8jo`o92pXb&|2 literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/filter-icons3.png b/ObjectListView/Resources/filter-icons3.png new file mode 100644 index 0000000000000000000000000000000000000000..80178919d5b63ab83df2b7c669ab0779a49aa2aa GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^+(695!3-or^+GlRDVB6cUq=Rpjs4tz5?L7-m>B|m zLR>-OY^*$7-1heN&W=uQZf+hP9-f|_-hqLkp`l@6VHp`2`FT0T#l=NMCB?<1B}K(e zO)YJ0ZTkrW0Q7{?;10DkVe@>jlz`)2*666>Be`EuO;P33J zzzE?i@Q5sCVBk9h!i=ICUJXD&$r9IylHmNblJdl&REB`W%)AmkKi3e2GGjecJqvT| zhFG8?MUW!rqSVBa%=|oskj&gv1|tJQLn{LlD?>vCBSR}gBP(MQ&19DgK*fQcE{-7* z;jU-hg&GtXm>qO(2x@=3_wWB9j=m(lnN#F*)B0@kMOI+Vn;qXQmn}9~_T~=D z+XX%QB%0i|8O%7kPm;e@o7oiiks3xCpOkgD9y%{jLaR6H_xy85}S Ib4q9e03rsV#sB~S literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-ascending.png b/ObjectListView/Resources/sort-ascending.png new file mode 100644 index 0000000000000000000000000000000000000000..a21be93fa9f9415cfb652bd3f1fea9f14d09338c GIT binary patch literal 1364 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1E30yA9S={>)b#X{vND5!2?h}ptRkldbB_{`{(WMnzDc9vUQs_&0BM1<bo1Nd^W+hLRw^;Qu2VFa&>RR|SSK zXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr=C^PE^0&oV$SnRjJ>Se)@el9KzgPb(xGQ0`HCE5kgy}D{ z`~Ouz>UtNs#CGW&tXB%1p1&yert|7m7J~gd`a(DPrKwMx!92N9ht=$^ar1VS;Aj5% zj}5qGI!+k)v>%we)P+^=ZeLFF8>M517RUD-ikl)^c|iKt?Ty_hV~;%rx{JZn)z4*} HQ$iB}j@iab literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-descending.png b/ObjectListView/Resources/sort-descending.png new file mode 100644 index 0000000000000000000000000000000000000000..92dbe63f20afc6c51cf837b3aa6b0de64bfd126d GIT binary patch literal 1371 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1D=Pzs0xPd_tHAPdYaI_y&(!qvlCm-bj|PW`1wjezAz8Cy3uk*KEb+`(5>mJ_ zzIa_`?dFp19SsHwZPq$dt*v|9EvGtJPjGOU;1Mu2FmhH_{erCc1!=j<%W^iBl`XC9 zUtQhMFk$`t#fzse-MhMN`o{iwySt|BpSf(^rcI02A6d8a^twH#_Z~dB@6@g1%a)zk zwD#DAn

      dzjor>jk9NOoV#%O_LIwZpWS`@{PE+*Po6w|`R*Oi*`r`I1Sk&yjoeww z7#J8CN`m}?|Br0I5d5886&RwN1s;*b3=DjSK$uZf!>a)(C|TkfQ4*Y=R#Ki=l*$m0 zn3-3i=jR%tP-d)Ws%K$t-4F{@qzF>vT$Gwvl9`{U5R#dj%3x$*XlP|%Vr6KgU|?xw zWMXAtBrKh33{*VX)5S4FBRIB?o$rtVkE^f7?kRgUb8oi9nmze<{a1>@M6*p#p1k~N z-Eu`SL2~V)lb*#tCz*=Q4?JJNw&&=s+HH*Mod1ib@bvsXa8~LjPfF4c_V0OmAFLZw zPrO#0*_f`&8uipQN%z&d#SVpjdlp=i+dJcJioJkf_=1P$=Bx_(H07fFXSt;FNoxyO jXDxlJeOk+k^#@aL!J4$pI`)r1=P`J?`njxgN@xNAhOF7) literal 0 HcmV?d00001 diff --git a/ObjectListView/SubControls/GlassPanelForm.cs b/ObjectListView/SubControls/GlassPanelForm.cs new file mode 100644 index 0000000..bcaba67 --- /dev/null +++ b/ObjectListView/SubControls/GlassPanelForm.cs @@ -0,0 +1,459 @@ +/* + * GlassPanelForm - A transparent form that is placed over an ObjectListView + * to allow flicker-free overlay images during scrolling. + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * 2010-08-18 JPP - Added WS_EX_TOOLWINDOW style so that the form won't appear in Alt-Tab list. + * v2.4 + * 2010-03-11 JPP - Work correctly in MDI applications -- more or less. Actually, less than more. + * They don't crash but they don't correctly handle overlapping MDI children. + * Overlays from one control are shown on top of the other windows. + * 2010-03-09 JPP - Correctly Unbind() when the related ObjectListView is disposed. + * 2009-10-28 JPP - Use FindForm() rather than TopMostControl, since the latter doesn't work + * as I expected when the OLV is part of an MDI child window. Thanks to + * wvd_vegt who tracked this down. + * v2.3 + * 2009-08-19 JPP - Only hide the glass pane on resize, not on move + * - Each glass panel now only draws one overlays + * v2.2 + * 2009-06-05 JPP - Handle when owning window is a topmost window + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + ///

      + /// A GlassPanelForm sits transparently over an ObjectListView to show overlays. + /// + internal partial class GlassPanelForm : Form + { + public GlassPanelForm() { + this.Name = "GlassPanelForm"; + this.Text = "GlassPanelForm"; + + ClientSize = new System.Drawing.Size(0, 0); + ControlBox = false; + FormBorderStyle = FormBorderStyle.None; + SizeGripStyle = SizeGripStyle.Hide; + StartPosition = FormStartPosition.Manual; + MaximizeBox = false; + MinimizeBox = false; + ShowIcon = false; + ShowInTaskbar = false; + FormBorderStyle = FormBorderStyle.None; + + SetStyle(ControlStyles.Selectable, false); + + this.Opacity = 0.5f; + this.BackColor = Color.FromArgb(255, 254, 254, 254); + this.TransparencyKey = this.BackColor; + this.HideGlass(); + NativeMethods.ShowWithoutActivate(this); + } + + protected override void Dispose(bool disposing) { + if (disposing) + this.Unbind(); + + base.Dispose(disposing); + } + + #region Properties + + /// + /// Get the low-level windows flag that will be given to CreateWindow. + /// + protected override CreateParams CreateParams { + get { + CreateParams cp = base.CreateParams; + cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT + cp.ExStyle |= 0x80; // WS_EX_TOOLWINDOW + return cp; + } + } + + #endregion + + #region Commands + + /// + /// Attach this form to the given ObjectListView + /// + public void Bind(ObjectListView olv, IOverlay overlay) { + if (this.objectListView != null) + this.Unbind(); + + this.objectListView = olv; + this.Overlay = overlay; + this.mdiClient = null; + this.mdiOwner = null; + + if (this.objectListView == null) + return; + + // NOTE: If you listen to any events here, you *must* stop listening in Unbind() + + this.objectListView.Disposed += new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged += new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged += new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged += new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged += new EventHandler(objectListView_ParentChanged); + + // Collect our ancestors in the widget hierarchy + if (this.ancestors == null) + this.ancestors = new List(); + Control parent = this.objectListView.Parent; + while (parent != null) { + this.ancestors.Add(parent); + parent = parent.Parent; + } + + // Listen for changes in the hierarchy + foreach (Control ancestor in this.ancestors) { + ancestor.ParentChanged += new EventHandler(objectListView_ParentChanged); + TabControl tabControl = ancestor as TabControl; + if (tabControl != null) { + tabControl.Selected += new TabControlEventHandler(tabControl_Selected); + } + } + + // Listen for changes in our owning form + this.Owner = this.objectListView.FindForm(); + this.myOwner = this.Owner; + if (this.Owner != null) { + this.Owner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.Owner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.Owner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.Owner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + if (this.Owner.TopMost) { + // We can't do this.TopMost = true; since that will activate the panel, + // taking focus away from the owner of the listview + NativeMethods.MakeTopMost(this); + } + + // We need special code to handle MDI + this.mdiOwner = this.Owner.MdiParent; + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + + // Find the MDIClient control, which houses all MDI children + foreach (Control c in this.mdiOwner.Controls) { + this.mdiClient = c as MdiClient; + if (this.mdiClient != null) { + break; + } + } + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged += new EventHandler(myMdiClient_ClientSizeChanged); + } + } + } + + this.UpdateTransparency(); + } + + void myMdiClient_ClientSizeChanged(object sender, EventArgs e) { + this.RecalculateBounds(); + this.Invalidate(); + } + + /// + /// Made the overlay panel invisible + /// + public void HideGlass() { + if (!this.isGlassShown) + return; + this.isGlassShown = false; + this.Bounds = new Rectangle(-10000, -10000, 1, 1); + } + + /// + /// Show the overlay panel in its correctly location + /// + /// + /// If the panel is always shown, this method does nothing. + /// If the panel is being resized, this method also does nothing. + /// + public void ShowGlass() { + if (this.isGlassShown || this.isDuringResizeSequence) + return; + + this.isGlassShown = true; + this.RecalculateBounds(); + } + + /// + /// Detach this glass panel from its previous ObjectListView + /// + /// + /// You should unbind the overlay panel before making any changes to the + /// widget hierarchy. + /// + public void Unbind() { + if (this.objectListView != null) { + this.objectListView.Disposed -= new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged -= new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged -= new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged -= new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged -= new EventHandler(objectListView_ParentChanged); + this.objectListView = null; + } + + if (this.ancestors != null) { + foreach (Control parent in this.ancestors) { + parent.ParentChanged -= new EventHandler(objectListView_ParentChanged); + TabControl tabControl = parent as TabControl; + if (tabControl != null) { + tabControl.Selected -= new TabControlEventHandler(tabControl_Selected); + } + } + this.ancestors = null; + } + + if (this.myOwner != null) { + this.myOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.myOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.myOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.myOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.myOwner = null; + } + + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.mdiOwner = null; + } + + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged -= new EventHandler(myMdiClient_ClientSizeChanged); + this.mdiClient = null; + } + } + + #endregion + + #region Event Handlers + + void objectListView_Disposed(object sender, EventArgs e) { + this.Unbind(); + } + + /// + /// Handle when the form that owns the ObjectListView begins to be resized + /// + /// + /// + void Owner_ResizeBegin(object sender, EventArgs e) { + // When the top level window is being resized, we just want to hide + // the overlay window. When the resizing finishes, we want to show + // the overlay window, if it was shown before the resize started. + this.isDuringResizeSequence = true; + this.wasGlassShownBeforeResize = this.isGlassShown; + } + + /// + /// Handle when the form that owns the ObjectListView finished to be resized + /// + /// + /// + void Owner_ResizeEnd(object sender, EventArgs e) { + this.isDuringResizeSequence = false; + if (this.wasGlassShownBeforeResize) + this.ShowGlass(); + } + + /// + /// The owning form has moved. Move the overlay panel too. + /// + /// + /// + void Owner_LocationChanged(object sender, EventArgs e) { + if (this.mdiOwner != null) + this.HideGlass(); + else + this.RecalculateBounds(); + } + + /// + /// The owning form is resizing. Hide our overlay panel until the resizing stops + /// + /// + /// + void Owner_SizeChanged(object sender, EventArgs e) { + this.HideGlass(); + } + + + /// + /// Handle when the bound OLV changes its location. The overlay panel must + /// be moved too, IFF it is currently visible. + /// + /// + /// + void objectListView_LocationChanged(object sender, EventArgs e) { + if (this.isGlassShown) { + this.RecalculateBounds(); + } + } + + /// + /// Handle when the bound OLV changes size. The overlay panel must + /// resize too, IFF it is currently visible. + /// + /// + /// + void objectListView_SizeChanged(object sender, EventArgs e) { + // This event is triggered in all sorts of places, and not always when the size changes. + //if (this.isGlassShown) { + // this.Size = this.objectListView.ClientSize; + //} + } + + /// + /// Handle when the bound OLV is part of a TabControl and that + /// TabControl changes tabs. The overlay panel is hidden. The + /// first time the bound OLV is redrawn, the overlay panel will + /// be shown again. + /// + /// + /// + void tabControl_Selected(object sender, TabControlEventArgs e) { + this.HideGlass(); + } + + /// + /// Somewhere the parent of the bound OLV has changed. Update + /// our events. + /// + /// + /// + void objectListView_ParentChanged(object sender, EventArgs e) { + ObjectListView olv = this.objectListView; + IOverlay overlay = this.Overlay; + this.Unbind(); + this.Bind(olv, overlay); + } + + /// + /// Handle when the bound OLV changes its visibility. + /// The overlay panel should match the OLV's visibility. + /// + /// + /// + void objectListView_VisibleChanged(object sender, EventArgs e) { + if (this.objectListView.Visible) + this.ShowGlass(); + else + this.HideGlass(); + } + + #endregion + + #region Implementation + + protected override void OnPaint(PaintEventArgs e) { + if (this.objectListView == null || this.Overlay == null) + return; + + Graphics g = e.Graphics; + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + //g.DrawRectangle(new Pen(Color.Green, 4.0f), this.ClientRectangle); + + // If we are part of an MDI app, make sure we don't draw outside the bounds + if (this.mdiClient != null) { + Rectangle r = mdiClient.RectangleToScreen(mdiClient.ClientRectangle); + Rectangle r2 = this.objectListView.RectangleToClient(r); + g.SetClip(r2, System.Drawing.Drawing2D.CombineMode.Intersect); + } + + this.Overlay.Draw(this.objectListView, g, this.objectListView.ClientRectangle); + } + + protected void RecalculateBounds() { + if (!this.isGlassShown) + return; + + Rectangle rect = this.objectListView.ClientRectangle; + rect.X = 0; + rect.Y = 0; + this.Bounds = this.objectListView.RectangleToScreen(rect); + } + + internal void UpdateTransparency() { + ITransparentOverlay transparentOverlay = this.Overlay as ITransparentOverlay; + if (transparentOverlay == null) + this.Opacity = this.objectListView.OverlayTransparency / 255.0f; + else + this.Opacity = transparentOverlay.Transparency / 255.0f; + } + + protected override void WndProc(ref Message m) { + const int WM_NCHITTEST = 132; + const int HTTRANSPARENT = -1; + switch (m.Msg) { + // Ignore all mouse interactions + case WM_NCHITTEST: + m.Result = (IntPtr)HTTRANSPARENT; + break; + } + base.WndProc(ref m); + } + + #endregion + + #region Implementation variables + + internal IOverlay Overlay; + + #endregion + + #region Private variables + + private ObjectListView objectListView; + private bool isDuringResizeSequence; + private bool isGlassShown; + private bool wasGlassShownBeforeResize; + + // Cache these so we can unsubscribe from events even when the OLV has been disposed. + private Form myOwner; + private Form mdiOwner; + private List ancestors; + MdiClient mdiClient; + + #endregion + + } +} diff --git a/ObjectListView/SubControls/HeaderControl.cs b/ObjectListView/SubControls/HeaderControl.cs new file mode 100644 index 0000000..298680b --- /dev/null +++ b/ObjectListView/SubControls/HeaderControl.cs @@ -0,0 +1,1230 @@ +/* + * HeaderControl - A limited implementation of HeaderControl + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * 2015-06-12 JPP - Use HeaderTextAlignOrDefault instead of HeaderTextAlign + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-11 JPP - Fixed bug that prevented columns from being resized in IDE Designer + * by dragging the column divider + * 2011-04-12 JPP - Added ability to draw filter indicator in a column's header + * v2.4.1 + * 2010-08-23 JPP - Added ability to draw header vertically (thanks to Mark Fenwick) + * - Uses OLVColumn.HeaderTextAlign to decide how to align the column's header + * 2010-08-08 JPP - Added ability to have image in header + * v2.4 + * 2010-03-22 JPP - Draw header using header styles + * 2009-10-30 JPP - Plugged GDI resource leak, where font handles were created during custom + * drawing, but never destroyed + * v2.3 + * 2009-10-03 JPP - Handle when ListView.HeaderFormatStyle is None + * 2009-08-24 JPP - Handle the header being destroyed + * v2.2.1 + * 2009-08-16 JPP - Correctly handle header themes + * 2009-08-15 JPP - Added formatting capabilities: font, color, word wrap + * v2.2 + * 2009-06-01 JPP - Use ToolTipControl + * 2009-05-10 JPP - Removed all unsafe code + * 2008-11-25 JPP - Initial version + * + * TO DO: + * - Put drawing code into header style object, so that it can be easily customized. + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.Remoting; +using System.Windows.Forms; +using System.Runtime.InteropServices; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; +using BrightIdeasSoftware.Properties; +using System.Security.Permissions; + +namespace BrightIdeasSoftware { + + /// + /// Class used to capture window messages for the header of the list view + /// control. + /// + public class HeaderControl : NativeWindow { + /// + /// Create a header control for the given ObjectListView. + /// + /// + public HeaderControl(ObjectListView olv) { + this.ListView = olv; + this.AssignHandle(NativeMethods.GetHeaderControl(olv)); + } + + #region Properties + + /// + /// Return the index of the column under the current cursor position, + /// or -1 if the cursor is not over a column + /// + /// Index of the column under the cursor, or -1 + public int ColumnIndexUnderCursor { + get { + Point pt = this.ScrolledCursorPosition; + return NativeMethods.GetColumnUnderPoint(this.Handle, pt); + } + } + + /// + /// Return the Windows handle behind this control + /// + /// + /// When an ObjectListView is initialized as part of a UserControl, the + /// GetHeaderControl() method returns 0 until the UserControl is + /// completely initialized. So the AssignHandle() call in the constructor + /// doesn't work. So we override the Handle property so value is always + /// current. + /// + public new IntPtr Handle { + get { return NativeMethods.GetHeaderControl(this.ListView); } + } + + //TODO: The Handle property may no longer be necessary. CHECK! 2008/11/28 + + /// + /// Gets or sets a style that should be applied to the font of the + /// column's header text when the mouse is over that column + /// + /// THIS IS EXPERIMENTAL. USE AT OWN RISK. August 2009 + [Obsolete("Use HeaderStyle.Hot.FontStyle instead")] + public FontStyle HotFontStyle { + get { return FontStyle.Regular; } + set { } + } + + /// + /// Gets the index of the column under the cursor if the cursor is over it's checkbox + /// + protected int GetColumnCheckBoxUnderCursor() { + Point pt = this.ScrolledCursorPosition; + + int columnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + return this.IsPointOverHeaderCheckBox(columnIndex, pt) ? columnIndex : -1; + } + + /// + /// Gets the client rectangle for the header + /// + public Rectangle ClientRectangle { + get { + Rectangle r = new Rectangle(); + NativeMethods.GetClientRect(this.Handle, ref r); + return r; + } + } + + /// + /// Return true if the given point is over the checkbox for the given column. + /// + /// + /// + /// + protected bool IsPointOverHeaderCheckBox(int columnIndex, Point pt) { + if (columnIndex < 0 || columnIndex >= this.ListView.Columns.Count) + return false; + + OLVColumn column = this.ListView.GetColumn(columnIndex); + if (!this.HasCheckBox(column)) + return false; + + Rectangle r = this.GetCheckBoxBounds(column); + r.Inflate(1, 1); // make the target slightly bigger + return r.Contains(pt); + } + + /// + /// Gets whether the cursor is over a "locked" divider, i.e. + /// one that cannot be dragged by the user. + /// + protected bool IsCursorOverLockedDivider { + get { + Point pt = this.ScrolledCursorPosition; + int dividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + if (dividerIndex >= 0 && dividerIndex < this.ListView.Columns.Count) { + OLVColumn column = this.ListView.GetColumn(dividerIndex); + return column.IsFixedWidth || column.FillsFreeSpace; + } else + return false; + } + } + + private Point ScrolledCursorPosition { + get { + Point pt = this.ListView.PointToClient(Cursor.Position); + pt.X += this.ListView.LowLevelScrollPosition.X; + return pt; + } + } + + /// + /// Gets or sets the listview that this header belongs to + /// + protected ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the maximum height of the header. -1 means no maximum. + /// + public int MaximumHeight + { + get { return this.ListView.HeaderMaximumHeight; } + } + + /// + /// Gets the minimum height of the header. -1 means no minimum. + /// + public int MinimumHeight + { + get { return this.ListView.HeaderMinimumHeight; } + } + + /// + /// Get or set the ToolTip that shows tips for the header + /// + public ToolTipControl ToolTip { + get { + if (this.toolTip == null) { + this.CreateToolTip(); + } + return this.toolTip; + } + protected set { this.toolTip = value; } + } + + private ToolTipControl toolTip; + + /// + /// Gets or sets whether the text in column headers should be word + /// wrapped when it is too long to fit within the column + /// + public bool WordWrap { + get { return this.wordWrap; } + set { this.wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Commands + + /// + /// Calculate how height the header needs to be + /// + /// Height in pixels + protected int CalculateHeight(Graphics g) { + TextFormatFlags flags = this.TextFormatFlags; + int columnUnderCursor = this.ColumnIndexUnderCursor; + float height = this.MinimumHeight; + for (int i = 0; i < this.ListView.Columns.Count; i++) { + OLVColumn column = this.ListView.GetColumn(i); + height = Math.Max(height, CalculateColumnHeight(g, column, flags, columnUnderCursor == i, i)); + } + return this.MaximumHeight == -1 ? (int) height : Math.Min(this.MaximumHeight, (int) height); + } + + private float CalculateColumnHeight(Graphics g, OLVColumn column, TextFormatFlags flags, bool isHot, int i) { + Font f = this.CalculateFont(column, isHot, false); + if (column.IsHeaderVertical) + return TextRenderer.MeasureText(g, column.Text, f, new Size(10000, 10000), flags).Width; + + const int fudge = 9; // 9 is a magic constant that makes it perfectly match XP behavior + if (!this.WordWrap) + return f.Height + fudge; + + Rectangle r = this.GetHeaderDrawRect(i); + if (this.HasNonThemedSortIndicator(column)) + r.Width -= 16; + if (column.HasHeaderImage) + r.Width -= column.ImageList.ImageSize.Width + 3; + if (this.HasFilterIndicator(column)) + r.Width -= this.CalculateFilterIndicatorWidth(r); + if (this.HasCheckBox(column)) + r.Width -= this.CalculateCheckBoxBounds(g, r).Width; + SizeF size = TextRenderer.MeasureText(g, column.Text, f, new Size(r.Width, 100), flags); + return size.Height + fudge; + } + + /// + /// Get the bounds of the checkbox against the given column + /// + /// + /// + public Rectangle GetCheckBoxBounds(OLVColumn column) { + Rectangle r = this.GetHeaderDrawRect(column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) + return this.CalculateCheckBoxBounds(g, r); + } + + /// + /// Should the given column be drawn with a checkbox against it? + /// + /// + /// + public bool HasCheckBox(OLVColumn column) { + return column.HeaderCheckBox || column.HeaderTriStateCheckBox; + } + + /// + /// Should the given column show a sort indicator? + /// + /// + /// + protected bool HasSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + return column == this.ListView.LastSortColumn && this.ListView.LastSortOrder != SortOrder.None; + } + + /// + /// Should the given column be drawn with a filter indicator against it? + /// + /// + /// + protected bool HasFilterIndicator(OLVColumn column) { + return (this.ListView.UseFiltering && this.ListView.UseFilterIndicator && column.HasFilterIndicator); + } + + /// + /// Should the given column show a non-themed sort indicator? + /// + /// + /// + protected bool HasNonThemedSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + if (VisualStyleRenderer.IsSupported) + return !VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp) && + this.HasSortIndicator(column); + else + return this.HasSortIndicator(column); + } + + /// + /// Return the bounds of the item with the given index + /// + /// + /// + public Rectangle GetItemRect(int itemIndex) { + const int HDM_FIRST = 0x1200; + const int HDM_GETITEMRECT = HDM_FIRST + 7; + NativeMethods.RECT r = new NativeMethods.RECT(); + NativeMethods.SendMessageRECT(this.Handle, HDM_GETITEMRECT, itemIndex, ref r); + return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); + } + + /// + /// Return the bounds within which the given column will be drawn + /// + /// + /// + public Rectangle GetHeaderDrawRect(int itemIndex) { + Rectangle r = this.GetItemRect(itemIndex); + + // Tweak the text rectangle a little to improve aesthetics + r.Inflate(-3, 0); + r.Y -= 2; + + return r; + } + + /// + /// Force the header to redraw by invalidating it + /// + public void Invalidate() { + NativeMethods.InvalidateRect(this.Handle, 0, true); + } + + /// + /// Force the header to redraw a single column by invalidating it + /// + public void Invalidate(OLVColumn column) { + NativeMethods.InvalidateRect(this.Handle, 0, true); // todo + } + + #endregion + + #region Tooltip + + /// + /// Create a native tool tip control for this listview + /// + protected virtual void CreateToolTip() { + this.ToolTip = new ToolTipControl(); + this.ToolTip.Create(this.Handle); + this.ToolTip.AddTool(this); + this.ToolTip.Showing += new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + + #endregion + + #region Windows messaging + + /// + /// Override the basic message pump + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + protected override void WndProc(ref Message m) { + const int WM_DESTROY = 2; + const int WM_SETCURSOR = 0x20; + const int WM_NOTIFY = 0x4E; + const int WM_MOUSEMOVE = 0x200; + const int WM_LBUTTONDOWN = 0x201; + const int WM_LBUTTONUP = 0x202; + const int WM_MOUSELEAVE = 675; + const int HDM_FIRST = 0x1200; + const int HDM_LAYOUT = (HDM_FIRST + 5); + + // System.Diagnostics.Debug.WriteLine(String.Format("WndProc: {0}", m.Msg)); + + switch (m.Msg) { + case WM_SETCURSOR: + if (!this.HandleSetCursor(ref m)) + return; + break; + + case WM_NOTIFY: + if (!this.HandleNotify(ref m)) + return; + break; + + case WM_MOUSEMOVE: + if (!this.HandleMouseMove(ref m)) + return; + break; + + case WM_MOUSELEAVE: + if (!this.HandleMouseLeave(ref m)) + return; + break; + + case HDM_LAYOUT: + if (!this.HandleLayout(ref m)) + return; + break; + + case WM_DESTROY: + if (!this.HandleDestroy(ref m)) + return; + break; + + case WM_LBUTTONDOWN: + if (!this.HandleLButtonDown(ref m)) + return; + break; + + case WM_LBUTTONUP: + if (!this.HandleLButtonUp(ref m)) + return; + break; + } + + base.WndProc(ref m); + } + + private bool HandleReflectNotify(ref Message m) + { + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + // System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr.code)); + return true; + } + + /// + /// Handle the LButtonDown windows message + /// + /// + /// + protected bool HandleLButtonDown(ref Message m) + { + // Was there a header checkbox under the cursor? + this.columnIndexCheckBoxMouseDown = this.GetColumnCheckBoxUnderCursor(); + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Redraw the header so the checkbox redraws + this.Invalidate(); + + // Force the owning control to ignore this mouse click + // We don't want to sort the listview when they click the checkbox + m.Result = (IntPtr)1; + return false; + } + + private int columnIndexCheckBoxMouseDown = -1; + + /// + /// Handle the LButtonUp windows message + /// + /// + /// + protected bool HandleLButtonUp(ref Message m) { + //System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + + // Was the mouse released over a header checkbox? + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Was the mouse released over the same checkbox on which it was pressed? + if (this.columnIndexCheckBoxMouseDown != this.GetColumnCheckBoxUnderCursor()) + return true; + + // Toggle the header's checkbox + OLVColumn column = this.ListView.GetColumn(this.columnIndexCheckBoxMouseDown); + this.ListView.ToggleHeaderCheckBox(column); + + return true; + } + + /// + /// Handle the SetCursor windows message + /// + /// + /// + protected bool HandleSetCursor(ref Message m) { + if (this.IsCursorOverLockedDivider) { + m.Result = (IntPtr) 1; // Don't change the cursor + return false; + } + return true; + } + + /// + /// Handle the MouseMove windows message + /// + /// + /// + protected bool HandleMouseMove(ref Message m) { + + // Forward the mouse move event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) { + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + this.ListView.HandleMouseMove(new Point(x, y)); + } + + int columnIndex = this.ColumnIndexUnderCursor; + + // If the mouse has moved to a different header, pop the current tip (if any) + // For some reason, references this.ToolTip when in design mode, causes the + // columns to not be resizable by dragging the divider in the Designer. No idea why. + if (columnIndex != this.columnShowingTip && !this.ListView.IsDesignMode) { + this.ToolTip.PopToolTip(this); + this.columnShowingTip = columnIndex; + } + + // If the mouse has moved onto or away from a checkbox, we need to draw + int checkBoxUnderCursor = this.GetColumnCheckBoxUnderCursor(); + if (checkBoxUnderCursor != this.lastCheckBoxUnderCursor) { + this.Invalidate(); + this.lastCheckBoxUnderCursor = checkBoxUnderCursor; + } + + return true; + } + + private int columnShowingTip = -1; + private int lastCheckBoxUnderCursor = -1; + + /// + /// Handle the MouseLeave windows message + /// + /// + /// + protected bool HandleMouseLeave(ref Message m) { + // Forward the mouse leave event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) + this.ListView.HandleMouseMove(new Point(-1, -1)); + + return true; + } + + /// + /// Handle the Notify windows message + /// + /// + /// + protected bool HandleNotify(ref Message m) { + // Can this ever happen? JPP 2009-05-22 + if (m.LParam == IntPtr.Zero) + return false; + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (nmhdr.code) + { + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("hdr TTN_SHOW"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleShow(ref m); + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("hdr TTN_POP"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandlePop(ref m); + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("hdr TTN_GETDISPINFO"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleGetDispInfo(ref m); + } + + return false; + } + + /// + /// Handle the CustomDraw windows message + /// + /// + /// + internal virtual bool HandleHeaderCustomDraw(ref Message m) { + const int CDRF_NEWFONT = 2; + const int CDRF_SKIPDEFAULT = 4; + const int CDRF_NOTIFYPOSTPAINT = 0x10; + const int CDRF_NOTIFYITEMDRAW = 0x20; + + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_ITEM = 0x00010000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + + NativeMethods.NMCUSTOMDRAW nmcustomdraw = (NativeMethods.NMCUSTOMDRAW) m.GetLParam(typeof (NativeMethods.NMCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("header cd: {0:x}, {1}, {2:x}", nmcustomdraw.dwDrawStage, nmcustomdraw.dwItemSpec, nmcustomdraw.uItemState)); + switch (nmcustomdraw.dwDrawStage) { + case CDDS_PREPAINT: + this.cachedNeedsCustomDraw = this.NeedsCustomDraw(); + m.Result = (IntPtr) CDRF_NOTIFYITEMDRAW; + return true; + + case CDDS_ITEMPREPAINT: + int columnIndex = nmcustomdraw.dwItemSpec.ToInt32(); + OLVColumn column = this.ListView.GetColumn(columnIndex); + + // These don't work when visual styles are enabled + //NativeMethods.SetBkColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Red)); + //NativeMethods.SetTextColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Blue)); + //m.Result = IntPtr.Zero; + + if (this.cachedNeedsCustomDraw) { + using (Graphics g = Graphics.FromHdc(nmcustomdraw.hdc)) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + this.CustomDrawHeaderCell(g, columnIndex, nmcustomdraw.uItemState); + } + m.Result = (IntPtr) CDRF_SKIPDEFAULT; + } else { + const int CDIS_SELECTED = 1; + bool isPressed = ((nmcustomdraw.uItemState & CDIS_SELECTED) == CDIS_SELECTED); + + // We don't need to modify this based on checkboxes, since there can't be checkboxes if we are here + bool isHot = columnIndex == this.ColumnIndexUnderCursor; + + Font f = this.CalculateFont(column, isHot, isPressed); + + this.fontHandle = f.ToHfont(); + NativeMethods.SelectObject(nmcustomdraw.hdc, this.fontHandle); + + m.Result = (IntPtr) (CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT); + } + + return true; + + case CDDS_ITEMPOSTPAINT: + if (this.fontHandle != IntPtr.Zero) { + NativeMethods.DeleteObject(this.fontHandle); + this.fontHandle = IntPtr.Zero; + } + break; + } + + return false; + } + + private bool cachedNeedsCustomDraw; + private IntPtr fontHandle; + + /// + /// The message divides a ListView's space between the header and the rows of the listview. + /// The WINDOWPOS structure controls the headers bounds, the RECT controls the listview bounds. + /// + /// + /// + protected bool HandleLayout(ref Message m) { + if (this.ListView.HeaderStyle == ColumnHeaderStyle.None) + return true; + + NativeMethods.HDLAYOUT hdlayout = (NativeMethods.HDLAYOUT) m.GetLParam(typeof (NativeMethods.HDLAYOUT)); + NativeMethods.RECT rect = (NativeMethods.RECT) Marshal.PtrToStructure(hdlayout.prc, typeof (NativeMethods.RECT)); + NativeMethods.WINDOWPOS wpos = (NativeMethods.WINDOWPOS) Marshal.PtrToStructure(hdlayout.pwpos, typeof (NativeMethods.WINDOWPOS)); + + using (Graphics g = this.ListView.CreateGraphics()) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + int height = this.CalculateHeight(g); + wpos.hwnd = this.Handle; + wpos.hwndInsertAfter = IntPtr.Zero; + wpos.flags = NativeMethods.SWP_FRAMECHANGED; + wpos.x = rect.left; + wpos.y = rect.top; + wpos.cx = rect.right - rect.left; + wpos.cy = height; + + rect.top = height; + + Marshal.StructureToPtr(rect, hdlayout.prc, false); + Marshal.StructureToPtr(wpos, hdlayout.pwpos, false); + } + + this.ListView.BeginInvoke((MethodInvoker) delegate { + this.Invalidate(); + this.ListView.Invalidate(); + }); + return false; + } + + /// + /// Handle when the underlying header control is destroyed + /// + /// + /// + protected bool HandleDestroy(ref Message m) { + if (this.toolTip != null) { + this.toolTip.Showing -= new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + return false; + } + + #endregion + + #region Rendering + + /// + /// Does this header need to be custom drawn? + /// + /// Word wrapping and colored text require custom drawing. Funnily enough, we + /// can change the font natively. + protected bool NeedsCustomDraw() { + if (this.WordWrap) + return true; + + if (this.ListView.HeaderUsesThemes) + return false; + + if (this.NeedsCustomDraw(this.ListView.HeaderFormatStyle)) + return true; + + foreach (OLVColumn column in this.ListView.Columns) { + if (column.HasHeaderImage || + !column.ShowTextInHeader || + column.IsHeaderVertical || + this.HasFilterIndicator(column) || + this.HasCheckBox(column) || + column.TextAlign != column.HeaderTextAlignOrDefault || + (column.Index == 0 && column.HeaderTextAlignOrDefault != HorizontalAlignment.Left) || + this.NeedsCustomDraw(column.HeaderFormatStyle)) + return true; + } + + return false; + } + + private bool NeedsCustomDraw(HeaderFormatStyle style) { + if (style == null) + return false; + + return (this.NeedsCustomDraw(style.Normal) || + this.NeedsCustomDraw(style.Hot) || + this.NeedsCustomDraw(style.Pressed)); + } + + private bool NeedsCustomDraw(HeaderStateStyle style) { + if (style == null) + return false; + + // If we want fancy colors or frames, we have to custom draw. Oddly enough, we + // can handle font changes without custom drawing. + if (!style.BackColor.IsEmpty) + return true; + + if (style.FrameWidth > 0f && !style.FrameColor.IsEmpty) + return true; + + return (!style.ForeColor.IsEmpty && style.ForeColor != Color.Black); + } + + /// + /// Draw one cell of the header + /// + /// + /// + /// + protected void CustomDrawHeaderCell(Graphics g, int columnIndex, int itemState) { + OLVColumn column = this.ListView.GetColumn(columnIndex); + + bool hasCheckBox = this.HasCheckBox(column); + bool isMouseOverCheckBox = columnIndex == this.lastCheckBoxUnderCursor; + bool isMouseDownOnCheckBox = isMouseOverCheckBox && Control.MouseButtons == MouseButtons.Left; + bool isHot = (columnIndex == this.ColumnIndexUnderCursor) && (!(hasCheckBox && isMouseOverCheckBox)); + + const int CDIS_SELECTED = 1; + bool isPressed = ((itemState & CDIS_SELECTED) == CDIS_SELECTED); + + // System.Diagnostics.Debug.WriteLine(String.Format("{2:hh:mm:ss.ff} - HeaderCustomDraw: {0}, {1}", columnIndex, itemState, DateTime.Now)); + + // Calculate which style should be used for the header + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + + // If there is an owner drawn delegate installed, give it a chance to draw the header + Rectangle fullCellBounds = this.GetItemRect(columnIndex); + if (column.HeaderDrawing != null) + { + if (!column.HeaderDrawing(g, fullCellBounds, columnIndex, column, isPressed, stateStyle)) + return; + } + + // Draw the background + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot); + else + this.DrawUnthemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot, stateStyle); + + Rectangle r = this.GetHeaderDrawRect(columnIndex); + + // Draw the sort indicator if this column has one + if (this.HasSortIndicator(column)) { + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp)) + this.DrawThemedSortIndicator(g, r); + else + r = this.DrawUnthemedSortIndicator(g, r); + } + + if (this.HasFilterIndicator(column)) + r = this.DrawFilterIndicator(g, r); + + if (hasCheckBox) + r = this.DrawCheckBox(g, r, column.HeaderCheckState, column.HeaderCheckBoxDisabled, isMouseOverCheckBox, isMouseDownOnCheckBox); + + // Debugging - Where is the text going to be drawn + // g.DrawRectangle(Pens.Blue, r); + + // Finally draw the text + this.DrawHeaderImageAndText(g, r, column, stateStyle); + } + + private Rectangle DrawCheckBox(Graphics g, Rectangle r, CheckState checkState, bool isDisabled, bool isHot, + bool isPressed) { + CheckBoxState checkBoxState = this.GetCheckBoxState(checkState, isDisabled, isHot, isPressed); + Rectangle checkBoxBounds = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, checkBoxBounds.Location, checkBoxState); + + // Move the left edge without changing the right edge + int newX = checkBoxBounds.Right + 3; + r.Width -= (newX - r.X); + r.X = newX; + + return r; + } + + private Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.CheckedNormal); + + // Vertically center the checkbox + int topOffset = (cellBounds.Height - checkBoxSize.Height)/2; + return new Rectangle(cellBounds.X + 3, cellBounds.Y + topOffset, checkBoxSize.Width, checkBoxSize.Height); + } + + private CheckBoxState GetCheckBoxState(CheckState checkState, bool isDisabled, bool isHot, bool isPressed) { + // Should the checkbox be drawn as disabled? + if (isDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the mouse button currently down? + if (isPressed) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedPressed; + case CheckState.Unchecked: + return CheckBoxState.UncheckedPressed; + default: + return CheckBoxState.MixedPressed; + } + } + + // Is the cursor currently over this checkbox? + if (isHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + } + + /// + /// Draw a background for the header, without using Themes. + /// + /// + /// + /// + /// + /// + /// + protected void DrawUnthemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot, HeaderStateStyle stateStyle) { + if (stateStyle.BackColor.IsEmpty) + // I know we're supposed to be drawing the unthemed background, but let's just see if we + // can draw something more interesting than the dull raised block + if (VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, r, columnIndex, isPressed, isHot); + else + ControlPaint.DrawBorder3D(g, r, Border3DStyle.RaisedInner); + else { + using (Brush b = new SolidBrush(stateStyle.BackColor)) + g.FillRectangle(b, r); + } + + // Draw the frame if the style asks for one + if (!stateStyle.FrameColor.IsEmpty && stateStyle.FrameWidth > 0f) { + RectangleF r2 = r; + r2.Inflate(-stateStyle.FrameWidth, -stateStyle.FrameWidth); + using (Pen pen = new Pen(stateStyle.FrameColor, stateStyle.FrameWidth)) + g.DrawRectangle(pen, r2.X, r2.Y, r2.Width, r2.Height); + } + } + + /// + /// Draw a more-or-less pure themed header background. + /// + /// + /// + /// + /// + /// + protected void DrawThemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot) { + int part = 1; // normal item + if (columnIndex == 0 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemLeft.Normal)) + part = 2; // left item + if (columnIndex == this.ListView.Columns.Count - 1 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemRight.Normal)) + part = 3; // right item + + int state = 1; // normal state + if (isPressed) + state = 3; // pressed + else if (isHot) + state = 2; // hot + + VisualStyleRenderer renderer = new VisualStyleRenderer("HEADER", part, state); + renderer.DrawBackground(g, r); + } + + /// + /// Draw a sort indicator using themes + /// + /// + /// + protected void DrawThemedSortIndicator(Graphics g, Rectangle r) { + VisualStyleRenderer renderer2 = null; + if (this.ListView.LastSortOrder == SortOrder.Ascending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedUp); + if (this.ListView.LastSortOrder == SortOrder.Descending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedDown); + if (renderer2 != null) { + Size sz = renderer2.GetPartSize(g, ThemeSizeType.True); + Point pt = renderer2.GetPoint(PointProperty.Offset); + // GetPoint() should work, but if it doesn't, put the arrow in the top middle + if (pt.X == 0 && pt.Y == 0) + pt = new Point(r.X + (r.Width/2) - (sz.Width/2), r.Y); + renderer2.DrawBackground(g, new Rectangle(pt, sz)); + } + } + + /// + /// Draw a sort indicator without using themes + /// + /// + /// + /// + protected Rectangle DrawUnthemedSortIndicator(Graphics g, Rectangle r) { + // No theme support for sort indicators. So, we draw a triangle at the right edge + // of the column header. + const int triangleHeight = 16; + const int triangleWidth = 16; + const int midX = triangleWidth/2; + const int midY = (triangleHeight/2) - 1; + const int deltaX = midX - 2; + const int deltaY = deltaX/2; + + Point triangleLocation = new Point(r.Right - triangleWidth - 2, r.Top + (r.Height - triangleHeight)/2); + Point[] pts = new Point[] {triangleLocation, triangleLocation, triangleLocation}; + + if (this.ListView.LastSortOrder == SortOrder.Ascending) { + pts[0].Offset(midX - deltaX, midY + deltaY); + pts[1].Offset(midX, midY - deltaY - 1); + pts[2].Offset(midX + deltaX, midY + deltaY); + } else { + pts[0].Offset(midX - deltaX, midY - deltaY); + pts[1].Offset(midX, midY + deltaY); + pts[2].Offset(midX + deltaX, midY - deltaY); + } + + g.FillPolygon(Brushes.SlateGray, pts); + r.Width = r.Width - triangleWidth; + return r; + } + + /// + /// Draw an indication that this column has a filter applied to it + /// + /// + /// + /// + protected Rectangle DrawFilterIndicator(Graphics g, Rectangle r) { + int width = this.CalculateFilterIndicatorWidth(r); + if (width <= 0) + return r; + + Image indicator = Resources.ColumnFilterIndicator; + int x = r.Right - width; + int y = r.Top + (r.Height - indicator.Height)/2; + g.DrawImageUnscaled(indicator, x, y); + + r.Width -= width; + return r; + } + + private int CalculateFilterIndicatorWidth(Rectangle r) { + if (Resources.ColumnFilterIndicator == null || r.Width < 48) + return 0; + return Resources.ColumnFilterIndicator.Width + 1; + } + + /// + /// Draw the header's image and text + /// + /// + /// + /// + /// + protected void DrawHeaderImageAndText(Graphics g, Rectangle r, OLVColumn column, HeaderStateStyle stateStyle) { + + TextFormatFlags flags = this.TextFormatFlags; + flags |= TextFormatFlags.VerticalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + flags |= TextFormatFlags.HorizontalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + flags |= TextFormatFlags.Right; + + Font f = this.ListView.HeaderUsesThemes ? this.ListView.Font : stateStyle.Font ?? this.ListView.Font; + Color color = this.ListView.HeaderUsesThemes ? Color.Black : stateStyle.ForeColor; + if (color.IsEmpty) + color = Color.Black; + + const int imageTextGap = 3; + + if (column.IsHeaderVertical) { + DrawVerticalText(g, r, column, f, color); + } else { + // Does the column have a header image and is there space for it? + if (column.HasHeaderImage && r.Width > column.ImageList.ImageSize.Width*2) + DrawImageAndText(g, r, column, flags, f, color, imageTextGap); + else + DrawText(g, r, column, flags, f, color); + } + } + + private void DrawText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, Color color) { + if (column.ShowTextInHeader) + TextRenderer.DrawText(g, column.Text, f, r, color, Color.Transparent, flags); + } + + private void DrawImageAndText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, + Color color, int imageTextGap) { + Rectangle textRect = r; + textRect.X += (column.ImageList.ImageSize.Width + imageTextGap); + textRect.Width -= (column.ImageList.ImageSize.Width + imageTextGap); + + Size textSize = Size.Empty; + if (column.ShowTextInHeader) + textSize = TextRenderer.MeasureText(g, column.Text, f, textRect.Size, flags); + + int imageY = r.Top + ((r.Height - column.ImageList.ImageSize.Height)/2); + int imageX = textRect.Left; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + imageX = textRect.Left + ((textRect.Width - textSize.Width)/2); + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + imageX = textRect.Right - textSize.Width; + imageX -= (column.ImageList.ImageSize.Width + imageTextGap); + + column.ImageList.Draw(g, imageX, imageY, column.ImageList.Images.IndexOfKey(column.HeaderImageKey)); + + this.DrawText(g, textRect, column, flags, f, color); + } + + private static void DrawVerticalText(Graphics g, Rectangle r, OLVColumn column, Font f, Color color) { + try { + // Create a matrix transformation that will rotate the text 90 degrees vertically + // AND place the text in the middle of where it was previously. [Think of tipping + // a box over by its bottom left edge -- you have to move it back a bit so it's + // in the same place as it started] + Matrix m = new Matrix(); + m.RotateAt(-90, new Point(r.X, r.Bottom)); + m.Translate(0, r.Height); + g.Transform = m; + StringFormat fmt = new StringFormat(StringFormatFlags.NoWrap); + fmt.Alignment = StringAlignment.Near; + fmt.LineAlignment = column.HeaderTextAlignAsStringAlignment; + //fmt.Trimming = StringTrimming.EllipsisCharacter; + + // The drawing is rotated 90 degrees, so switch our text boundaries + Rectangle textRect = r; + textRect.Width = r.Height; + textRect.Height = r.Width; + using (Brush b = new SolidBrush(color)) + g.DrawString(column.Text, f, b, textRect, fmt); + } + finally { + g.ResetTransform(); + } + } + + /// + /// Return the header format that should be used for the given column + /// + /// + /// + protected HeaderFormatStyle CalculateHeaderStyle(OLVColumn column) { + return column.HeaderFormatStyle ?? this.ListView.HeaderFormatStyle ?? new HeaderFormatStyle(); + } + + /// + /// What style should be applied to the header? + /// + /// + /// + /// + /// + protected HeaderStateStyle CalculateStateStyle(OLVColumn column, bool isHot, bool isPressed) { + HeaderFormatStyle headerStyle = this.CalculateHeaderStyle(column); + if (this.ListView.IsDesignMode) + return headerStyle.Normal; + if (isPressed) + return headerStyle.Pressed; + if (isHot) + return headerStyle.Hot; + return headerStyle.Normal; + } + + /// + /// What font should be used to draw the header text? + /// + /// + /// + /// + /// + protected Font CalculateFont(OLVColumn column, bool isHot, bool isPressed) { + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + return stateStyle.Font ?? this.ListView.Font; + } + + /// + /// What flags will be used when drawing text + /// + protected TextFormatFlags TextFormatFlags { + get { + TextFormatFlags flags = TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPrefix | + TextFormatFlags.WordEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.WordWrap) + flags |= TextFormatFlags.WordBreak; + else + flags |= TextFormatFlags.SingleLine; + if (this.ListView.RightToLeft == RightToLeft.Yes) + flags |= TextFormatFlags.RightToLeft; + + return flags; + } + } + + /// + /// Perform a HitTest for the header control + /// + /// + /// + /// Null if the given point isn't over the header + internal OlvListViewHitTestInfo.HeaderHitTestInfo HitTest(int x, int y) + { + Rectangle r = this.ClientRectangle; + if (!r.Contains(x, y)) + return null; + + Point pt = new Point(x + this.ListView.LowLevelScrollPosition.X, y); + + OlvListViewHitTestInfo.HeaderHitTestInfo hti = new OlvListViewHitTestInfo.HeaderHitTestInfo(); + hti.ColumnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + hti.IsOverCheckBox = this.IsPointOverHeaderCheckBox(hti.ColumnIndex, pt); + hti.OverDividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + + return hti; + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolStripCheckedListBox.cs b/ObjectListView/SubControls/ToolStripCheckedListBox.cs new file mode 100644 index 0000000..e8eab01 --- /dev/null +++ b/ObjectListView/SubControls/ToolStripCheckedListBox.cs @@ -0,0 +1,189 @@ +/* + * ToolStripCheckedListBox - Puts a CheckedListBox into a tool strip menu item + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class put a CheckedListBox into a tool strip menu item. + /// + public class ToolStripCheckedListBox : ToolStripControlHost { + + /// + /// Create a ToolStripCheckedListBox + /// + public ToolStripCheckedListBox() + : base(new CheckedListBox()) { + this.CheckedListBoxControl.MaximumSize = new Size(400, 700); + this.CheckedListBoxControl.ThreeDCheckBoxes = true; + this.CheckedListBoxControl.CheckOnClick = true; + this.CheckedListBoxControl.SelectionMode = SelectionMode.One; + } + + /// + /// Gets the control embedded in the menu + /// + public CheckedListBox CheckedListBoxControl { + get { + return Control as CheckedListBox; + } + } + + /// + /// Gets the items shown in the checkedlistbox + /// + public CheckedListBox.ObjectCollection Items { + get { + return this.CheckedListBoxControl.Items; + } + } + + /// + /// Gets or sets whether an item should be checked when it is clicked + /// + public bool CheckedOnClick { + get { + return this.CheckedListBoxControl.CheckOnClick; + } + set { + this.CheckedListBoxControl.CheckOnClick = value; + } + } + + /// + /// Gets a collection of the checked items + /// + public CheckedListBox.CheckedItemCollection CheckedItems { + get { + return this.CheckedListBoxControl.CheckedItems; + } + } + + /// + /// Add a possibly checked item to the control + /// + /// + /// + public void AddItem(object item, bool isChecked) { + this.Items.Add(item); + if (isChecked) + this.CheckedListBoxControl.SetItemChecked(this.Items.Count - 1, true); + } + + /// + /// Add an item with the given state to the control + /// + /// + /// + public void AddItem(object item, CheckState state) { + this.Items.Add(item); + this.CheckedListBoxControl.SetItemCheckState(this.Items.Count - 1, state); + } + + /// + /// Gets the checkedness of the i'th item + /// + /// + /// + public CheckState GetItemCheckState(int i) { + return this.CheckedListBoxControl.GetItemCheckState(i); + } + + /// + /// Set the checkedness of the i'th item + /// + /// + /// + public void SetItemState(int i, CheckState checkState) { + if (i >= 0 && i < this.Items.Count) + this.CheckedListBoxControl.SetItemCheckState(i, checkState); + } + + /// + /// Check all the items in the control + /// + public void CheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, true); + } + + /// + /// Unchecked all the items in the control + /// + public void UncheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, false); + } + + #region Events + + /// + /// Listen for events on the underlying control + /// + /// + protected override void OnSubscribeControlEvents(Control c) { + base.OnSubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck += new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Stop listening for events on the underlying control + /// + /// + protected override void OnUnsubscribeControlEvents(Control c) { + base.OnUnsubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck -= new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Tell the world that an item was checked + /// + public event ItemCheckEventHandler ItemCheck; + + /// + /// Trigger the ItemCheck event + /// + /// + /// + private void OnItemCheck(object sender, ItemCheckEventArgs e) { + if (ItemCheck != null) { + ItemCheck(this, e); + } + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolTipControl.cs b/ObjectListView/SubControls/ToolTipControl.cs new file mode 100644 index 0000000..22c1f63 --- /dev/null +++ b/ObjectListView/SubControls/ToolTipControl.cs @@ -0,0 +1,699 @@ +/* + * ToolTipControl - A limited wrapper around a Windows tooltip control + * + * For some reason, the ToolTip class in the .NET framework is implemented in a significantly + * different manner to other controls. For our purposes, the worst of these problems + * is that we cannot get the Handle, so we cannot send Windows level messages to the control. + * + * Author: Phillip Piper + * Date: 2009-05-17 7:22PM + * + * Change log: + * v2.3 + * 2009-06-13 JPP - Moved ToolTipShowingEventArgs to Events.cs + * v2.2 + * 2009-06-06 JPP - Fixed some Vista specific problems + * 2009-05-17 JPP - Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using System.Security.Permissions; + +namespace BrightIdeasSoftware +{ + /// + /// A limited wrapper around a Windows tooltip window. + /// + public class ToolTipControl : NativeWindow + { + #region Constants + + /// + /// These are the standard icons that a tooltip can display. + /// + public enum StandardIcons + { + /// + /// No icon + /// + None = 0, + + /// + /// Info + /// + Info = 1, + + /// + /// Warning + /// + Warning = 2, + + /// + /// Error + /// + Error = 3, + + /// + /// Large info (Vista and later only) + /// + InfoLarge = 4, + + /// + /// Large warning (Vista and later only) + /// + WarningLarge = 5, + + /// + /// Large error (Vista and later only) + /// + ErrorLarge = 6 + } + + const int GWL_STYLE = -16; + const int WM_GETFONT = 0x31; + const int WM_SETFONT = 0x30; + const int WS_BORDER = 0x800000; + const int WS_EX_TOPMOST = 8; + + const int TTM_ADDTOOL = 0x432; + const int TTM_ADJUSTRECT = 0x400 + 31; + const int TTM_DELTOOL = 0x433; + const int TTM_GETBUBBLESIZE = 0x400 + 30; + const int TTM_GETCURRENTTOOL = 0x400 + 59; + const int TTM_GETTIPBKCOLOR = 0x400 + 22; + const int TTM_GETTIPTEXTCOLOR = 0x400 + 23; + const int TTM_GETDELAYTIME = 0x400 + 21; + const int TTM_NEWTOOLRECT = 0x400 + 52; + const int TTM_POP = 0x41c; + const int TTM_SETDELAYTIME = 0x400 + 3; + const int TTM_SETMAXTIPWIDTH = 0x400 + 24; + const int TTM_SETTIPBKCOLOR = 0x400 + 19; + const int TTM_SETTIPTEXTCOLOR = 0x400 + 20; + const int TTM_SETTITLE = 0x400 + 33; + const int TTM_SETTOOLINFO = 0x400 + 54; + + const int TTF_IDISHWND = 1; + //const int TTF_ABSOLUTE = 0x80; + const int TTF_CENTERTIP = 2; + const int TTF_RTLREADING = 4; + const int TTF_SUBCLASS = 0x10; + //const int TTF_TRACK = 0x20; + //const int TTF_TRANSPARENT = 0x100; + const int TTF_PARSELINKS = 0x1000; + + const int TTS_NOPREFIX = 2; + const int TTS_BALLOON = 0x40; + const int TTS_USEVISUALSTYLE = 0x100; + + const int TTN_FIRST = -520; + + /// + /// + /// + public const int TTN_SHOW = (TTN_FIRST - 1); + + /// + /// + /// + public const int TTN_POP = (TTN_FIRST - 2); + + /// + /// + /// + public const int TTN_LINKCLICK = (TTN_FIRST - 3); + + /// + /// + /// + public const int TTN_GETDISPINFO = (TTN_FIRST - 10); + + const int TTDT_AUTOMATIC = 0; + const int TTDT_RESHOW = 1; + const int TTDT_AUTOPOP = 2; + const int TTDT_INITIAL = 3; + + #endregion + + #region Properties + + /// + /// Get or set if the style of the tooltip control + /// + internal int WindowStyle { + get { + return (int)NativeMethods.GetWindowLong(this.Handle, GWL_STYLE); + } + set { + NativeMethods.SetWindowLong(this.Handle, GWL_STYLE, value); + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool IsBalloon { + get { + return (this.WindowStyle & TTS_BALLOON) == TTS_BALLOON; + } + set { + if (this.IsBalloon == value) + return; + + int windowStyle = this.WindowStyle; + if (value) { + windowStyle |= (TTS_BALLOON | TTS_USEVISUALSTYLE); + // On XP, a border makes the balloon look wrong + if (!ObjectListView.IsVistaOrLater) + windowStyle &= ~WS_BORDER; + } else { + windowStyle &= ~(TTS_BALLOON | TTS_USEVISUALSTYLE); + if (!ObjectListView.IsVistaOrLater) { + if (this.hasBorder) + windowStyle |= WS_BORDER; + else + windowStyle &= ~WS_BORDER; + } + } + this.WindowStyle = windowStyle; + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool HasBorder { + get { + return this.hasBorder; + } + set { + if (this.hasBorder == value) + return; + + if (value) { + this.WindowStyle |= WS_BORDER; + } else { + this.WindowStyle &= ~WS_BORDER; + } + } + } + private bool hasBorder = true; + + /// + /// Get or set the background color of the tooltip + /// + public Color BackColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPBKCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPBKCOLOR, color, 0); + //int x2 = Marshal.GetLastWin32Error(); + } + } + } + + /// + /// Get or set the color of the text and border on the tooltip. + /// + public Color ForeColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPTEXTCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPTEXTCOLOR, color, 0); + } + } + } + + /// + /// Get or set the title that will be shown on the tooltip. + /// + public string Title { + get { + return this.title; + } + set { + if (String.IsNullOrEmpty(value)) + this.title = String.Empty; + else + if (value.Length >= 100) + this.title = value.Substring(0, 99); + else + this.title = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private string title; + + /// + /// Get or set the icon that will be shown on the tooltip. + /// + public StandardIcons StandardIcon { + get { + return this.standardIcon; + } + set { + this.standardIcon = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private StandardIcons standardIcon; + + /// + /// Gets or sets the font that will be used to draw this control. + /// is still. + /// + /// Setting this to null reverts to the default font. + public Font Font { + get { + IntPtr hfont = NativeMethods.SendMessage(this.Handle, WM_GETFONT, 0, 0); + if (hfont == IntPtr.Zero) + return Control.DefaultFont; + else + return Font.FromHfont(hfont); + } + set { + Font newFont = value ?? Control.DefaultFont; + if (newFont == this.font) + return; + + this.font = newFont; + IntPtr hfont = this.font.ToHfont(); // THINK: When should we delete this hfont? + NativeMethods.SendMessage(this.Handle, WM_SETFONT, hfont, 0); + } + } + private Font font; + + /// + /// Gets or sets how many milliseconds the tooltip will remain visible while the mouse + /// is still. + /// + public int AutoPopDelay { + get { return this.GetDelayTime(TTDT_AUTOPOP); } + set { this.SetDelayTime(TTDT_AUTOPOP, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown. + /// + public int InitialDelay { + get { return this.GetDelayTime(TTDT_INITIAL); } + set { this.SetDelayTime(TTDT_INITIAL, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown again. + /// + public int ReshowDelay { + get { return this.GetDelayTime(TTDT_RESHOW); } + set { this.SetDelayTime(TTDT_RESHOW, value); } + } + + private int GetDelayTime(int which) { + return (int)NativeMethods.SendMessage(this.Handle, TTM_GETDELAYTIME, which, 0); + } + + private void SetDelayTime(int which, int value) { + NativeMethods.SendMessage(this.Handle, TTM_SETDELAYTIME, which, value); + } + + #endregion + + #region Commands + + /// + /// Create the underlying control. + /// + /// The parent of the tooltip + /// This does nothing if the control has already been created + public void Create(IntPtr parentHandle) { + if (this.Handle != IntPtr.Zero) + return; + + CreateParams cp = new CreateParams(); + cp.ClassName = "tooltips_class32"; + cp.Style = TTS_NOPREFIX; + cp.ExStyle = WS_EX_TOPMOST; + cp.Parent = parentHandle; + this.CreateHandle(cp); + + // Ensure that multiline tooltips work correctly + this.SetMaxWidth(); + } + + /// + /// Take a copy of the current settings and restore them when the + /// tooltip is popped. + /// + /// + /// This call cannot be nested. Subsequent calls to this method will be ignored + /// until PopSettings() is called. + /// + public void PushSettings() { + // Ignore any nested calls + if (this.settings != null) + return; + this.settings = new Hashtable(); + this.settings["IsBalloon"] = this.IsBalloon; + this.settings["HasBorder"] = this.HasBorder; + this.settings["BackColor"] = this.BackColor; + this.settings["ForeColor"] = this.ForeColor; + this.settings["Title"] = this.Title; + this.settings["StandardIcon"] = this.StandardIcon; + this.settings["AutoPopDelay"] = this.AutoPopDelay; + this.settings["InitialDelay"] = this.InitialDelay; + this.settings["ReshowDelay"] = this.ReshowDelay; + this.settings["Font"] = this.Font; + } + private Hashtable settings; + + /// + /// Restore the settings of the tooltip as they were when PushSettings() + /// was last called. + /// + public void PopSettings() { + if (this.settings == null) + return; + + this.IsBalloon = (bool)this.settings["IsBalloon"]; + this.HasBorder = (bool)this.settings["HasBorder"]; + this.BackColor = (Color)this.settings["BackColor"]; + this.ForeColor = (Color)this.settings["ForeColor"]; + this.Title = (string)this.settings["Title"]; + this.StandardIcon = (StandardIcons)this.settings["StandardIcon"]; + this.AutoPopDelay = (int)this.settings["AutoPopDelay"]; + this.InitialDelay = (int)this.settings["InitialDelay"]; + this.ReshowDelay = (int)this.settings["ReshowDelay"]; + this.Font = (Font)this.settings["Font"]; + + this.settings = null; + } + + /// + /// Add the given window to those for whom this tooltip will show tips + /// + /// The window + public void AddTool(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_ADDTOOL, 0, lParam); + } + + /// + /// Hide any currently visible tooltip + /// + /// + public void PopToolTip(IWin32Window window) { + NativeMethods.SendMessage(this.Handle, TTM_POP, 0, 0); + } + + //public void Munge() { + // NativeMethods.TOOLINFO tool = new NativeMethods.TOOLINFO(); + // IntPtr result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETCURRENTTOOL, 0, tool); + // System.Diagnostics.Trace.WriteLine("-"); + // System.Diagnostics.Trace.WriteLine(result); + // result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETBUBBLESIZE, 0, tool); + // System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", result.ToInt32() >> 16, result.ToInt32() & 0xFFFF)); + // NativeMethods.ChangeSize(this, result.ToInt32() & 0xFFFF, result.ToInt32() >> 16); + // //NativeMethods.RECT r = new NativeMethods.RECT(); + // //r.right + // //IntPtr x = NativeMethods.SendMessageRECT(this.Handle, TTM_ADJUSTRECT, true, ref r); + + // //System.Diagnostics.Trace.WriteLine(String.Format("{0} {1} {2} {3}", r.left, r.top, r.right, r.bottom)); + //} + + /// + /// Remove the given window from those managed by this tooltip + /// + /// + public void RemoveToolTip(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_DELTOOL, 0, lParam); + } + + /// + /// Set the maximum width of a tooltip string. + /// + public void SetMaxWidth() { + this.SetMaxWidth(SystemInformation.MaxWindowTrackSize.Width); + } + + /// + /// Set the maximum width of a tooltip string. + /// + /// Setting this ensures that line breaks in the tooltip are honoured. + public void SetMaxWidth(int maxWidth) { + NativeMethods.SendMessage(this.Handle, TTM_SETMAXTIPWIDTH, 0, maxWidth); + } + + #endregion + + #region Implementation + + /// + /// Make a TOOLINFO structure for the given window + /// + /// + /// A filled in TOOLINFO + private NativeMethods.TOOLINFO MakeToolInfoStruct(IWin32Window window) { + + NativeMethods.TOOLINFO toolinfo_tooltip = new NativeMethods.TOOLINFO(); + toolinfo_tooltip.hwnd = window.Handle; + toolinfo_tooltip.uFlags = TTF_IDISHWND | TTF_SUBCLASS; + toolinfo_tooltip.uId = window.Handle; + toolinfo_tooltip.lpszText = (IntPtr)(-1); // LPSTR_TEXTCALLBACK + + return toolinfo_tooltip; + } + + /// + /// Handle a WmNotify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleNotify(ref Message msg) { + + //THINK: What do we have to do here? Nothing it seems :) + + //NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Trace.WriteLine("HandleNotify"); + //System.Diagnostics.Trace.WriteLine(nmheader.nhdr.code); + + //switch (nmheader.nhdr.code) { + //} + + return false; + } + + /// + /// Handle a get display info message + /// + /// The msg + /// True if the message has been handled + public virtual bool HandleGetDispInfo(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleGetDispInfo"); + this.SetMaxWidth(); + ToolTipShowingEventArgs args = new ToolTipShowingEventArgs(); + args.ToolTipControl = this; + this.OnShowing(args); + if (String.IsNullOrEmpty(args.Text)) + return false; + + this.ApplyEventFormatting(args); + + NativeMethods.NMTTDISPINFO dispInfo = (NativeMethods.NMTTDISPINFO)msg.GetLParam(typeof(NativeMethods.NMTTDISPINFO)); + dispInfo.lpszText = args.Text; + dispInfo.hinst = IntPtr.Zero; + if (args.RightToLeft == RightToLeft.Yes) + dispInfo.uFlags |= TTF_RTLREADING; + Marshal.StructureToPtr(dispInfo, msg.LParam, false); + + return true; + } + + private void ApplyEventFormatting(ToolTipShowingEventArgs args) { + if (!args.IsBalloon.HasValue && + !args.BackColor.HasValue && + !args.ForeColor.HasValue && + args.Title == null && + !args.StandardIcon.HasValue && + !args.AutoPopDelay.HasValue && + args.Font == null) + return; + + this.PushSettings(); + if (args.IsBalloon.HasValue) + this.IsBalloon = args.IsBalloon.Value; + if (args.BackColor.HasValue) + this.BackColor = args.BackColor.Value; + if (args.ForeColor.HasValue) + this.ForeColor = args.ForeColor.Value; + if (args.StandardIcon.HasValue) + this.StandardIcon = args.StandardIcon.Value; + if (args.AutoPopDelay.HasValue) + this.AutoPopDelay = args.AutoPopDelay.Value; + if (args.Font != null) + this.Font = args.Font; + if (args.Title != null) + this.Title = args.Title; + } + + /// + /// Handle a TTN_LINKCLICK message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleLinkClick(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleLinkClick"); + return false; + } + + /// + /// Handle a TTN_POP message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandlePop(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandlePop"); + this.PopSettings(); + return true; + } + + /// + /// Handle a TTN_SHOW message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleShow(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleShow"); + return false; + } + + /// + /// Handle a reflected notify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleReflectNotify(ref Message msg) { + + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + switch (nmheader.nhdr.code) { + case TTN_SHOW: + //System.Diagnostics.Trace.WriteLine("reflect TTN_SHOW"); + if (this.HandleShow(ref msg)) + return true; + break; + case TTN_POP: + //System.Diagnostics.Trace.WriteLine("reflect TTN_POP"); + if (this.HandlePop(ref msg)) + return true; + break; + case TTN_LINKCLICK: + //System.Diagnostics.Trace.WriteLine("reflect TTN_LINKCLICK"); + if (this.HandleLinkClick(ref msg)) + return true; + break; + case TTN_GETDISPINFO: + //System.Diagnostics.Trace.WriteLine("reflect TTN_GETDISPINFO"); + if (this.HandleGetDispInfo(ref msg)) + return true; + break; + } + + return false; + } + + /// + /// Mess with the basic message pump of the tooltip + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + override protected void WndProc(ref Message msg) { + //System.Diagnostics.Trace.WriteLine(String.Format("xx {0:x}", msg.Msg)); + switch (msg.Msg) { + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref msg)) + return; + break; + + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref msg)) + return; + break; + } + + base.WndProc(ref msg); + } + + #endregion + + #region Events + + /// + /// Tell the world that a tooltip is about to show + /// + public event EventHandler Showing; + + /// + /// Tell the world that a tooltip is about to disappear + /// + public event EventHandler Pop; + + /// + /// + /// + /// + protected virtual void OnShowing(ToolTipShowingEventArgs e) { + if (this.Showing != null) + this.Showing(this, e); + } + + /// + /// + /// + /// + protected virtual void OnPop(EventArgs e) { + if (this.Pop != null) + this.Pop(this, e); + } + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/TreeListView.cs b/ObjectListView/TreeListView.cs new file mode 100644 index 0000000..0b52c63 --- /dev/null +++ b/ObjectListView/TreeListView.cs @@ -0,0 +1,2269 @@ +/* + * TreeListView - A listview that can show a tree of objects in a column + * + * Author: Phillip Piper + * Date: 23/09/2008 11:15 AM + * + * Change log: + * 2018-05-03 JPP - Added ITreeModel to allow models to provide the required information to TreeListView. + * 2018-04-30 JPP - Fix small visual glitch where connecting lines were not correctly drawn when filters changed + * v2.9.2 + * 2016-06-02 JPP - Added bounds check to GetNthObject(). + * v2.9 + * 2015-08-02 JPP - Fixed buy with hierarchical checkboxes where setting the checkedness of a deeply + * nested object would sometimes not correctly calculate the changes in the hierarchy. SF #150. + * 2015-06-27 JPP - Corrected small UI glitch when focus was lost and HideSelection was false. SF #135. + * v2.8.1 + * 2014-11-28 JPP - Fixed issue in RefreshObject() where a model with less children than previous that could not + * longer be expanded would cause an exception. + * 2014-11-23 JPP - Fixed an issue where collapsing a branch could leave the internal object->index map out of date. + * v2.8 + * 2014-10-08 JPP - Fixed an issue where pre-expanded branches would not initially expand properly + * 2014-09-29 JPP - Fixed issue where RefreshObject() on a root object could cause exceptions + * - Fixed issue where CollapseAll() while filtering could cause exception + * 2014-03-09 JPP - Fixed issue where removing a branches only child and then calling RefreshObject() + * could throw an exception. + * v2.7 + * 2014-02-23 JPP - Added Reveal() method to show a deeply nested models. + * 2014-02-05 JPP - Fix issue where refreshing a non-root item would collapse all expanded children of that item + * 2014-02-01 JPP - ClearObjects() now actually, you know, clears objects :) + * - Corrected issue where Expanded event was being raised twice. + * - RebuildChildren() no longer checks if CanExpand is true before rebuilding. + * 2014-01-16 JPP - Corrected an off-by-1 error in hit detection, which meant that clicking in the last 16 pixels + * of an items label was being ignored. + * 2013-11-20 JPP - Moved event triggers into Collapse() and Expand() so that the events are always triggered. + * - CheckedObjects now includes objects that are in a branch that is currently collapsed + * - CollapseAll() and ExpandAll() now trigger cancellable events + * 2013-09-29 JPP - Added TreeFactory to allow the underlying Tree to be replaced by another implementation. + * 2013-09-23 JPP - Fixed long standing issue where RefreshObject() would not work on root objects + * which overrode Equals()/GetHashCode(). + * 2013-02-23 JPP - Added HierarchicalCheckboxes. When this is true, the checkedness of a parent + * is an synopsis of the checkedness of its children. When all children are checked, + * the parent is checked. When all children are unchecked, the parent is unchecked. + * If some children are checked and some are not, the parent is indeterminate. + * v2.6 + * 2012-10-25 JPP - Circumvent annoying issue in ListView control where changing + * selection would leave artefacts on the control. + * 2012-08-10 JPP - Don't trigger selection changed events during expands + * + * v2.5.1 + * 2012-04-30 JPP - Fixed issue where CheckedObjects would return model objects that had been filtered out. + * - Allow any column to render the tree, not just column 0 (still not sure about this one) + * v2.5.0 + * 2011-04-20 JPP - Added ExpandedObjects property and RebuildAll() method. + * 2011-04-09 JPP - Added Expanding, Collapsing, Expanded and Collapsed events. + * The ..ing events are cancellable. These are only fired in response + * to user actions. + * v2.4.1 + * 2010-06-15 JPP - Fixed issue in Tree.RemoveObjects() which resulted in removed objects + * being reported as still existing. + * v2.3 + * 2009-09-01 JPP - Fixed off-by-one error that was messing up hit detection + * 2009-08-27 JPP - Fixed issue when dragging a node from one place to another in the tree + * v2.2.1 + * 2009-07-14 JPP - Clicks to the left of the expander in tree cells are now ignored. + * v2.2 + * 2009-05-12 JPP - Added tree traverse operations: GetParent and GetChildren. + * - Added DiscardAllState() to completely reset the TreeListView. + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-09 JPP - Fixed issue where any command (Expand/Collapse/Refresh) on a model + * object that was once visible but that is currently in a collapsed branch + * would cause the control to crash. + * 2009-05-07 JPP - Fixed issue where RefreshObjects() would fail when none of the given + * objects were present/visible. + * 2009-04-20 JPP - Fixed issue where calling Expand() on an already expanded branch confused + * the display of the children (SF#2499313) + * 2009-03-06 JPP - Calculate edit rectangle on column 0 more accurately + * v2.1 + * 2009-02-24 JPP - All commands now work when the list is empty (SF #2631054) + * - TreeListViews can now be printed with ListViewPrinter + * 2009-01-27 JPP - Changed to use new Renderer and HitTest scheme + * 2009-01-22 JPP - Added RevealAfterExpand property. If this is true (the default), + * after expanding a branch, the control scrolls to reveal as much of the + * expanded branch as possible. + * 2009-01-13 JPP - Changed TreeRenderer to work with visual styles are disabled + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * - Changed some classes from 'internal' to 'protected' so that they + * can be accessed by subclasses of TreeListView. + * 2008-12-22 JPP - Added UseWaitCursorWhenExpanding property + * - Made TreeRenderer public so that it can be subclassed + * - Added LinePen property to TreeRenderer to allow the connection drawing + * pen to be changed + * - Fixed some rendering issues where the text highlight rect was miscalculated + * - Fixed connection line problem when there is only a single root + * v2.0 + * 2008-12-10 JPP - Expand/collapse with mouse now works when there is no SmallImageList. + * 2008-12-01 JPP - Search-by-typing now works. + * 2008-11-26 JPP - Corrected calculation of expand/collapse icon (SF#2338819) + * - Fixed ugliness with dotted lines in renderer (SF#2332889) + * - Fixed problem with custom selection colors (SF#2338805) + * 2008-11-19 JPP - Expand/collapse now preserve the selection -- more or less :) + * - Overrode RefreshObjects() to rebuild the given objects and their children + * 2008-11-05 JPP - Added ExpandAll() and CollapseAll() commands + * - CanExpand is no longer cached + * - Renamed InitialBranches to RootModels since it deals with model objects + * 2008-09-23 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeListView combines an expandable tree structure with list view columns. + /// + /// + /// To support tree operations, two delegates must be provided: + /// + /// + /// + /// CanExpandGetter + /// + /// + /// This delegate must accept a model object and return a boolean indicating + /// if that model should be expandable. + /// + /// + /// + /// + /// ChildrenGetter + /// + /// + /// This delegate must accept a model object and return an IEnumerable of model + /// objects that will be displayed as children of the parent model. This delegate will only be called + /// for a model object if the CanExpandGetter has already returned true for that model. + /// + /// + /// + /// + /// ParentGetter + /// + /// + /// This delegate must accept a model object and return the parent model. + /// This delegate will only be called when HierarchicalCheckboxes is true OR when Reveal() is called. + /// + /// + /// + /// + /// The top level branches of the tree are set via the Roots property. SetObjects(), AddObjects() + /// and RemoveObjects() are interpreted as operations on this collection of roots. + /// + /// + /// To add new children to an existing branch, make changes to your model objects and then + /// call RefreshObject() on the parent. + /// + /// The tree must be a directed acyclic graph -- no cycles are allowed. Put more mundanely, + /// each model object must appear only once in the tree. If the same model object appears in two + /// places in the tree, the control will become confused. + /// + public partial class TreeListView : VirtualObjectListView + { + /// + /// Make a default TreeListView + /// + public TreeListView() { + this.OwnerDraw = true; + this.View = View.Details; + this.CheckedObjectsMustStillExistInList = false; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.RegenerateTree(); + this.TreeColumnRenderer = new TreeRenderer(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + + // This improves hit detection even if we don't have any state image + this.SmallImageList = new ImageList(); + // this.StateImageList.ImageSize = new Size(6, 6); + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + /// + /// + /// This is called *often* -- on every mouse move when required. It must be fast. + /// Don't do database lookups, linear searches, or pi calculations. Just return the + /// value of a property. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't make + /// calls back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CanExpandGetterDelegate CanExpandGetter { + get { return this.TreeModel.CanExpandGetter; } + set { this.TreeModel.CanExpandGetter = value; } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + return false; + } + } + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't do anything + /// that will result in calls being made back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ChildrenGetterDelegate ChildrenGetter { + get { return this.TreeModel.ChildrenGetter; } + set { this.TreeModel.ChildrenGetter = value; } + } + + /// + /// This is the delegate that will be used to fetch the parent of a model object + /// + /// The parent of the given model, or null if the model doesn't exist or + /// if the model is a root + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ParentGetterDelegate ParentGetter { + get { return parentGetter ?? Tree.DefaultParentGetter; } + set { parentGetter = value; } + } + private ParentGetterDelegate parentGetter; + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + public override IList CheckedObjects { + get { + return base.CheckedObjects; + } + set { + ArrayList objectsToRecalculate = new ArrayList(this.CheckedObjects); + if (value != null) + objectsToRecalculate.AddRange(value); + + base.CheckedObjects = value; + + if (this.HierarchicalCheckboxes) + RecalculateHierarchicalCheckBoxGraph(objectsToRecalculate); + } + } + + /// + /// Gets or sets the model objects that are expanded. + /// + /// + /// This can be used to expand model objects before they are seen. + /// + /// Setting this does *not* force the control to rebuild + /// its display. You need to call RebuildAll(true). + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable ExpandedObjects { + get { + return this.TreeModel.mapObjectToExpanded.Keys; + } + set { + this.TreeModel.mapObjectToExpanded.Clear(); + if (value != null) { + foreach (object x in value) + this.TreeModel.SetModelExpanded(x, true); + } + } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// TreeListViews do not currently support whole list filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IListFilter ListFilter { + get { return null; } + set { + System.Diagnostics.Debug.Assert(value == null, "TreeListView do not support ListFilters"); + } + } + + /// + /// Gets or sets whether this tree list view will display hierarchical checkboxes. + /// Hierarchical checkboxes is when a parent's "checkedness" is calculated from + /// the "checkedness" of its children. If all children are checked, the parent + /// will be checked. If all children are unchecked, the parent will also be unchecked. + /// If some children are checked and others are not, the parent will be indeterminate. + /// + /// + /// Hierarchical checkboxes don't work with either CheckStateGetters or CheckedAspectName + /// (which is basically the same thing). This is because it is too expensive to build the + /// initial state of the control if these are installed, since the control would have to walk + /// *every* branch recursively since a single bottom level leaf could change the checkedness + /// of the top root. + /// + [Category("ObjectListView"), + Description("Show hierarchical checkboxes be enabled?"), + DefaultValue(false)] + public virtual bool HierarchicalCheckboxes { + get { return this.hierarchicalCheckboxes; } + set { + if (this.hierarchicalCheckboxes == value) + return; + + this.hierarchicalCheckboxes = value; + this.CheckBoxes = value; + if (value) + this.TriStateCheckBoxes = false; + } + } + private bool hierarchicalCheckboxes; + + /// + /// Gets or sets the collection of root objects of the tree + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { return this.Roots; } + set { this.Roots = value; } + } + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable ObjectsForClustering { + get { + for (int i = 0; i < this.TreeModel.GetObjectCount(); i++) + yield return this.TreeModel.GetNthObject(i); + } + } + + /// + /// After expanding a branch, should the TreeListView attempts to show as much of the + /// revealed descendants as possible. + /// + [Category("ObjectListView"), + Description("Should the parent of an expand subtree be scrolled to the top revealing the children?"), + DefaultValue(true)] + public bool RevealAfterExpand { + get { return revealAfterExpand; } + set { revealAfterExpand = value; } + } + private bool revealAfterExpand = true; + + /// + /// The model objects that form the top level branches of the tree. + /// + /// Setting this does NOT reset the state of the control. + /// In particular, it does not collapse branches. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Roots { + get { return this.TreeModel.RootObjects; } + set { + this.TreeColumnRenderer = this.TreeColumnRenderer; + this.TreeModel.RootObjects = value ?? new ArrayList(); + this.UpdateVirtualListSize(); + } + } + + /// + /// Make sure that at least one column is displaying a tree. + /// If no columns is showing the tree, make column 0 do it. + /// + protected virtual void EnsureTreeRendererPresent(TreeRenderer renderer) { + if (this.Columns.Count == 0) + return; + + foreach (OLVColumn col in this.Columns) { + if (col.Renderer is TreeRenderer) { + col.Renderer = renderer; + return; + } + } + + // No column held a tree renderer, so give column 0 one + OLVColumn columnZero = this.GetColumn(0); + columnZero.Renderer = renderer; + columnZero.WordWrap = columnZero.WordWrap; + } + + /// + /// Gets or sets the renderer that will be used to draw the tree structure. + /// Setting this to null resets the renderer to default. + /// + /// If a column is currently rendering the tree, the renderer + /// for that column will be replaced. If no column is rendering the tree, + /// column 0 will be given this renderer. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual TreeRenderer TreeColumnRenderer { + get { return treeRenderer ?? (treeRenderer = new TreeRenderer()); } + set { + treeRenderer = value ?? new TreeRenderer(); + EnsureTreeRendererPresent(treeRenderer); + } + } + private TreeRenderer treeRenderer; + + /// + /// This is the delegate that will be used to create the underlying Tree structure + /// that the TreeListView uses to manage the information about the tree. + /// + /// + /// The factory must not return null. + /// + /// Most users of TreeListView will never have to use this delegate. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public TreeFactoryDelegate TreeFactory { + get { return treeFactory; } + set { treeFactory = value; } + } + private TreeFactoryDelegate treeFactory; + + /// + /// Should a wait cursor be shown when a branch is being expanded? + /// + /// When this is true, the wait cursor will be shown whilst the children of the + /// branch are being fetched. If the children of the branch have already been cached, + /// the cursor will not change. + [Category("ObjectListView"), + Description("Should a wait cursor be shown when a branch is being expanded?"), + DefaultValue(true)] + public virtual bool UseWaitCursorWhenExpanding { + get { return useWaitCursorWhenExpanding; } + set { useWaitCursorWhenExpanding = value; } + } + private bool useWaitCursorWhenExpanding = true; + + /// + /// Gets the model that is used to manage the tree structure + /// + /// + /// Don't mess with this property unless you really know what you are doing. + /// If you don't already know what it's for, you don't need it. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Tree TreeModel { + get { return this.treeModel; } + protected set { this.treeModel = value; } + } + private Tree treeModel; + + //------------------------------------------------------------------------------------------ + // Accessing + + /// + /// Return true if the branch at the given model is expanded + /// + /// + /// + public virtual bool IsExpanded(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.IsExpanded); + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// + public virtual void Collapse(Object model) { + if (this.GetItemCount() == 0) + return; + + OLVListItem item = this.ModelToItem(model); + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(model, item); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.Collapse(model); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(model, item)); + } + } + + /// + /// Collapse all subtrees within this control + /// + public virtual void CollapseAll() { + if (this.GetItemCount() == 0) + return; + + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(null, null); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.CollapseAll(); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(null, null)); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.Roots = null; + this.DiscardAllState(); + } + } + + /// + /// Collapse all roots and forget everything we know about all models + /// + public virtual void DiscardAllState() { + this.CheckStateMap.Clear(); + this.RebuildAll(false); + } + + /// + /// Expand the subtree underneath the given model object + /// + /// + public virtual void Expand(Object model) { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + OLVListItem item = this.ModelToItem(model); + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(model, item); + this.OnExpanding(args); + if (args.Canceled) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // Expand the model first + int index = this.TreeModel.Expand(model); + if (index < 0) + return; + + // Update the size of the list and restore the selection + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + + // Redraw the items that were changed by the expand operation + this.RedrawItems(index, this.GetItemCount() - 1, true); + + this.OnExpanded(new TreeBranchExpandedEventArgs(model, item)); + + if (this.RevealAfterExpand && index > 0) { + // TODO: This should be a separate method + this.BeginUpdate(); + try { + int countPerPage = NativeMethods.GetCountPerPage(this); + int descedentCount = this.TreeModel.GetVisibleDescendentCount(model); + // If all of the descendants can be shown in the window, make sure that last one is visible. + // If all the descendants can't fit into the window, move the model to the top of the window + // (which will show as many of the descendants as possible) + if (descedentCount < countPerPage) { + this.EnsureVisible(index + descedentCount); + } else { + this.TopItemIndex = index; + } + } + finally { + this.EndUpdate(); + } + } + } + + /// + /// Expand all the branches within this tree recursively. + /// + /// Be careful: this method could take a long time for large trees. + public virtual void ExpandAll() { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(null, null); + this.OnExpanding(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.ExpandAll(); + if (index < 0) + return; + + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnExpanded(new TreeBranchExpandedEventArgs(null, null)); + } + + /// + /// Completely rebuild the tree structure + /// + /// If true, the control will try to preserve selection and expansion + public virtual void RebuildAll(bool preserveState) { + int previousTopItemIndex = preserveState ? this.TopItemIndex : -1; + + this.RebuildAll( + preserveState ? this.SelectedObjects : null, + preserveState ? this.ExpandedObjects : null, + preserveState ? this.CheckedObjects : null); + + if (preserveState) + this.TopItemIndex = previousTopItemIndex; + } + + /// + /// Completely rebuild the tree structure + /// + /// If not null, this list of objects will be selected after the tree is rebuilt + /// If not null, this collection of objects will be expanded after the tree is rebuilt + /// If not null, this collection of objects will be checked after the tree is rebuilt + protected virtual void RebuildAll(IList selected, IEnumerable expanded, IList checkedObjects) { + // Remember the bits of info we don't want to forget (anyone ever see Memento?) + IEnumerable roots = this.Roots; + CanExpandGetterDelegate canExpand = this.CanExpandGetter; + ChildrenGetterDelegate childrenGetter = this.ChildrenGetter; + + try { + this.BeginUpdate(); + + // Give ourselves a new data structure + this.RegenerateTree(); + + // Put back the bits we didn't want to forget + this.CanExpandGetter = canExpand; + this.ChildrenGetter = childrenGetter; + if (expanded != null) + this.ExpandedObjects = expanded; + this.Roots = roots; + if (selected != null) + this.SelectedObjects = selected; + if (checkedObjects != null) + this.CheckedObjects = checkedObjects; + } + finally { + this.EndUpdate(); + } + } + + /// + /// Unroll all the ancestors of the given model and make sure it is then visible. + /// + /// This works best when a ParentGetter is installed. + /// The object to be revealed + /// If true, the model will be selected and focused after being revealed + /// True if the object was found and revealed. False if it was not found. + public virtual void Reveal(object modelToReveal, bool selectAfterReveal) { + // Collect all the ancestors of the model + ArrayList ancestors = new ArrayList(); + foreach (object ancestor in this.GetAncestors(modelToReveal)) + ancestors.Add(ancestor); + + // Arrange them from root down to the model's immediate parent + ancestors.Reverse(); + try { + this.BeginUpdate(); + foreach (object ancestor in ancestors) + this.Expand(ancestor); + this.EnsureModelVisible(modelToReveal); + if (selectAfterReveal) + this.SelectObject(modelToReveal, true); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker) delegate { this.RefreshObjects(modelObjects); }); + return; + } + // There is no point in refreshing anything if the list is empty + if (this.GetItemCount() == 0) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // We actually need to refresh the parents. + // Refreshes on root objects have to be handled differently + ArrayList updatedRoots = new ArrayList(); + Hashtable modelsAndParents = new Hashtable(); + foreach (Object model in modelObjects) { + if (model == null) + continue; + modelsAndParents[model] = true; + object parent = GetParent(model); + if (parent == null) { + updatedRoots.Add(model); + } else { + modelsAndParents[parent] = true; + } + } + + // Update any changed roots + if (updatedRoots.Count > 0) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.Roots, false); + bool changed = false; + foreach (Object model in updatedRoots) { + int index = newRoots.IndexOf(model); + if (index >= 0 && !ReferenceEquals(newRoots[index], model)) { + newRoots[index] = model; + changed = true; + } + } + if (changed) + this.Roots = newRoots; + } + + // Refresh each object, remembering where the first update occurred + int firstChange = Int32.MaxValue; + foreach (Object model in modelsAndParents.Keys) { + if (model != null) { + int index = this.TreeModel.RebuildChildren(model); + if (index >= 0) + firstChange = Math.Min(firstChange, index); + } + } + + // If we didn't refresh any objects, don't do anything else + if (firstChange >= this.GetItemCount()) + return; + + this.ClearCachedInfo(); + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + + // Redraw everything from the first update to the end of the list + this.RedrawItems(firstChange, this.GetItemCount() - 1, true); + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected override bool SetObjectCheckedness(object modelObject, CheckState state) { + // If the checkedness of the given model changes AND this tree has + // hierarchical checkboxes, then we need to update the checkedness of + // its children, and recalculate the checkedness of the parent (recursively) + if (!base.SetObjectCheckedness(modelObject, state)) + return false; + + if (!this.HierarchicalCheckboxes) + return true; + + // Give each child the same checkedness as the model + + CheckState? checkedness = this.GetCheckState(modelObject); + if (!checkedness.HasValue || checkedness.Value == CheckState.Indeterminate) + return true; + + foreach (object child in this.GetChildrenWithoutExpanding(modelObject)) { + this.SetObjectCheckedness(child, checkedness.Value); + } + + ArrayList args = new ArrayList(); + args.Add(modelObject); + this.RecalculateHierarchicalCheckBoxGraph(args); + + return true; + } + + + private IEnumerable GetChildrenWithoutExpanding(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + return br.Children; + } + + /// + /// Toggle the expanded state of the branch at the given model object + /// + /// + public virtual void ToggleExpansion(Object model) { + if (this.IsExpanded(model)) + this.Collapse(model); + else + this.Expand(model); + } + + //------------------------------------------------------------------------------------------ + // Commands - Tree traversal + + /// + /// Return whether or not the given model can expand. + /// + /// + /// The given model must have already been seen in the tree + public virtual bool CanExpand(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.CanExpand); + } + + /// + /// Return the model object that is the parent of the given model object. + /// + /// + /// + /// The given model must have already been seen in the tree. + public virtual Object GetParent(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return br == null || br.ParentBranch == null ? null : br.ParentBranch.Model; + } + + /// + /// Return the collection of model objects that are the children of the + /// given model as they exist in the tree at the moment. + /// + /// + /// + /// + /// This method returns the collection of children as the tree knows them. If the given + /// model has never been presented to the user (e.g. it belongs to a parent that has + /// never been expanded), then this method will return an empty collection. + /// + /// Because of this, if you want to traverse the whole tree, this is not the method to use. + /// It's better to traverse the your data model directly. + /// + /// + /// If the given model has not already been seen in the tree or + /// if it is not expandable, an empty collection will be returned. + /// + /// + public virtual IEnumerable GetChildren(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + br.FetchChildren(); + + return br.Children; + } + + //------------------------------------------------------------------------------------------ + // Delegates + + /// + /// Delegates of this type are use to decide if the given model object can be expanded + /// + /// The model under consideration + /// Can the given model be expanded? + public delegate bool CanExpandGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the children of the given model object + /// + /// The parent whose children should be fetched + /// An enumerable over the children + public delegate IEnumerable ChildrenGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the parent of the given model object. + /// + /// The child whose parent should be fetched + /// The parent of the child or null if the child is a root + public delegate Object ParentGetterDelegate(Object model); + + /// + /// Delegates of this type are used to create a new underlying Tree structure. + /// + /// The view for which the Tree is being created + /// A subclass of Tree + public delegate Tree TreeFactoryDelegate(TreeListView view); + + //------------------------------------------------------------------------------------------ + #region Implementation + + /// + /// Handle a left button down event + /// + /// + /// + protected override bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + // Did they click in the expander? + if (hti.HitTestLocation == HitTestLocation.ExpandButton) { + this.PossibleFinishCellEditing(); + this.ToggleExpansion(hti.RowObject); + return true; + } + + return base.ProcessLButtonDown(hti); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + /// This differs from the base method by also setting up the IndentCount property. + public override OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvItem = base.MakeListViewItem(itemIndex); + Branch br = this.TreeModel.GetBranch(olvItem.RowObject); + if (br != null) + olvItem.IndentCount = br.Level; + return olvItem; + } + + /// + /// Reinitialise the Tree structure + /// + protected virtual void RegenerateTree() { + this.TreeModel = this.TreeFactory == null ? new Tree(this) : this.TreeFactory(this); + Trace.Assert(this.TreeModel != null); + this.VirtualListDataSource = this.TreeModel; + } + + /// + /// Recalculate the state of the checkboxes of all the items in the given list + /// and their ancestors. + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateHierarchicalCheckBoxGraph(IList toCheck) { + if (toCheck == null || toCheck.Count == 0) + return; + + // Avoid recursive calculations + if (isRecalculatingHierarchicalCheckBox) + return; + + try { + isRecalculatingHierarchicalCheckBox = true; + foreach (object ancestor in CalculateDistinctAncestors(toCheck)) + this.RecalculateSingleHierarchicalCheckBox(ancestor); + } + finally { + isRecalculatingHierarchicalCheckBox = false; + } + + } + private bool isRecalculatingHierarchicalCheckBox; + + /// + /// Recalculate the hierarchy state of the given item and its ancestors + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateSingleHierarchicalCheckBox(object modelObject) { + + if (modelObject == null) + return; + + // Only branches have calculated check states. Leaf node checkedness is not calculated + if (!this.CanExpandUncached(modelObject)) + return; + + // Set the checkedness of the given model based on the state of its children. + CheckState? aggregate = null; + foreach (object child in this.GetChildrenUncached(modelObject)) { + CheckState? checkedness = this.GetCheckState(child); + if (!checkedness.HasValue) + continue; + + if (aggregate.HasValue) { + if (aggregate.Value != checkedness.Value) { + aggregate = CheckState.Indeterminate; + break; + } + } else + aggregate = checkedness; + } + + base.SetObjectCheckedness(modelObject, aggregate ?? CheckState.Indeterminate); + } + + private bool CanExpandUncached(object model) { + return this.CanExpandGetter != null && model != null && this.CanExpandGetter(model); + } + + private IEnumerable GetChildrenUncached(object model) { + return this.ChildrenGetter != null && model != null ? this.ChildrenGetter(model) : new ArrayList(); + } + + /// + /// Yield the unique ancestors of the given collection of objects. + /// The order of the ancestors is guaranteed to be deeper objects first. + /// Roots will always be last. + /// + /// + /// Unique ancestors of the given objects + protected virtual IEnumerable CalculateDistinctAncestors(IList toCheck) { + + if (toCheck.Count == 1) { + foreach (object ancestor in this.GetAncestors(toCheck[0])) { + yield return ancestor; + } + } else { + // WARNING - Clever code + + // Example: Root --> GP +--> P +--> A + // | +--> B + // | + // +--> Q +--> X + // +--> Y + // + // Calculate ancestors of A, B, X and Y + + // Build a list of all ancestors of all objects we need to check + ArrayList allAncestors = new ArrayList(); + foreach (object child in toCheck) { + foreach (object ancestor in this.GetAncestors(child)) { + allAncestors.Add(ancestor); + } + } + + // allAncestors = { P, GP, Root, P, GP, Root, Q, GP, Root, Q, GP, Root } + + // Reverse them so "higher" ancestors come first + allAncestors.Reverse(); + + // allAncestors = { Root, GP, Q, Root, GP, Q, Root, GP, P, Root, GP, P } + + ArrayList uniqueAncestors = new ArrayList(); + Dictionary alreadySeen = new Dictionary(); + foreach (object ancestor in allAncestors) { + if (!alreadySeen.ContainsKey(ancestor)) { + alreadySeen[ancestor] = true; + uniqueAncestors.Add(ancestor); + } + } + + // uniqueAncestors = { Root, GP, Q, P } + + uniqueAncestors.Reverse(); + foreach (object x in uniqueAncestors) + yield return x; + } + } + + /// + /// Return all the ancestors of the given model + /// + /// + /// + /// This uses ParentGetter if possible. + /// + /// If the given model is a root OR if the model doesn't exist, the collection will be empty + /// + /// The model whose ancestors should be calculated + /// Return a collection of ancestors of the given model. + protected virtual IEnumerable GetAncestors(object model) { + ParentGetterDelegate parentGetterDelegate = this.ParentGetter ?? this.GetParent; + + object parent = parentGetterDelegate(model); + while (parent != null) { + yield return parent; + parent = parentGetterDelegate(parent); + } + } + + #endregion + + //------------------------------------------------------------------------------------------ + #region Event handlers + + /// + /// The application is idle and a SelectionChanged event has been scheduled + /// + /// + /// + protected override void HandleApplicationIdle(object sender, EventArgs e) { + base.HandleApplicationIdle(sender, e); + + // There is an annoying redraw issue on ListViews that use indentation and + // that have full row select enabled. When the selection reduces to a subset + // of previously selected rows, or when the selection is extended using + // shift-pageup/down, then the space occupied by the indentation is not + // invalidated, and hence remains highlighted. + // Ideally we'd want to know exactly which rows were selected or deselected + // and then invalidate just the indentation region of those rows, + // but that's too much work. So just redraw the control. + // Actually... the selection issues show just slightly for non-full row select + // controls as well. So, always redraw the control after the selection + // changes. + this.Invalidate(); + } + + /// + /// Decide if the given key event should be handled as a normal key input to the control? + /// + /// + /// + protected override bool IsInputKey(Keys keyData) { + // We want to handle Left and Right keys within the control + Keys key = keyData & Keys.KeyCode; + if (key == Keys.Left || key == Keys.Right) + return true; + + return base.IsInputKey(keyData); + } + + /// + /// Handle focus being lost, including making sure that the whole control is redrawn. + /// + /// + protected override void OnLostFocus(EventArgs e) + { + // When this focus is lost, the normal invalidation logic doesn't invalid the region + // of the control created by the IndentLevel on each row. This makes the control + // look wrong when HideSelection is false, since part of the selected row's background + // correctly changes colour to the "inactive" colour, but the left part of the row + // created by IndentLevel doesn't change colour. + // SF #135. + + this.Invalidate(); + } + + /// + /// Handle the keyboard input to mimic a TreeView. + /// + /// + /// Was the key press handled? + protected override void OnKeyDown(KeyEventArgs e) { + OLVListItem focused = this.FocusedItem as OLVListItem; + if (focused == null) { + base.OnKeyDown(e); + return; + } + + Object modelObject = focused.RowObject; + Branch br = this.TreeModel.GetBranch(modelObject); + + switch (e.KeyCode) { + case Keys.Left: + // If the branch is expanded, collapse it. If it's collapsed, + // select the parent of the branch. + if (br.IsExpanded) + this.Collapse(modelObject); + else { + if (br.ParentBranch != null && br.ParentBranch.Model != null) + this.SelectObject(br.ParentBranch.Model, true); + } + e.Handled = true; + break; + + case Keys.Right: + // If the branch is expanded, select the first child. + // If it isn't expanded and can be, expand it. + if (br.IsExpanded) { + List filtered = br.FilteredChildBranches; + if (filtered.Count > 0) + this.SelectObject(filtered[0].Model, true); + } else { + if (br.CanExpand) + this.Expand(modelObject); + } + e.Handled = true; + break; + } + + base.OnKeyDown(e); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Support classes + + /// + /// A Tree object represents a tree structure data model that supports both + /// tree and flat list operations as well as fast access to branches. + /// + /// If you create a subclass of Tree, you must install it in the TreeListView + /// via the TreeFactory delegate. + public class Tree : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Create a Tree + /// + /// + public Tree(TreeListView treeView) { + this.treeView = treeView; + this.trunk = new Branch(null, this, null); + this.trunk.IsExpanded = true; + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + public CanExpandGetterDelegate CanExpandGetter { + get { return canExpandGetter ?? DefaultCanExpandGetter; } + set { canExpandGetter = value; } + } + private CanExpandGetterDelegate canExpandGetter; + + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + public ChildrenGetterDelegate ChildrenGetter { + get { return childrenGetter ?? DefaultChildrenGetter; } + set { childrenGetter = value; } + } + private ChildrenGetterDelegate childrenGetter; + + /// + /// Get or return the top level model objects in the tree + /// + public IEnumerable RootObjects { + get { return this.trunk.Children; } + set { + this.trunk.Children = value; + foreach (Branch br in this.trunk.ChildBranches) + br.RefreshChildren(); + this.RebuildList(); + } + } + + /// + /// What tree view is this Tree the model for? + /// + public TreeListView TreeView { + get { return this.treeView; } + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// The model to be collapsed. If the model isn't in the tree, + /// or if it is already collapsed, the command does nothing. + /// The index of the model in flat list version of the tree + public virtual int Collapse(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.IsExpanded) + return -1; + + // Remember that the branch is collapsed, even if it's currently not visible + if (!br.Visible) { + br.Collapse(); + return -1; + } + + int count = br.NumberVisibleDescendents; + br.Collapse(); + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + this.objectList.RemoveRange(index + 1, count); + this.RebuildObjectMap(0); + return index; + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual int CollapseAll() { + this.trunk.CollapseAll(); + this.RebuildList(); + return 0; + } + + /// + /// Expand the subtree underneath the given model object + /// + /// The model to be expanded. + /// The index of the model in flat list version of the tree + /// + /// If the model isn't in the tree, + /// if it cannot be expanded or if it is already expanded, the command does nothing. + /// + public virtual int Expand(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.CanExpand || br.IsExpanded) + return -1; + + // Remember that the branch is expanded, even if it's currently not visible + br.Expand(); + if (!br.Visible) + { + return -1; + } + + int index = this.GetObjectIndex(model); + this.InsertChildren(br, index + 1); + return index; + } + + /// + /// Expand all branches in this tree + /// + /// Return the index of the first branch that was expanded + public virtual int ExpandAll() { + this.trunk.ExpandAll(); + this.Sort(this.lastSortColumn, this.lastSortOrder); + return 0; + } + + /// + /// Return the Branch object that represents the given model in the tree + /// + /// The model whose branches is to be returned + /// The branch that represents the given model, or null if the model + /// isn't in the tree. + public virtual Branch GetBranch(object model) { + if (model == null) + return null; + + Branch br; + this.mapObjectToBranch.TryGetValue(model, out br); + return br; + } + + /// + /// Return the number of visible descendants that are below the given model. + /// + /// The model whose descendent count is to be returned + /// The number of visible descendants. 0 if the model doesn't exist or is collapsed + public virtual int GetVisibleDescendentCount(object model) + { + Branch br = this.GetBranch(model); + return br == null || !br.IsExpanded ? 0 : br.NumberVisibleDescendents; + } + + /// + /// Rebuild the children of the given model, refreshing any cached information held about the given object + /// + /// + /// The index of the model in flat list version of the tree + public virtual int RebuildChildren(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.Visible) + return -1; + + int count = br.NumberVisibleDescendents; + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + if (count > 0) + this.objectList.RemoveRange(index + 1, count); + + // Refresh our knowledge of our children (do this even if CanExpand is false, because + // the branch have already collected some children and that information could be stale) + br.RefreshChildren(); + + // Insert the refreshed children if the branch can expand and is expanded + if (br.CanExpand && br.IsExpanded) + this.InsertChildren(br, index + 1); + else + this.RebuildObjectMap(index); + + return index; + } + + //------------------------------------------------------------------------------------------ + // Implementation + + private static bool DefaultCanExpandGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel != null && treeModel.TreeCanExpand; + } + + private static IEnumerable DefaultChildrenGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel == null ? new ArrayList() : treeModel.TreeChildren; + } + + internal static object DefaultParentGetter(object model) { + ITreeModelWithParent treeModel = model as ITreeModelWithParent; + return treeModel == null ? null : treeModel.TreeParent; + } + + /// + /// Is the given model expanded? + /// + /// + /// + internal bool IsModelExpanded(object model) { + // Special case: model == null is the container for the roots. This is always expanded + if (model == null) + return true; + bool isExpanded; + this.mapObjectToExpanded.TryGetValue(model, out isExpanded); + return isExpanded; + } + + /// + /// Remember whether or not the given model was expanded + /// + /// + /// + internal void SetModelExpanded(object model, bool isExpanded) { + if (model == null) return; + + if (isExpanded) + this.mapObjectToExpanded[model] = true; + else + this.mapObjectToExpanded.Remove(model); + } + + /// + /// Insert the children of the given branch into the given position + /// + /// The branch whose children should be inserted + /// The index where the children should be inserted + protected virtual void InsertChildren(Branch br, int index) { + // Expand the branch + br.Expand(); + br.Sort(this.GetBranchComparer()); + + // Insert the branch's visible descendants after the branch itself + this.objectList.InsertRange(index, br.Flatten()); + this.RebuildObjectMap(index); + } + + /// + /// Rebuild our flat internal list of objects. + /// + protected virtual void RebuildList() { + this.objectList = ArrayList.Adapter(this.trunk.Flatten()); + List filtered = this.trunk.FilteredChildBranches; + if (filtered.Count > 0) { + filtered[0].IsFirstBranch = true; + filtered[0].IsOnlyBranch = (filtered.Count == 1); + } + this.RebuildObjectMap(0); + } + + /// + /// Rebuild our reverse index that maps an object to its location + /// in the filteredObjectList array. + /// + /// + protected virtual void RebuildObjectMap(int startIndex) { + if (startIndex == 0) + this.mapObjectToIndex.Clear(); + for (int i = startIndex; i < this.objectList.Count; i++) + this.mapObjectToIndex[this.objectList[i]] = i; + } + + /// + /// Create a new branch within this tree + /// + /// + /// + /// + internal Branch MakeBranch(Branch parent, object model) { + Branch br = new Branch(parent, this, model); + + // Remember that the given branch is part of this tree. + this.mapObjectToBranch[model] = br; + return br; + } + + //------------------------------------------------------------------------------------------ + + #region IVirtualListDataSource Members + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + if (n >= 0 && n < this.objectList.Count) + return this.objectList[n]; + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return this.trunk.NumberVisibleDescendents; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) + { + int index; + if (model != null && this.mapObjectToIndex.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int first, int last) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return AbstractVirtualListDataSource.DefaultSearchText(value, first, last, column, this); + } + + /// + /// Sort the tree on the given column and in the given order + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + this.lastSortColumn = column; + this.lastSortOrder = order; + + // TODO: Need to raise an AboutToSortEvent here + + // Sorting is going to change the order of the branches so clear + // the "first branch" flag + foreach (Branch b in this.trunk.ChildBranches) + b.IsFirstBranch = false; + + this.trunk.Sort(this.GetBranchComparer()); + this.RebuildList(); + } + + /// + /// + /// + /// + protected virtual BranchComparer GetBranchComparer() { + if (this.lastSortColumn == null) + return null; + + return new BranchComparer(new ModelObjectComparer( + this.lastSortColumn, + this.lastSortOrder, + this.treeView.SecondarySortColumn ?? this.treeView.GetColumn(0), + this.treeView.SecondarySortColumn == null ? this.lastSortOrder : this.treeView.SecondarySortOrder)); + } + + /// + /// Add the given collection of objects to the roots of this tree + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, true); + foreach (Object x in modelObjects) + newRoots.Add(x); + this.SetObjects(newRoots); + } + + /// + /// + /// + /// + /// + public void InsertObjects(int index, ICollection modelObjects) { + throw new NotImplementedException(); + } + + /// + /// Remove all of the given objects from the roots of the tree. + /// Any objects that is not already in the roots collection is ignored. + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + ArrayList newRoots = new ArrayList(); + foreach (Object x in this.treeView.Roots) + newRoots.Add(x); + foreach (Object x in modelObjects) { + newRoots.Remove(x); + this.mapObjectToIndex.Remove(x); + } + this.SetObjects(newRoots); + } + + /// + /// Set the roots of this tree to be the given collection + /// + /// + public virtual void SetObjects(IEnumerable collection) { + // We interpret a SetObjects() call as setting the roots of the tree + this.treeView.Roots = collection; + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public void UpdateObject(int index, object modelObject) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, false); + if (index < newRoots.Count) + newRoots[index] = modelObject; + SetObjects(newRoots); + } + + #endregion + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + public void ApplyFilters(IModelFilter mFilter, IListFilter lFilter) { + this.modelFilter = mFilter; + this.listFilter = lFilter; + this.RebuildList(); + } + + /// + /// Is this list currently being filtered? + /// + internal bool IsFiltering { + get { + return this.treeView.UseFiltering && (this.modelFilter != null || this.listFilter != null); + } + } + + /// + /// Should the given model be included in this control? + /// + /// The model to consider + /// True if it will be included + internal bool IncludeModel(object model) { + if (!this.treeView.UseFiltering) + return true; + + if (this.modelFilter == null) + return true; + + return this.modelFilter.Filter(model); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private OLVColumn lastSortColumn; + private SortOrder lastSortOrder; + private readonly Dictionary mapObjectToBranch = new Dictionary(); +// ReSharper disable once InconsistentNaming + internal Dictionary mapObjectToExpanded = new Dictionary(); + private readonly Dictionary mapObjectToIndex = new Dictionary(); + private ArrayList objectList = new ArrayList(); + private readonly TreeListView treeView; + private readonly Branch trunk; + + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IModelFilter modelFilter; + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IListFilter listFilter; + } + + /// + /// A Branch represents a sub-tree within a tree + /// + public class Branch + { + /// + /// Indicators for branches + /// + [Flags] + public enum BranchFlags + { + /// + /// FirstBranch of tree + /// + FirstBranch = 1, + + /// + /// LastChild of parent + /// + LastChild = 2, + + /// + /// OnlyBranch of tree + /// + OnlyBranch = 4 + } + + #region Life and death + + /// + /// Create a Branch + /// + /// + /// + /// + public Branch(Branch parent, Tree tree, Object model) { + this.ParentBranch = parent; + this.Tree = tree; + this.Model = model; + } + + #endregion + + #region Public properties + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// Get the ancestor branches of this branch, with the 'oldest' ancestor first. + /// + public virtual IList Ancestors { + get { + List ancestors = new List(); + if (this.ParentBranch != null) + this.ParentBranch.PushAncestors(ancestors); + return ancestors; + } + } + + private void PushAncestors(IList list) { + // This is designed to ignore the trunk (which has no parent) + if (this.ParentBranch != null) { + this.ParentBranch.PushAncestors(list); + list.Add(this); + } + } + + /// + /// Can this branch be expanded? + /// + public virtual bool CanExpand { + get { + if (this.Tree.CanExpandGetter == null || this.Model == null) + return false; + + return this.Tree.CanExpandGetter(this.Model); + } + } + + /// + /// Gets or sets our children + /// + public List ChildBranches { + get { return this.childBranches; } + set { this.childBranches = value; } + } + private List childBranches = new List(); + + /// + /// Get/set the model objects that are beneath this branch + /// + public virtual IEnumerable Children { + get { + ArrayList children = new ArrayList(); + foreach (Branch x in this.ChildBranches) + children.Add(x.Model); + return children; + } + set { + this.ChildBranches.Clear(); + + TreeListView treeListView = this.Tree.TreeView; + CheckState? checkedness = null; + if (treeListView != null && treeListView.HierarchicalCheckboxes) + checkedness = treeListView.GetCheckState(this.Model); + foreach (Object x in value) { + this.AddChild(x); + + // If the tree view is showing hierarchical checkboxes, then + // when a child object is first added, it has the same checkedness as this branch + if (checkedness.HasValue && checkedness.Value == CheckState.Checked) + treeListView.SetObjectCheckedness(x, checkedness.Value); + } + } + } + + private void AddChild(object childModel) { + Branch br = this.Tree.GetBranch(childModel); + if (br == null) + br = this.Tree.MakeBranch(this, childModel); + else { + br.ParentBranch = this; + br.Model = childModel; + br.ClearCachedInfo(); + } + this.ChildBranches.Add(br); + } + + /// + /// Gets a list of all the branches that survive filtering + /// + public List FilteredChildBranches { + get { + if (!this.IsExpanded) + return new List(); + + if (!this.Tree.IsFiltering) + return this.ChildBranches; + + List filtered = new List(); + foreach (Branch b in this.ChildBranches) { + if (this.Tree.IncludeModel(b.Model)) + filtered.Add(b); + else { + // Also include this branch if it has any filtered branches (yes, its recursive) + if (b.FilteredChildBranches.Count > 0) + filtered.Add(b); + } + } + return filtered; + } + } + + /// + /// Gets or set whether this branch is expanded + /// + public bool IsExpanded { + get { return this.Tree.IsModelExpanded(this.Model); } + set { this.Tree.SetModelExpanded(this.Model, value); } + } + + /// + /// Return true if this branch is the first branch of the entire tree + /// + public virtual bool IsFirstBranch { + get { + return ((this.flags & Branch.BranchFlags.FirstBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.FirstBranch; + else + this.flags &= ~Branch.BranchFlags.FirstBranch; + } + } + + /// + /// Return true if this branch is the last child of its parent + /// + public virtual bool IsLastChild { + get { + return ((this.flags & Branch.BranchFlags.LastChild) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.LastChild; + else + this.flags &= ~Branch.BranchFlags.LastChild; + } + } + + /// + /// Return true if this branch is the only top level branch + /// + public virtual bool IsOnlyBranch { + get { + return ((this.flags & Branch.BranchFlags.OnlyBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.OnlyBranch; + else + this.flags &= ~Branch.BranchFlags.OnlyBranch; + } + } + + /// + /// Gets the depth level of this branch + /// + public int Level { + get { + if (this.ParentBranch == null) + return 0; + + return this.ParentBranch.Level + 1; + } + } + + /// + /// Gets or sets which model is represented by this branch + /// + public Object Model { + get { return model; } + set { model = value; } + } + private Object model; + + /// + /// Return the number of descendants of this branch that are currently visible + /// + /// + public virtual int NumberVisibleDescendents { + get { + if (!this.IsExpanded) + return 0; + + List filtered = this.FilteredChildBranches; + int count = filtered.Count; + foreach (Branch br in filtered) + count += br.NumberVisibleDescendents; + return count; + } + } + + /// + /// Gets or sets our parent branch + /// + public Branch ParentBranch { + get { return parentBranch; } + set { parentBranch = value; } + } + private Branch parentBranch; + + /// + /// Gets or sets our overall tree + /// + public Tree Tree { + get { return tree; } + set { tree = value; } + } + private Tree tree; + + /// + /// Is this branch currently visible? A branch is visible + /// if it has no parent (i.e. it's a root), or its parent + /// is visible and expanded. + /// + public virtual bool Visible { + get { + if (this.ParentBranch == null) + return true; + + return this.ParentBranch.IsExpanded && this.ParentBranch.Visible; + } + } + + #endregion + + #region Commands + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Clear any cached information that this branch is holding + /// + public virtual void ClearCachedInfo() { + this.Children = new ArrayList(); + this.alreadyHasChildren = false; + } + + /// + /// Collapse this branch + /// + public virtual void Collapse() { + this.IsExpanded = false; + } + + /// + /// Expand this branch + /// + public virtual void Expand() { + if (this.CanExpand) { + this.IsExpanded = true; + this.FetchChildren(); + } + } + + /// + /// Expand this branch recursively + /// + public virtual void ExpandAll() { + this.Expand(); + foreach (Branch br in this.ChildBranches) { + if (br.CanExpand) + br.ExpandAll(); + } + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual void CollapseAll() + { + this.Collapse(); + foreach (Branch br in this.ChildBranches) { + if (br.IsExpanded) + br.CollapseAll(); + } + } + + /// + /// Fetch the children of this branch. + /// + /// This should only be called when CanExpand is true. + public virtual void FetchChildren() { + if (this.alreadyHasChildren) + return; + + this.alreadyHasChildren = true; + + if (this.Tree.ChildrenGetter == null) + return; + + Cursor previous = Cursor.Current; + try { + if (this.Tree.TreeView.UseWaitCursorWhenExpanding) + Cursor.Current = Cursors.WaitCursor; + this.Children = this.Tree.ChildrenGetter(this.Model); + } + finally { + Cursor.Current = previous; + } + } + + /// + /// Collapse the visible descendants of this branch into list of model objects + /// + /// + public virtual IList Flatten() { + ArrayList flatList = new ArrayList(); + if (this.IsExpanded) + this.FlattenOnto(flatList); + return flatList; + } + + /// + /// Flatten this branch's visible descendants onto the given list. + /// + /// + /// The branch itself is not included in the list. + public virtual void FlattenOnto(IList flatList) { + Branch lastBranch = null; + foreach (Branch br in this.FilteredChildBranches) { + lastBranch = br; + br.IsFirstBranch = br.IsOnlyBranch = br.IsLastChild = false; + flatList.Add(br.Model); + if (br.IsExpanded) { + br.FetchChildren(); // make sure we have the branches children + br.FlattenOnto(flatList); + } + } + if (lastBranch != null) + lastBranch.IsLastChild = true; + } + + /// + /// Force a refresh of all children recursively + /// + public virtual void RefreshChildren() { + + // Forget any previous children. We always do this so that if + // IsExpanded or CanExpand have changed, we aren't left with stale information. + this.ClearCachedInfo(); + + if (!this.IsExpanded || !this.CanExpand) + return; + + this.FetchChildren(); + foreach (Branch br in this.ChildBranches) + br.RefreshChildren(); + } + + /// + /// Sort the sub-branches and their descendants so they are ordered according + /// to the given comparer. + /// + /// The comparer that orders the branches + public virtual void Sort(BranchComparer comparer) { + if (this.ChildBranches.Count == 0) + return; + + if (comparer != null) + this.ChildBranches.Sort(comparer); + + foreach (Branch br in this.ChildBranches) + br.Sort(comparer); + } + + #endregion + + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private bool alreadyHasChildren; + private BranchFlags flags; + } + + /// + /// This class sorts branches according to how their respective model objects are sorted + /// + public class BranchComparer : IComparer + { + /// + /// Create a BranchComparer + /// + /// + public BranchComparer(IComparer actualComparer) { + this.actualComparer = actualComparer; + } + + /// + /// Order the two branches + /// + /// + /// + /// + public int Compare(Branch x, Branch y) { + return this.actualComparer.Compare(x.Model, y.Model); + } + + private readonly IComparer actualComparer; + } + + } + + /// + /// This interface should be implemented by model objects that can provide children, + /// but that don't have a parent. This is either because the model objects are always + /// root level, or because they are used in TreeListView that never uses parent + /// calculations. Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithChildren { + /// + /// Get whether this this model can be expanded? If true, an expand glyph will be drawn next to it. + /// + /// This is called often! It must be fast. Dont do a database lookup, calculate pi, or do linear searches just return a property value. + bool TreeCanExpand { get; } + + /// + /// Get the models that will be shown under this model when it is expanded. + /// + /// This is only called when CanExpand returns true. + IEnumerable TreeChildren { get; } + } + + /// + /// This interface should be implemented by model objects that can never have children, + /// but that are used in a TreeListView that uses parent calculations. + /// Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithParent { + + /// + /// Get the hierarchical parent of this model. + /// + object TreeParent { get; } + } + + /// + /// ITreeModel allows model objects to provide the required information to TreeListView + /// without using the normal Getter delegates. + /// + public interface ITreeModel: ITreeModelWithChildren, ITreeModelWithParent { + + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs new file mode 100644 index 0000000..e8e520e --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs @@ -0,0 +1,190 @@ +namespace BrightIdeasSoftware +{ + partial class ColumnSelectionForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonMoveUp = new System.Windows.Forms.Button(); + this.buttonMoveDown = new System.Windows.Forms.Button(); + this.buttonShow = new System.Windows.Forms.Button(); + this.buttonHide = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.buttonOK = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.objectListView1 = new BrightIdeasSoftware.ObjectListView(); + this.olvColumn1 = new BrightIdeasSoftware.OLVColumn(); + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit(); + this.SuspendLayout(); + // + // buttonMoveUp + // + this.buttonMoveUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveUp.Location = new System.Drawing.Point(295, 31); + this.buttonMoveUp.Name = "buttonMoveUp"; + this.buttonMoveUp.Size = new System.Drawing.Size(87, 23); + this.buttonMoveUp.TabIndex = 1; + this.buttonMoveUp.Text = "Move &Up"; + this.buttonMoveUp.UseVisualStyleBackColor = true; + this.buttonMoveUp.Click += new System.EventHandler(this.buttonMoveUp_Click); + // + // buttonMoveDown + // + this.buttonMoveDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveDown.Location = new System.Drawing.Point(295, 60); + this.buttonMoveDown.Name = "buttonMoveDown"; + this.buttonMoveDown.Size = new System.Drawing.Size(87, 23); + this.buttonMoveDown.TabIndex = 2; + this.buttonMoveDown.Text = "Move &Down"; + this.buttonMoveDown.UseVisualStyleBackColor = true; + this.buttonMoveDown.Click += new System.EventHandler(this.buttonMoveDown_Click); + // + // buttonShow + // + this.buttonShow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonShow.Location = new System.Drawing.Point(295, 89); + this.buttonShow.Name = "buttonShow"; + this.buttonShow.Size = new System.Drawing.Size(87, 23); + this.buttonShow.TabIndex = 3; + this.buttonShow.Text = "&Show"; + this.buttonShow.UseVisualStyleBackColor = true; + this.buttonShow.Click += new System.EventHandler(this.buttonShow_Click); + // + // buttonHide + // + this.buttonHide.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonHide.Location = new System.Drawing.Point(295, 118); + this.buttonHide.Name = "buttonHide"; + this.buttonHide.Size = new System.Drawing.Size(87, 23); + this.buttonHide.TabIndex = 4; + this.buttonHide.Text = "&Hide"; + this.buttonHide.UseVisualStyleBackColor = true; + this.buttonHide.Click += new System.EventHandler(this.buttonHide_Click); + // + // label1 + // + this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.label1.BackColor = System.Drawing.SystemColors.Control; + this.label1.Location = new System.Drawing.Point(13, 9); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(366, 19); + this.label1.TabIndex = 5; + this.label1.Text = "Choose the columns you want to see in this list. "; + // + // buttonOK + // + this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOK.Location = new System.Drawing.Point(198, 304); + this.buttonOK.Name = "buttonOK"; + this.buttonOK.Size = new System.Drawing.Size(87, 23); + this.buttonOK.TabIndex = 6; + this.buttonOK.Text = "&OK"; + this.buttonOK.UseVisualStyleBackColor = true; + this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(295, 304); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(87, 23); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "&Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // objectListView1 + // + this.objectListView1.AllColumns.Add(this.olvColumn1); + this.objectListView1.AlternateRowBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); + this.objectListView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick; + this.objectListView1.CheckBoxes = true; + this.objectListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.olvColumn1}); + this.objectListView1.FullRowSelect = true; + this.objectListView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; + this.objectListView1.HideSelection = false; + this.objectListView1.Location = new System.Drawing.Point(12, 31); + this.objectListView1.MultiSelect = false; + this.objectListView1.Name = "objectListView1"; + this.objectListView1.ShowGroups = false; + this.objectListView1.ShowSortIndicators = false; + this.objectListView1.Size = new System.Drawing.Size(273, 259); + this.objectListView1.TabIndex = 0; + this.objectListView1.UseCompatibleStateImageBehavior = false; + this.objectListView1.View = System.Windows.Forms.View.Details; + this.objectListView1.SelectionChanged += new System.EventHandler(this.objectListView1_SelectionChanged); + // + // olvColumn1 + // + this.olvColumn1.AspectName = "Text"; + this.olvColumn1.IsVisible = true; + this.olvColumn1.Text = "Column"; + this.olvColumn1.Width = 267; + // + // ColumnSelectionForm + // + this.AcceptButton = this.buttonOK; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(391, 339); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOK); + this.Controls.Add(this.label1); + this.Controls.Add(this.buttonHide); + this.Controls.Add(this.buttonShow); + this.Controls.Add(this.buttonMoveDown); + this.Controls.Add(this.buttonMoveUp); + this.Controls.Add(this.objectListView1); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ColumnSelectionForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.Text = "Column Selection"; + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private BrightIdeasSoftware.ObjectListView objectListView1; + private System.Windows.Forms.Button buttonMoveUp; + private System.Windows.Forms.Button buttonMoveDown; + private System.Windows.Forms.Button buttonShow; + private System.Windows.Forms.Button buttonHide; + private BrightIdeasSoftware.OLVColumn olvColumn1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button buttonOK; + private System.Windows.Forms.Button buttonCancel; + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/ColumnSelectionForm.cs b/ObjectListView/Utilities/ColumnSelectionForm.cs new file mode 100644 index 0000000..6b8e7e0 --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.cs @@ -0,0 +1,263 @@ +/* + * ColumnSelectionForm - A utility form that allows columns to be rearranged and/or hidden + * + * Author: Phillip Piper + * Date: 1/04/2011 11:15 AM + * + * Change log: + * 2013-04-21 JPP - Fixed obscure bug in column re-ordered. Thanks to Edwin Chen. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This form is an example of how an application could allows the user to select which columns + /// an ObjectListView will display, as well as select which order the columns are displayed in. + /// + /// + /// In Tile view, ColumnHeader.DisplayIndex does nothing. To reorder the columns you have + /// to change the order of objects in the Columns property. + /// Remember that the first column is special! + /// It has to remain the first column. + /// + public partial class ColumnSelectionForm : Form + { + /// + /// Make a new ColumnSelectionForm + /// + public ColumnSelectionForm() + { + InitializeComponent(); + } + + /// + /// Open this form so it will edit the columns that are available in the listview's current view + /// + /// The ObjectListView whose columns are to be altered + public void OpenOn(ObjectListView olv) + { + this.OpenOn(olv, olv.View); + } + + /// + /// Open this form so it will edit the columns that are available in the given listview + /// when the listview is showing the given type of view. + /// + /// The ObjectListView whose columns are to be altered + /// The view that is to be altered. Must be View.Details or View.Tile + public void OpenOn(ObjectListView olv, View view) + { + if (view != View.Details && view != View.Tile) + return; + + this.InitializeForm(olv, view); + if (this.ShowDialog() == DialogResult.OK) + this.Apply(olv, view); + } + + /// + /// Initialize the form to show the columns of the given view + /// + /// + /// + protected void InitializeForm(ObjectListView olv, View view) + { + this.AllColumns = olv.AllColumns; + this.RearrangableColumns = new List(this.AllColumns); + foreach (OLVColumn col in this.RearrangableColumns) { + if (view == View.Details) + this.MapColumnToVisible[col] = col.IsVisible; + else + this.MapColumnToVisible[col] = col.IsTileViewColumn; + } + this.RearrangableColumns.Sort(new SortByDisplayOrder(this)); + + this.objectListView1.BooleanCheckStateGetter = delegate(Object rowObject) { + return this.MapColumnToVisible[(OLVColumn)rowObject]; + }; + + this.objectListView1.BooleanCheckStatePutter = delegate(Object rowObject, bool newValue) { + // Some columns should always be shown, so ignore attempts to hide them + OLVColumn column = (OLVColumn)rowObject; + if (!column.CanBeHidden) + return true; + + this.MapColumnToVisible[column] = newValue; + EnableControls(); + return newValue; + }; + + this.objectListView1.SetObjects(this.RearrangableColumns); + this.EnableControls(); + } + private List AllColumns = null; + private List RearrangableColumns = new List(); + private Dictionary MapColumnToVisible = new Dictionary(); + + /// + /// The user has pressed OK. Do what's required. + /// + /// + /// + protected void Apply(ObjectListView olv, View view) + { + olv.Freeze(); + + // Update the column definitions to reflect whether they have been hidden + if (view == View.Details) { + foreach (OLVColumn col in olv.AllColumns) + col.IsVisible = this.MapColumnToVisible[col]; + } else { + foreach (OLVColumn col in olv.AllColumns) + col.IsTileViewColumn = this.MapColumnToVisible[col]; + } + + // Collect the columns are still visible + List visibleColumns = this.RearrangableColumns.FindAll( + delegate(OLVColumn x) { return this.MapColumnToVisible[x]; }); + + // Detail view and Tile view have to be handled in different ways. + if (view == View.Details) { + // Of the still visible columns, change DisplayIndex to reflect their position in the rearranged list + olv.ChangeToFilteredColumns(view); + foreach (OLVColumn col in visibleColumns) { + col.DisplayIndex = visibleColumns.IndexOf((OLVColumn)col); + col.LastDisplayIndex = col.DisplayIndex; + } + } else { + // In Tile view, DisplayOrder does nothing. So to change the display order, we have to change the + // order of the columns in the Columns property. + // Remember, the primary column is special and has to remain first! + OLVColumn primaryColumn = this.AllColumns[0]; + visibleColumns.Remove(primaryColumn); + + olv.Columns.Clear(); + olv.Columns.Add(primaryColumn); + olv.Columns.AddRange(visibleColumns.ToArray()); + olv.CalculateReasonableTileSize(); + } + + olv.Unfreeze(); + } + + #region Event handlers + + private void buttonMoveUp_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex-1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonMoveDown_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex + 1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonShow_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = true; + } + + private void buttonHide_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = false; + } + + private void buttonOK_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.OK; + this.Close(); + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.Cancel; + this.Close(); + } + + private void objectListView1_SelectionChanged(object sender, EventArgs e) + { + EnableControls(); + } + + #endregion + + #region Control enabling + + /// + /// Enable the controls on the dialog to match the current state + /// + protected void EnableControls() + { + if (this.objectListView1.SelectedIndices.Count == 0) { + this.buttonMoveUp.Enabled = false; + this.buttonMoveDown.Enabled = false; + this.buttonShow.Enabled = false; + this.buttonHide.Enabled = false; + } else { + // Can't move the first row up or the last row down + this.buttonMoveUp.Enabled = (this.objectListView1.SelectedIndices[0] != 0); + this.buttonMoveDown.Enabled = (this.objectListView1.SelectedIndices[0] < (this.objectListView1.GetItemCount() - 1)); + + OLVColumn selectedColumn = (OLVColumn)this.objectListView1.SelectedObject; + + // Some columns cannot be hidden (and hence cannot be Shown) + this.buttonShow.Enabled = !this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + this.buttonHide.Enabled = this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + } + } + #endregion + + /// + /// A Comparer that will sort a list of columns so that visible ones come before hidden ones, + /// and that are ordered by their display order. + /// + private class SortByDisplayOrder : IComparer + { + public SortByDisplayOrder(ColumnSelectionForm form) + { + this.Form = form; + } + private ColumnSelectionForm Form; + + #region IComparer Members + + int IComparer.Compare(OLVColumn x, OLVColumn y) + { + if (this.Form.MapColumnToVisible[x] && !this.Form.MapColumnToVisible[y]) + return -1; + + if (!this.Form.MapColumnToVisible[x] && this.Form.MapColumnToVisible[y]) + return 1; + + if (x.DisplayIndex == y.DisplayIndex) + return x.Text.CompareTo(y.Text); + else + return x.DisplayIndex - y.DisplayIndex; + } + + #endregion + } + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.resx b/ObjectListView/Utilities/ColumnSelectionForm.resx new file mode 100644 index 0000000..19dc0dd --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ObjectListView/Utilities/Generator.cs b/ObjectListView/Utilities/Generator.cs new file mode 100644 index 0000000..705ed30 --- /dev/null +++ b/ObjectListView/Utilities/Generator.cs @@ -0,0 +1,563 @@ +/* + * Generator - Utility methods that generate columns or methods + * + * Author: Phillip Piper + * Date: 15/08/2009 22:37 + * + * Change log: + * 2015-06-17 JPP - Columns without [OLVColumn] now auto size + * 2012-08-16 JPP - Generator now considers [OLVChildren] and [OLVIgnore] attributes. + * 2012-06-14 JPP - Allow columns to be generated even if they are not marked with [OLVColumn] + * - Converted class from static to instance to allow it to be subclassed. + * Also, added IGenerator to allow it to be completely reimplemented. + * v2.5.1 + * 2010-11-01 JPP - DisplayIndex is now set correctly for columns that lack that attribute + * v2.4.1 + * 2010-08-25 JPP - Generator now also resets sort columns + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * - Don't double set the Text property + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; +using System.Reflection.Emit; +using System.Text.RegularExpressions; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An object that implements the IGenerator interface provides the ability + /// to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + public interface IGenerator { + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties); + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + IList GenerateColumns(Type type, bool allProperties); + } + + /// + /// The Generator class provides methods to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + /// + /// For a given type, a Generator can create columns to match the public properties + /// of that type. The generator can consider all public properties or only those public properties marked with + /// [OLVColumn] attribute. + /// + public class Generator : IGenerator { + #region Static convenience methods + + /// + /// Gets or sets the actual generator used by the static convenience methods. + /// + /// If you subclass the standard generator or implement IGenerator yourself, + /// you should install an instance of your subclass/implementation here. + public static IGenerator Instance { + get { return Generator.instance ?? (Generator.instance = new Generator()); } + set { Generator.instance = value; } + } + private static IGenerator instance; + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable) { + Generator.GenerateColumns(olv, enumerable, false); + } + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable, bool allProperties) { + // Generate columns based on the type of the first model in the collection and then quit + if (enumerable != null) { + foreach (object model in enumerable) { + Generator.Instance.GenerateAndReplaceColumns(olv, model.GetType(), allProperties); + return; + } + } + + // If we reach here, the collection was empty, so we clear the list + Generator.Instance.GenerateAndReplaceColumns(olv, null, allProperties); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + static public void GenerateColumns(ObjectListView olv, Type type) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, false); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, Type type, bool allProperties) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, allProperties); + } + + /// + /// Generate a list of OLVColumns based on the public properties of the given type + /// that have a OLVColumn attribute. + /// + /// + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + static public IList GenerateColumns(Type type) { + return Generator.Instance.GenerateColumns(type, false); + } + + #endregion + + #region Public interface + + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + public virtual void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties) { + IList columns = this.GenerateColumns(type, allProperties); + TreeListView tlv = olv as TreeListView; + if (tlv != null) + this.TryGenerateChildrenDelegates(tlv, type); + this.ReplaceColumns(olv, columns); + } + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + public virtual IList GenerateColumns(Type type, bool allProperties) { + List columns = new List(); + + // Sanity + if (type == null) + return columns; + + // Iterate all public properties in the class and build columns from those that have + // an OLVColumn attribute and that are not ignored. + foreach (PropertyInfo pinfo in type.GetProperties()) { + if (Attribute.GetCustomAttribute(pinfo, typeof(OLVIgnoreAttribute)) != null) + continue; + + OLVColumnAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVColumnAttribute)) as OLVColumnAttribute; + if (attr == null) { + if (allProperties) + columns.Add(this.MakeColumnFromPropertyInfo(pinfo)); + } else { + columns.Add(this.MakeColumnFromAttribute(pinfo, attr)); + } + } + + // How many columns have DisplayIndex specifically set? + int countPositiveDisplayIndex = 0; + foreach (OLVColumn col in columns) { + if (col.DisplayIndex >= 0) + countPositiveDisplayIndex += 1; + } + + // Give columns that don't have a DisplayIndex an incremental index + int columnIndex = countPositiveDisplayIndex; + foreach (OLVColumn col in columns) + if (col.DisplayIndex < 0) + col.DisplayIndex = (columnIndex++); + + columns.Sort(delegate(OLVColumn x, OLVColumn y) { + return x.DisplayIndex.CompareTo(y.DisplayIndex); + }); + + return columns; + } + + #endregion + + #region Implementation + + /// + /// Replace all the columns in the given listview with the given list of columns. + /// + /// + /// + protected virtual void ReplaceColumns(ObjectListView olv, IList columns) { + olv.Reset(); + + // Are there new columns to add? + if (columns == null || columns.Count == 0) + return; + + // Setup the columns + olv.AllColumns.AddRange(columns); + this.PostCreateColumns(olv); + } + + /// + /// Post process columns after creating them and adding them to the AllColumns collection. + /// + /// + public virtual void PostCreateColumns(ObjectListView olv) { + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.CheckBoxes; })) + olv.UseSubItemCheckBoxes = true; + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.Index > 0 && (x.ImageGetter != null || !String.IsNullOrEmpty(x.ImageAspectName)); })) + olv.ShowImagesOnSubItems = true; + olv.RebuildColumns(); + olv.AutoSizeColumns(); + } + + /// + /// Create a column from the given PropertyInfo and OLVColumn attribute + /// + /// + /// + /// + protected virtual OLVColumn MakeColumnFromAttribute(PropertyInfo pinfo, OLVColumnAttribute attr) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, attr); + } + + /// + /// Make a column from the given PropertyInfo + /// + /// + /// + protected virtual OLVColumn MakeColumnFromPropertyInfo(PropertyInfo pinfo) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, null); + } + + /// + /// Make a column from the given PropertyDescriptor + /// + /// + /// + public virtual OLVColumn MakeColumnFromPropertyDescriptor(PropertyDescriptor pd) { + OLVColumnAttribute attr = pd.Attributes[typeof(OLVColumnAttribute)] as OLVColumnAttribute; + return MakeColumn(pd.Name, DisplayNameToColumnTitle(pd.DisplayName), !pd.IsReadOnly, pd.PropertyType, attr); + } + + /// + /// Create a column with all the given information + /// + /// + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, bool editable, Type propertyType, OLVColumnAttribute attr) { + + OLVColumn column = this.MakeColumn(aspectName, title, attr); + column.Name = (attr == null || String.IsNullOrEmpty(attr.Name)) ? aspectName : attr.Name; + this.ConfigurePossibleBooleanColumn(column, propertyType); + + if (attr == null) { + column.IsEditable = editable; + column.Width = -1; // Auto size + return column; + } + + column.AspectToStringFormat = attr.AspectToStringFormat; + if (attr.IsCheckBoxesSet) + column.CheckBoxes = attr.CheckBoxes; + column.DisplayIndex = attr.DisplayIndex; + column.FillsFreeSpace = attr.FillsFreeSpace; + if (attr.IsFreeSpaceProportionSet) + column.FreeSpaceProportion = attr.FreeSpaceProportion; + column.GroupWithItemCountFormat = attr.GroupWithItemCountFormat; + column.GroupWithItemCountSingularFormat = attr.GroupWithItemCountSingularFormat; + column.Hyperlink = attr.Hyperlink; + column.ImageAspectName = attr.ImageAspectName; + column.IsEditable = attr.IsEditableSet ? attr.IsEditable : editable; + column.IsTileViewColumn = attr.IsTileViewColumn; + column.IsVisible = attr.IsVisible; + column.MaximumWidth = attr.MaximumWidth; + column.MinimumWidth = attr.MinimumWidth; + column.Tag = attr.Tag; + if (attr.IsTextAlignSet) + column.TextAlign = attr.TextAlign; + column.ToolTipText = attr.ToolTipText; + if (attr.IsTriStateCheckBoxesSet) + column.TriStateCheckBoxes = attr.TriStateCheckBoxes; + column.UseInitialLetterForGroup = attr.UseInitialLetterForGroup; + column.Width = attr.Width; + if (attr.GroupCutoffs != null && attr.GroupDescriptions != null) + column.MakeGroupies(attr.GroupCutoffs, attr.GroupDescriptions); + return column; + } + + /// + /// Create a column. + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, OLVColumnAttribute attr) { + string columnTitle = (attr == null || String.IsNullOrEmpty(attr.Title)) ? title : attr.Title; + return new OLVColumn(columnTitle, aspectName); + } + + /// + /// Convert a property name to a displayable title. + /// + /// + /// + protected virtual string DisplayNameToColumnTitle(string displayName) { + string title = displayName.Replace("_", " "); + // Put a space between a lower-case letter that is followed immediately by an upper case letter + title = Regex.Replace(title, @"(\p{Ll})(\p{Lu})", @"$1 $2"); + return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title); + } + + /// + /// Configure the given column to show a checkbox if appropriate + /// + /// + /// + protected virtual void ConfigurePossibleBooleanColumn(OLVColumn column, Type propertyType) { + if (propertyType != typeof(bool) && propertyType != typeof(bool?) && propertyType != typeof(CheckState)) + return; + + column.CheckBoxes = true; + column.TextAlign = HorizontalAlignment.Center; + column.Width = 32; + column.TriStateCheckBoxes = (propertyType == typeof(bool?) || propertyType == typeof(CheckState)); + } + + /// + /// If this given type has an property marked with [OLVChildren], make delegates that will + /// traverse that property as the children of an instance of the model + /// + /// + /// + protected virtual void TryGenerateChildrenDelegates(TreeListView tlv, Type type) { + foreach (PropertyInfo pinfo in type.GetProperties()) { + OLVChildrenAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVChildrenAttribute)) as OLVChildrenAttribute; + if (attr != null) { + this.GenerateChildrenDelegates(tlv, pinfo); + return; + } + } + } + + /// + /// Generate CanExpand and ChildrenGetter delegates from the given property. + /// + /// + /// + protected virtual void GenerateChildrenDelegates(TreeListView tlv, PropertyInfo pinfo) { + Munger childrenGetter = new Munger(pinfo.Name); + tlv.CanExpandGetter = delegate(object x) { + try { + IEnumerable result = childrenGetter.GetValueEx(x) as IEnumerable; + return !ObjectListView.IsEnumerableEmpty(result); + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return false; + } + }; + tlv.ChildrenGetter = delegate(object x) { + try { + return childrenGetter.GetValueEx(x) as IEnumerable; + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return null; + } + }; + } + #endregion + + /* + #region Dynamic methods + + /// + /// Generate methods so that reflection is not needed. + /// + /// + /// + public static void GenerateMethods(ObjectListView olv, Type type) { + foreach (OLVColumn column in olv.Columns) { + GenerateColumnMethods(column, type); + } + } + + public static void GenerateColumnMethods(OLVColumn column, Type type) { + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) + column.AspectGetter = Generator.GenerateAspectGetter(type, column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + private static AspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, typeof(Object), new Type[] { type }, type, true); + Generator.GenerateIL(type, path, getter.GetILGenerator()); + return (AspectGetterDelegate)getter.CreateDelegate(typeof(AspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private static void GenerateIL(Type modelType, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + OpCodes.Castclass + // Generate the IL to access each part of the dotted chain + Type type = modelType; + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = Generator.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !modelType.IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private static Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + */ + } +} diff --git a/ObjectListView/Utilities/OLVExporter.cs b/ObjectListView/Utilities/OLVExporter.cs new file mode 100644 index 0000000..1400ba1 --- /dev/null +++ b/ObjectListView/Utilities/OLVExporter.cs @@ -0,0 +1,277 @@ +/* + * OLVExporter - Export the contents of an ObjectListView into various text-based formats + * + * Author: Phillip Piper + * Date: 7 August 2012, 10:35pm + * + * Change log: + * 2012-08-07 JPP Initial code + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace BrightIdeasSoftware { + /// + /// An OLVExporter converts a collection of rows from an ObjectListView + /// into a variety of textual formats. + /// + public class OLVExporter { + + /// + /// What format will be used for exporting + /// + public enum ExportFormat { + + /// + /// Tab separated values, according to http://www.iana.org/assignments/media-types/text/tab-separated-values + /// + TabSeparated = 1, + + /// + /// Alias for TabSeparated + /// + TSV = 1, + + /// + /// Comma separated values, according to http://www.ietf.org/rfc/rfc4180.txt + /// + CSV, + + /// + /// HTML table, according to me + /// + HTML + } + + #region Life and death + + /// + /// Create an empty exporter + /// + public OLVExporter() {} + + /// + /// Create an exporter that will export all the rows of the given ObjectListView + /// + /// + public OLVExporter(ObjectListView olv) : this(olv, olv.Objects) {} + + /// + /// Create an exporter that will export all the given rows from the given ObjectListView + /// + /// + /// + public OLVExporter(ObjectListView olv, IEnumerable objectsToExport) { + if (olv == null) throw new ArgumentNullException("olv"); + if (objectsToExport == null) throw new ArgumentNullException("objectsToExport"); + + this.ListView = olv; + this.ModelObjects = ObjectListView.EnumerableToArray(objectsToExport, true); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the textual + /// representation. If this is false (the default), only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + set { includeHiddenColumns = value; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. Default is true. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + set { includeColumnHeaders = value; } + } + private bool includeColumnHeaders = true; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// to be exported + /// + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + set { modelObjects = value; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + #region Commands + + /// + /// Export the nominated rows from the nominated ObjectListView. + /// Returns the result in the expected format. + /// + /// + /// + /// This will perform only one conversion, even if called multiple times with different formats. + public string ExportTo(ExportFormat format) { + if (results == null) + this.Convert(); + + return results[format]; + } + + /// + /// Convert + /// + public void Convert() { + + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + StringBuilder sbText = new StringBuilder(); + StringBuilder sbCsv = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (this.IncludeColumnHeaders) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.Text); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + + foreach (object modelObject in this.ModelObjects) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.GetStringValue(modelObject)); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + sbHtml.AppendLine("
      ", "", "
      ", "", "
      "); + + results = new Dictionary(); + results[ExportFormat.TabSeparated] = sbText.ToString(); + results[ExportFormat.CSV] = sbCsv.ToString(); + results[ExportFormat.HTML] = sbHtml.ToString(); + } + + private delegate string StringToString(string str); + + private void WriteOneRow(StringBuilder sb, IEnumerable strings, string startRow, string betweenCells, string endRow, StringToString encoder) { + sb.Append(startRow); + bool first = true; + foreach (string s in strings) { + if (!first) + sb.Append(betweenCells); + sb.Append(encoder == null ? s : encoder(s)); + first = false; + } + sb.AppendLine(endRow); + } + + private Dictionary results; + + #endregion + + #region Encoding + + /// + /// Encode a string such that it can be used as a value in a CSV file. + /// This basically means replacing any quote mark with two quote marks, + /// and enclosing the whole string in quotes. + /// + /// + /// + private static string CsvEncode(string text) { + if (text == null) + return null; + + const string DOUBLEQUOTE = @""""; // one double quote + const string TWODOUBEQUOTES = @""""""; // two double quotes + + StringBuilder sb = new StringBuilder(DOUBLEQUOTE); + sb.Append(text.Replace(DOUBLEQUOTE, TWODOUBEQUOTES)); + sb.Append(DOUBLEQUOTE); + + return sb.ToString(); + } + + /// + /// HTML-encodes a string and returns the encoded string. + /// + /// The text string to encode. + /// The HTML-encoded text. + /// Taken from http://www.west-wind.com/weblog/posts/2009/Feb/05/Html-and-Uri-String-Encoding-without-SystemWeb + private static string HtmlEncode(string text) { + if (text == null) + return null; + + StringBuilder sb = new StringBuilder(text.Length); + + int len = text.Length; + for (int i = 0; i < len; i++) { + switch (text[i]) { + case '<': + sb.Append("<"); + break; + case '>': + sb.Append(">"); + break; + case '"': + sb.Append("""); + break; + case '&': + sb.Append("&"); + break; + default: + if (text[i] > 159) { + // decimal numeric entity + sb.Append("&#"); + sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture)); + sb.Append(";"); + } else + sb.Append(text[i]); + break; + } + } + return sb.ToString(); + } + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/TypedObjectListView.cs b/ObjectListView/Utilities/TypedObjectListView.cs new file mode 100644 index 0000000..8eb6bd0 --- /dev/null +++ b/ObjectListView/Utilities/TypedObjectListView.cs @@ -0,0 +1,561 @@ +/* + * TypedObjectListView - A wrapper around an ObjectListView that provides type-safe delegates. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * v2.6 + * 2012-10-26 JPP - Handle rare case where a null model object was passed into aspect getters. + * v2.3 + * 2009-03-31 JPP - Added Objects property + * 2008-11-26 JPP - Added tool tip getting methods + * 2008-11-05 JPP - Added CheckState handling methods + * 2008-10-24 JPP - Generate dynamic methods MkII. This one handles value types + * 2008-10-21 JPP - Generate dynamic methods + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; +using System.Reflection.Emit; + +namespace BrightIdeasSoftware +{ + /// + /// A TypedObjectListView is a type-safe wrapper around an ObjectListView. + /// + /// + /// VCS does not support generics on controls. It can be faked to some degree, but it + /// cannot be completely overcome. In our case in particular, there is no way to create + /// the custom OLVColumn's that we need to truly be generic. So this wrapper is an + /// experiment in providing some type-safe access in a way that is useful and available today. + /// A TypedObjectListView is not more efficient than a normal ObjectListView. + /// Underneath, the same name of casts are performed. But it is easier to use since you + /// do not have to write the casts yourself. + /// + /// + /// The class of model object that the list will manage + /// + /// To use a TypedObjectListView, you write code like this: + /// + /// TypedObjectListView<Person> tlist = new TypedObjectListView<Person>(this.listView1); + /// tlist.CheckStateGetter = delegate(Person x) { return x.IsActive; }; + /// tlist.GetColumn(0).AspectGetter = delegate(Person x) { return x.Name; }; + /// ... + /// + /// To iterate over the selected objects, you can write something elegant like this: + /// + /// foreach (Person x in tlist.SelectedObjects) { + /// x.GrantSalaryIncrease(); + /// } + /// + /// + public class TypedObjectListView where T : class + { + /// + /// Create a typed wrapper around the given list. + /// + /// The listview to be wrapped + public TypedObjectListView(ObjectListView olv) { + this.olv = olv; + } + + //-------------------------------------------------------------------------------------- + // Properties + + /// + /// Return the model object that is checked, if only one row is checked. + /// If zero rows are checked, or more than one row, null is returned. + /// + public virtual T CheckedObject { + get { return (T)this.olv.CheckedObject; } + } + + /// + /// Return the list of all the checked model objects + /// + public virtual IList CheckedObjects { + get { + IList checkedObjects = this.olv.CheckedObjects; + List objects = new List(checkedObjects.Count); + foreach (object x in checkedObjects) + objects.Add((T)x); + + return objects; + } + set { this.olv.CheckedObjects = (IList)value; } + } + + /// + /// The ObjectListView that is being wrapped + /// + public virtual ObjectListView ListView { + get { return olv; } + set { olv = value; } + } + private ObjectListView olv; + + /// + /// Get or set the list of all model objects + /// + public virtual IList Objects { + get { + List objects = new List(this.olv.GetItemCount()); + for (int i = 0; i < this.olv.GetItemCount(); i++) + objects.Add(this.GetModelObject(i)); + + return objects; + } + set { this.olv.SetObjects(value); } + } + + /// + /// Return the model object that is selected, if only one row is selected. + /// If zero rows are selected, or more than one row, null is returned. + /// + public virtual T SelectedObject { + get { return (T)this.olv.SelectedObject; } + set { this.olv.SelectedObject = value; } + } + + /// + /// The list of model objects that are selected. + /// + public virtual IList SelectedObjects { + get { + List objects = new List(this.olv.SelectedIndices.Count); + foreach (int index in this.olv.SelectedIndices) + objects.Add((T)this.olv.GetModelObject(index)); + + return objects; + } + set { this.olv.SelectedObjects = (IList)value; } + } + + //-------------------------------------------------------------------------------------- + // Accessors + + /// + /// Return a typed wrapper around the column at the given index + /// + /// The index of the column + /// A typed column or null + public virtual TypedColumn GetColumn(int i) { + return new TypedColumn(this.olv.GetColumn(i)); + } + + /// + /// Return a typed wrapper around the column with the given name + /// + /// The name of the column + /// A typed column or null + public virtual TypedColumn GetColumn(string name) { + return new TypedColumn(this.olv.GetColumn(name)); + } + + /// + /// Return the model object at the given index + /// + /// The index of the model object + /// The model object or null + public virtual T GetModelObject(int index) { + return (T)this.olv.GetModelObject(index); + } + + //-------------------------------------------------------------------------------------- + // Delegates + + /// + /// CheckStateGetter + /// + /// + /// + public delegate CheckState TypedCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the check state getter + /// + public virtual TypedCheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { + this.checkStateGetter = value; + if (value == null) + this.olv.CheckStateGetter = null; + else + this.olv.CheckStateGetter = delegate(object x) { + return this.checkStateGetter((T)x); + }; + } + } + private TypedCheckStateGetterDelegate checkStateGetter; + + /// + /// BooleanCheckStateGetter + /// + /// + /// + public delegate bool TypedBooleanCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the boolean check state getter + /// + public virtual TypedBooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.olv.BooleanCheckStateGetter = null; + else + this.olv.BooleanCheckStateGetter = delegate(object x) { + return value((T)x); + }; + } + } + + /// + /// CheckStatePutter + /// + /// + /// + /// + public delegate CheckState TypedCheckStatePutterDelegate(T rowObject, CheckState newValue); + + /// + /// Gets or sets the check state putter delegate + /// + public virtual TypedCheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { + this.checkStatePutter = value; + if (value == null) + this.olv.CheckStatePutter = null; + else + this.olv.CheckStatePutter = delegate(object x, CheckState newValue) { + return this.checkStatePutter((T)x, newValue); + }; + } + } + private TypedCheckStatePutterDelegate checkStatePutter; + + /// + /// BooleanCheckStatePutter + /// + /// + /// + /// + public delegate bool TypedBooleanCheckStatePutterDelegate(T rowObject, bool newValue); + + /// + /// Gets or sets the boolean check state putter + /// + public virtual TypedBooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.olv.BooleanCheckStatePutter = null; + else + this.olv.BooleanCheckStatePutter = delegate(object x, bool newValue) { + return value((T)x, newValue); + }; + } + } + + /// + /// ToolTipGetter + /// + /// + /// + /// + public delegate String TypedCellToolTipGetterDelegate(OLVColumn column, T modelObject); + + /// + /// Gets or sets the cell tooltip getter + /// + public virtual TypedCellToolTipGetterDelegate CellToolTipGetter { + set { + if (value == null) + this.olv.CellToolTipGetter = null; + else + this.olv.CellToolTipGetter = delegate(OLVColumn col, Object x) { + return value(col, (T)x); + }; + } + } + + /// + /// Gets or sets the header tool tip getter + /// + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return this.olv.HeaderToolTipGetter; } + set { this.olv.HeaderToolTipGetter = value; } + } + + //-------------------------------------------------------------------------------------- + // Commands + + /// + /// This method will generate AspectGetters for any column that has an AspectName. + /// + public virtual void GenerateAspectGetters() { + for (int i = 0; i < this.ListView.Columns.Count; i++) + this.GetColumn(i).GenerateAspectGetter(); + } + } + + /// + /// A type-safe wrapper around an OLVColumn + /// + /// + public class TypedColumn where T : class + { + /// + /// Creates a TypedColumn + /// + /// + public TypedColumn(OLVColumn column) { + this.column = column; + } + private OLVColumn column; + + /// + /// + /// + /// + /// + public delegate Object TypedAspectGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate void TypedAspectPutterDelegate(T rowObject, Object newValue); + + /// + /// + /// + /// + /// + public delegate Object TypedGroupKeyGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate Object TypedImageGetterDelegate(T rowObject); + + /// + /// + /// + public TypedAspectGetterDelegate AspectGetter { + get { return this.aspectGetter; } + set { + this.aspectGetter = value; + if (value == null) + this.column.AspectGetter = null; + else + this.column.AspectGetter = delegate(object x) { + return x == null ? null : this.aspectGetter((T)x); + }; + } + } + private TypedAspectGetterDelegate aspectGetter; + + /// + /// + /// + public TypedAspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { + this.aspectPutter = value; + if (value == null) + this.column.AspectPutter = null; + else + this.column.AspectPutter = delegate(object x, object newValue) { + this.aspectPutter((T)x, newValue); + }; + } + } + private TypedAspectPutterDelegate aspectPutter; + + /// + /// + /// + public TypedImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { + this.imageGetter = value; + if (value == null) + this.column.ImageGetter = null; + else + this.column.ImageGetter = delegate(object x) { + return this.imageGetter((T)x); + }; + } + } + private TypedImageGetterDelegate imageGetter; + + /// + /// + /// + public TypedGroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { + this.groupKeyGetter = value; + if (value == null) + this.column.GroupKeyGetter = null; + else + this.column.GroupKeyGetter = delegate(object x) { + return this.groupKeyGetter((T)x); + }; + } + } + private TypedGroupKeyGetterDelegate groupKeyGetter; + + #region Dynamic methods + + /// + /// Generate an aspect getter that does the same thing as the AspectName, + /// except without using reflection. + /// + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + /// If AspectName is empty, this method will do nothing, otherwise + /// this will replace any existing AspectGetter. + /// + /// + public void GenerateAspectGetter() { + if (!String.IsNullOrEmpty(this.column.AspectName)) + this.AspectGetter = this.GenerateAspectGetter(typeof(T), this.column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + private TypedAspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, + typeof(Object), new Type[] { type }, type, true); + this.GenerateIL(type, path, getter.GetILGenerator()); + return (TypedAspectGetterDelegate)getter.CreateDelegate(typeof(TypedAspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private void GenerateIL(Type type, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + + // Generate the IL to access each part of the dotted chain + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = this.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !typeof(T).IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + if (Munger.IgnoreMissingAspects) + il.Emit(OpCodes.Ldnull); + else + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + } +} diff --git a/ObjectListView/VirtualObjectListView.cs b/ObjectListView/VirtualObjectListView.cs new file mode 100644 index 0000000..8c3ba28 --- /dev/null +++ b/ObjectListView/VirtualObjectListView.cs @@ -0,0 +1,1255 @@ +/* + * VirtualObjectListView - A virtual listview delays fetching model objects until they are actually displayed. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-06-14 JPP - Moved handling of CheckBoxes on virtual lists into base class (ObjectListView). + * This allows the property to be set correctly, even when set via an upcast reference. + * 2015-03-25 JPP - Subscribe to change notifications when objects are added + * v2.8 + * 2014-09-26 JPP - Correct an incorrect use of checkStateMap when setting CheckedObjects + * and a CheckStateGetter is installed + * v2.6 + * 2012-06-13 JPP - Corrected several bugs related to groups on virtual lists. + * - Added EnsureNthGroupVisible() since EnsureGroupVisible() can't work on virtual lists. + * v2.5.1 + * 2012-05-04 JPP - Avoid bug/feature in ListView.VirtalListSize setter that causes flickering + * when the size of the list changes. + * 2012-04-24 JPP - Fixed bug that occurred when adding/removing item while the view was grouped. + * v2.5 + * 2011-05-31 JPP - Setting CheckedObjects is more efficient on large collections + * 2011-04-05 JPP - CheckedObjects now only returns objects that are currently in the list. + * ClearObjects() now resets all check state info. + * 2011-03-31 JPP - Filtering on grouped virtual lists no longer behaves strangely. + * 2011-03-17 JPP - Virtual lists can (finally) set CheckBoxes back to false if it has been set to true. + * (this is a little hacky and may not work reliably). + * - GetNextItem() and GetPreviousItem() now work on grouped virtual lists. + * 2011-03-08 JPP - BREAKING CHANGE: 'DataSource' was renamed to 'VirtualListDataSource'. This was necessary + * to allow FastDataListView which is both a DataListView AND a VirtualListView -- + * which both used a 'DataSource' property :( + * v2.4 + * 2010-04-01 JPP - Support filtering + * v2.3 + * 2009-08-28 JPP - BIG CHANGE. Virtual lists can now have groups! + * - Objects property now uses "yield return" -- much more efficient for big lists + * 2009-08-07 JPP - Use new scheme for formatting rows/cells + * v2.2.1 + * 2009-07-24 JPP - Added specialised version of RefreshSelectedObjects() which works efficiently with virtual lists + * (thanks to chriss85 for finding this bug) + * 2009-07-03 JPP - Standardized code format + * v2.2 + * 2009-04-06 JPP - ClearObjects() now works again + * v2.1 + * 2009-02-24 JPP - Removed redundant OnMouseDown() since checkbox + * handling is now handled in the base class + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-12-07 JPP - Trigger Before/AfterSearching events + * 2008-11-15 JPP - Fixed some caching issues + * 2008-11-05 JPP - Rewrote handling of check boxes + * 2008-10-28 JPP - Handle SetSelectedObjects(null) + * 2008-10-02 JPP - MAJOR CHANGE: Use IVirtualListDataSource + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A virtual object list view operates in virtual mode, that is, it only gets model objects for + /// a row when it is needed. This gives it the ability to handle very large numbers of rows with + /// minimal resources. + /// + /// A listview is not a great user interface for a large number of items. But if you've + /// ever wanted to have a list with 10 million items, go ahead, knock yourself out. + /// Virtual lists can never iterate their contents. That would defeat the whole purpose. + /// Animated GIFs should not be used in virtual lists. Animated GIFs require some state + /// information to be stored for each animation, but virtual lists specifically do not keep any state information. + /// In any case, you really do not want to keep state information for 10 million animations! + /// + /// Although it isn't documented, .NET virtual lists cannot have checkboxes. This class codes around this limitation, + /// but you must use the functions provided by ObjectListView: CheckedObjects, CheckObject(), UncheckObject() and their friends. + /// If you use the normal check box properties (CheckedItems or CheckedIndicies), they will throw an exception, since the + /// list is in virtual mode, and .NET "knows" it can't handle checkboxes in virtual mode. + /// + /// Due to the limits of the underlying Windows control, virtual lists do not trigger ItemCheck/ItemChecked events. + /// Use a CheckStatePutter instead. + /// To enable grouping, you must provide an implementation of IVirtualGroups interface, via the GroupingStrategy property. + /// Similarly, to enable filtering on the list, your VirtualListDataSource must also implement the IFilterableDataSource interface. + /// + public class VirtualObjectListView : ObjectListView + { + /// + /// Create a VirtualObjectListView + /// + public VirtualObjectListView() + : base() { + this.VirtualMode = true; // Virtual lists have to be virtual -- no prizes for guessing that :) + + this.CacheVirtualItems += new CacheVirtualItemsEventHandler(this.HandleCacheVirtualItems); + this.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(this.HandleRetrieveVirtualItem); + this.SearchForVirtualItem += new SearchForVirtualItemEventHandler(this.HandleSearchForVirtualItem); + + // At the moment, we don't need to handle this event. But we'll keep this comment to remind us about it. + this.VirtualItemsSelectionRangeChanged += new ListViewVirtualItemsSelectionRangeChangedEventHandler(this.HandleVirtualItemsSelectionRangeChanged); + + this.VirtualListDataSource = new VirtualListVersion1DataSource(this); + + // Virtual lists have to manage their own check state, since the normal ListView control + // doesn't even allow checkboxes on virtual lists + this.PersistentCheckBoxes = true; + } + + #region Public Properties + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + // Virtual lists need Vista and a grouping strategy to show groups + return (ObjectListView.IsVistaOrLater && this.GroupingStrategy != null); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + /// This class optimizes the management of CheckStates so that it will work efficiently even on + /// large lists of item. However, those optimizations are impossible if you install a CheckStateGetter. + /// With a CheckStateGetter installed, the performance of this method is O(n) where n is the size + /// of the list. This could be painfully slow. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IList CheckedObjects { + get { + // If we aren't should checkboxes, then no objects can be checked + if (!this.CheckBoxes) + return new ArrayList(); + + // If the data source has somehow vanished, we can't do anything + if (this.VirtualListDataSource == null) + return new ArrayList(); + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) + return base.CheckedObjects; + + // Collect items that are checked AND that still exist in the list. + ArrayList objects = new ArrayList(); + foreach (KeyValuePair kvp in this.CheckStateMap) + { + if (kvp.Value == CheckState.Checked && + (!this.CheckedObjectsMustStillExistInList || + this.VirtualListDataSource.GetObjectIndex(kvp.Key) >= 0)) + objects.Add(kvp.Key); + } + return objects; + } + set { + if (!this.CheckBoxes) + return; + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) { + base.CheckedObjects = value; + return; + } + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + + // Uncheck anything that is no longer checked + Object[] keys = new Object[this.CheckStateMap.Count]; + this.CheckStateMap.Keys.CopyTo(keys, 0); + foreach (Object key in keys) { + if (!table.Contains(key)) + this.SetObjectCheckedness(key, CheckState.Unchecked); + } + + // Check all the new checked objects + foreach (Object x in table.Keys) + this.SetObjectCheckedness(x, CheckState.Checked); + + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting virtual CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + } + + /// + /// Gets or sets whether or not an object will be included in the CheckedObjects + /// collection, even if it is not present in the control at the moment + /// + /// + /// This property is an implementation detail and should not be altered. + /// + protected internal bool CheckedObjectsMustStillExistInList { + get { return checkedObjectsMustStillExistInList; } + set { checkedObjectsMustStillExistInList = value; } + } + private bool checkedObjectsMustStillExistInList = true; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + for (int i = 0; i < this.GetItemCount(); i++) + yield return this.GetModelObject(i); + } + } + + /// + /// Gets or sets the strategy that will be used to create groups + /// + /// + /// This must be provided for a virtual list to show groups. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IVirtualGroups GroupingStrategy { + get { return this.groupingStrategy; } + set { this.groupingStrategy = value; } + } + private IVirtualGroups groupingStrategy; + + /// + /// Gets whether or not the current list is filtering its contents + /// + /// + /// This is only possible if our underlying data source supports filtering. + /// + public override bool IsFiltering { + get { + return base.IsFiltering && (this.VirtualListDataSource is IFilterableDataSource); + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// Setting this property preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code -- performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists, but if you try to iterate through a list + /// of 10 million objects, it may take some time :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + try { + // If we are filtering, we have to temporarily disable filtering so we get + // the whole collection + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(null, null); + return this.FilteredObjects; + } finally { + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + } + } + set { base.Objects = value; } + } + + /// + /// This delegate is used to fetch a rowObject, given it's index within the list + /// + /// Only use this property if you are not using a VirtualListDataSource. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowGetterDelegate RowGetter { + get { return ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter; } + set { ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter = value; } + } + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + override public bool ShowGroups { + get { + // Pre-Vista, virtual lists cannot show groups + return ObjectListView.IsVistaOrLater && this.showGroups; + } + set { + this.showGroups = value; + if (this.Created && !value) + this.DisableVirtualGroups(); + } + } + private bool showGroups; + + + /// + /// Get/set the data source that is behind this virtual list + /// + /// Setting this will cause the list to redraw. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IVirtualListDataSource VirtualListDataSource { + get { + return this.virtualListDataSource; + } + set { + this.virtualListDataSource = value; + this.CustomSorter = delegate(OLVColumn column, SortOrder sortOrder) { + this.ClearCachedInfo(); + this.virtualListDataSource.Sort(column, sortOrder); + }; + this.BuildList(false); + } + } + private IVirtualListDataSource virtualListDataSource; + + /// + /// Gets or sets the number of rows in this virtual list. + /// + /// + /// There is an annoying feature/bug in the .NET ListView class. + /// When you change the VirtualListSize property, it always scrolls so + /// that the focused item is the top item. This is annoying since it makes + /// the virtual list seem to flicker as the control scrolls to show the focused + /// item and then scrolls back to where ObjectListView wants it to be. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected new virtual int VirtualListSize { + get { return base.VirtualListSize; } + set { + if (value == this.VirtualListSize || value < 0) + return; + + // Get around the 'private' marker on 'virtualListSize' field using reflection + if (virtualListSizeFieldInfo == null) { + virtualListSizeFieldInfo = typeof(ListView).GetField("virtualListSize", BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(virtualListSizeFieldInfo != null); + } + + // Set the base class private field so that it keeps on working + virtualListSizeFieldInfo.SetValue(this, value); + + // Send a raw message to change the virtual list size *without* changing the scroll position + if (this.IsHandleCreated && !this.DesignMode) + NativeMethods.SetItemCount(this, value); + } + } + static private FieldInfo virtualListSizeFieldInfo; + + #endregion + + #region OLV accessing + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + public override int GetItemCount() { + return this.VirtualListSize; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public override object GetModelObject(int index) { + if (this.VirtualListDataSource != null && index >= 0 && index < this.GetItemCount()) + return this.VirtualListDataSource.GetNthObject(index); + else + return null; + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public override int IndexOf(Object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return -1; + + return this.VirtualListDataSource.GetObjectIndex(modelObject); + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public override OLVListItem ModelToItem(object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return null; + + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + return index >= 0 ? this.GetItem(index) : null; + } + + #endregion + + #region Object manipulation + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void AddObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.AddObjects(args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.CheckStateMap.Clear(); + this.SetObjects(new ArrayList()); + } + } + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The index of the group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// + public virtual void EnsureNthGroupVisible(int groupIndex) { + if (!this.ShowGroups) + return; + + if (groupIndex <= 0 || groupIndex >= this.OLVGroups.Count) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + int lastItemInGroup = this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1); + Rectangle r = this.GetItemRect(lastItemInGroup); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Inserts the given collection of model objects to this control at hte given location + /// + /// The index where the new objects will be inserted + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the given position of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void InsertObjects(int index, ICollection modelObjects) + { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(index, modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.InsertObjects(index, args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + /// This method does not resort the items. + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + try { + this.BeginUpdate(); + this.ClearCachedInfo(); + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0) { + this.VirtualListDataSource.UpdateObject(index, modelObject); + this.RedrawItems(index, index, true); + } + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public override void RefreshSelectedObjects() { + foreach (int index in this.SelectedIndices) + this.RedrawItems(index, index, true); + } + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// Due to problems in the underlying ListView, if you remove all the objects from + /// the control using this method and the list scroll vertically when you do so, + /// then when you subsequently add more objects to the control, + /// the vertical scroll bar will become confused and the control will draw one or more + /// blank lines at the top of the list. + /// + public override void RemoveObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the removed objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + + try { + this.BeginUpdate(); + this.VirtualListDataSource.RemoveObjects(args.ObjectsToRemove); + this.BuildList(); + this.UnsubscribeNotifications(args.ObjectsToRemove); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Select the row that is displaying the given model object. All other rows are deselected. + /// + /// Model object to select + /// Should the object be focused as well? + public override void SelectObject(object modelObject, bool setFocus) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + // Check that the object is in the list (plus not all data sources can locate objects) + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index < 0 || index >= this.VirtualListSize) + return; + + // If the given model is already selected, don't do anything else (prevents an flicker) + if (this.SelectedIndices.Count == 1 && this.SelectedIndices[0] == index) + return; + + // Finally, select the row + this.SelectedIndices.Clear(); + this.SelectedIndices.Add(index); + if (setFocus && this.SelectedItem != null) + this.SelectedItem.Focused = true; + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + /// This method has O(n) performance where n is the number of model objects passed. + /// Do not use this to select all the rows in the list -- use SelectAll() for that. + public override void SelectObjects(IList modelObjects) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0 && index < this.VirtualListSize) + this.SelectedIndices.Add(index); + } + } + + /// + /// Set the collection of objects that this control will show. + /// + /// + /// Should the state of the list be preserved as far as is possible. + public override void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(null, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + + this.BeginUpdate(); + try { + this.VirtualListDataSource.SetObjects(args.NewObjects); + this.BuildList(); + this.UpdateNotificationSubscriptions(args.NewObjects); + } + finally { + this.EndUpdate(); + } + } + + #endregion + + #region Check boxes +// +// /// +// /// Check all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void CheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Checked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - CheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// +// } +// +// /// +// /// Uncheck all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void UncheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Unchecked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - UncheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does know and the value from the control will be used. + /// + /// + /// + protected override CheckState? GetCheckState(object modelObject) + { + if (this.CheckStateGetter != null) + return base.GetCheckState(modelObject); + + CheckState state; + if (modelObject != null && this.CheckStateMap.TryGetValue(modelObject, out state)) + return state; + return CheckState.Unchecked; + } + + #endregion + + #region Implementation + + /// + /// Rebuild the list with its current contents. + /// + /// + /// Invalidate any cached information when we rebuild the list. + /// + public override void BuildList(bool shouldPreserveSelection) { + this.UpdateVirtualListSize(); + this.ClearCachedInfo(); + if (this.ShowGroups) + this.BuildGroups(); + else + this.Sort(); + this.Invalidate(); + } + + /// + /// Clear any cached info this list may have been using + /// + public override void ClearCachedInfo() { + this.lastRetrieveVirtualItemIndex = -1; + } + + /// + /// Do the work of creating groups for this control + /// + /// + protected override void CreateGroups(IEnumerable groups) { + + // In a virtual list, we cannot touch the Groups property. + // It was obviously not written for virtual list and often throws exceptions. + + NativeMethods.ClearGroups(this); + + this.EnableVirtualGroups(); + + foreach (OLVGroup group in groups) { + System.Diagnostics.Debug.Assert(group.Items.Count == 0, "Groups in virtual lists cannot set Items. Use VirtualItemCount instead."); + System.Diagnostics.Debug.Assert(group.VirtualItemCount > 0, "VirtualItemCount must be greater than 0."); + + group.InsertGroupNewStyle(this); + } + } + + /// + /// Do the plumbing to disable groups on a virtual list + /// + protected void DisableVirtualGroups() { + NativeMethods.ClearGroups(this); + //System.Diagnostics.Debug.WriteLine(err); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 0, 0); + //System.Diagnostics.Debug.WriteLine(x); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr x2 = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, 0, 0); + //System.Diagnostics.Debug.WriteLine(x2); + } + + /// + /// Do the plumbing to enable groups on a virtual list + /// + protected void EnableVirtualGroups() { + + // We need to implement the IOwnerDataCallback interface + if (this.ownerDataCallbackImpl == null) + this.ownerDataCallbackImpl = new OwnerDataCallbackImpl(this); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr ptr = Marshal.GetComInterfaceForObject(ownerDataCallbackImpl, typeof(IOwnerDataCallback)); + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, ptr, 0); + //System.Diagnostics.Debug.WriteLine(x); + Marshal.Release(ptr); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 1, 0); + //System.Diagnostics.Debug.WriteLine(x); + } + private OwnerDataCallbackImpl ownerDataCallbackImpl; + + /// + /// Return the position of the given itemIndex in the list as it currently shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups) + return itemIndex; + + int groupIndex = this.GroupingStrategy.GetGroup(itemIndex); + int displayIndex = 0; + for (int i = 0; i < groupIndex - 1; i++) + displayIndex += this.OLVGroups[i].VirtualItemCount; + displayIndex += this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemIndex); + + return displayIndex; + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public override OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return base.GetLastItemInDisplayOrder(); + + if (this.OLVGroups.Count > 0) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + if (lastGroup.VirtualItemCount > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.OLVGroups == null || this.OLVGroups.Count == 0) + return this.GetItem(n); + + foreach (OLVGroup group in this.OLVGroups) { + if (n < group.VirtualItemCount) + return this.GetItem(this.GroupingStrategy.GetGroupMember(group, n)); + + n -= group.VirtualItemCount; + } + + return null; + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A OLVListItem + public override OLVListItem GetNextItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetNextItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given item is null, return the first member of the first group + if (itemToFind == null) { + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[0], 0)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the last member, just return the next member + if (indexWithinGroup < this.OLVGroups[groupIndex].VirtualItemCount - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup + 1)); + + // The item is the last member of its group. Return the first member of the next group + // (unless there isn't a next group) + if (groupIndex < this.OLVGroups.Count - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex + 1], 0)); + + return null; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public override OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetPreviousItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given items is null, return the last member of the last group + if (itemToFind == null) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the first member of the group, just return the previous member + if (indexWithinGroup > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup - 1)); + + // The item is the first member of its group. Return the last member of the previous group + // (if there is one) + if (groupIndex > 0) { + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// + protected override IList MakeGroups(GroupingParameters parms) { + if (this.GroupingStrategy == null) + return new List(); + else + return this.GroupingStrategy.GetGroups(parms); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + public virtual OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvi = new OLVListItem(this.GetModelObject(itemIndex)); + this.FillInValues(olvi, olvi.RowObject); + + this.PostProcessOneRow(itemIndex, this.GetDisplayOrderOfItemIndex(itemIndex), olvi); + + if (this.HotRowIndex == itemIndex) + this.UpdateHotRow(olvi); + + return olvi; + } + + /// + /// On virtual lists, this cannot work. + /// + protected override void PostProcessRows() { + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected override CheckState PutCheckState(object modelObject, CheckState state) { + state = base.PutCheckState(modelObject, state); + this.CheckStateMap[modelObject] = state; + return state; + } + + /// + /// Refresh the given item in the list + /// + /// The item to refresh + public override void RefreshItem(OLVListItem olvi) { + this.ClearCachedInfo(); + this.RedrawItems(olvi.Index, olvi.Index, true); + } + + /// + /// Change the size of the list + /// + /// + protected virtual void SetVirtualListSize(int newSize) { + if (newSize < 0 || this.VirtualListSize == newSize) + return; + + int oldSize = this.VirtualListSize; + + this.ClearCachedInfo(); + + // There is a bug in .NET when a virtual ListView is cleared + // (i.e. VirtuaListSize set to 0) AND it is scrolled vertically: the scroll position + // is wrong when the list is next populated. To avoid this, before + // clearing a virtual list, we make sure the list is scrolled to the top. + // [6 weeks later] Damn this is a pain! There are cases where this can also throw exceptions! + try { + if (newSize == 0 && this.TopItemIndex > 0) + this.TopItemIndex = 0; + } + catch (Exception) { + // Ignore any failures + } + + // In strange cases, this can throw the exceptions too. The best we can do is ignore them :( + try { + this.VirtualListSize = newSize; + } + catch (ArgumentOutOfRangeException) { + // pass + } + catch (NullReferenceException) { + // pass + } + + // Tell the world that the size of the list has changed + this.OnItemsChanged(new ItemsChangedEventArgs(oldSize, this.VirtualListSize)); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// VirtualObjectListViews always own their collections, so this is a no-op. + /// + /// + protected override void TakeOwnershipOfObjects() { + } + + /// + /// Change the state of the control to reflect changes in filtering + /// + protected override void UpdateFiltering() { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + if (filterable == null) + return; + + this.BeginUpdate(); + try { + int originalSize = this.VirtualListSize; + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + this.BuildList(); + + //// If the filtering actually did something, rebuild the groups if they are being shown + //if (originalSize != this.VirtualListSize && this.ShowGroups) + // this.BuildGroups(); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change the size of the virtual list so that it matches its data source + /// + public virtual void UpdateVirtualListSize() { + if (this.VirtualListDataSource != null) + this.SetVirtualListSize(this.VirtualListDataSource.GetObjectCount()); + } + + #endregion + + #region Event handlers + + /// + /// Handle the CacheVirtualItems event + /// + /// + /// + protected virtual void HandleCacheVirtualItems(object sender, CacheVirtualItemsEventArgs e) { + if (this.VirtualListDataSource != null) + this.VirtualListDataSource.PrepareCache(e.StartIndex, e.EndIndex); + } + + /// + /// Handle a RetrieveVirtualItem + /// + /// + /// + protected virtual void HandleRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { + // .NET 2.0 seems to generate a lot of these events. Before drawing *each* sub-item, + // this event is triggered 4-8 times for the same index. So we save lots of CPU time + // by caching the last result. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleRetrieveVirtualItem({0})", e.ItemIndex)); + + if (this.lastRetrieveVirtualItemIndex != e.ItemIndex) { + this.lastRetrieveVirtualItemIndex = e.ItemIndex; + this.lastRetrieveVirtualItem = this.MakeListViewItem(e.ItemIndex); + } + e.Item = this.lastRetrieveVirtualItem; + } + + /// + /// Handle the SearchForVirtualList event, which is called when the user types into a virtual list + /// + /// + /// + protected virtual void HandleSearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e) { + // The event has e.IsPrefixSearch, but as far as I can tell, this is always false (maybe that's different under Vista) + // So we ignore IsPrefixSearch and IsTextSearch and always to a case insensitive prefix match. + + // We can't do anything if we don't have a data source + if (this.VirtualListDataSource == null) + return; + + // Where should we start searching? If the last row is focused, the SearchForVirtualItemEvent starts searching + // from the next row, which is actually an invalidate index -- so we make sure we never go past the last object. + int start = Math.Min(e.StartIndex, this.VirtualListDataSource.GetObjectCount() - 1); + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(e.Text, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return; + + // Do the search + int i = this.FindMatchingRow(args.StringToFind, args.StartSearchFrom, e.Direction); + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(args.StringToFind, i); + this.OnAfterSearching(args2); + + // If we found a match, tell the event + if (i != -1) + e.Index = i; + } + + /// + /// Handle the VirtualItemsSelectionRangeChanged event, which is called "when the selection state of a range of items has changed" + /// + /// + /// + /// This method is not called whenever the selection changes on a virtual list. It only seems to be triggered when + /// the user uses Shift-Ctrl-Click to change the selection + protected virtual void HandleVirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e) { + // System.Diagnostics.Debug.WriteLine(string.Format("HandleVirtualItemsSelectionRangeChanged: {0}->{1}, selected: {2}", e.StartIndex, e.EndIndex, e.IsSelected)); + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected override int FindMatchInRange(string text, int first, int last, OLVColumn column) { + return this.VirtualListDataSource.SearchText(text, first, last, column); + } + + #endregion + + #region Variable declarations + + private OLVListItem lastRetrieveVirtualItem; + private int lastRetrieveVirtualItemIndex = -1; + + #endregion + } +} diff --git a/ObjectListView/olv-keyfile.snk b/ObjectListView/olv-keyfile.snk new file mode 100644 index 0000000000000000000000000000000000000000..2658a0adcf122aaa2a591535b53464d516af3378 GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa500986W$cIN!~W%bg8iKqt=v+03$~e~mJs!s zjxU8c(azlkAM^?lBdSg#@Xo86g5b(px(_u*|NRInNPMa(oZ7FOGX3y+S9*R?1vg*78kM6LjIK||X zWAU4blpG9GP}*;3w5@>NY`@4N-#_U$uE!7hH-#IbZu}s16Lpq{mQ;i43=-|@nVZDs zG|+jdK4Cm@V#c*g=H%5QNh=MIIeg0)t4qN7H3-6RuS70^Bde3q0o`&}OfWbuURm=Y zn5*%bskV-f%^ClA~ zN7~lW00)-QecLE7reqRZ{s)OjgHOfCAWI2#-kPm(z2TWw^;P~&q24T=-IOLtj~kL+ zUJ}~BbjP&wIAX literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 83a0af9..d214231 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,138 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General * Stich991 - Italian translation * tuku473 - Design suggestions, colors, Spanish translation -* Lachesis - French translation -* Delusional Moonlight - Russian translation ### AlphaDream Engine * irdkwia - Finding games that used the engine diff --git a/VG Music Studio - Core/ADPCMDecoder.cs b/VG Music Studio - Core/ADPCMDecoder.cs index cb2a5d8..f2ee92c 100644 --- a/VG Music Studio - Core/ADPCMDecoder.cs +++ b/VG Music Studio - Core/ADPCMDecoder.cs @@ -1,6 +1,5 @@ namespace Kermalis.VGMusicStudio.Core; -// TODO: Struct or something to prevent allocations internal sealed class ADPCMDecoder { private static readonly short[] _indexTable = new short[8] diff --git a/VG Music Studio - Core/Assembler.cs b/VG Music Studio - Core/Assembler.cs index b23b512..5274414 100644 --- a/VG Music Studio - Core/Assembler.cs +++ b/VG Music Studio - Core/Assembler.cs @@ -4,18 +4,17 @@ using System.Diagnostics; using System.Globalization; using System.IO; -using static Kermalis.EndianBinaryIO.EndianBinaryPrimitives; namespace Kermalis.VGMusicStudio.Core; internal sealed class Assembler : IDisposable { - private sealed class Pair // Must be a class + private class Pair { public bool Global; public int Offset; } - private struct Pointer + private class Pointer { public string Label; public int BinaryOffset; @@ -52,8 +51,7 @@ public Assembler(string fileName, int baseOffset, Endianness endianness, Diction _stream = new MemoryStream(); _writer = new EndianBinaryWriter(_stream, endianness: endianness); - string status = Read(fileName); - Debug.WriteLine(status); + Debug.WriteLine(Read(fileName)); SetBaseOffset(baseOffset); } @@ -66,11 +64,13 @@ public void SetBaseOffset(int baseOffset) // There is a pointer (p) to SEQ_STUFF at the binary offset 0x1DFC _stream.Position = p.BinaryOffset; _stream.Read(span); - int oldPointer = ReadInt32(span, Endianness); // If there was a pointer to "SEQ_STUFF+4", the pointer would be 0x1504, at binary offset 0x1DFC + int oldPointer = EndianBinaryPrimitives.ReadInt32(span, Endianness); // If there was a pointer to "SEQ_STUFF+4", the pointer would be 0x1504, at binary offset 0x1DFC int labelOffset = oldPointer - BaseOffset; // Then labelOffset is 0x1004 (SEQ_STUFF+4) _stream.Position = p.BinaryOffset; - _writer.WriteInt32(baseOffset + labelOffset); // Copy the new pointer to binary offset 0x1DF4 + _writer.WriteInt32(baseOffset + labelOffset); // b will contain {0x04, 0x28, 0x00, 0x00} [0x2804] (SEQ_STUFF+4 + baseOffset) + // Copy the new pointer to binary offset 0x1DF4 + // TODO: UPDATE THESE OLD COMMENTS LOL } BaseOffset = baseOffset; } @@ -115,7 +115,7 @@ private string Read(string fileName) } bool readingCMD = false; // If it's reading the command - string? cmd = null; + string cmd = null; var args = new List(); string str = string.Empty; foreach (char c in line) @@ -124,7 +124,7 @@ private string Read(string fileName) { break; } - if (c == '.' && cmd is null) + else if (c == '.' && cmd == null) { readingCMD = true; } @@ -156,7 +156,7 @@ private string Read(string fileName) str += c; } } - if (cmd is null) + if (cmd == null) { continue; // Commented line } @@ -191,12 +191,11 @@ private string Read(string fileName) } case "global": { - if (!_labels.TryGetValue(args[0], out Pair? pair)) + if (!_labels.ContainsKey(args[0])) { - pair = new Pair(); - _labels.Add(args[0], pair); + _labels.Add(args[0], new Pair()); } - pair.Global = true; + _labels[args[0]].Global = true; break; } case "align": @@ -285,7 +284,7 @@ private int ParseInt(string value) { return def; } - if (_labels.TryGetValue(value, out Pair? pair)) + if (_labels.TryGetValue(value, out Pair pair)) { _lPointers.Add(new Pointer { Label = value, BinaryOffset = BinaryLength }); return pair.Offset; @@ -359,7 +358,7 @@ private int ParseInt(string value) return ret; } - throw new ArgumentOutOfRangeException(nameof(value), value, null); + throw new ArgumentOutOfRangeException(nameof(value)); } public void Dispose() diff --git a/VG Music Studio - Core/Config.cs b/VG Music Studio - Core/Config.cs index 2f26ad5..f3c34b3 100644 --- a/VG Music Studio - Core/Config.cs +++ b/VG Music Studio - Core/Config.cs @@ -1,32 +1,24 @@ -using Kermalis.VGMusicStudio.Core.Properties; -using Kermalis.VGMusicStudio.Core.Util; -using System; +using System; using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core; public abstract class Config : IDisposable { - public readonly struct Song + public sealed class Song { - public readonly int Index; - public readonly string Name; + public long Index; + public string Name; - public Song(int index, string name) + public Song(long index, string name) { Index = index; Name = name; } - public static bool operator ==(Song left, Song right) - { - return left.Equals(right); - } - public static bool operator !=(Song left, Song right) - { - return !(left == right); - } - public override bool Equals(object? obj) { return obj is Song other && other.Index == Index; @@ -45,16 +37,32 @@ public sealed class Playlist public string Name; public List Songs; - public Playlist(string name, List songs) + public Playlist(string name, IEnumerable songs) { Name = name; - Songs = songs; + Songs = songs.ToList(); } public override string ToString() { - int num = Songs.Count; - return string.Format("{0} - ({1:N0} {2})", Name, num, LanguageUtils.HandlePlural(num, Strings.Song_s_)); + int songCount = Songs.Count; + CultureInfo cul = Thread.CurrentThread.CurrentUICulture; + if (cul.TwoLetterISOLanguageName == "it") // Italian + { + // PlaylistName - (1 Canzone) + // PlaylistName - (2 Canzoni) + return $"{Name} - ({songCount} {(songCount == 1 ? "Canzone" : "Canzoni")})"; + } + if (cul.TwoLetterISOLanguageName == "es") // Spanish + { + // PlaylistName - (1 Canción) + // PlaylistName - (2 Canciones) + return $"{Name} - ({songCount} {(songCount == 1 ? "Canción" : "Canciones")})"; + } + // Fallback to en-US + // PlaylistName - (1 Song) + // PlaylistName - (2 Songs) + return $"{Name} - ({songCount} {(songCount == 1 ? "Song" : "Songs")})"; } } @@ -65,7 +73,7 @@ protected Config() Playlists = new List(); } - public bool TryGetFirstSong(int index, out Song song) + public Song? GetFirstSong(long index) { foreach (Playlist p in Playlists) { @@ -73,17 +81,15 @@ public bool TryGetFirstSong(int index, out Song song) { if (s.Index == index) { - song = s; - return true; + return s; } } } - song = default; - return false; + return null; } public abstract string GetGameName(); - public abstract string GetSongName(int index); + public abstract string GetSongName(long index); public virtual void Dispose() { diff --git a/VG Music Studio - Core/Config.yaml b/VG Music Studio - Core/Config.yaml index c7c809c..d4bdf7b 100644 --- a/VG Music Studio - Core/Config.yaml +++ b/VG Music Studio - Core/Config.yaml @@ -6,132 +6,132 @@ PlaylistMode: "Random" # "Random" or "Sequential" PlaylistSongLoops: 0 # Loops >= 0 and Loops <= 9223372036854775807 # How many times a song should loop before fading out PlaylistFadeOutMilliseconds: 10000 # Milliseconds >= 0 and Milliseconds <= 9223372036854775807 # How many milliseconds it should take to fade out of a song MiddleCOctave: 4 # Octave >= --128 and Octave <= 127 # The octave that holds middle C. Used in the visual and track viewer -Colors: # Each color must be a RGB hex code - 0: "CF7FFF" - 1: "BF6CFF" - 2: "A750FF" - 3: "6C00B7" - 4: "5C1FFF" - 5: "7750FF" - 6: "FFF06A" - 7: "FF701C" - 8: "C8AAFF" - 9: "3FFFFF" - 10: "28FFDF" - 11: "6CFFB4" - 12: "98FF6C" - 13: "AAFFB0" - 14: "DD008C" - 15: "FFDFAA" - 16: "FF3F8C" - 17: "DF00FF" - 18: "C900AB" - 19: "FF1394" - 20: "FF7FF5" - 21: "004FD4" - 22: "0075EB" - 23: "0039FF" - 24: "FF7A68" - 25: "FF674C" - 26: "FF965D" - 27: "FF6524" - 28: "FF552A" - 29: "FF0606" - 30: "940028" - 31: "BD0004" - 32: "E9B96A" - 33: "E59A4E" - 34: "E48845" - 35: "FFEE5B" - 36: "E4A845" - 37: "BD7B0C" - 38: "BFBFBF" - 39: "BF00BF" - 40: "B900D4" - 41: "9400C5" - 42: "5F00BF" - 43: "6F3FFF" - 44: "1C00BD" - 45: "FF6AD9" - 46: "FF8AD6" - 47: "CE7F50" - 48: "155BFF" - 49: "3700AA" - 50: "3200C9" - 51: "5500D4" - 52: "FFECC9" - 53: "FFDFBF" - 54: "FFD9D4" - 55: "FF5C3F" - 56: "FF991D" - 57: "FFA715" - 58: "FFFF00" - 59: "FFB304" - 60: "FF6B08" - 61: "FA4400" - 62: "C6FF50" - 63: "9EFF1B" - 64: "FFE79F" - 65: "FFCA83" - 66: "FFDD54" - 67: "FFD015" - 68: "FFEE1F" - 69: "FF7330" - 70: "0075B4" - 71: "0097C9" - 72: "5FFFFF" - 73: "00D8FF" - 74: "00B4D4" - 75: "54BFFF" - 76: "8CFFF9" - 77: "0087D8" - 78: "00D4AF" - 79: "7FFF54" - 80: "19FF24" - 81: "FF90B4" - 82: "2AFFA4" - 83: "AFFF5F" - 84: "FF5F63" - 85: "74F4FF" - 86: "FF35CC" - 87: "ACFF00" - 88: "4AFFD1" - 89: "B4FBFF" - 90: "C90074" - 91: "002F6A" - 92: "00BF5F" - 93: "006DBF" - 94: "AE00F8" - 95: "BFBFFF" - 96: "AAE9FF" - 97: "AA00A1" - 98: "FF5454" - 99: "E9AF00" - 100: "BFEFFF" - 101: "139F00" - 102: "D9B4FF" - 103: "CC9012" - 104: "EED045" - 105: "F5E51E" - 106: "E3FF1F" - 107: "CBFF74" - 108: "8AFFB5" - 109: "DCFF94" - 110: "009FFF" - 111: "E9DE00" - 112: "FF6AB4" - 113: "7FBFBF" - 114: "AFD7E4" - 115: "7F3F3F" - 116: "C6844D" - 117: "A4765A" - 118: "9B4D9B" - 119: "AFBFCF" - 120: "BF2F00" - 121: "25A4AF" - 122: "00A9D4" - 123: "FFFF7F" - 124: "AF0F13" - 125: "A0A3A8" - 126: "C6A28D" - 127: "7F7FBF" \ No newline at end of file +Colors: + 0: {H: 185, S: 240, L: 180} + 1: {H: 183, S: 240, L: 170} + 2: {H: 180, S: 240, L: 157} + 3: {H: 184, S: 240, L: 85} + 4: {H: 171, S: 240, L: 134} + 5: {H: 168, S: 240, L: 159} + 6: {H: 36, S: 240, L: 170} + 7: {H: 15, S: 240, L: 134} + 8: {H: 175, S: 240, L: 200} + 9: {H: 120, S: 240, L: 150} + 10: {H: 114, S: 240, L: 138} + 11: {H: 99, S: 240, L: 171} + 12: {H: 68, S: 240, L: 171} + 13: {H: 83, S: 240, L: 200} + 14: {H: 215, S: 240, L: 104} + 15: {H: 25, S: 240, L: 200} + 16: {H: 224, S: 240, L: 150} + 17: {H: 195, S: 240, L: 120} + 18: {H: 206, S: 240, L: 95} + 19: {H: 218, S: 240, L: 129} + 20: {H: 203, S: 240, L: 180} + 21: {H: 145, S: 240, L: 100} + 22: {H: 140, S: 240, L: 111} + 23: {H: 151, S: 240, L: 120} + 24: {H: 5, S: 240, L: 169} + 25: {H: 6, S: 240, L: 156} + 26: {H: 14, S: 240, L: 164} + 27: {H: 12, S: 240, L: 137} + 28: {H: 8, S: 240, L: 140} + 29: {H: 0, S: 240, L: 123} + 30: {H: 229, S: 240, L: 70} + 31: {H: 239, S: 240, L: 89} + 32: {H: 25, S: 180, L: 160} + 33: {H: 20, S: 180, L: 145} + 34: {H: 17, S: 180, L: 140} + 35: {H: 36, S: 240, L: 163} + 36: {H: 25, S: 180, L: 140} + 37: {H: 25, S: 210, L: 95} + 38: {H: 160, S: 0, L: 180} + 39: {H: 200, S: 240, L: 90} + 40: {H: 195, S: 240, L: 100} + 41: {H: 190, S: 240, L: 93} + 42: {H: 180, S: 240, L: 90} + 43: {H: 170, S: 240, L: 150} + 44: {H: 166, S: 240, L: 89} + 45: {H: 210, S: 240, L: 170} + 46: {H: 214, S: 240, L: 185} + 47: {H: 15, S: 135, L: 135} + 48: {H: 148, S: 240, L: 130} + 49: {H: 173, S: 240, L: 80} + 50: {H: 170, S: 240, L: 95} + 51: {H: 176, S: 240, L: 100} + 52: {H: 26, S: 240, L: 215} + 53: {H: 20, S: 240, L: 210} + 54: {H: 5, S: 240, L: 220} + 55: {H: 6, S: 240, L: 150} + 56: {H: 22, S: 240, L: 134} + 57: {H: 25, S: 240, L: 130} + 58: {H: 40, S: 240, L: 120} + 59: {H: 28, S: 240, L: 122} + 60: {H: 16, S: 240, L: 124} + 61: {H: 11, S: 240, L: 118} + 62: {H: 53, S: 240, L: 158} + 63: {H: 57, S: 240, L: 133} + 64: {H: 30, S: 240, L: 195} + 65: {H: 23, S: 240, L: 182} + 66: {H: 32, S: 240, L: 160} + 67: {H: 32, S: 240, L: 130} + 68: {H: 37, S: 240, L: 135} + 69: {H: 13, S: 240, L: 143} + 70: {H: 134, S: 240, L: 85} + 71: {H: 130, S: 240, L: 95} + 72: {H: 120, S: 240, L: 165} + 73: {H: 126, S: 240, L: 120} + 74: {H: 126, S: 240, L: 100} + 75: {H: 135, S: 240, L: 160} + 76: {H: 118, S: 240, L: 186} + 77: {H: 135, S: 240, L: 102} + 78: {H: 113, S: 240, L: 100} + 79: {H: 70, S: 240, L: 160} + 80: {H: 82, S: 240, L: 132} + 81: {H: 227, S: 240, L: 188} + 82: {H: 103, S: 240, L: 140} + 83: {H: 60, S: 240, L: 165} + 84: {H: 239, S: 240, L: 165} + 85: {H: 123, S: 240, L: 175} + 86: {H: 210, S: 240, L: 145} + 87: {H: 53, S: 240, L: 120} + 88: {H: 110, S: 240, L: 155} + 89: {H: 122, S: 240, L: 205} + 90: {H: 217, S: 240, L: 95} + 91: {H: 142, S: 240, L: 50} + 92: {H: 100, S: 240, L: 90} + 93: {H: 137, S: 240, L: 90} + 94: {H: 188, S: 240, L: 117} + 95: {H: 160, S: 240, L: 210} + 96: {H: 130, S: 240, L: 200} + 97: {H: 202, S: 240, L: 80} + 98: {H: 0, S: 240, L: 160} + 99: {H: 30, S: 240, L: 110} + 100: {H: 130, S: 240, L: 210} + 101: {H: 75, S: 240, L: 75} + 102: {H: 180, S: 240, L: 205} + 103: {H: 27, S: 200, L: 105} + 104: {H: 33, S: 200, L: 145} + 105: {H: 37, S: 220, L: 130} + 106: {H: 45, S: 240, L: 135} + 107: {H: 55, S: 240, L: 175} + 108: {H: 95, S: 240, L: 185} + 109: {H: 53, S: 240, L: 190} + 110: {H: 135, S: 240, L: 120} + 111: {H: 38, S: 240, L: 110} + 112: {H: 220, S: 240, L: 170} + 113: {H: 120, S: 80, L: 150} + 114: {H: 130, S: 120, L: 190} + 115: {H: 0, S: 80, L: 90} + 116: {H: 18, S: 125, L: 130} + 117: {H: 15, S: 70, L: 120} + 118: {H: 200, S: 80, L: 110} + 119: {H: 140, S: 60, L: 180} + 120: {H: 10, S: 240, L: 90} + 121: {H: 123, S: 156, L: 100} + 122: {H: 128, S: 240, L: 100} + 123: {H: 40, S: 240, L: 180} + 124: {H: 239, S: 200, L: 90} + 125: {H: 145, S: 10, L: 155} + 126: {H: 15, S: 80, L: 160} + 127: {H: 160, S: 80, L: 150} \ No newline at end of file diff --git a/VG Music Studio - Core/Engine.cs b/VG Music Studio - Core/Engine.cs index a37f0e0..e58922a 100644 --- a/VG Music Studio - Core/Engine.cs +++ b/VG Music Studio - Core/Engine.cs @@ -8,7 +8,7 @@ public abstract class Engine : IDisposable public abstract Config Config { get; } public abstract Mixer Mixer { get; } - public abstract Player Player { get; } + public abstract IPlayer Player { get; } public virtual void Dispose() { diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs index 7b4fa85..f799d45 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs @@ -1,5 +1,5 @@ -using Kermalis.VGMusicStudio.Core.GBA.MP2K; -using System; +using System; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -42,13 +42,13 @@ public void SetVolume(byte vol, sbyte pan) public abstract void Process(float[] buffer); } -internal sealed class AlphaDreamPCMChannel : AlphaDreamChannel +internal class PCMChannel : AlphaDreamChannel { private SampleHeader _sampleHeader; private int _sampleOffset; private bool _bFixed; - public AlphaDreamPCMChannel(AlphaDreamMixer mixer) : base(mixer) + public PCMChannel(AlphaDreamMixer mixer) : base(mixer) { // } @@ -60,7 +60,8 @@ public void Init(byte key, ADSR adsr, int sampleOffset, bool bFixed) Key = key; _adsr = adsr; - _sampleHeader = new SampleHeader(_mixer.Config.ROM, sampleOffset, out _sampleOffset); + _sampleHeader = MemoryMarshal.Read(_mixer.Config.ROM.AsSpan(sampleOffset)); + _sampleOffset = sampleOffset + 0x10; _bFixed = bFixed; Stopped = false; } @@ -148,18 +149,17 @@ public override void Process(float[] buffer) } while (--samplesPerBuffer > 0); } } -internal sealed class AlphaDreamSquareChannel : AlphaDreamChannel +internal class SquareChannel : AlphaDreamChannel { private float[] _pat; - public AlphaDreamSquareChannel(AlphaDreamMixer mixer) - : base(mixer) + public SquareChannel(AlphaDreamMixer mixer) : base(mixer) { // } public void Init(byte key, ADSR env, byte vol, sbyte pan, int pitch) { - _pat = MP2KUtils.SquareD50; // TODO: Which square pattern? + _pat = MP2K.Utils.SquareD50; // TODO: Which square pattern? Key = key; _adsr = env; SetVolume(vol, pan); diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs index 750ae76..4858291 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using YamlDotNet.Core; using YamlDotNet.RepresentationModel; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -114,7 +113,7 @@ void Load(YamlMappingNode gameToLoad) var songs = new List(); foreach (KeyValuePair song in (YamlMappingNode)kvp.Value) { - int songIndex = (int)ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, int.MaxValue); + long songIndex = ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, long.MaxValue); if (songs.Any(s => s.Index == songIndex)) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorAlphaDreamMP2KSongRepeated, name, songIndex))); @@ -140,7 +139,7 @@ void Load(YamlMappingNode gameToLoad) } AudioEngineVersion = ConfigUtils.ParseEnum(nameof(AudioEngineVersion), audioEngineVersionNode.ToString()); - if (songTableOffsetsNode is null) + if (songTableOffsetsNode == null) { throw new BetterKeyNotFoundException(nameof(SongTableOffsets), null); } @@ -190,7 +189,7 @@ void Load(YamlMappingNode gameToLoad) // The complete playlist if (!Playlists.Any(p => p.Name == "Music")) { - Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index).ToList())); + Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index))); } } catch (BetterKeyNotFoundException ex) @@ -201,7 +200,7 @@ void Load(YamlMappingNode gameToLoad) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + ex.Message)); } - catch (YamlException ex) + catch (YamlDotNet.Core.YamlException ex) { throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + ex.Message)); } @@ -212,13 +211,10 @@ public override string GetGameName() { return Name; } - public override string GetSongName(int index) + public override string GetSongName(long index) { - if (TryGetFirstSong(index, out Song s)) - { - return s.Name; - } - return index.ToString(); + Song? s = GetFirstSong(index); + return s is not null ? s.Name : index.ToString(); } public override void Dispose() diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs index fdee70e..ae021f7 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs @@ -12,9 +12,9 @@ public sealed class AlphaDreamEngine : Engine public AlphaDreamEngine(byte[] rom) { - if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) + if (rom.Length > GBAUtils.CartridgeCapacity) { - throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); + throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CartridgeCapacity:X7} bytes."); } Config = new AlphaDreamConfig(rom); diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs deleted file mode 100644 index 3698f7f..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal enum AudioEngineVersion : byte -{ - Hamtaro, - MLSS, -} - -internal enum EnvelopeState : byte -{ - Attack, - Decay, - Sustain, - Release, -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs deleted file mode 100644 index f81833a..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong : ILoadedSong -{ - public List?[] Events { get; } - public long MaxTicks { get; private set; } - public int LongestTrack; - - private readonly AlphaDreamPlayer _player; - - public AlphaDreamLoadedSong(AlphaDreamPlayer player, int songOffset) - { - _player = player; - - Events = new List[AlphaDreamPlayer.NUM_TRACKS]; - songOffset -= GBAUtils.CARTRIDGE_OFFSET; - EndianBinaryReader r = player.Config.Reader; - r.Stream.Position = songOffset; - ushort trackBits = r.ReadUInt16(); - int usedTracks = 0; - for (byte trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - AlphaDreamTrack track = player.Tracks[trackIndex]; - if ((trackBits & (1 << trackIndex)) == 0) - { - track.IsEnabled = false; - track.StartOffset = 0; - continue; - } - - track.IsEnabled = true; - r.Stream.Position = songOffset + 2 + (2 * usedTracks++); - track.StartOffset = songOffset + r.ReadInt16(); - - AddTrackEvents(trackIndex, track.StartOffset); - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs deleted file mode 100644 index 66ae341..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs +++ /dev/null @@ -1,266 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex]!.Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex]!.Exists(e => e.Offset == cmdOffset); - } - - private void AddTrackEvents(byte trackIndex, int trackStart) - { - Events[trackIndex] = new List(); - AddEvents(trackIndex, trackStart); - } - private void AddEvents(byte trackIndex, int startOffset) - { - EndianBinaryReader r = _player.Config.Reader; - r.Stream.Position = startOffset; - - bool cont = true; - while (cont) - { - long cmdOffset = r.Stream.Position; - byte cmd = r.ReadByte(); - switch (cmd) - { - case 0x00: - { - byte keyArg = r.ReadByte(); - switch (_player.Config.AudioEngineVersion) - { - case AudioEngineVersion.Hamtaro: - { - byte volume = r.ReadByte(); - byte duration = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FreeNoteHamtaroCommand { Note = (byte)(keyArg - 0x80), Volume = volume, Duration = duration }); - } - break; - } - case AudioEngineVersion.MLSS: - { - byte duration = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FreeNoteMLSSCommand { Note = (byte)(keyArg - 0x80), Duration = duration }); - } - break; - } - } - break; - } - case 0xF0: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xF1: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xF2: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x80) }); - } - break; - } - case 0xF4: - { - byte range = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendRangeCommand { Range = range }); - } - break; - } - case 0xF5: - { - sbyte bend = r.ReadSByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = bend }); - } - break; - } - case 0xF6: - { - byte rest = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = rest }); - } - break; - } - case 0xF8: - { - short jumpOffset = r.ReadInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - int off = (int)(r.Stream.Position + jumpOffset); - AddEvent(trackIndex, cmdOffset, new JumpCommand { Offset = off }); - if (!EventExists(trackIndex, off)) - { - AddEvents(trackIndex, off); - } - } - cont = false; - break; - } - case 0xF9: - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackTempoCommand { Tempo = tempoArg }); - } - break; - } - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand()); - } - cont = false; - break; - } - default: - { - if (cmd >= 0xE0) - { - throw new AlphaDreamInvalidCMDException(trackIndex, (int)cmdOffset, cmd); - } - - byte key = r.ReadByte(); - switch (_player.Config.AudioEngineVersion) - { - case AudioEngineVersion.Hamtaro: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteHamtaroCommand { Note = key, Volume = volume, Duration = cmd }); - } - break; - } - case AudioEngineVersion.MLSS: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteMLSSCommand { Note = key, Duration = cmd }); - } - break; - } - } - break; - } - } - } - } - - public void SetTicks() - { - MaxTicks = 0; - bool u = false; - for (int trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - List? evs = Events[trackIndex]; - if (evs is null) - { - continue; - } - - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - AlphaDreamTrack track = _player.Tracks[trackIndex]; - track.Init(); - - long elapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - if (e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(elapsedTicks); - ExecuteNext(track, ref u); - if (track.Stopped) - { - break; - } - - elapsedTicks += track.Rest; - track.Rest = 0; - } - if (elapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = elapsedTicks; - } - track.NoteDuration = 0; - } - } - internal void SetCurTick(long ticks) - { - bool u = false; - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 75) - { - _player.TempoStack -= 75; - for (int trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - AlphaDreamTrack track = _player.Tracks[trackIndex]; - if (track.IsEnabled && !track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track, ref u); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) - { - _player.Tracks[i].NoteDuration = 0; - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs deleted file mode 100644 index 5b71b59..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong -{ - private static bool TryGetVoiceEntry(byte[] rom, int voiceTableOffset, byte voice, byte key, out VoiceEntry e) - { - short voiceOffset = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + (voice * 2))); - short nextVoiceOffset = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + ((voice + 1) * 2))); - if (voiceOffset == nextVoiceOffset) - { - e = default; - return false; - } - - int pos = voiceTableOffset + voiceOffset; // Prevent object creation in the last iteration - ref readonly var refE = ref VoiceEntry.Get(rom.AsSpan(pos)); - while (refE.MinKey > key || refE.MaxKey < key) - { - pos += 8; - if (pos == nextVoiceOffset) - { - e = default; - return false; - } - refE = ref VoiceEntry.Get(rom.AsSpan(pos)); - } - e = refE; - return true; - } - private void PlayNote(AlphaDreamTrack track, byte key, byte duration) - { - AlphaDreamConfig cfg = _player.Config; - if (!TryGetVoiceEntry(cfg.ROM, cfg.VoiceTableOffset, track.Voice, key, out VoiceEntry entry)) - { - return; - } - - track.NoteDuration = duration; - if (track.Index >= 8) - { - // TODO: "Sample" byte in VoiceEntry - var sqr = (AlphaDreamSquareChannel)track.Channel; - sqr.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, track.Volume, track.Panpot, track.GetPitch()); - } - else - { - int sto = cfg.SampleTableOffset; - int sampleOffset = ReadInt32LittleEndian(cfg.ROM.AsSpan(sto + (entry.Sample * 4))); // Some entries are 0. If you play them, are they silent, or does it not care if they are 0? - - var pcm = (AlphaDreamPCMChannel)track.Channel; - pcm.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, sto + sampleOffset, entry.IsFixedFrequency == VoiceEntry.FIXED_FREQ_TRUE); - pcm.SetVolume(track.Volume, track.Panpot); - pcm.SetPitch(track.GetPitch()); - } - } - public void ExecuteNext(AlphaDreamTrack track, ref bool update) - { - byte[] rom = _player.Config.ROM; - byte cmd = rom[track.DataOffset++]; - switch (cmd) - { - case 0x00: // Free Note - { - byte note = (byte)(rom[track.DataOffset++] - 0x80); - if (_player.Config.AudioEngineVersion == AudioEngineVersion.Hamtaro) - { - track.Volume = rom[track.DataOffset++]; - update = true; - } - - byte duration = rom[track.DataOffset++]; - track.Rest += duration; - if (track.PrevCommand == 0 && track.Channel.Key == note) - { - track.NoteDuration += duration; - } - else - { - PlayNote(track, note, duration); - } - break; - } - case <= 0xDF: // Note - { - byte key = rom[track.DataOffset++]; - if (_player.Config.AudioEngineVersion == AudioEngineVersion.Hamtaro) - { - track.Volume = rom[track.DataOffset++]; - update = true; - } - - track.Rest += cmd; - if (track.PrevCommand == 0 && track.Channel.Key == key) - { - track.NoteDuration += cmd; - } - else - { - PlayNote(track, key, cmd); - } - break; - } - case 0xF0: // Voice - { - track.Voice = rom[track.DataOffset++]; - break; - } - case 0xF1: // Volume - { - track.Volume = rom[track.DataOffset++]; - update = true; - break; - } - case 0xF2: // Panpot - { - track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x80); - update = true; - break; - } - case 0xF4: // Pitch Bend Range - { - track.PitchBendRange = rom[track.DataOffset++]; - update = true; - break; - } - case 0xF5: // Pitch Bend - { - track.PitchBend = (sbyte)rom[track.DataOffset++]; - update = true; - break; - } - case 0xF6: // Rest - { - track.Rest = rom[track.DataOffset++]; - break; - } - case 0xF8: // Jump - { - track.DataOffset += 2 + ReadInt16LittleEndian(rom.AsSpan(track.DataOffset)); - break; - } - case 0xF9: // Track Tempo - { - _player.Tempo = rom[track.DataOffset++]; // TODO: Implement per track - break; - } - case 0xFF: // Finish - { - track.Stopped = true; - break; - } - default: throw new AlphaDreamInvalidCMDException(track.Index, track.DataOffset - 1, cmd); - } - - track.PrevCommand = cmd; - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs index 1cc823c..05c4afd 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs @@ -19,8 +19,6 @@ public sealed class AlphaDreamMixer : Mixer private readonly float[][] _trackBuffers = new float[AlphaDreamPlayer.NUM_TRACKS][]; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal AlphaDreamMixer(AlphaDreamConfig config) { Config = config; @@ -71,7 +69,17 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } - internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } + internal void Process(Track[] tracks, bool output, bool recording) { _audio.Clear(); float masterStep; @@ -98,8 +106,8 @@ internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) } for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) { - AlphaDreamTrack track = tracks[i]; - if (!track.IsEnabled || track.NoteDuration == 0 || track.Channel.Stopped || Mutes[i]) + Track track = tracks[i]; + if (!track.Enabled || track.NoteDuration == 0 || track.Channel.Stopped || Mutes[i]) { continue; } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs index e202a38..6d8f062 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs @@ -1,167 +1,714 @@ -using System; -using static System.Buffers.Binary.BinaryPrimitives; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; -public sealed class AlphaDreamPlayer : Player +public sealed class AlphaDreamPlayer : IPlayer, ILoadedSong { internal const int NUM_TRACKS = 12; // 8 PCM, 4 PSG - protected override string Name => "AlphaDream Player"; - - internal readonly AlphaDreamTrack[] Tracks; - internal readonly AlphaDreamConfig Config; + private readonly Track[] _tracks = new Track[NUM_TRACKS]; private readonly AlphaDreamMixer _mixer; - private AlphaDreamLoadedSong? _loadedSong; - - internal byte Tempo; - internal int TempoStack; + private readonly AlphaDreamConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private byte _tempo; + private int _tempoStack; private long _elapsedLoops; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => _mixer; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; + + public PlayerState State { get; private set; } + public event Action? SongEnded; internal AlphaDreamPlayer(AlphaDreamConfig config, AlphaDreamMixer mixer) - : base(GBAUtils.AGB_FPS) { - Config = config; + _config = config; _mixer = mixer; - Tracks = new AlphaDreamTrack[NUM_TRACKS]; for (byte i = 0; i < NUM_TRACKS; i++) { - Tracks[i] = new AlphaDreamTrack(i, mixer); + _tracks[i] = new Track(i, mixer); } - } - public override void LoadSong(int index) + _time = new TimeBarrier(GBAUtils.AGB_FPS); + } + private void CreateThread() { - if (_loadedSong is not null) - { - _loadedSong = null; - } - - int songPtr = Config.SongTableOffsets[0] + (index * 4); - int songOffset = ReadInt32LittleEndian(Config.ROM.AsSpan(songPtr)); - if (songOffset == 0) - { - return; - } - - // If there's an exception, this will remain null - _loadedSong = new AlphaDreamLoadedSong(this, songOffset); - _loadedSong.SetTicks(); + _thread = new Thread(Tick) { Name = "AlphaDream Player Tick" }; + _thread.Start(); } - public override void UpdateSongState(SongState info) + private void WaitThread() { - info.Tempo = Tempo; - for (int i = 0; i < NUM_TRACKS; i++) + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) { - AlphaDreamTrack track = Tracks[i]; - if (track.IsEnabled) - { - track.UpdateSongState(info.Tracks[i]); - } + _thread.Join(); } } - internal override void InitEmulation() + + private void InitEmulation() { - Tempo = 120; // Player tempo is set to 75 on init, but I did not separate player and track tempo yet - TempoStack = 0; + _tempo = 120; // Player tempo is set to 75 on init, but I did not separate player and track tempo yet + _tempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; _mixer.ResetFade(); for (int i = 0; i < NUM_TRACKS; i++) { - Tracks[i].Init(); + _tracks[i].Init(); } } - protected override void SetCurTick(long ticks) + private void SetTicks() { - _loadedSong!.SetCurTick(ticks); + MaxTicks = 0; + bool u = false; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + if (Events[trackIndex] == null) + { + continue; + } + + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = _tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + if (e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + ExecuteNext(track, ref u); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.NoteDuration = 0; + } } - protected override void OnStopped() + public void LoadSong(long index) { - // - } + _config.Reader.Stream.Position = _config.SongTableOffsets[0] + (index * 4); + int songOffset = _config.Reader.ReadInt32(); + if (songOffset == 0) + { + Events = null; + return; + } - protected override bool Tick(bool playing, bool recording) + Events = new List[NUM_TRACKS]; + songOffset -= GBAUtils.CartridgeOffset; + _config.Reader.Stream.Position = songOffset; + ushort trackBits = _config.Reader.ReadUInt16(); + for (byte i = 0, usedTracks = 0; i < NUM_TRACKS; i++) + { + Track track = _tracks[i]; + if ((trackBits & (1 << i)) == 0) + { + track.Enabled = false; + track.StartOffset = 0; + continue; + } + + track.Enabled = true; + Events[i] = new List(); + bool EventExists(long offset) + { + return Events[i].Any(e => e.Offset == offset); + } + + _config.Reader.Stream.Position = songOffset + 2 + (2 * usedTracks++); + AddEvents(track.StartOffset = songOffset + _config.Reader.ReadInt16()); + void AddEvents(int startOffset) + { + _config.Reader.Stream.Position = startOffset; + bool cont = true; + while (cont) + { + long offset = _config.Reader.Stream.Position; + void AddEvent(ICommand command) + { + Events[i].Add(new SongEvent(offset, command)); + } + byte cmd = _config.Reader.ReadByte(); + switch (cmd) + { + case 0x00: + { + byte keyArg = _config.Reader.ReadByte(); + switch (_config.AudioEngineVersion) + { + case AudioEngineVersion.Hamtaro: + { + byte volume = _config.Reader.ReadByte(); + byte duration = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new FreeNoteHamtaroCommand { Note = (byte)(keyArg - 0x80), Volume = volume, Duration = duration }); + } + break; + } + case AudioEngineVersion.MLSS: + { + byte duration = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new FreeNoteMLSSCommand { Note = (byte)(keyArg - 0x80), Duration = duration }); + } + break; + } + } + break; + } + case 0xF0: + { + byte voice = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = voice }); + } + break; + } + case 0xF1: + { + byte volume = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VolumeCommand { Volume = volume }); + } + break; + } + case 0xF2: + { + byte panArg = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = (sbyte)(panArg - 0x80) }); + } + break; + } + case 0xF4: + { + byte range = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendRangeCommand { Range = range }); + } + break; + } + case 0xF5: + { + sbyte bend = _config.Reader.ReadSByte(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = bend }); + } + break; + } + case 0xF6: + { + byte rest = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = rest }); + } + break; + } + case 0xF8: + { + short jumpOffset = _config.Reader.ReadInt16(); + if (!EventExists(offset)) + { + int off = (int)(_config.Reader.Stream.Position + jumpOffset); + AddEvent(new JumpCommand { Offset = off }); + if (!EventExists(off)) + { + AddEvents(off); + } + } + cont = false; + break; + } + case 0xF9: + { + byte tempoArg = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new TrackTempoCommand { Tempo = tempoArg }); + } + break; + } + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + cont = false; + break; + } + default: + { + if (cmd >= 0xE0) + { + throw new AlphaDreamInvalidCMDException(i, (int)offset, cmd); + } + + byte key = _config.Reader.ReadByte(); + switch (_config.AudioEngineVersion) + { + case AudioEngineVersion.Hamtaro: + { + byte volume = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new NoteHamtaroCommand { Note = key, Volume = volume, Duration = cmd }); + } + break; + } + case AudioEngineVersion.MLSS: + { + if (!EventExists(offset)) + { + AddEvent(new NoteMLSSCommand { Note = key, Duration = cmd }); + } + break; + } + } + break; + } + } + } + } + } + SetTicks(); + } + public void SetCurrentPosition(long ticks) { - bool allDone = false; // TODO: Individual track tempo - while (!allDone && TempoStack >= 75) + if (Events == null) { - TempoStack -= 75; - allDone = true; - for (int i = 0; i < NUM_TRACKS; i++) + SongEnded?.Invoke(); + } + else if (State == PlayerState.Playing || State == PlayerState.Paused || State == PlayerState.Stopped) + { + if (State == PlayerState.Playing) { - AlphaDreamTrack track = Tracks[i]; - if (track.IsEnabled) + Pause(); + } + InitEmulation(); + bool u = false; + while (true) + { + if (ElapsedTicks == ticks) + { + goto finish; + } + + while (_tempoStack >= 75) { - TickTrack(track, ref allDone); + _tempoStack -= 75; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref u); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } } + _tempoStack += _tempo; } - if (_mixer.IsFadeDone()) + finish: + for (int i = 0; i < NUM_TRACKS; i++) { - allDone = true; + _tracks[i].NoteDuration = 0; } + Pause(); + } + } + public void Play() + { + if (State is PlayerState.ShutDown or PlayerState.Recording) + { + return; } - if (!allDone) + + if (Events is null) { - TempoStack += Tempo; + SongEnded?.Invoke(); + return; } - _mixer.Process(Tracks, playing, recording); - return allDone; + + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } - private void TickTrack(AlphaDreamTrack track, ref bool allDone) + public void Pause() { - byte prevDuration = track.NoteDuration; - track.Tick(); - bool update = false; - while (track.Rest == 0 && !track.Stopped) + switch (State) { - _loadedSong!.ExecuteNext(track, ref update); + case PlayerState.Playing: + { + State = PlayerState.Paused; + WaitThread(); + break; + } + case PlayerState.Paused: + case PlayerState.Stopped: + { + State = PlayerState.Playing; + CreateThread(); + break; + } } - if (track.Index == _loadedSong!.LongestTrack) + } + public void Stop() + { + if (State is PlayerState.Playing or PlayerState.Paused) { - HandleTicksAndLoop(_loadedSong, track); + State = PlayerState.Stopped; + WaitThread(); } - if (prevDuration == 1 && track.NoteDuration == 0) // Note was not renewed + } + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() + { + if (State != PlayerState.ShutDown) { - track.Channel.State = EnvelopeState.Release; + State = PlayerState.ShutDown; + WaitThread(); } - if (track.NoteDuration != 0) // A note is playing + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int i = 0; i < NUM_TRACKS; i++) { - allDone = false; - if (update) + Track track = _tracks[i]; + if (!track.Enabled) + { + continue; + } + + SongState.Track tin = info.Tracks[i]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.Type = track.Type; + tin.Volume = track.Volume; + tin.PitchBend = track.GetPitch(); + tin.Panpot = track.Panpot; + if (track.NoteDuration != 0 && !track.Channel.Stopped) { - track.Channel.SetVolume(track.Volume, track.Panpot); - track.Channel.SetPitch(track.GetPitch()); + tin.Keys[0] = track.Channel.Key; + ChannelVolume vol = track.Channel.GetVolume(); + tin.LeftVolume = vol.LeftVol; + tin.RightVolume = vol.RightVol; } + else + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + } + } + } + + private bool TryGetVoiceEntry(byte voice, byte key, out VoiceEntry e) + { + int vto = _config.VoiceTableOffset; + byte[] rom = _config.ROM; + short voiceOffset = BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(vto + (voice * 2))); + short nextVoiceOffset = BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(vto + ((voice + 1) * 2))); + if (voiceOffset == nextVoiceOffset) + { + e = default; + return false; } - if (!track.Stopped) + + int pos = vto + voiceOffset; // Prevent object creation in the last iteration + ref VoiceEntry refE = ref MemoryMarshal.AsRef(rom.AsSpan(pos)); + while (refE.MinKey > key || refE.MaxKey < key) { - allDone = false; + pos += 8; + if (pos == nextVoiceOffset) + { + e = default; + return false; + } + refE = ref MemoryMarshal.AsRef(rom.AsSpan(pos)); } + e = refE; + return true; } - private void HandleTicksAndLoop(AlphaDreamLoadedSong s, AlphaDreamTrack track) + private void PlayNote(Track track, byte key, byte duration) { - if (ElapsedTicks != s.MaxTicks) + if (!TryGetVoiceEntry(track.Voice, key, out VoiceEntry entry)) { - ElapsedTicks++; return; } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + track.NoteDuration = duration; + if (track.Index >= 8) { - return; + // TODO: "Sample" byte in VoiceEntry + var sqr = (SquareChannel)track.Channel; + sqr.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, track.Volume, track.Panpot, track.GetPitch()); } + else + { + int sto = _config.SampleTableOffset; + byte[] rom = _config.ROM; + int sampleOffset = BinaryPrimitives.ReadInt32LittleEndian(rom.AsSpan(sto + (entry.Sample * 4))); // Some entries are 0. If you play them, are they silent, or does it not care if they are 0? - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index]!, track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !_mixer.IsFading()) + var pcm = (PCMChannel)track.Channel; + pcm.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, sto + sampleOffset, entry.IsFixedFrequency == 0x80); + pcm.SetVolume(track.Volume, track.Panpot); + pcm.SetPitch(track.GetPitch()); + } + } + private void ExecuteNext(Track track, ref bool update) + { + byte[] rom = _config.ROM; + byte cmd = rom[track.DataOffset++]; + switch (cmd) { - _mixer.BeginFadeOut(); + case 0x00: // Free Note + { + byte note = (byte)(rom[track.DataOffset++] - 0x80); + if (_config.AudioEngineVersion == AudioEngineVersion.Hamtaro) + { + track.Volume = rom[track.DataOffset++]; + update = true; + } + + byte duration = rom[track.DataOffset++]; + track.Rest += duration; + if (track.PrevCommand == 0 && track.Channel.Key == note) + { + track.NoteDuration += duration; + } + else + { + PlayNote(track, note, duration); + } + break; + } + case <= 0xDF: // Note + { + byte key = rom[track.DataOffset++]; + if (_config.AudioEngineVersion == AudioEngineVersion.Hamtaro) + { + track.Volume = rom[track.DataOffset++]; + update = true; + } + + track.Rest += cmd; + if (track.PrevCommand == 0 && track.Channel.Key == key) + { + track.NoteDuration += cmd; + } + else + { + PlayNote(track, key, cmd); + } + break; + } + case 0xF0: // Voice + { + track.Voice = rom[track.DataOffset++]; + break; + } + case 0xF1: // Volume + { + track.Volume = rom[track.DataOffset++]; + update = true; + break; + } + case 0xF2: // Panpot + { + track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x80); + update = true; + break; + } + case 0xF4: // Pitch Bend Range + { + track.PitchBendRange = rom[track.DataOffset++]; + update = true; + break; + } + case 0xF5: // Pitch Bend + { + track.PitchBend = (sbyte)rom[track.DataOffset++]; + update = true; + break; + } + case 0xF6: // Rest + { + track.Rest = rom[track.DataOffset++]; + break; + } + case 0xF8: // Jump + { + track.DataOffset += 2 + BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(track.DataOffset, 2)); + break; + } + case 0xF9: // Track Tempo + { + _tempo = rom[track.DataOffset++]; + break; + } + case 0xFF: // Finish + { + track.Stopped = true; + break; + } + default: throw new AlphaDreamInvalidCMDException(track.Index, track.DataOffset - 1, cmd); + } + + track.PrevCommand = cmd; + } + + private void Tick() + { + _time.Start(); + while (true) + { + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 75) + { + _tempoStack -= 75; + bool allDone = true; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled) + { + byte prevDuration = track.NoteDuration; + track.Tick(); + bool update = false; + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref update); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (prevDuration == 1 && track.NoteDuration == 0) // Note was not renewed + { + track.Channel.State = EnvelopeState.Release; + } + if (!track.Stopped) + { + allDone = false; + } + if (track.NoteDuration != 0) + { + allDone = false; + if (update) + { + track.Channel.SetVolume(track.Volume, track.Panpot); + track.Channel.SetPitch(track.GetPitch()); + } + } + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.Process(_tracks, playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.Process(_tracks, playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs index 606f9b5..f9f351f 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs @@ -4,6 +4,7 @@ using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -54,7 +55,7 @@ private static void AddInfo(AlphaDreamConfig config, DLS dls) } ofs += config.SampleTableOffset; - var sh = new SampleHeader(config.ROM, ofs, out int sampleOffset); + ref SampleHeader sh = ref MemoryMarshal.AsRef(config.ROM.AsSpan(ofs)); // Create format chunk var fmt = new FormatChunk(WaveFormat.PCM); @@ -80,7 +81,7 @@ private static void AddInfo(AlphaDreamConfig config, DLS dls) } // Get PCM sample byte[] pcm = new byte[sh.Length]; - Array.Copy(config.ROM, sampleOffset, pcm, 0, sh.Length); + Array.Copy(config.ROM, ofs + 0x10, pcm, 0, sh.Length); // Add int dlsIndex = waves.Count; @@ -126,7 +127,7 @@ private static void AddInstruments(AlphaDreamConfig config, DLS dls, Dictionary< lins.Add(ins); for (int e = 0; e < numEntries; e++) { - ref readonly var entry = ref VoiceEntry.Get(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); + ref VoiceEntry entry = ref MemoryMarshal.AsRef(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); // Sample if (entry.Sample >= config.SampleTableSize) { @@ -139,7 +140,7 @@ private static void AddInstruments(AlphaDreamConfig config, DLS dls, Dictionary< continue; } - void Add(ushort low, ushort high, ushort baseNote) + void Add(ushort low, ushort high, ushort baseKey) { var rgnh = new RegionHeaderChunk(); rgnh.KeyRange.Low = low; @@ -149,7 +150,7 @@ void Add(ushort low, ushort high, ushort baseNote) rgnh, new WaveSampleChunk { - UnityNote = baseNote, + UnityNote = baseKey, Options = WaveSampleOptions.NoTruncation | WaveSampleOptions.NoCompression, Loop = value.Item1.Loop, }, diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs index 30c0529..6ed9a2c 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs @@ -1,63 +1,57 @@ using Kermalis.SoundFont2; using Kermalis.VGMusicStudio.Core.Util; using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; -using static System.Buffers.Binary.BinaryPrimitives; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; public static class AlphaDreamSoundFontSaver_SF2 { - public static void Save(string path, AlphaDreamConfig cfg) - { - Save(path, cfg.ROM, cfg.Name, cfg.SampleTableOffset, (int)cfg.SampleTableSize, cfg.VoiceTableOffset); - } - private static void Save(string path, - byte[] rom, string romName, - int sampleTableOffset, int sampleTableSize, int voiceTableOffset) + public static void Save(AlphaDreamConfig config, string path) { var sf2 = new SF2(); - AddInfo(romName, sf2.InfoChunk); - Dictionary sampleDict = AddSamples(rom, sampleTableOffset, sampleTableSize, sf2); - AddInstruments(rom, voiceTableOffset, sampleTableSize, sf2, sampleDict); + AddInfo(config, sf2.InfoChunk); + Dictionary sampleDict = AddSamples(config, sf2); + AddInstruments(config, sf2, sampleDict); sf2.Save(path); } - private static void AddInfo(string romName, InfoListChunk chunk) + private static void AddInfo(AlphaDreamConfig config, InfoListChunk chunk) { - chunk.Bank = romName; + chunk.Bank = config.Name; //chunk.Copyright = config.Creator; chunk.Tools = ConfigUtils.PROGRAM_NAME + " by Kermalis"; } - private static Dictionary AddSamples(byte[] rom, int sampleTableOffset, int sampleTableSize, SF2 sf2) + private static Dictionary AddSamples(AlphaDreamConfig config, SF2 sf2) { - var sampleDict = new Dictionary(sampleTableSize); - for (int i = 0; i < sampleTableSize; i++) + var sampleDict = new Dictionary((int)config.SampleTableSize); + for (int i = 0; i < config.SampleTableSize; i++) { - int ofs = ReadInt32LittleEndian(rom.AsSpan(sampleTableOffset + (i * 4))); + int ofs = BinaryPrimitives.ReadInt32LittleEndian(config.ROM.AsSpan(config.SampleTableOffset + (i * 4))); if (ofs == 0) { continue; } - ofs += sampleTableOffset; - var sh = new SampleHeader(rom, ofs, out int sampleOffset); + ofs += config.SampleTableOffset; + ref SampleHeader sh = ref MemoryMarshal.AsRef(config.ROM.AsSpan(ofs)); - short[] pcm16 = new short[sh.Length]; - SampleUtils.PCMU8ToPCM16(rom.AsSpan(sampleOffset), pcm16); + short[] pcm16 = SampleUtils.PCMU8ToPCM16(config.ROM.AsSpan(ofs + 0x10, sh.Length)); int sf2Index = (int)sf2.AddSample(pcm16, $"Sample {i}", sh.DoesLoop == SampleHeader.LOOP_TRUE, (uint)sh.LoopOffset, (uint)sh.SampleRate >> 10, 60, 0); sampleDict.Add(i, (sh, sf2Index)); } return sampleDict; } - private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleTableSize, SF2 sf2, Dictionary sampleDict) + private static void AddInstruments(AlphaDreamConfig config, SF2 sf2, Dictionary sampleDict) { for (ushort v = 0; v < 256; v++) { - short off = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + (v * 2))); - short nextOff = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + ((v + 1) * 2))); + short off = BinaryPrimitives.ReadInt16LittleEndian(config.ROM.AsSpan(config.VoiceTableOffset + (v * 2))); + short nextOff = BinaryPrimitives.ReadInt16LittleEndian(config.ROM.AsSpan(config.VoiceTableOffset + ((v + 1) * 2))); int numEntries = (nextOff - off) / 8; // Each entry is 8 bytes if (numEntries == 0) { @@ -70,10 +64,10 @@ private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleT sf2.AddPresetGenerator(SF2Generator.Instrument, new SF2GeneratorAmount { Amount = (short)sf2.AddInstrument(name) }); for (int e = 0; e < numEntries; e++) { - ref readonly var entry = ref VoiceEntry.Get(rom.AsSpan(voiceTableOffset + off + (e * 8))); + ref VoiceEntry entry = ref MemoryMarshal.AsRef(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); sf2.AddInstrumentBag(); // Key range - if (entry.MinKey != 0 || entry.MaxKey != 0x7F) + if (!(entry.MinKey == 0 && entry.MaxKey == 0x7F)) { sf2.AddInstrumentGenerator(SF2Generator.KeyRange, new SF2GeneratorAmount { LowByte = entry.MinKey, HighByte = entry.MaxKey }); } @@ -83,7 +77,7 @@ private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleT sf2.AddInstrumentGenerator(SF2Generator.ScaleTuning, new SF2GeneratorAmount { Amount = 0 }); } // Sample - if (entry.Sample < sampleTableSize) + if (entry.Sample < config.SampleTableSize) { if (!sampleDict.TryGetValue(entry.Sample, out (SampleHeader, int) value)) { diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs deleted file mode 100644 index 720c72e..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SampleHeader -{ - public const int SIZE = 16; - public const int LOOP_TRUE = 0x40_000_000; - - /// 0x40_000_000 if True - public readonly int DoesLoop; - /// Right shift 10 for value - public readonly int SampleRate; - public readonly int LoopOffset; - public readonly int Length; - // byte[Length] Sample; - - public SampleHeader(byte[] rom, int offset, out int sampleOffset) - { - ReadOnlySpan data = rom.AsSpan(offset, SIZE); - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(data); - } - else - { - DoesLoop = ReadInt32LittleEndian(data.Slice(0, 4)); - SampleRate = ReadInt32LittleEndian(data.Slice(4, 4)); - LoopOffset = ReadInt32LittleEndian(data.Slice(8, 4)); - Length = ReadInt32LittleEndian(data.Slice(12, 4)); - } - sampleOffset = offset + SIZE; - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct VoiceEntry -{ - public const int SIZE = 8; - public const byte FIXED_FREQ_TRUE = 0x80; - - public readonly byte MinKey; - public readonly byte MaxKey; - public readonly byte Sample; - /// 0x80 if True - public readonly byte IsFixedFrequency; - public readonly byte Unknown1; - public readonly byte Unknown2; - public readonly byte Unknown3; - public readonly byte Unknown4; - - public static ref readonly VoiceEntry Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} - -internal struct ChannelVolume -{ - public float LeftVol, RightVol; -} -internal struct ADSR // TODO -{ - public byte A, D, S, R; -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs deleted file mode 100644 index ded6a34..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed class AlphaDreamTrack -{ - public readonly byte Index; - public readonly string Type; - public readonly AlphaDreamChannel Channel; - - public byte Voice; - public byte PitchBendRange; - public byte Volume; - public byte Rest; - public byte NoteDuration; - public sbyte PitchBend; - public sbyte Panpot; - public bool IsEnabled; - public bool Stopped; - public int StartOffset; - public int DataOffset; - public byte PrevCommand; - - public int GetPitch() - { - return PitchBend * (PitchBendRange / 2); - } - - public AlphaDreamTrack(byte i, AlphaDreamMixer mixer) - { - Index = i; - if (i >= 8) - { - Type = GBAUtils.PSGTypes[i & 3]; - Channel = new AlphaDreamSquareChannel(mixer); // TODO: PSG Channels 3 and 4 - } - else - { - Type = "PCM8"; - Channel = new AlphaDreamPCMChannel(mixer); - } - } - // 0x819B040 - public void Init() - { - Voice = 0; - Rest = 1; // Unsure why Rest starts at 1 - PitchBendRange = 2; - NoteDuration = 0; - PitchBend = 0; - Panpot = 0; // Start centered; ROM sets this to 0x7F since it's unsigned there - DataOffset = StartOffset; - Stopped = false; - Volume = 200; - PrevCommand = 0xFF; - //Tempo = 120; - //TempoStack = 0; - } - public void Tick() - { - if (Rest != 0) - { - Rest--; - } - if (NoteDuration > 0) - { - NoteDuration--; - } - } - - public void UpdateSongState(SongState.Track tin) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.Type = Type; - tin.Volume = Volume; - tin.PitchBend = GetPitch(); - tin.Panpot = Panpot; - if (NoteDuration != 0 && !Channel.Stopped) - { - tin.Keys[0] = Channel.Key; - ChannelVolume vol = Channel.GetVolume(); - tin.LeftVolume = vol.LeftVol; - tin.RightVolume = vol.RightVol; - } - else - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs b/VG Music Studio - Core/GBA/AlphaDream/Commands.cs similarity index 77% rename from VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs rename to VG Music Studio - Core/GBA/AlphaDream/Commands.cs index b27f327..faaee21 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/Commands.cs @@ -3,13 +3,13 @@ namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; public string Arguments => string.Empty; } -internal sealed class FreeNoteHamtaroCommand : ICommand // TODO: When optimization comes, get rid of free note vs note and just have the label differ +internal class FreeNoteHamtaroCommand : ICommand // TODO: When optimization comes, get rid of free note vs note and just have the label differ { public Color Color => Color.SkyBlue; public string Label => "Free Note"; @@ -19,7 +19,7 @@ internal sealed class FreeNoteHamtaroCommand : ICommand // TODO: When optimizati public byte Volume { get; set; } public byte Duration { get; set; } } -internal sealed class FreeNoteMLSSCommand : ICommand +internal class FreeNoteMLSSCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Free Note"; @@ -28,7 +28,7 @@ internal sealed class FreeNoteMLSSCommand : ICommand public byte Note { get; set; } public byte Duration { get; set; } } -internal sealed class JumpCommand : ICommand +internal class JumpCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Jump"; @@ -36,7 +36,7 @@ internal sealed class JumpCommand : ICommand public int Offset { get; set; } } -internal sealed class NoteHamtaroCommand : ICommand +internal class NoteHamtaroCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -46,7 +46,7 @@ internal sealed class NoteHamtaroCommand : ICommand public byte Volume { get; set; } public byte Duration { get; set; } } -internal sealed class NoteMLSSCommand : ICommand +internal class NoteMLSSCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -55,7 +55,7 @@ internal sealed class NoteMLSSCommand : ICommand public byte Note { get; set; } public byte Duration { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -63,7 +63,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -71,7 +71,7 @@ internal sealed class PitchBendCommand : ICommand public sbyte Bend { get; set; } } -internal sealed class PitchBendRangeCommand : ICommand +internal class PitchBendRangeCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend Range"; @@ -79,7 +79,7 @@ internal sealed class PitchBendRangeCommand : ICommand public byte Range { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -87,7 +87,7 @@ internal sealed class RestCommand : ICommand public byte Rest { get; set; } } -internal sealed class TrackTempoCommand : ICommand +internal class TrackTempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => "Track Tempo"; @@ -95,7 +95,7 @@ internal sealed class TrackTempoCommand : ICommand public byte Tempo { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -103,7 +103,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/GBA/AlphaDream/Enums.cs b/VG Music Studio - Core/GBA/AlphaDream/Enums.cs new file mode 100644 index 0000000..bca47c4 --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Enums.cs @@ -0,0 +1,16 @@ +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream +{ + internal enum AudioEngineVersion : byte + { + Hamtaro, + MLSS, + } + + internal enum EnvelopeState : byte + { + Attack, + Decay, + Sustain, + Release, + } +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/Structs.cs b/VG Music Studio - Core/GBA/AlphaDream/Structs.cs new file mode 100644 index 0000000..dcd8832 --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Structs.cs @@ -0,0 +1,40 @@ +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; + +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 16)] +internal struct SampleHeader +{ + public const int LOOP_TRUE = 0x40_000_000; + + /// 0x40_000_000 if True + public int DoesLoop; + /// Right shift 10 for value + public int SampleRate; + public int LoopOffset; + public int Length; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 8)] +internal struct VoiceEntry +{ + public const byte FIXED_FREQ_TRUE = 0x80; + + public byte MinKey; + public byte MaxKey; + public byte Sample; + /// 0x80 if True + public byte IsFixedFrequency; + public byte Unknown1; + public byte Unknown2; + public byte Unknown3; + public byte Unknown4; +} + +internal struct ChannelVolume +{ + public float LeftVol, RightVol; +} +internal class ADSR // TODO +{ + public byte A, D, S, R; +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/Track.cs b/VG Music Studio - Core/GBA/AlphaDream/Track.cs new file mode 100644 index 0000000..d9401fc --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Track.cs @@ -0,0 +1,69 @@ +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream +{ + internal class Track + { + public readonly byte Index; + public readonly string Type; + public readonly AlphaDreamChannel Channel; + + public byte Voice; + public byte PitchBendRange; + public byte Volume; + public byte Rest; + public byte NoteDuration; + public sbyte PitchBend; + public sbyte Panpot; + public bool Enabled; + public bool Stopped; + public int StartOffset; + public int DataOffset; + public byte PrevCommand; + + public int GetPitch() + { + return PitchBend * (PitchBendRange / 2); + } + + public Track(byte i, AlphaDreamMixer mixer) + { + Index = i; + if (i >= 8) + { + Type = GBAUtils.PSGTypes[i & 3]; + Channel = new SquareChannel(mixer); // TODO: PSG Channels 3 and 4 + } + else + { + Type = "PCM8"; + Channel = new PCMChannel(mixer); + } + } + // 0x819B040 + public void Init() + { + Voice = 0; + Rest = 1; // Unsure why Rest starts at 1 + PitchBendRange = 2; + NoteDuration = 0; + PitchBend = 0; + Panpot = 0; // Start centered; ROM sets this to 0x7F since it's unsigned there + DataOffset = StartOffset; + Stopped = false; + Volume = 200; + PrevCommand = 0xFF; + //Tempo = 120; + //TempoStack = 0; + } + public void Tick() + { + if (Rest != 0) + { + Rest--; + } + if (NoteDuration > 0) + { + NoteDuration--; + } + } + } +} diff --git a/VG Music Studio - Core/GBA/GBAUtils.cs b/VG Music Studio - Core/GBA/GBAUtils.cs index c59b491..5106acf 100644 --- a/VG Music Studio - Core/GBA/GBAUtils.cs +++ b/VG Music Studio - Core/GBA/GBAUtils.cs @@ -3,10 +3,10 @@ internal static class GBAUtils { public const double AGB_FPS = 59.7275; - public const int SYSTEM_CLOCK = 16_777_216; // 16.777216 MHz (16*1024*1024 Hz) + public const int SystemClock = 16_777_216; // 16.777216 MHz (16*1024*1024 Hz) - public const int CARTRIDGE_OFFSET = 0x08_000_000; - public const int CARTRIDGE_CAPACITY = 0x02_000_000; + public const int CartridgeOffset = 0x08_000_000; + public const int CartridgeCapacity = 0x02_000_000; public static readonly string[] PSGTypes = new string[4] { "Square 1", "Square 2", "PCM4", "Noise" }; } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channel.cs similarity index 65% rename from VG Music Studio - Core/GBA/MP2K/MP2KChannel.cs rename to VG Music Studio - Core/GBA/MP2K/Channel.cs index 9f32498..f25482d 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KChannel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channel.cs @@ -1,15 +1,16 @@ using System; using System.Collections; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; -internal abstract class MP2KChannel +internal abstract class Channel { public EnvelopeState State = EnvelopeState.Dead; - public MP2KTrack? Owner; + public Track? Owner; protected readonly MP2KMixer _mixer; - public NoteInfo Note; + public NoteInfo Note; // Must be a struct & field protected ADSR _adsr; protected int _instPan; @@ -18,7 +19,7 @@ internal abstract class MP2KChannel protected float _interPos; protected float _frequency; - protected MP2KChannel(MP2KMixer mixer) + protected Channel(MP2KMixer mixer) { _mixer = mixer; } @@ -39,33 +40,39 @@ public virtual void Release() // Returns whether the note is active or not public virtual bool TickNote() { - if (State >= EnvelopeState.Releasing) - { - return false; - } - - if (Note.Duration > 0) + if (State < EnvelopeState.Releasing) { - Note.Duration--; - if (Note.Duration == 0) + if (Note.Duration > 0) + { + Note.Duration--; + if (Note.Duration == 0) + { + State = EnvelopeState.Releasing; + return false; + } + return true; + } + else { - State = EnvelopeState.Releasing; - return false; + return true; } } - return true; + else + { + return false; + } } public void Stop() { State = EnvelopeState.Dead; - if (Owner is not null) + if (Owner != null) { Owner.Channels.Remove(this); } Owner = null; } } -internal sealed class MP2KPCM8Channel : MP2KChannel +internal class PCM8Channel : Channel { private SampleHeader _sampleHeader; private int _sampleOffset; @@ -77,16 +84,11 @@ internal sealed class MP2KPCM8Channel : MP2KChannel private byte _rightVol; private sbyte[]? _decompressedSample; - public MP2KPCM8Channel(MP2KMixer mixer) - : base(mixer) - { - // - } - public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed) + public PCM8Channel(MP2KMixer mixer) : base(mixer) { } + public void Init(Track owner, NoteInfo note, ADSR adsr, int sampleOffset, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed) { State = EnvelopeState.Initializing; - _pos = 0; - _interPos = 0; + _pos = 0; _interPos = 0; if (Owner is not null) { Owner.Channels.Remove(this); @@ -97,14 +99,15 @@ public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, by _adsr = adsr; _instPan = instPan; byte[] rom = _mixer.Config.ROM; - _sampleHeader = SampleHeader.Get(rom, sampleOffset, out _sampleOffset); + _sampleHeader = MemoryMarshal.Read(rom.AsSpan(sampleOffset)); + _sampleOffset = sampleOffset + 0x10; _bFixed = bFixed; _bCompressed = bCompressed; - _decompressedSample = bCompressed ? MP2KUtils.Decompress(rom.AsSpan(_sampleOffset), _sampleHeader.Length) : null; - _bGoldenSun = _mixer.Config.HasGoldenSunSynths && _sampleHeader.Length == 0 && _sampleHeader.DoesLoop == SampleHeader.LOOP_TRUE && _sampleHeader.LoopOffset == 0; + _decompressedSample = bCompressed ? Utils.Decompress(_sampleOffset, _sampleHeader.Length) : null; + _bGoldenSun = _mixer.Config.HasGoldenSunSynths && _sampleHeader.DoesLoop == 0x40000000 && _sampleHeader.LoopOffset == 0 && _sampleHeader.Length == 0; if (_bGoldenSun) { - _gsPSG = GoldenSunPSG.Get(rom.AsSpan(_sampleOffset)); + _gsPSG = MemoryMarshal.Read(rom.AsSpan(_sampleOffset)); } SetVolume(vol, pan); SetPitch(pitch); @@ -112,11 +115,11 @@ public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, by public override ChannelVolume GetVolume() { - const float MAX = 0x10_000; + const float max = 0x10000; return new ChannelVolume { - LeftVol = _leftVol * _velocity / MAX * _mixer.PCM8MasterVolume, - RightVol = _rightVol * _velocity / MAX * _mixer.PCM8MasterVolume + LeftVol = _leftVol * _velocity / max * _mixer.PCM8MasterVolume, + RightVol = _rightVol * _velocity / max * _mixer.PCM8MasterVolume }; } public override void SetVolume(byte vol, sbyte pan) @@ -219,149 +222,134 @@ public override void Process(float[] buffer) float interStep = _bFixed && !_bGoldenSun ? _mixer.SampleRate * _mixer.SampleRateReciprocal : _frequency * _mixer.SampleRateReciprocal; if (_bGoldenSun) // Most Golden Sun processing is thanks to ipatix { - Process_GS(buffer, vol, interStep); - } - else if (_bCompressed) - { - Process_Compressed(buffer, vol, interStep); - } - else - { - Process_Standard(buffer, vol, interStep, _mixer.Config.ROM); - } - } - private void Process_GS(float[] buffer, ChannelVolume vol, float interStep) - { - interStep /= 0x40; - switch (_gsPSG.Type) - { - case GoldenSunPSGType.Square: + interStep /= 0x40; + switch (_gsPSG.Type) { - _pos += _gsPSG.CycleSpeed << 24; - int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; - iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; - iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); - float threshold = iThreshold / (float)0x100_000_000; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + case GoldenSunPSGType.Square: { - float samp = _interPos < threshold ? 0.5f : -0.5f; - samp += 0.5f - threshold; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - if (_interPos >= 1) + _pos += _gsPSG.CycleSpeed << 24; + int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; + iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; + iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); + float threshold = iThreshold / (float)0x100000000; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do { - _interPos--; - } - } while (--samplesPerBuffer > 0); - break; - } - case GoldenSunPSGType.Saw: - { - const int FIX = 0x70; + float samp = _interPos < threshold ? 0.5f : -0.5f; + samp += 0.5f - threshold; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + } while (--samplesPerBuffer > 0); + break; + } + case GoldenSunPSGType.Saw: { - _interPos += interStep; - if (_interPos >= 1) + const int fix = 0x70; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do { - _interPos--; - } - int var1 = (int)(_interPos * 0x100) - FIX; - int var2 = (int)(_interPos * 0x10000) << 17; - int var3 = var1 - (var2 >> 27); - _pos = var3 + (_pos >> 1); + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + int var1 = (int)(_interPos * 0x100) - fix; + int var2 = (int)(_interPos * 0x10000) << 17; + int var3 = var1 - (var2 >> 27); + _pos = var3 + (_pos >> 1); - float samp = _pos / (float)0x100; + float samp = _pos / (float)0x100; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; - } - case GoldenSunPSGType.Triangle: - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } + case GoldenSunPSGType.Triangle: { - _interPos += interStep; - if (_interPos >= 1) + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do { - _interPos--; - } - float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } } } - } - private void Process_Compressed(float[] buffer, ChannelVolume vol, float interStep) - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + else if (_bCompressed) { - float samp = _decompressedSample![_pos] / (float)0x80; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _decompressedSample.Length) + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do { - Stop(); - break; - } - } while (--samplesPerBuffer > 0); - } - private void Process_Standard(float[] buffer, ChannelVolume vol, float interStep, byte[] rom) - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = (sbyte)rom[_pos + _sampleOffset] / (float)0x80; + float samp = _decompressedSample![_pos] / (float)0x80; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _sampleHeader.Length) - { - if (_sampleHeader.DoesLoop != SampleHeader.LOOP_TRUE) + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _decompressedSample.Length) { Stop(); - return; + break; } + } while (--samplesPerBuffer > 0); + } + else + { + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = (sbyte)_mixer.Config.ROM[_pos + _sampleOffset] / (float)0x80; - _pos = _sampleHeader.LoopOffset; - } - } while (--samplesPerBuffer > 0); + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _sampleHeader.Length) + { + if (_sampleHeader.DoesLoop == 0x40000000) + { + _pos = _sampleHeader.LoopOffset; + } + else + { + Stop(); + break; + } + } + } while (--samplesPerBuffer > 0); + } } } -internal abstract class MP2KPSGChannel : MP2KChannel +internal abstract class PSGChannel : Channel { protected enum GBPan : byte { Left, Center, - Right, + Right } private byte _processStep; @@ -370,15 +358,11 @@ protected enum GBPan : byte private byte _sustainVelocity; protected GBPan _panpot = GBPan.Center; - public MP2KPSGChannel(MP2KMixer mixer) - : base(mixer) - { - // - } - protected void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan) + public PSGChannel(MP2KMixer mixer) : base(mixer) { } + protected void Init(Track owner, NoteInfo note, ADSR env, int instPan) { State = EnvelopeState.Initializing; - if (Owner is not null) + if (Owner != null) { Owner.Channels.Remove(this); } @@ -643,25 +627,24 @@ void rel() } } } -internal sealed class MP2KSquareChannel : MP2KPSGChannel +internal class SquareChannel : PSGChannel { - private float[]? _pat; + private float[] _pat; - public MP2KSquareChannel(MP2KMixer mixer) - : base(mixer) + public SquareChannel(MP2KMixer mixer) : base(mixer) { // } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, SquarePattern pattern) + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, SquarePattern pattern) { Init(owner, note, env, instPan); - _pat = pattern switch + switch (pattern) { - SquarePattern.D12 => MP2KUtils.SquareD12, - SquarePattern.D25 => MP2KUtils.SquareD25, - SquarePattern.D50 => MP2KUtils.SquareD50, - _ => MP2KUtils.SquareD75, - }; + default: _pat = Utils.SquareD12; break; + case SquarePattern.D25: _pat = Utils.SquareD25; break; + case SquarePattern.D50: _pat = Utils.SquareD50; break; + case SquarePattern.D75: _pat = Utils.SquareD75; break; + } } public override void SetPitch(int pitch) @@ -680,11 +663,10 @@ public override void Process(float[] buffer) ChannelVolume vol = GetVolume(); float interStep = _frequency * _mixer.SampleRateReciprocal; - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; do { - float samp = _pat![_pos]; + float samp = _pat[_pos]; buffer[bufPos++] += samp * vol.LeftVol; buffer[bufPos++] += samp * vol.RightVol; @@ -696,19 +678,18 @@ public override void Process(float[] buffer) } while (--samplesPerBuffer > 0); } } -internal sealed class MP2KPCM4Channel : MP2KPSGChannel +internal class PCM4Channel : PSGChannel { - private readonly float[] _sample; + private float[] _sample; - public MP2KPCM4Channel(MP2KMixer mixer) - : base(mixer) + public PCM4Channel(MP2KMixer mixer) : base(mixer) { - _sample = new float[0x20]; + // } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, int sampleOffset) + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, int sampleOffset) { Init(owner, note, env, instPan); - MP2KUtils.PCM4ToFloat(_mixer.Config.ROM.AsSpan(sampleOffset), _sample); + _sample = Utils.PCM4ToFloat(sampleOffset); } public override void SetPitch(int pitch) @@ -727,8 +708,7 @@ public override void Process(float[] buffer) ChannelVolume vol = GetVolume(); float interStep = _frequency * _mixer.SampleRateReciprocal; - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; do { float samp = _sample[_pos]; @@ -743,19 +723,18 @@ public override void Process(float[] buffer) } while (--samplesPerBuffer > 0); } } -internal sealed class MP2KNoiseChannel : MP2KPSGChannel +internal class NoiseChannel : PSGChannel { private BitArray _pat; - public MP2KNoiseChannel(MP2KMixer mixer) - : base(mixer) + public NoiseChannel(MP2KMixer mixer) : base(mixer) { // } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, NoisePattern pattern) + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, NoisePattern pattern) { Init(owner, note, env, instPan); - _pat = pattern == NoisePattern.Fine ? MP2KUtils.NoiseFine : MP2KUtils.NoiseRough; + _pat = pattern == NoisePattern.Fine ? Utils.NoiseFine : Utils.NoiseRough; } public override void SetPitch(int pitch) @@ -773,7 +752,7 @@ public override void SetPitch(int pitch) key = 59; } } - byte v = MP2KUtils.NoiseFrequencyTable[key]; + byte v = Utils.NoiseFrequencyTable[key]; // The following emulates 0x0400007C - SOUND4CNT_H int r = v & 7; // Bits 0-2 int s = v >> 4; // Bits 4-7 @@ -791,8 +770,7 @@ public override void Process(float[] buffer) ChannelVolume vol = GetVolume(); float interStep = _frequency * _mixer.SampleRateReciprocal; - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; do { float samp = _pat[_pos & (_pat.Length - 1)] ? 0.5f : -0.5f; diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs b/VG Music Studio - Core/GBA/MP2K/Commands.cs similarity index 79% rename from VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs rename to VG Music Studio - Core/GBA/MP2K/Commands.cs index 4959a5b..5778eec 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs +++ b/VG Music Studio - Core/GBA/MP2K/Commands.cs @@ -3,7 +3,7 @@ namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; -internal sealed class CallCommand : ICommand +internal class CallCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Call"; @@ -11,7 +11,7 @@ internal sealed class CallCommand : ICommand public int Offset { get; set; } } -internal sealed class EndOfTieCommand : ICommand +internal class EndOfTieCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "End Of Tie"; @@ -19,7 +19,7 @@ internal sealed class EndOfTieCommand : ICommand public int Note { get; set; } } -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; @@ -27,7 +27,7 @@ internal sealed class FinishCommand : ICommand public bool Prev { get; set; } } -internal sealed class JumpCommand : ICommand +internal class JumpCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Jump"; @@ -35,7 +35,7 @@ internal sealed class JumpCommand : ICommand public int Offset { get; set; } } -internal sealed class LFODelayCommand : ICommand +internal class LFODelayCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Delay"; @@ -43,7 +43,7 @@ internal sealed class LFODelayCommand : ICommand public byte Delay { get; set; } } -internal sealed class LFODepthCommand : ICommand +internal class LFODepthCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Depth"; @@ -51,7 +51,7 @@ internal sealed class LFODepthCommand : ICommand public byte Depth { get; set; } } -internal sealed class LFOSpeedCommand : ICommand +internal class LFOSpeedCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Speed"; @@ -59,7 +59,7 @@ internal sealed class LFOSpeedCommand : ICommand public byte Speed { get; set; } } -internal sealed class LFOTypeCommand : ICommand +internal class LFOTypeCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Type"; @@ -67,7 +67,7 @@ internal sealed class LFOTypeCommand : ICommand public LFOType Type { get; set; } } -internal sealed class LibraryCommand : ICommand +internal class LibraryCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Library Call"; @@ -76,7 +76,7 @@ internal sealed class LibraryCommand : ICommand public byte Command { get; set; } public byte Argument { get; set; } } -internal sealed class MemoryAccessCommand : ICommand +internal class MemoryAccessCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Memory Access"; @@ -86,7 +86,7 @@ internal sealed class MemoryAccessCommand : ICommand public byte Address { get; set; } public byte Data { get; set; } } -internal sealed class NoteCommand : ICommand +internal class NoteCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -96,7 +96,7 @@ internal sealed class NoteCommand : ICommand public byte Velocity { get; set; } public int Duration { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -104,7 +104,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -112,7 +112,7 @@ internal sealed class PitchBendCommand : ICommand public sbyte Bend { get; set; } } -internal sealed class PitchBendRangeCommand : ICommand +internal class PitchBendRangeCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend Range"; @@ -120,7 +120,7 @@ internal sealed class PitchBendRangeCommand : ICommand public byte Range { get; set; } } -internal sealed class PriorityCommand : ICommand +internal class PriorityCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Priority"; @@ -128,7 +128,7 @@ internal sealed class PriorityCommand : ICommand public byte Priority { get; set; } } -internal sealed class RepeatCommand : ICommand +internal class RepeatCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Repeat"; @@ -137,7 +137,7 @@ internal sealed class RepeatCommand : ICommand public byte Times { get; set; } public int Offset { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -145,13 +145,13 @@ internal sealed class RestCommand : ICommand public byte Rest { get; set; } } -internal sealed class ReturnCommand : ICommand +internal class ReturnCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Return"; public string Arguments => string.Empty; } -internal sealed class TempoCommand : ICommand +internal class TempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => "Tempo"; @@ -159,7 +159,7 @@ internal sealed class TempoCommand : ICommand public ushort Tempo { get; set; } } -internal sealed class TransposeCommand : ICommand +internal class TransposeCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Transpose"; @@ -167,7 +167,7 @@ internal sealed class TransposeCommand : ICommand public sbyte Transpose { get; set; } } -internal sealed class TuneCommand : ICommand +internal class TuneCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Fine Tune"; @@ -175,7 +175,7 @@ internal sealed class TuneCommand : ICommand public sbyte Tune { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -183,7 +183,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/GBA/MP2K/Enums.cs b/VG Music Studio - Core/GBA/MP2K/Enums.cs new file mode 100644 index 0000000..cb169c6 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Enums.cs @@ -0,0 +1,76 @@ +using System; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal enum EnvelopeState : byte + { + Initializing, + Rising, + Decaying, + Playing, + Releasing, + Dying, + Dead, + } + internal enum ReverbType : byte + { + None, + Normal, + Camelot1, + Camelot2, + MGAT, + } + + internal enum GoldenSunPSGType : byte + { + Square, + Saw, + Triangle, + } + internal enum LFOType : byte + { + Pitch, + Volume, + Panpot, + } + internal enum SquarePattern : byte + { + D12, + D25, + D50, + D75, + } + internal enum NoisePattern : byte + { + Fine, + Rough, + } + internal enum VoiceType : byte + { + PCM8, + Square1, + Square2, + PCM4, + Noise, + Invalid5, + Invalid6, + Invalid7, + } + [Flags] + internal enum VoiceFlags : byte + { + // These are flags that apply to the types + /// PCM8 + Fixed = 0x08, + /// Square1, Square2, PCM4, Noise + OffWithNoise = 0x08, + /// PCM8 + Reversed = 0x10, + /// PCM8 (Only in Pokémon main series games) + Compressed = 0x20, + + // These are flags that cancel out every other bit after them if set so they should only be checked with equality + KeySplit = 0x40, + Drum = 0x80, + } +} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs b/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs index f7ea0b3..c583a1e 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs @@ -125,7 +125,7 @@ void Load(YamlMappingNode gameToLoad) var songs = new List(); foreach (KeyValuePair song in (YamlMappingNode)kvp.Value) { - int songIndex = (int)ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, int.MaxValue); + long songIndex = ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, long.MaxValue); if (songs.Any(s => s.Index == songIndex)) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorAlphaDreamMP2KSongRepeated, name, songIndex))); @@ -178,7 +178,7 @@ void Load(YamlMappingNode gameToLoad) { throw new BetterKeyNotFoundException(nameof(SampleRate), null); } - SampleRate = (int)ConfigUtils.ParseValue(nameof(SampleRate), sampleRateNode.ToString(), 0, MP2KUtils.FrequencyTable.Length - 1); + SampleRate = (int)ConfigUtils.ParseValue(nameof(SampleRate), sampleRateNode.ToString(), 0, Utils.FrequencyTable.Length - 1); if (reverbTypeNode is null) { @@ -211,7 +211,10 @@ void Load(YamlMappingNode gameToLoad) HasPokemonCompression = ConfigUtils.ParseBoolean(nameof(HasPokemonCompression), hasPokemonCompression.ToString()); // The complete playlist - ConfigUtils.TryCreateMasterPlaylist(Playlists); + if (!Playlists.Any(p => p.Name == "Music")) + { + Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index))); + } } catch (BetterKeyNotFoundException ex) { @@ -232,13 +235,10 @@ public override string GetGameName() { return Name; } - public override string GetSongName(int index) + public override string GetSongName(long index) { - if (TryGetFirstSong(index, out Song s)) - { - return s.Name; - } - return index.ToString(); + Song? s = GetFirstSong(index); + return s is not null ? s.Name : index.ToString(); } public override void Dispose() diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs index 43c40ba..43d5264 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs @@ -12,9 +12,9 @@ public sealed class MP2KEngine : Engine public MP2KEngine(byte[] rom) { - if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) + if (rom.Length > GBAUtils.CartridgeCapacity) { - throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); + throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CartridgeCapacity:X7} bytes."); } Config = new MP2KConfig(rom); diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs deleted file mode 100644 index 86029a6..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal enum EnvelopeState : byte -{ - Initializing, - Rising, - Decaying, - Playing, - Releasing, - Dying, - Dead, -} -internal enum ReverbType : byte -{ - None, - Normal, - Camelot1, - Camelot2, - MGAT, -} - -internal enum GoldenSunPSGType : byte -{ - Square, - Saw, - Triangle, -} -internal enum LFOType : byte -{ - Pitch, - Volume, - Panpot, -} -internal enum SquarePattern : byte -{ - D12, - D25, - D50, - D75, -} -internal enum NoisePattern : byte -{ - Fine, - Rough, -} -internal enum VoiceType : byte -{ - PCM8, - Square1, - Square2, - PCM4, - Noise, - Invalid5, - Invalid6, - Invalid7, -} -[Flags] -internal enum VoiceFlags : byte -{ - // These are flags that apply to the types - /// PCM8 - Fixed = 0x08, - /// Square1, Square2, PCM4, Noise - OffWithNoise = 0x08, - /// PCM8 - Reversed = 0x10, - /// PCM8 (Only in Pokémon main series games) - Compressed = 0x20, - - // These are flags that cancel out every other bit after them if set so they should only be checked with equality - KeySplit = 0x40, - Drum = 0x80, -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs index b336371..1c8da7c 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs @@ -1,46 +1,535 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; internal sealed partial class MP2KLoadedSong : ILoadedSong { - public List[] Events { get; } + public List[] Events { get; private set; } public long MaxTicks { get; private set; } - public int LongestTrack; + public long ElapsedTicks { get; internal set; } + internal int LongestTrack; private readonly MP2KPlayer _player; - private readonly int _voiceTableOffset; - public readonly MP2KTrack[] Tracks; + public readonly int VoiceTableOffset; + internal readonly Track[] Tracks; - public MP2KLoadedSong(MP2KPlayer player, int index) + public MP2KLoadedSong(long index, MP2KPlayer player, MP2KConfig cfg, int? oldVoiceTableOffset, string?[] voiceTypeCache) { _player = player; - MP2KConfig cfg = player.Config; - var entry = SongEntry.Get(cfg.ROM, cfg.SongTableOffsets[0], index); - int headerOffset = entry.HeaderOffset - GBAUtils.CARTRIDGE_OFFSET; - - var header = SongHeader.Get(cfg.ROM, headerOffset, out int tracksOffset); - _voiceTableOffset = header.VoiceTableOffset - GBAUtils.CARTRIDGE_OFFSET; + ref SongEntry entry = ref MemoryMarshal.AsRef(cfg.ROM.AsSpan(cfg.SongTableOffsets[0] + ((int)index * 8))); + cfg.Reader.Stream.Position = entry.HeaderOffset - GBA.GBAUtils.CartridgeOffset; + SongHeader header = cfg.Reader.ReadObject(); // TODO: Can I RefStruct this? If not, should still ditch reader and use pointer + VoiceTableOffset = header.VoiceTableOffset - GBA.GBAUtils.CartridgeOffset; + if (oldVoiceTableOffset != VoiceTableOffset) + { + Array.Clear(voiceTypeCache); + } - Tracks = new MP2KTrack[header.NumTracks]; + Tracks = new Track[header.NumTracks]; Events = new List[header.NumTracks]; for (byte trackIndex = 0; trackIndex < header.NumTracks; trackIndex++) { - int trackStart = SongHeader.GetTrackOffset(cfg.ROM, tracksOffset, trackIndex) - GBAUtils.CARTRIDGE_OFFSET; - Tracks[trackIndex] = new MP2KTrack(trackIndex, trackStart); + int trackStart = header.TrackOffsets[trackIndex] - GBA.GBAUtils.CartridgeOffset; + Tracks[trackIndex] = new Track(trackIndex, trackStart); + Events[trackIndex] = new List(); - AddTrackEvents(trackIndex, trackStart); + byte runCmd = 0, prevKey = 0, prevVelocity = 0x7F; + int callStackDepth = 0; + AddEvents(trackStart, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); } } - public void CheckVoiceTypeCache(ref int? old, string?[] voiceTypeCache) + private static void AddEvent(List trackEvents, long offset, ICommand command) { - if (old != _voiceTableOffset) + trackEvents.Add(new SongEvent(offset, command)); + } + private static bool EventExists(List trackEvents, long offset) + { + return trackEvents.Any(e => e.Offset == offset); + } + private static void EmulateNote(List trackEvents, long offset, byte key, byte velocity, byte addedDuration, + ref byte runCmd, ref byte prevKey, ref byte prevVelocity) + { + prevKey = key; + prevVelocity = velocity; + if (!EventExists(trackEvents, offset)) { - old = _voiceTableOffset; - Array.Clear(voiceTypeCache); + AddEvent(trackEvents, offset, new NoteCommand + { + Note = key, + Velocity = velocity, + Duration = runCmd == 0xCF ? -1 : (Utils.RestTable[runCmd - 0xCF] + addedDuration), + }); + } + } + private void AddEvents(long startOffset, MP2KConfig cfg, byte trackIndex, + ref byte runCmd, ref byte prevKey, ref byte prevVelocity, ref int callStackDepth) + { + cfg.Reader.Stream.Position = startOffset; + List trackEvents = Events[trackIndex]; + + Span peek = stackalloc byte[3]; + bool cont = true; + while (cont) + { + long offset = cfg.Reader.Stream.Position; + + byte cmd = cfg.Reader.ReadByte(); + if (cmd >= 0xBD) // Commands that work within running status + { + runCmd = cmd; + } + + #region TIE & Notes + + if (runCmd >= 0xCF && cmd <= 0x7F) // Within running status + { + byte velocity, addedDuration; + cfg.Reader.PeekBytes(peek.Slice(0, 2)); + if (peek[0] > 0x7F) + { + velocity = prevVelocity; + addedDuration = 0; + } + else if (peek[1] > 3) + { + velocity = cfg.Reader.ReadByte(); + addedDuration = 0; + } + else + { + velocity = cfg.Reader.ReadByte(); + addedDuration = cfg.Reader.ReadByte(); + } + EmulateNote(trackEvents, offset, cmd, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); + } + else if (cmd >= 0xCF) + { + byte key, velocity, addedDuration; + cfg.Reader.PeekBytes(peek); + if (peek[0] > 0x7F) + { + key = prevKey; + velocity = prevVelocity; + addedDuration = 0; + } + else if (peek[1] > 0x7F) + { + key = cfg.Reader.ReadByte(); + velocity = prevVelocity; + addedDuration = 0; + } + // TIE (0xCF) cannot have an added duration so it needs to stop here + else if (cmd == 0xCF || peek[2] > 3) + { + key = cfg.Reader.ReadByte(); + velocity = cfg.Reader.ReadByte(); + addedDuration = 0; + } + else + { + key = cfg.Reader.ReadByte(); + velocity = cfg.Reader.ReadByte(); + addedDuration = cfg.Reader.ReadByte(); + } + EmulateNote(trackEvents, offset, key, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); + } + + #endregion + + #region Rests + + else if (cmd >= 0x80 && cmd <= 0xB0) + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new RestCommand { Rest = Utils.RestTable[cmd - 0x80] }); + } + } + + #endregion + + #region Commands + + else if (runCmd < 0xCF && cmd <= 0x7F) + { + switch (runCmd) + { + case 0xBD: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VoiceCommand { Voice = cmd }); + } + break; + } + case 0xBE: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VolumeCommand { Volume = cmd }); + } + break; + } + case 0xBF: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PanpotCommand { Panpot = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xC0: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendCommand { Bend = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xC1: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendRangeCommand { Range = cmd }); + } + break; + } + case 0xC2: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOSpeedCommand { Speed = cmd }); + } + break; + } + case 0xC3: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODelayCommand { Delay = cmd }); + } + break; + } + case 0xC4: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODepthCommand { Depth = cmd }); + } + break; + } + case 0xC5: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOTypeCommand { Type = (LFOType)cmd }); + } + break; + } + case 0xC8: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TuneCommand { Tune = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xCD: + { + byte arg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LibraryCommand { Command = cmd, Argument = arg }); + } + break; + } + case 0xCE: + { + prevKey = cmd; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new EndOfTieCommand { Note = cmd }); + } + break; + } + default: throw new MP2KInvalidRunningStatusCMDException(trackIndex, (int)offset, runCmd); + } + } + else if (cmd > 0xB0 && cmd < 0xCF) + { + switch (cmd) + { + case 0xB1: + case 0xB6: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new FinishCommand { Prev = cmd == 0xB6 }); + } + cont = false; + break; + } + case 0xB2: + { + int jumpOffset = cfg.Reader.ReadInt32() - GBA.GBAUtils.CartridgeOffset; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new JumpCommand { Offset = jumpOffset }); + if (!EventExists(trackEvents, jumpOffset)) + { + AddEvents(jumpOffset, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); + } + } + cont = false; + break; + } + case 0xB3: + { + int callOffset = cfg.Reader.ReadInt32() - GBA.GBAUtils.CartridgeOffset; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new CallCommand { Offset = callOffset }); + } + if (callStackDepth < 3) + { + long backup = cfg.Reader.Stream.Position; + callStackDepth++; + AddEvents(callOffset, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); + cfg.Reader.Stream.Position = backup; + } + else + { + throw new MP2KTooManyNestedCallsException(trackIndex); + } + break; + } + case 0xB4: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new ReturnCommand()); + } + if (callStackDepth != 0) + { + cont = false; + callStackDepth--; + } + break; + } + /*case 0xB5: // TODO: Logic so this isn't an infinite loop + { + byte times = config.Reader.ReadByte(); + int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; + if (!EventExists(offset, trackEvents)) + { + AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); + } + break; + }*/ + case 0xB9: + { + byte op = cfg.Reader.ReadByte(); + byte address = cfg.Reader.ReadByte(); + byte data = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new MemoryAccessCommand { Operator = op, Address = address, Data = data }); + } + break; + } + case 0xBA: + { + byte priority = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PriorityCommand { Priority = priority }); + } + break; + } + case 0xBB: + { + byte tempoArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TempoCommand { Tempo = (ushort)(tempoArg * 2) }); + } + break; + } + case 0xBC: + { + sbyte transpose = cfg.Reader.ReadSByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TransposeCommand { Transpose = transpose }); + } + break; + } + // Commands that work within running status: + case 0xBD: + { + byte voice = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VoiceCommand { Voice = voice }); + } + break; + } + case 0xBE: + { + byte volume = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VolumeCommand { Volume = volume }); + } + break; + } + case 0xBF: + { + byte panArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); + } + break; + } + case 0xC0: + { + byte bendArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendCommand { Bend = (sbyte)(bendArg - 0x40) }); + } + break; + } + case 0xC1: + { + byte range = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendRangeCommand { Range = range }); + } + break; + } + case 0xC2: + { + byte speed = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOSpeedCommand { Speed = speed }); + } + break; + } + case 0xC3: + { + byte delay = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODelayCommand { Delay = delay }); + } + break; + } + case 0xC4: + { + byte depth = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODepthCommand { Depth = depth }); + } + break; + } + case 0xC5: + { + byte type = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOTypeCommand { Type = (LFOType)type }); + } + break; + } + case 0xC8: + { + byte tuneArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TuneCommand { Tune = (sbyte)(tuneArg - 0x40) }); + } + break; + } + case 0xCD: + { + byte command = cfg.Reader.ReadByte(); + byte arg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LibraryCommand { Command = command, Argument = arg }); + } + break; + } + case 0xCE: + { + int key = cfg.Reader.PeekByte() <= 0x7F ? (prevKey = cfg.Reader.ReadByte()) : -1; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new EndOfTieCommand { Note = key }); + } + break; + } + default: throw new MP2KInvalidCMDException(trackIndex, (int)offset, cmd); + } + } + + #endregion + } + } + + internal void SetTicks() + { + MaxTicks = 0; + bool u = false; + for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) + { + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = Tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + if (track.CallStackDepth == 0 && e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + _player.ExecuteNext(track, ref u); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + LongestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.StopAllChannels(); + } + } + + public void Dispose() + { + for (int i = 0; i < Tracks.Length; i++) + { + Tracks[i].StopAllChannels(); } } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs deleted file mode 100644 index 2bfd97f..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs +++ /dev/null @@ -1,542 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed partial class MP2KLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex].Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex].Exists(e => e.Offset == cmdOffset); - } - - private void EmulateNote(byte trackIndex, long cmdOffset, byte key, byte velocity, byte addedDuration, ref byte runCmd, ref byte prevKey, ref byte prevVelocity) - { - prevKey = key; - prevVelocity = velocity; - if (EventExists(trackIndex, cmdOffset)) - { - return; - } - - AddEvent(trackIndex, cmdOffset, new NoteCommand - { - Note = key, - Velocity = velocity, - Duration = runCmd == 0xCF ? -1 : (MP2KUtils.RestTable[runCmd - 0xCF] + addedDuration), - }); - } - - private void AddTrackEvents(byte trackIndex, long trackStart) - { - Events[trackIndex] = new List(); - byte runCmd = 0; - byte prevKey = 0; - byte prevVelocity = 0x7F; - int callStackDepth = 0; - AddEvents(trackIndex, trackStart, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - } - private void AddEvents(byte trackIndex, long startOffset, ref byte runCmd, ref byte prevKey, ref byte prevVelocity, ref int callStackDepth) - { - EndianBinaryReader r = _player.Config.Reader; - r.Stream.Position = startOffset; - - Span peek = stackalloc byte[3]; - bool cont = true; - while (cont) - { - long offset = r.Stream.Position; - - byte cmd = r.ReadByte(); - if (cmd >= 0xBD) // Commands that work within running status - { - runCmd = cmd; - } - - #region TIE & Notes - - if (runCmd >= 0xCF && cmd <= 0x7F) // Within running status - { - byte velocity, addedDuration; - r.PeekBytes(peek.Slice(0, 2)); - if (peek[0] > 0x7F) - { - velocity = prevVelocity; - addedDuration = 0; - } - else if (peek[1] > 3) - { - velocity = r.ReadByte(); - addedDuration = 0; - } - else - { - velocity = r.ReadByte(); - addedDuration = r.ReadByte(); - } - EmulateNote(trackIndex, offset, cmd, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); - } - else if (cmd >= 0xCF) - { - byte key, velocity, addedDuration; - r.PeekBytes(peek); - if (peek[0] > 0x7F) - { - key = prevKey; - velocity = prevVelocity; - addedDuration = 0; - } - else if (peek[1] > 0x7F) - { - key = r.ReadByte(); - velocity = prevVelocity; - addedDuration = 0; - } - // TIE (0xCF) cannot have an added duration so it needs to stop here - else if (cmd == 0xCF || peek[2] > 3) - { - key = r.ReadByte(); - velocity = r.ReadByte(); - addedDuration = 0; - } - else - { - key = r.ReadByte(); - velocity = r.ReadByte(); - addedDuration = r.ReadByte(); - } - EmulateNote(trackIndex, offset, key, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); - } - - #endregion - - #region Rests - - else if (cmd >= 0x80 && cmd <= 0xB0) - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new RestCommand { Rest = MP2KUtils.RestTable[cmd - 0x80] }); - } - } - - #endregion - - #region Commands - - else if (runCmd < 0xCF && cmd <= 0x7F) - { - switch (runCmd) - { - case 0xBD: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VoiceCommand { Voice = cmd }); - } - break; - } - case 0xBE: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VolumeCommand { Volume = cmd }); - } - break; - } - case 0xBF: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PanpotCommand { Panpot = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xC0: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendCommand { Bend = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xC1: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendRangeCommand { Range = cmd }); - } - break; - } - case 0xC2: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOSpeedCommand { Speed = cmd }); - } - break; - } - case 0xC3: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODelayCommand { Delay = cmd }); - } - break; - } - case 0xC4: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODepthCommand { Depth = cmd }); - } - break; - } - case 0xC5: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOTypeCommand { Type = (LFOType)cmd }); - } - break; - } - case 0xC8: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TuneCommand { Tune = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xCD: - { - byte arg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LibraryCommand { Command = cmd, Argument = arg }); - } - break; - } - case 0xCE: - { - prevKey = cmd; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new EndOfTieCommand { Note = cmd }); - } - break; - } - default: throw new MP2KInvalidRunningStatusCMDException(trackIndex, (int)offset, runCmd); - } - } - else if (cmd > 0xB0 && cmd < 0xCF) - { - switch (cmd) - { - case 0xB1: - case 0xB6: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new FinishCommand { Prev = cmd == 0xB6 }); - } - cont = false; - break; - } - case 0xB2: - { - int jumpOffset = r.ReadInt32() - GBAUtils.CARTRIDGE_OFFSET; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new JumpCommand { Offset = jumpOffset }); - if (!EventExists(trackIndex, jumpOffset)) - { - AddEvents(trackIndex, jumpOffset, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - } - } - cont = false; - break; - } - case 0xB3: - { - int callOffset = r.ReadInt32() - GBAUtils.CARTRIDGE_OFFSET; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new CallCommand { Offset = callOffset }); - } - if (callStackDepth < 3) - { - long backup = r.Stream.Position; - callStackDepth++; - AddEvents(trackIndex, callOffset, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - r.Stream.Position = backup; - } - else - { - throw new MP2KTooManyNestedCallsException(trackIndex); - } - break; - } - case 0xB4: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new ReturnCommand()); - } - if (callStackDepth != 0) - { - cont = false; - callStackDepth--; - } - break; - } - /*case 0xB5: // TODO: Logic so this isn't an infinite loop - { - byte times = config.Reader.ReadByte(); - int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; - if (!EventExists(offset, trackEvents)) - { - AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); - } - break; - }*/ - case 0xB9: - { - byte op = r.ReadByte(); - byte address = r.ReadByte(); - byte data = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new MemoryAccessCommand { Operator = op, Address = address, Data = data }); - } - break; - } - case 0xBA: - { - byte priority = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PriorityCommand { Priority = priority }); - } - break; - } - case 0xBB: - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TempoCommand { Tempo = (ushort)(tempoArg * 2) }); - } - break; - } - case 0xBC: - { - sbyte transpose = r.ReadSByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TransposeCommand { Transpose = transpose }); - } - break; - } - // Commands that work within running status: - case 0xBD: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xBE: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xBF: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); - } - break; - } - case 0xC0: - { - byte bendArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendCommand { Bend = (sbyte)(bendArg - 0x40) }); - } - break; - } - case 0xC1: - { - byte range = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendRangeCommand { Range = range }); - } - break; - } - case 0xC2: - { - byte speed = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOSpeedCommand { Speed = speed }); - } - break; - } - case 0xC3: - { - byte delay = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODelayCommand { Delay = delay }); - } - break; - } - case 0xC4: - { - byte depth = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODepthCommand { Depth = depth }); - } - break; - } - case 0xC5: - { - byte type = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOTypeCommand { Type = (LFOType)type }); - } - break; - } - case 0xC8: - { - byte tuneArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TuneCommand { Tune = (sbyte)(tuneArg - 0x40) }); - } - break; - } - case 0xCD: - { - byte command = r.ReadByte(); - byte arg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LibraryCommand { Command = command, Argument = arg }); - } - break; - } - case 0xCE: - { - int key = r.PeekByte() <= 0x7F ? (prevKey = r.ReadByte()) : -1; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new EndOfTieCommand { Note = key }); - } - break; - } - default: throw new MP2KInvalidCMDException(trackIndex, (int)offset, cmd); - } - } - - #endregion - } - } - - public void SetTicks() - { - MaxTicks = 0; - bool u = false; - for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) - { - List evs = Events[trackIndex]; - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - MP2KTrack track = Tracks[trackIndex]; - track.Init(); - - _player.ElapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - if (track.CallStackDepth == 0 && e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(_player.ElapsedTicks); - ExecuteNext(track, ref u); - if (track.Stopped) - { - break; - } - - _player.ElapsedTicks += track.Rest; - track.Rest = 0; - } - if (_player.ElapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = _player.ElapsedTicks; - } - track.StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - bool u = false; - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - while (_player.TempoStack >= 150) - { - _player.TempoStack -= 150; - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - MP2KTrack track = Tracks[trackIndex]; - if (!track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track, ref u); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < Tracks.Length; i++) - { - Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs index 12c8439..4a9cd2d 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs @@ -10,14 +10,7 @@ public sealed class MIDISaveArgs { public bool SaveCommandsBeforeTranspose; // TODO: I forgor why I would want this public bool ReverseVolume; - public (int AbsoluteTick, (byte Numerator, byte Denominator))[] TimeSignatures; - - public MIDISaveArgs(bool saveCmdsBeforeTranspose, bool reverseVol, (int, (byte, byte))[] timeSignatures) - { - SaveCommandsBeforeTranspose = saveCmdsBeforeTranspose; - ReverseVolume = reverseVol; - TimeSignatures = timeSignatures; - } + public List<(int AbsoluteTick, (byte Numerator, byte Denominator))> TimeSignatures; } internal sealed partial class MP2KLoadedSong @@ -58,7 +51,6 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) long startOfPatternTicks = 0; long endOfPatternTicks = 0; sbyte transpose = 0; - int? endTicks = null; var playing = new List(); List trackEvents = Events[trackIndex]; for (int i = 0; i < trackEvents.Count; i++) @@ -111,14 +103,13 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) key = 0x7F; } track.Insert(ticks, new NoteOnMessage(trackIndex, (MIDINote)key, 0)); - //track.Insert(ticks, new NoteOffMessage(trackIndex, (MIDINote)key, 0)); playing.Remove(nc); } break; } case FinishCommand _: { - endTicks = ticks; + track.Insert(ticks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); goto endOfTrack; } case JumpCommand c: @@ -179,7 +170,6 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) if (c.Duration != -1) { track.Insert(ticks + c.Duration, new NoteOnMessage(trackIndex, (MIDINote)note, 0)); - //track.Insert(ticks + c.Duration, new NoteOffMessage(trackIndex, (MIDINote)note, 0)); } else { @@ -253,7 +243,7 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } } endOfTrack: - track.Insert(endTicks ?? track.NumTicks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); + ; } metaTrack.Insert(metaTrack.NumTicks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs deleted file mode 100644 index b3c038c..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs +++ /dev/null @@ -1,458 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed partial class MP2KLoadedSong -{ - private void TryPlayNote(MP2KTrack track, byte note, byte velocity, byte addedDuration) - { - int n = note + track.Transpose; - if (n < 0) - { - n = 0; - } - else if (n > 0x7F) - { - n = 0x7F; - } - note = (byte)n; - track.PrevNote = note; - track.PrevVelocity = velocity; - // Tracks do not play unless they have had a voice change event - if (track.Ready) - { - PlayNote(_player.Config.ROM, track, note, velocity, addedDuration); - } - } - private void PlayNote(byte[] rom, MP2KTrack track, byte note, byte velocity, byte addedDuration) - { - bool fromDrum = false; - int offset = _voiceTableOffset + (track.Voice * 12); - while (true) - { - var v = new VoiceEntry(rom.AsSpan(offset)); - if (v.Type == (int)VoiceFlags.KeySplit) - { - fromDrum = false; // In case there is a multi within a drum - byte inst = rom[v.Int8 - GBAUtils.CARTRIDGE_OFFSET + note]; - offset = v.Int4 - GBAUtils.CARTRIDGE_OFFSET + (inst * 12); - } - else if (v.Type == (int)VoiceFlags.Drum) - { - fromDrum = true; - offset = v.Int4 - GBAUtils.CARTRIDGE_OFFSET + (note * 12); - } - else - { - var ni = new NoteInfo - { - Duration = track.RunCmd == 0xCF ? -1 : (MP2KUtils.RestTable[track.RunCmd - 0xCF] + addedDuration), - Velocity = velocity, - OriginalNote = note, - Note = fromDrum ? v.RootNote : note, - }; - var type = (VoiceType)(v.Type & 0x7); - int instPan = v.Pan; - instPan = (instPan & 0x80) != 0 ? instPan - 0xC0 : 0; - switch (type) - { - case VoiceType.PCM8: - { - bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; - bool bCompressed = _player.Config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); - _player.MMixer.AllocPCM8Channel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - bFixed, bCompressed, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } - case VoiceType.Square1: - case VoiceType.Square2: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (SquarePattern)v.Int4); - return; - } - case VoiceType.PCM4: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } - case VoiceType.Noise: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (NoisePattern)v.Int4); - return; - } - } - return; // Prevent infinite loop with invalid instruments - } - } - } - public void ExecuteNext(MP2KTrack track, ref bool update) - { - byte[] rom = _player.Config.ROM; - byte cmd = rom[track.DataOffset++]; - if (cmd >= 0xBD) // Commands that work within running status - { - track.RunCmd = cmd; - } - - if (track.RunCmd >= 0xCF && cmd <= 0x7F) // Within running status - { - byte peek0 = rom[track.DataOffset]; - byte peek1 = rom[track.DataOffset + 1]; - byte velocity, addedDuration; - if (peek0 > 0x7F) - { - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (peek1 > 3) - { - track.DataOffset++; - velocity = peek0; - addedDuration = 0; - } - else - { - track.DataOffset += 2; - velocity = peek0; - addedDuration = peek1; - } - TryPlayNote(track, cmd, velocity, addedDuration); - } - else if (cmd >= 0xCF) - { - byte peek0 = rom[track.DataOffset]; - byte peek1 = rom[track.DataOffset + 1]; - byte peek2 = rom[track.DataOffset + 2]; - byte key, velocity, addedDuration; - if (peek0 > 0x7F) - { - key = track.PrevNote; - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (peek1 > 0x7F) - { - track.DataOffset++; - key = peek0; - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (cmd == 0xCF || peek2 > 3) - { - track.DataOffset += 2; - key = peek0; - velocity = peek1; - addedDuration = 0; - } - else - { - track.DataOffset += 3; - key = peek0; - velocity = peek1; - addedDuration = peek2; - } - TryPlayNote(track, key, velocity, addedDuration); - } - else if (cmd >= 0x80 && cmd <= 0xB0) - { - track.Rest = MP2KUtils.RestTable[cmd - 0x80]; - } - else if (track.RunCmd < 0xCF && cmd <= 0x7F) - { - switch (track.RunCmd) - { - case 0xBD: - { - track.Voice = cmd; - //track.Ready = true; // This is unnecessary because if we're in running status of a voice command, then Ready was already set - break; - } - case 0xBE: - { - track.Volume = cmd; - update = true; - break; - } - case 0xBF: - { - track.Panpot = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xC0: - { - track.PitchBend = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xC1: - { - track.PitchBendRange = cmd; - update = true; - break; - } - case 0xC2: - { - track.LFOSpeed = cmd; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC3: - { - track.LFODelay = cmd; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC4: - { - track.LFODepth = cmd; - update = true; - break; - } - case 0xC5: - { - track.LFOType = (LFOType)cmd; - update = true; - break; - } - case 0xC8: - { - track.Tune = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xCD: - { - track.DataOffset++; - break; - } - case 0xCE: - { - track.PrevNote = cmd; - int k = cmd + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.ReleaseChannels(k); - break; - } - default: throw new MP2KInvalidRunningStatusCMDException(track.Index, track.DataOffset - 1, track.RunCmd); - } - } - else if (cmd > 0xB0 && cmd < 0xCF) - { - switch (cmd) - { - case 0xB1: - case 0xB6: - { - track.Stopped = true; - //track.ReleaseAllTieingChannels(); // Necessary? - break; - } - case 0xB2: - { - track.DataOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBAUtils.CARTRIDGE_OFFSET; - break; - } - case 0xB3: - { - if (track.CallStackDepth >= 3) - { - throw new MP2KTooManyNestedCallsException(track.Index); - } - - int callOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBAUtils.CARTRIDGE_OFFSET; - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackDepth++; - track.DataOffset = callOffset; - break; - } - case 0xB4: - { - if (track.CallStackDepth != 0) - { - track.CallStackDepth--; - track.DataOffset = track.CallStack[track.CallStackDepth]; - } - break; - } - /*case 0xB5: // TODO: Logic so this isn't an infinite loop - { - byte times = config.Reader.ReadByte(); - int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; - if (!EventExists(offset)) - { - AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); - } - break; - }*/ - case 0xB9: - { - track.DataOffset += 3; - break; - } - case 0xBA: - { - track.Priority = rom[track.DataOffset++]; - break; - } - case 0xBB: - { - _player.Tempo = (ushort)(rom[track.DataOffset++] * 2); - break; - } - case 0xBC: - { - track.Transpose = (sbyte)rom[track.DataOffset++]; - break; - } - // Commands that work within running status: - case 0xBD: - { - track.Voice = rom[track.DataOffset++]; - track.Ready = true; - break; - } - case 0xBE: - { - track.Volume = rom[track.DataOffset++]; - update = true; - break; - } - case 0xBF: - { - track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xC0: - { - track.PitchBend = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xC1: - { - track.PitchBendRange = rom[track.DataOffset++]; - update = true; - break; - } - case 0xC2: - { - track.LFOSpeed = rom[track.DataOffset++]; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC3: - { - track.LFODelay = rom[track.DataOffset++]; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC4: - { - track.LFODepth = rom[track.DataOffset++]; - update = true; - break; - } - case 0xC5: - { - track.LFOType = (LFOType)rom[track.DataOffset++]; - update = true; - break; - } - case 0xC8: - { - track.Tune = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xCD: - { - track.DataOffset += 2; - break; - } - case 0xCE: - { - byte peek = rom[track.DataOffset]; - if (peek > 0x7F) - { - track.ReleaseChannels(track.PrevNote); - } - else - { - track.DataOffset++; - track.PrevNote = peek; - int k = peek + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.ReleaseChannels(k); - } - break; - } - default: throw new MP2KInvalidCMDException(track.Index, track.DataOffset - 1, cmd); - } - } - } - - public void UpdateInstrumentCache(byte voice, out string str) - { - byte t = _player.Config.ROM[_voiceTableOffset + (voice * 12)]; - if (t == (byte)VoiceFlags.KeySplit) - { - str = "Key Split"; - } - else if (t == (byte)VoiceFlags.Drum) - { - str = "Drum"; - } - else - { - switch ((VoiceType)(t & 0x7)) // Disregard the other flags - { - case VoiceType.PCM8: str = "PCM8"; break; - case VoiceType.Square1: str = "Square 1"; break; - case VoiceType.Square2: str = "Square 2"; break; - case VoiceType.PCM4: str = "PCM4"; break; - case VoiceType.Noise: str = "Noise"; break; - case VoiceType.Invalid5: str = "Invalid 5"; break; - case VoiceType.Invalid6: str = "Invalid 6"; break; - default: str = "Invalid 7"; break; // VoiceType.Invalid7 - } - } - } - public void UpdateSongState(SongState info, string?[] voiceTypeCache) - { - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - Tracks[trackIndex].UpdateSongState(info.Tracks[trackIndex], this, voiceTypeCache); - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index 8997f70..638301b 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -2,6 +2,9 @@ using NAudio.Wave; using System; using System.Linq; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.CoreAudioApi; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; @@ -9,6 +12,7 @@ public sealed class MP2KMixer : Mixer { internal readonly int SampleRate; internal readonly int SamplesPerBuffer; + public readonly int BufferLength; internal readonly float SampleRateReciprocal; private readonly float _samplesReciprocal; internal readonly float PCM8MasterVolume; @@ -20,61 +24,59 @@ public sealed class MP2KMixer : Mixer internal readonly MP2KConfig Config; private readonly WaveBuffer _audio; private readonly float[][] _trackBuffers; - private readonly MP2KPCM8Channel[] _pcm8Channels; - private readonly MP2KSquareChannel _sq1; - private readonly MP2KSquareChannel _sq2; - private readonly MP2KPCM4Channel _pcm4; - private readonly MP2KNoiseChannel _noise; - private readonly MP2KPSGChannel[] _psgChannels; + private readonly PCM8Channel[] _pcm8Channels; + private readonly SquareChannel _sq1; + private readonly SquareChannel _sq2; + private readonly PCM4Channel _pcm4; + private readonly NoiseChannel _noise; + private readonly PSGChannel[] _psgChannels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal MP2KMixer(MP2KConfig config) { - Config = config; - (SampleRate, SamplesPerBuffer) = MP2KUtils.FrequencyTable[config.SampleRate]; - SampleRateReciprocal = 1f / SampleRate; - _samplesReciprocal = 1f / SamplesPerBuffer; - PCM8MasterVolume = config.Volume / 15f; + Config = config; + (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; - _pcm8Channels = new MP2KPCM8Channel[24]; - for (int i = 0; i < _pcm8Channels.Length; i++) - { - _pcm8Channels[i] = new MP2KPCM8Channel(this); - } - _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; + _pcm8Channels = new PCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new PCM8Channel(this); + } + _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; - int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; - _trackBuffers = new float[0x10][]; - for (int i = 0; i < _trackBuffers.Length; i++) - { - _trackBuffers[i] = new float[amt]; - } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) - { - DiscardOnBufferOverflow = true, - BufferLength = SamplesPerBuffer * 64, - }; - Init(_buffer); - } + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + Init(_buffer); + } - internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) + internal PCM8Channel AllocPCM8Channel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) { - MP2KPCM8Channel? nChn = null; - IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner is null ? 0xFF : c.Owner.Index); - foreach (MP2KPCM8Channel i in byOwner) // Find free + PCM8Channel nChn = null; + IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner == null ? 0xFF : c.Owner.Index); + foreach (PCM8Channel i in byOwner) // Find free { - if (i.State == EnvelopeState.Dead || i.Owner is null) + if (i.State == EnvelopeState.Dead || i.Owner == null) { nChn = i; break; } } - if (nChn is null) // Find releasing + if (nChn == null) // Find releasing { - foreach (MP2KPCM8Channel i in byOwner) + foreach (PCM8Channel i in byOwner) { if (i.State == EnvelopeState.Releasing) { @@ -83,40 +85,40 @@ internal MP2KMixer(MP2KConfig config) } } } - if (nChn is null) // Find prioritized + if (nChn == null) // Find prioritized { - foreach (MP2KPCM8Channel i in byOwner) + foreach (PCM8Channel i in byOwner) { - if (owner.Priority > i.Owner!.Priority) + if (owner.Priority > i.Owner.Priority) { nChn = i; break; } } } - if (nChn is null) // None available + if (nChn == null) // None available { - MP2KPCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one - if (lowest.Owner!.Index >= owner.Index) + PCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one + if (lowest.Owner.Index >= owner.Index) { nChn = lowest; } } - if (nChn is not null) // Could still be null from the above if + if (nChn != null) // Could still be null from the above if { nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); } return nChn; } - internal MP2KPSGChannel? AllocPSGChannel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) + internal PSGChannel AllocPSGChannel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) { - MP2KPSGChannel nChn; + PSGChannel nChn; switch (type) { case VoiceType.Square1: { nChn = _sq1; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -126,7 +128,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.Square2: { nChn = _sq2; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -136,7 +138,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.PCM4: { nChn = _pcm4; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -146,7 +148,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.Noise: { nChn = _noise; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -157,20 +159,20 @@ internal MP2KMixer(MP2KConfig config) } nChn.SetVolume(vol, pan); nChn.SetPitch(pitch); - return nChn; - } + return nChn; + } - internal void BeginFadeIn() + internal void BeginFadeIn() { _fadePos = 0f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; _isFading = true; } internal void BeginFadeOut() { _fadePos = 1f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; _isFading = true; } @@ -188,6 +190,16 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } internal void Process(bool output, bool recording) { for (int i = 0; i < _trackBuffers.Length; i++) @@ -199,8 +211,8 @@ internal void Process(bool output, bool recording) for (int i = 0; i < _pcm8Channels.Length; i++) { - MP2KPCM8Channel c = _pcm8Channels[i]; - if (c.Owner is not null) + PCM8Channel c = _pcm8Channels[i]; + if (c.Owner != null) { c.Process(_trackBuffers[c.Owner.Index]); } @@ -208,8 +220,8 @@ internal void Process(bool output, bool recording) for (int i = 0; i < _psgChannels.Length; i++) { - MP2KPSGChannel c = _psgChannels[i]; - if (c.Owner is not null) + PSGChannel c = _psgChannels[i]; + if (c.Owner != null) { c.Process(_trackBuffers[c.Owner.Index]); } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs index 7ebe510..7bbd6d1 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs @@ -1,155 +1,786 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; -public sealed partial class MP2KPlayer : Player +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +public sealed partial class MP2KPlayer : IPlayer { - protected override string Name => "MP2K Player"; + private readonly MP2KMixer _mixer; + private readonly MP2KConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private ushort _tempo; + private int _tempoStack; + private long _elapsedLoops; - private readonly string?[] _voiceTypeCache; - internal readonly MP2KConfig Config; - internal readonly MP2KMixer MMixer; private MP2KLoadedSong? _loadedSong; + public ILoadedSong? LoadedSong => _loadedSong; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } - internal ushort Tempo; - internal int TempoStack; - private long _elapsedLoops; - - private int? _prevVoiceTableOffset; + public PlayerState State { get; private set; } + public event Action? SongEnded; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => MMixer; + private readonly string?[] _voiceTypeCache; internal MP2KPlayer(MP2KConfig config, MP2KMixer mixer) - : base(GBAUtils.AGB_FPS) { - Config = config; - MMixer = mixer; + _config = config; + _mixer = mixer; _voiceTypeCache = new string[256]; + + _time = new TimeBarrier(GBA.GBAUtils.AGB_FPS); + } + private void CreateThread() + { + _thread = new Thread(Tick) { Name = "MP2K Player Tick" }; + _thread.Start(); + } + private void WaitThread() + { + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) + { + _thread.Join(); + } } - public override void LoadSong(int index) + private void InitEmulation() { + _tempo = 150; + _tempoStack = 0; + _elapsedLoops = 0; + _loadedSong!.ElapsedTicks = 0; + _mixer.ResetFade(); + for (int trackIndex = 0; trackIndex < _loadedSong.Tracks.Length; trackIndex++) + { + _loadedSong.Tracks[trackIndex].Init(); + } + } + public void LoadSong(long index) + { + int? oldVoiceTableOffset = _loadedSong?.VoiceTableOffset; if (_loadedSong is not null) { + _loadedSong.Dispose(); _loadedSong = null; } // If there's an exception, this will remain null - _loadedSong = new MP2KLoadedSong(this, index); + _loadedSong = new MP2KLoadedSong(index, this, _config, oldVoiceTableOffset, _voiceTypeCache); + _loadedSong.SetTicks(); if (_loadedSong.Events.Length == 0) { + _loadedSong.Dispose(); _loadedSong = null; - return; } - - _loadedSong.CheckVoiceTypeCache(ref _prevVoiceTableOffset, _voiceTypeCache); - _loadedSong.SetTicks(); } - public override void UpdateSongState(SongState info) + public void SetCurrentPosition(long ticks) { - info.Tempo = Tempo; - _loadedSong!.UpdateSongState(info, _voiceTypeCache); + if (_loadedSong is null) + { + SongEnded?.Invoke(); + return; + } + + if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) + { + return; + } + + if (State is PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + MP2KLoadedSong s = _loadedSong; + bool u = false; + while (ticks != s.ElapsedTicks) + { + while (_tempoStack >= 150) + { + _tempoStack -= 150; + for (int trackIndex = 0; trackIndex < s.Tracks.Length; trackIndex++) + { + Track track = s.Tracks[trackIndex]; + if (!track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref u); + } + } + } + s.ElapsedTicks++; + if (s.ElapsedTicks == ticks) + { + break; + } + } + _tempoStack += _tempo; + } + + for (int i = 0; i < s.Tracks.Length; i++) + { + s.Tracks[i].StopAllChannels(); + } + Pause(); } - internal override void InitEmulation() + public void Play() { - Tempo = 150; - TempoStack = 0; - _elapsedLoops = 0; - ElapsedTicks = 0; - MMixer.ResetFade(); - MP2KTrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (_loadedSong is null) + { + SongEnded?.Invoke(); + return; + } + + if (State is not PlayerState.ShutDown) { - tracks[i].Init(); + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } } - protected override void SetCurTick(long ticks) + public void Pause() { - _loadedSong!.SetCurTick(ticks); + switch (State) + { + case PlayerState.Playing: + { + State = PlayerState.Paused; + WaitThread(); + break; + } + case PlayerState.Paused: + case PlayerState.Stopped: + { + State = PlayerState.Playing; + CreateThread(); + break; + } + } } - protected override void OnStopped() + public void Stop() { - MP2KTrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (State is PlayerState.Playing or PlayerState.Paused) { - tracks[i].StopAllChannels(); + State = PlayerState.Stopped; + WaitThread(); } } - - protected override bool Tick(bool playing, bool recording) + public void Record(string fileName) { - MP2KLoadedSong s = _loadedSong!; + _mixer.CreateWaveWriter(fileName); - bool allDone = false; - while (!allDone && TempoStack >= 150) + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + + _mixer.CloseWaveWriter(); + } + + public void SaveAsMIDI(string fileName, MIDISaveArgs args) + { + _loadedSong!.SaveAsMIDI(fileName, args); + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int trackIndex = 0; trackIndex < _loadedSong!.Tracks.Length; trackIndex++) { - TempoStack -= 150; - allDone = true; - for (int i = 0; i < s.Tracks.Length; i++) + Track track = _loadedSong.Tracks[trackIndex]; + SongState.Track tin = info.Tracks[trackIndex]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.LFO = track.LFODepth; + ref string? voiceType = ref _voiceTypeCache[track.Voice]; + if (voiceType is null) + { + byte t = _config.ROM[_loadedSong.VoiceTableOffset + (track.Voice * 12)]; + if (t == (byte)VoiceFlags.KeySplit) + { + voiceType = "Key Split"; + } + else if (t == (byte)VoiceFlags.Drum) + { + voiceType = "Drum"; + } + else + { + switch ((VoiceType)(t & 0x7)) // Disregard the other flags + { + case VoiceType.PCM8: voiceType = "PCM8"; break; + case VoiceType.Square1: voiceType = "Square 1"; break; + case VoiceType.Square2: voiceType = "Square 2"; break; + case VoiceType.PCM4: voiceType = "PCM4"; break; + case VoiceType.Noise: voiceType = "Noise"; break; + case VoiceType.Invalid5: voiceType = "Invalid 5"; break; + case VoiceType.Invalid6: voiceType = "Invalid 6"; break; + default: voiceType = "Invalid 7"; break; // VoiceType.Invalid7 + } + } + } + tin.Type = voiceType; + tin.Volume = track.GetVolume(); + tin.PitchBend = track.GetPitch(); + tin.Panpot = track.GetPanpot(); + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) { - TickTrack(s, s.Tracks[i], ref allDone); + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; } - if (MMixer.IsFadeDone()) + else { - allDone = true; + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (c.State < EnvelopeState.Releasing) + { + tin.Keys[numKeys++] = c.Note.OriginalNote; + } + ChannelVolume vol = c.GetVolume(); + if (vol.LeftVol > left) + { + left = vol.LeftVol; + } + if (vol.RightVol > right) + { + right = vol.RightVol; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; } } - if (!allDone) - { - TempoStack += Tempo; - } - MMixer.Process(playing, recording); - return allDone; } - private void TickTrack(MP2KLoadedSong s, MP2KTrack track, ref bool allDone) + + private void PlayNote(Track track, byte note, byte velocity, byte addedDuration) { - track.Tick(); - bool update = false; - while (track.Rest == 0 && !track.Stopped) + int n = note + track.Transpose; + if (n < 0) { - s.ExecuteNext(track, ref update); + n = 0; } - if (track.Index == s.LongestTrack) + else if (n > 0x7F) { - HandleTicksAndLoop(s, track); + n = 0x7F; } - if (!track.Stopped) + note = (byte)n; + track.PrevNote = note; + track.PrevVelocity = velocity; + if (!track.Ready) { - allDone = false; + return; // Tracks do not play unless they have had a voice change event } - if (track.Channels.Count > 0) + + bool fromDrum = false; + int offset = _loadedSong!.VoiceTableOffset + (track.Voice * 12); + while (true) { - allDone = false; - if (update || track.LFODepth > 0) + ref VoiceEntry v = ref MemoryMarshal.AsRef(_config.ROM.AsSpan(offset)); + if (v.Type == (int)VoiceFlags.KeySplit) + { + fromDrum = false; // In case there is a multi within a drum + byte inst = _config.ROM[v.Int8 - GBAUtils.CartridgeOffset + note]; + offset = v.Int4 - GBAUtils.CartridgeOffset + (inst * 12); + } + else if (v.Type == (int)VoiceFlags.Drum) { - track.UpdateChannels(); + fromDrum = true; + offset = v.Int4 - GBAUtils.CartridgeOffset + (note * 12); + } + else + { + var ni = new NoteInfo + { + Duration = track.RunCmd == 0xCF ? -1 : (Utils.RestTable[track.RunCmd - 0xCF] + addedDuration), + Velocity = velocity, + OriginalNote = note, + Note = fromDrum ? v.RootNote : note, + }; + var type = (VoiceType)(v.Type & 0x7); + int instPan = v.Pan; + instPan = (instPan & 0x80) != 0 ? instPan - 0xC0 : 0; + switch (type) + { + case VoiceType.PCM8: + { + bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; + bool bCompressed = _config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); + _mixer.AllocPCM8Channel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + bFixed, bCompressed, v.Int4 - GBAUtils.CartridgeOffset); + return; + } + case VoiceType.Square1: + case VoiceType.Square2: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (SquarePattern)v.Int4); + return; + } + case VoiceType.PCM4: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, v.Int4 - GBAUtils.CartridgeOffset); + return; + } + case VoiceType.Noise: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (NoisePattern)v.Int4); + return; + } + } + return; // Prevent infinite loop with invalid instruments } } } - private void HandleTicksAndLoop(MP2KLoadedSong s, MP2KTrack track) + internal void ExecuteNext(Track track, ref bool update) { - if (ElapsedTicks != s.MaxTicks) + byte[] rom = _config.ROM; + byte cmd = rom[track.DataOffset++]; + if (cmd >= 0xBD) // Commands that work within running status { - ElapsedTicks++; - return; + track.RunCmd = cmd; } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + if (track.RunCmd >= 0xCF && cmd <= 0x7F) // Within running status { - return; + byte peek0 = rom[track.DataOffset]; + byte peek1 = rom[track.DataOffset + 1]; + byte velocity, addedDuration; + if (peek0 > 0x7F) + { + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (peek1 > 3) + { + track.DataOffset++; + velocity = peek0; + addedDuration = 0; + } + else + { + track.DataOffset += 2; + velocity = peek0; + addedDuration = peek1; + } + PlayNote(track, cmd, velocity, addedDuration); } + else if (cmd >= 0xCF) + { + byte peek0 = rom[track.DataOffset]; + byte peek1 = rom[track.DataOffset + 1]; + byte peek2 = rom[track.DataOffset + 2]; + byte key, velocity, addedDuration; + if (peek0 > 0x7F) + { + key = track.PrevNote; + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (peek1 > 0x7F) + { + track.DataOffset++; + key = peek0; + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (cmd == 0xCF || peek2 > 3) + { + track.DataOffset += 2; + key = peek0; + velocity = peek1; + addedDuration = 0; + } + else + { + track.DataOffset += 3; + key = peek0; + velocity = peek1; + addedDuration = peek2; + } + PlayNote(track, key, velocity, addedDuration); + } + else if (cmd >= 0x80 && cmd <= 0xB0) + { + track.Rest = Utils.RestTable[cmd - 0x80]; + } + else if (track.RunCmd < 0xCF && cmd <= 0x7F) + { + switch (track.RunCmd) + { + case 0xBD: + { + track.Voice = cmd; + //track.Ready = true; // This is unnecessary because if we're in running status of a voice command, then Ready was already set + break; + } + case 0xBE: + { + track.Volume = cmd; + update = true; + break; + } + case 0xBF: + { + track.Panpot = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xC0: + { + track.PitchBend = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xC1: + { + track.PitchBendRange = cmd; + update = true; + break; + } + case 0xC2: + { + track.LFOSpeed = cmd; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC3: + { + track.LFODelay = cmd; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC4: + { + track.LFODepth = cmd; + update = true; + break; + } + case 0xC5: + { + track.LFOType = (LFOType)cmd; + update = true; + break; + } + case 0xC8: + { + track.Tune = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xCD: + { + track.DataOffset++; + break; + } + case 0xCE: + { + track.PrevNote = cmd; + int k = cmd + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.ReleaseChannels(k); + break; + } + default: throw new MP2KInvalidRunningStatusCMDException(track.Index, track.DataOffset - 1, track.RunCmd); + } + } + else if (cmd > 0xB0 && cmd < 0xCF) + { + switch (cmd) + { + case 0xB1: + case 0xB6: + { + track.Stopped = true; + //track.ReleaseAllTieingChannels(); // Necessary? + break; + } + case 0xB2: + { + track.DataOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBA.GBAUtils.CartridgeOffset; + break; + } + case 0xB3: + { + if (track.CallStackDepth >= 3) + { + throw new MP2KTooManyNestedCallsException(track.Index); + } + + int callOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBA.GBAUtils.CartridgeOffset; + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackDepth++; + track.DataOffset = callOffset; + break; + } + case 0xB4: + { + if (track.CallStackDepth != 0) + { + track.CallStackDepth--; + track.DataOffset = track.CallStack[track.CallStackDepth]; + } + break; + } + /*case 0xB5: // TODO: Logic so this isn't an infinite loop + { + byte times = config.Reader.ReadByte(); + int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; + if (!EventExists(offset)) + { + AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); + } + break; + }*/ + case 0xB9: + { + track.DataOffset += 3; + break; + } + case 0xBA: + { + track.Priority = rom[track.DataOffset++]; + break; + } + case 0xBB: + { + _tempo = (ushort)(rom[track.DataOffset++] * 2); + break; + } + case 0xBC: + { + track.Transpose = (sbyte)rom[track.DataOffset++]; + break; + } + // Commands that work within running status: + case 0xBD: + { + track.Voice = rom[track.DataOffset++]; + track.Ready = true; + break; + } + case 0xBE: + { + track.Volume = rom[track.DataOffset++]; + update = true; + break; + } + case 0xBF: + { + track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xC0: + { + track.PitchBend = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xC1: + { + track.PitchBendRange = rom[track.DataOffset++]; + update = true; + break; + } + case 0xC2: + { + track.LFOSpeed = rom[track.DataOffset++]; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC3: + { + track.LFODelay = rom[track.DataOffset++]; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC4: + { + track.LFODepth = rom[track.DataOffset++]; + update = true; + break; + } + case 0xC5: + { + track.LFOType = (LFOType)rom[track.DataOffset++]; + update = true; + break; + } + case 0xC8: + { + track.Tune = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xCD: + { + track.DataOffset += 2; + break; + } + case 0xCE: + { + byte peek = rom[track.DataOffset]; + if (peek > 0x7F) + { + track.ReleaseChannels(track.PrevNote); + } + else + { + track.DataOffset++; + track.PrevNote = peek; + int k = peek + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.ReleaseChannels(k); + } + break; + } + default: throw new MP2KInvalidCMDException(track.Index, track.DataOffset - 1, cmd); + } + } + } - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !MMixer.IsFading()) + private void Tick() + { + MP2KLoadedSong s = _loadedSong!; + _time.Start(); + while (true) { - MMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 150) + { + _tempoStack -= 150; + bool allDone = true; + for (int trackIndex = 0; trackIndex < s.Tracks.Length; trackIndex++) + { + Track track = s.Tracks[trackIndex]; + track.Tick(); + bool update = false; + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref update); + } + if (trackIndex == s.LongestTrack) + { + if (s.ElapsedTicks == s.MaxTicks) + { + if (!track.Stopped) + { + List evs = s.Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + s.ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + s.ElapsedTicks++; + } + } + if (!track.Stopped) + { + allDone = false; + } + if (track.Channels.Count > 0) + { + allDone = false; + if (update || track.LFODepth > 0) + { + track.UpdateChannels(); + } + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.Process(playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.Process(playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } - public void SaveAsMIDI(string fileName, MIDISaveArgs args) + public void Dispose() { - _loadedSong!.SaveAsMIDI(fileName, args); + if (State is not PlayerState.ShutDown) + { + State = PlayerState.ShutDown; + WaitThread(); + } } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs b/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs deleted file mode 100644 index 5b33542..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SongEntry -{ - public const int SIZE = 8; - - public readonly int HeaderOffset; - public readonly short Player; - public readonly byte Unknown1; - public readonly byte Unknown2; - - public SongEntry(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - HeaderOffset = ReadInt32LittleEndian(src.Slice(0)); - Player = ReadInt16LittleEndian(src.Slice(4)); - Unknown1 = src[6]; - Unknown2 = src[7]; - } - } - - public static SongEntry Get(byte[] rom, int songTableOffset, int songNum) - { - return new SongEntry(rom.AsSpan(songTableOffset + (songNum * SIZE))); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SongHeader -{ - public const int SIZE = 8; - - public readonly byte NumTracks; - public readonly byte NumBlocks; - public readonly byte Priority; - public readonly byte Reverb; - public readonly int VoiceTableOffset; - // int[NumTracks] TrackOffset; - - public SongHeader(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - NumTracks = src[0]; - NumBlocks = src[1]; - Priority = src[2]; - Reverb = src[3]; - VoiceTableOffset = ReadInt32LittleEndian(src.Slice(4)); - } - } - - public static SongHeader Get(byte[] rom, int offset, out int tracksOffset) - { - tracksOffset = offset + SIZE; - return new SongHeader(rom.AsSpan(offset)); - } - public static int GetTrackOffset(byte[] rom, int tracksOffset, int trackIndex) - { - return ReadInt32LittleEndian(rom.AsSpan(tracksOffset + (trackIndex * 4))); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct VoiceEntry -{ - public const int SIZE = 12; - - public readonly byte Type; // 0 - public readonly byte RootNote; // 1 - public readonly byte Unknown; // 2 - public readonly byte Pan; // 3 - /// SquarePattern for Square1/Square2, NoisePattern for Noise, Address for PCM8/PCM4/KeySplit/Drum - public readonly int Int4; // 4 - /// ADSR for PCM8/Square1/Square2/PCM4/Noise, KeysAddress for KeySplit - public readonly ADSR ADSR; // 8 - - public int Int8 => (ADSR.R << 24) | (ADSR.S << 16) | (ADSR.D << 8) | (ADSR.A); - - public VoiceEntry(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - Type = src[0]; - RootNote = src[1]; - Unknown = src[2]; - Pan = src[3]; - Int4 = ReadInt32LittleEndian(src.Slice(4)); - ADSR = ADSR.Get(src.Slice(8)); - } - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal struct ADSR -{ - public const int SIZE = 4; - - public byte A; - public byte D; - public byte S; - public byte R; - - public static ref readonly ADSR Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct GoldenSunPSG -{ - public const int SIZE = 6; - - /// Always 0x80 - public readonly byte Unknown; - public readonly GoldenSunPSGType Type; - public readonly byte InitialCycle; - public readonly byte CycleSpeed; - public readonly byte CycleAmplitude; - public readonly byte MinimumCycle; - - public static ref readonly GoldenSunPSG Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal struct SampleHeader -{ - public const int SIZE = 16; - public const int LOOP_TRUE = 0x40_000_000; - - /// 0x40_000_000 if True - public int DoesLoop; - /// Right shift 10 for value - public int SampleRate; - public int LoopOffset; - public int Length; - // byte[Length] Sample; - - public SampleHeader(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - DoesLoop = ReadInt32LittleEndian(src.Slice(0, 4)); - SampleRate = ReadInt32LittleEndian(src.Slice(4, 4)); - LoopOffset = ReadInt32LittleEndian(src.Slice(8, 4)); - Length = ReadInt32LittleEndian(src.Slice(12, 4)); - } - } - - public static SampleHeader Get(byte[] rom, int offset, out int sampleOffset) - { - sampleOffset = offset + SIZE; - return new SampleHeader(rom.AsSpan(offset)); - } -} - -internal struct ChannelVolume -{ - public float LeftVol, RightVol; -} -internal struct NoteInfo -{ - public byte Note, OriginalNote; - public byte Velocity; - /// -1 if forever - public int Duration; -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs b/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs deleted file mode 100644 index e612465..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KTrack -{ - public readonly byte Index; - private readonly int _startOffset; - public byte Voice; - public byte PitchBendRange; - public byte Priority; - public byte Volume; - public byte Rest; - public byte LFOPhase; - public byte LFODelayCount; - public byte LFOSpeed; - public byte LFODelay; - public byte LFODepth; - public LFOType LFOType; - public sbyte PitchBend; - public sbyte Tune; - public sbyte Panpot; - public sbyte Transpose; - public bool Ready; - public bool Stopped; - public int DataOffset; - public int[] CallStack = new int[3]; - public byte CallStackDepth; - public byte RunCmd; - public byte PrevNote; - public byte PrevVelocity; - - public readonly List Channels = new(); - - public int GetPitch() - { - int lfo = LFOType == LFOType.Pitch ? (MP2KUtils.Tri(LFOPhase) * LFODepth) >> 8 : 0; - return (PitchBend * PitchBendRange) + Tune + lfo; - } - public byte GetVolume() - { - int lfo = LFOType == LFOType.Volume ? (MP2KUtils.Tri(LFOPhase) * LFODepth * 3 * Volume) >> 19 : 0; - int v = Volume + lfo; - if (v < 0) - { - v = 0; - } - else if (v > 0x7F) - { - v = 0x7F; - } - return (byte)v; - } - public sbyte GetPanpot() - { - int lfo = LFOType == LFOType.Panpot ? (MP2KUtils.Tri(LFOPhase) * LFODepth * 3) >> 12 : 0; - int p = Panpot + lfo; - if (p < -0x40) - { - p = -0x40; - } - else if (p > 0x3F) - { - p = 0x3F; - } - return (sbyte)p; - } - - public MP2KTrack(byte i, int startOffset) - { - Index = i; - _startOffset = startOffset; - } - public void Init() - { - Voice = 0; - Priority = 0; - Rest = 0; - LFODelay = 0; - LFODelayCount = 0; - LFOPhase = 0; - LFODepth = 0; - CallStackDepth = 0; - PitchBend = 0; - Tune = 0; - Panpot = 0; - Transpose = 0; - DataOffset = _startOffset; - RunCmd = 0; - PrevNote = 0; - PrevVelocity = 0x7F; - PitchBendRange = 2; - LFOType = LFOType.Pitch; - Ready = false; - Stopped = false; - LFOSpeed = 22; - Volume = 100; - StopAllChannels(); - } - public void Tick() - { - if (Rest != 0) - { - Rest--; - } - if (LFODepth > 0) - { - LFOPhase += LFOSpeed; - } - else - { - LFOPhase = 0; - } - int active = 0; - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - if (chans[i].TickNote()) - { - active++; - } - } - if (active != 0) - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - } - else - { - LFODelayCount = LFODelay; - } - if ((LFODelay == LFODelayCount && LFODelay != 0) || LFOSpeed == 0) - { - LFOPhase = 0; - } - } - - public void ReleaseChannels(int key) - { - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - MP2KChannel c = chans[i]; - if (c.Note.OriginalNote == key && c.Note.Duration == -1) - { - c.Release(); - } - } - } - public void StopAllChannels() - { - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - public void UpdateChannels() - { - byte vol = GetVolume(); - sbyte pan = GetPanpot(); - int pitch = GetPitch(); - for (int i = 0; i < Channels.Count; i++) - { - MP2KChannel c = Channels[i]; - c.SetVolume(vol, pan); - c.SetPitch(pitch); - } - } - - public void UpdateSongState(SongState.Track tin, MP2KLoadedSong loadedSong, string?[] voiceTypeCache) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.LFO = LFODepth; - ref string? cache = ref voiceTypeCache[Voice]; - if (cache is null) - { - loadedSong.UpdateInstrumentCache(Voice, out cache); - } - tin.Type = cache; - tin.Volume = GetVolume(); - tin.PitchBend = GetPitch(); - tin.Panpot = GetPanpot(); - - MP2KChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - MP2KChannel c = channels[j]; - if (c.State < EnvelopeState.Releasing) - { - tin.Keys[numKeys++] = c.Note.OriginalNote; - } - ChannelVolume vol = c.GetVolume(); - if (vol.LeftVol > left) - { - left = vol.LeftVol; - } - if (vol.RightVol > right) - { - right = vol.RightVol; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs b/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs deleted file mode 100644 index f754d87..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal static class MP2KUtils -{ - public static readonly byte[] RestTable = new byte[49] - { - 00, 01, 02, 03, 04, 05, 06, 07, - 08, 09, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 28, 30, 32, 36, 40, 42, 44, - 48, 52, 54, 56, 60, 64, 66, 68, - 72, 76, 78, 80, 84, 88, 90, 92, - 96, - }; - public static readonly (int sampleRate, int samplesPerBuffer)[] FrequencyTable = new (int, int)[12] - { - (05734, 096), // 59.72916666666667 - (07884, 132), // 59.72727272727273 - (10512, 176), // 59.72727272727273 - (13379, 224), // 59.72767857142857 - (15768, 264), // 59.72727272727273 - (18157, 304), // 59.72697368421053 - (21024, 352), // 59.72727272727273 - (26758, 448), // 59.72767857142857 - (31536, 528), // 59.72727272727273 - (36314, 608), // 59.72697368421053 - (40137, 672), // 59.72767857142857 - (42048, 704), // 59.72727272727273 - }; - - // Squares - public static readonly float[] SquareD12 = new float[8] { 0.875f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, }; - public static readonly float[] SquareD25 = new float[8] { 0.750f, 0.750f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, }; - public static readonly float[] SquareD50 = new float[8] { 0.500f, 0.500f, 0.500f, 0.500f, -0.500f, -0.500f, -0.500f, -0.500f, }; - public static readonly float[] SquareD75 = new float[8] { 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, -0.750f, -0.750f, }; - - // Noises - public static readonly BitArray NoiseFine; - public static readonly BitArray NoiseRough; - public static readonly byte[] NoiseFrequencyTable = new byte[60] - { - 0xD7, 0xD6, 0xD5, 0xD4, - 0xC7, 0xC6, 0xC5, 0xC4, - 0xB7, 0xB6, 0xB5, 0xB4, - 0xA7, 0xA6, 0xA5, 0xA4, - 0x97, 0x96, 0x95, 0x94, - 0x87, 0x86, 0x85, 0x84, - 0x77, 0x76, 0x75, 0x74, - 0x67, 0x66, 0x65, 0x64, - 0x57, 0x56, 0x55, 0x54, - 0x47, 0x46, 0x45, 0x44, - 0x37, 0x36, 0x35, 0x34, - 0x27, 0x26, 0x25, 0x24, - 0x17, 0x16, 0x15, 0x14, - 0x07, 0x06, 0x05, 0x04, - 0x03, 0x02, 0x01, 0x00, - }; - - // PCM4 - /// dest must be 0x20 bytes - public static void PCM4ToFloat(ReadOnlySpan src, Span dest) - { - float sum = 0; - for (int i = 0; i < 0x10; i++) - { - byte b = src[i]; - float first = (b >> 4) / 16f; - float second = (b & 0xF) / 16f; - sum += dest[i * 2] = first; - sum += dest[(i * 2) + 1] = second; - } - float dcCorrection = sum / 0x20; - for (int i = 0; i < 0x20; i++) - { - dest[i] -= dcCorrection; - } - } - - // Pokémon Only - private static readonly sbyte[] _compressionLookup = new sbyte[16] - { - 0, 1, 4, 9, 16, 25, 36, 49, -64, -49, -36, -25, -16, -9, -4, -1, - }; - // TODO: Do runtime - public static sbyte[] Decompress(ReadOnlySpan src, int sampleLength) - { - var samples = new List(); - sbyte compressionLevel = 0; - int compressionByte = 0, compressionIdx = 0; - - for (int i = 0; true; i++) - { - byte b = src[i]; - if (compressionByte == 0) - { - compressionByte = 0x20; - compressionLevel = (sbyte)b; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - else - { - if (compressionByte < 0x20) - { - compressionLevel += _compressionLookup[b >> 4]; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - compressionByte--; - compressionLevel += _compressionLookup[b & 0xF]; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - } - - return samples.ToArray(); - } - - static MP2KUtils() - { - NoiseFine = new BitArray(0x8_000); - int reg = 0x4_000; - for (int i = 0; i < NoiseFine.Length; i++) - { - if ((reg & 1) == 1) - { - reg >>= 1; - reg ^= 0x6_000; - NoiseFine[i] = true; - } - else - { - reg >>= 1; - NoiseFine[i] = false; - } - } - NoiseRough = new BitArray(0x80); - reg = 0x40; - for (int i = 0; i < NoiseRough.Length; i++) - { - if ((reg & 1) == 1) - { - reg >>= 1; - reg ^= 0x60; - NoiseRough[i] = true; - } - else - { - reg >>= 1; - NoiseRough[i] = false; - } - } - } - public static int Tri(int index) - { - index = (index - 64) & 0xFF; - return (index < 128) ? (index * 12) - 768 : 2_304 - (index * 12); - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/Structs.cs b/VG Music Studio - Core/GBA/MP2K/Structs.cs new file mode 100644 index 0000000..fe06998 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Structs.cs @@ -0,0 +1,80 @@ +using Kermalis.EndianBinaryIO; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 8)] +internal struct SongEntry +{ + public int HeaderOffset; + public short Player; + public byte Unknown1; + public byte Unknown2; +} +internal class SongHeader +{ + public byte NumTracks { get; set; } + public byte NumBlocks { get; set; } + public byte Priority { get; set; } + public byte Reverb { get; set; } + public int VoiceTableOffset { get; set; } + [BinaryArrayVariableLength(nameof(NumTracks))] + public int[] TrackOffsets { get; set; } +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 12)] +internal struct VoiceEntry +{ + public byte Type; // 0 + public byte RootNote; // 1 + public byte Unknown; // 2 + public byte Pan; // 3 + /// SquarePattern for Square1/Square2, NoisePattern for Noise, Address for PCM8/PCM4/KeySplit/Drum + public int Int4; // 4 + /// ADSR for PCM8/Square1/Square2/PCM4/Noise, KeysAddress for KeySplit + public ADSR ADSR; // 8 + + public int Int8 => (ADSR.R << 24) | (ADSR.S << 16) | (ADSR.D << 8) | (ADSR.A); +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4)] +internal struct ADSR +{ + public byte A; + public byte D; + public byte S; + public byte R; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 6)] +internal struct GoldenSunPSG +{ + /// Always 0x80 + public byte Unknown; + public GoldenSunPSGType Type; + public byte InitialCycle; + public byte CycleSpeed; + public byte CycleAmplitude; + public byte MinimumCycle; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 16)] +internal struct SampleHeader +{ + public const int LOOP_TRUE = 0x40_000_000; + + /// 0x40_000_000 if True + public int DoesLoop; + /// Right shift 10 for value + public int SampleRate; + public int LoopOffset; + public int Length; +} + +internal struct ChannelVolume +{ + public float LeftVol, RightVol; +} +internal struct NoteInfo +{ + public byte Note, OriginalNote; + public byte Velocity; + /// -1 if forever + public int Duration; +} diff --git a/VG Music Studio - Core/GBA/MP2K/Track.cs b/VG Music Studio - Core/GBA/MP2K/Track.cs new file mode 100644 index 0000000..7b047ff --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Track.cs @@ -0,0 +1,174 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal class Track + { + public readonly byte Index; + private readonly int _startOffset; + public byte Voice; + public byte PitchBendRange; + public byte Priority; + public byte Volume; + public byte Rest; + public byte LFOPhase; + public byte LFODelayCount; + public byte LFOSpeed; + public byte LFODelay; + public byte LFODepth; + public LFOType LFOType; + public sbyte PitchBend; + public sbyte Tune; + public sbyte Panpot; + public sbyte Transpose; + public bool Ready; + public bool Stopped; + public int DataOffset; + public int[] CallStack = new int[3]; + public byte CallStackDepth; + public byte RunCmd; + public byte PrevNote; + public byte PrevVelocity; + + public readonly List Channels = new List(); + + public int GetPitch() + { + int lfo = LFOType == LFOType.Pitch ? (Utils.Tri(LFOPhase) * LFODepth) >> 8 : 0; + return (PitchBend * PitchBendRange) + Tune + lfo; + } + public byte GetVolume() + { + int lfo = LFOType == LFOType.Volume ? (Utils.Tri(LFOPhase) * LFODepth * 3 * Volume) >> 19 : 0; + int v = Volume + lfo; + if (v < 0) + { + v = 0; + } + else if (v > 0x7F) + { + v = 0x7F; + } + return (byte)v; + } + public sbyte GetPanpot() + { + int lfo = LFOType == LFOType.Panpot ? (Utils.Tri(LFOPhase) * LFODepth * 3) >> 12 : 0; + int p = Panpot + lfo; + if (p < -0x40) + { + p = -0x40; + } + else if (p > 0x3F) + { + p = 0x3F; + } + return (sbyte)p; + } + + public Track(byte i, int startOffset) + { + Index = i; + _startOffset = startOffset; + } + public void Init() + { + Voice = 0; + Priority = 0; + Rest = 0; + LFODelay = 0; + LFODelayCount = 0; + LFOPhase = 0; + LFODepth = 0; + CallStackDepth = 0; + PitchBend = 0; + Tune = 0; + Panpot = 0; + Transpose = 0; + DataOffset = _startOffset; + RunCmd = 0; + PrevNote = 0; + PrevVelocity = 0x7F; + PitchBendRange = 2; + LFOType = LFOType.Pitch; + Ready = false; + Stopped = false; + LFOSpeed = 22; + Volume = 100; + StopAllChannels(); + } + public void Tick() + { + if (Rest != 0) + { + Rest--; + } + if (LFODepth > 0) + { + LFOPhase += LFOSpeed; + } + else + { + LFOPhase = 0; + } + int active = 0; + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + if (chans[i].TickNote()) + { + active++; + } + } + if (active != 0) + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + } + else + { + LFODelayCount = LFODelay; + } + if ((LFODelay == LFODelayCount && LFODelay != 0) || LFOSpeed == 0) + { + LFOPhase = 0; + } + } + + public void ReleaseChannels(int key) + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + Channel c = chans[i]; + if (c.Note.OriginalNote == key && c.Note.Duration == -1) + { + c.Release(); + } + } + } + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } + public void UpdateChannels() + { + byte vol = GetVolume(); + sbyte pan = GetPanpot(); + int pitch = GetPitch(); + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + c.SetVolume(vol, pan); + c.SetPitch(pitch); + } + } + } +} diff --git a/VG Music Studio - Core/GBA/MP2K/Utils.cs b/VG Music Studio - Core/GBA/MP2K/Utils.cs new file mode 100644 index 0000000..223bb43 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Utils.cs @@ -0,0 +1,175 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal static class Utils + { + public static readonly byte[] RestTable = new byte[49] + { + 00, 01, 02, 03, 04, 05, 06, 07, + 08, 09, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 28, 30, 32, 36, 40, 42, 44, + 48, 52, 54, 56, 60, 64, 66, 68, + 72, 76, 78, 80, 84, 88, 90, 92, + 96, + }; + public static readonly (int sampleRate, int samplesPerBuffer)[] FrequencyTable = new (int, int)[12] + { + (05734, 096), // 59.72916666666667 + (07884, 132), // 59.72727272727273 + (10512, 176), // 59.72727272727273 + (13379, 224), // 59.72767857142857 + (15768, 264), // 59.72727272727273 + (18157, 304), // 59.72697368421053 + (21024, 352), // 59.72727272727273 + (26758, 448), // 59.72767857142857 + (31536, 528), // 59.72727272727273 + (36314, 608), // 59.72697368421053 + (40137, 672), // 59.72767857142857 + (42048, 704), // 59.72727272727273 + }; + + // Squares + public static readonly float[] SquareD12 = new float[8] { 0.875f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, }; + public static readonly float[] SquareD25 = new float[8] { 0.750f, 0.750f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, }; + public static readonly float[] SquareD50 = new float[8] { 0.500f, 0.500f, 0.500f, 0.500f, -0.500f, -0.500f, -0.500f, -0.500f, }; + public static readonly float[] SquareD75 = new float[8] { 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, -0.750f, -0.750f, }; + + // Noises + public static readonly BitArray NoiseFine; + public static readonly BitArray NoiseRough; + public static readonly byte[] NoiseFrequencyTable = new byte[60] + { + 0xD7, 0xD6, 0xD5, 0xD4, + 0xC7, 0xC6, 0xC5, 0xC4, + 0xB7, 0xB6, 0xB5, 0xB4, + 0xA7, 0xA6, 0xA5, 0xA4, + 0x97, 0x96, 0x95, 0x94, + 0x87, 0x86, 0x85, 0x84, + 0x77, 0x76, 0x75, 0x74, + 0x67, 0x66, 0x65, 0x64, + 0x57, 0x56, 0x55, 0x54, + 0x47, 0x46, 0x45, 0x44, + 0x37, 0x36, 0x35, 0x34, + 0x27, 0x26, 0x25, 0x24, + 0x17, 0x16, 0x15, 0x14, + 0x07, 0x06, 0x05, 0x04, + 0x03, 0x02, 0x01, 0x00, + }; + + // PCM4 + // TODO: Do runtime instead of make arrays + public static float[] PCM4ToFloat(int sampleOffset) + { + var config = (MP2KConfig)Engine.Instance.Config; + float[] sample = new float[0x20]; + float sum = 0; + for (int i = 0; i < 0x10; i++) + { + byte b = config.ROM[sampleOffset + i]; + float first = (b >> 4) / 16f; + float second = (b & 0xF) / 16f; + sum += sample[i * 2] = first; + sum += sample[(i * 2) + 1] = second; + } + float dcCorrection = sum / 0x20; + for (int i = 0; i < 0x20; i++) + { + sample[i] -= dcCorrection; + } + return sample; + } + + // Pokémon Only + private static readonly sbyte[] _compressionLookup = new sbyte[16] + { + 0, 1, 4, 9, 16, 25, 36, 49, -64, -49, -36, -25, -16, -9, -4, -1, + }; + public static sbyte[] Decompress(int sampleOffset, int sampleLength) + { + var config = (MP2KConfig)Engine.Instance.Config; + var samples = new List(); + sbyte compressionLevel = 0; + int compressionByte = 0, compressionIdx = 0; + + for (int i = 0; true; i++) + { + byte b = config.ROM[sampleOffset + i]; + if (compressionByte == 0) + { + compressionByte = 0x20; + compressionLevel = (sbyte)b; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + else + { + if (compressionByte < 0x20) + { + compressionLevel += _compressionLookup[b >> 4]; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + compressionByte--; + compressionLevel += _compressionLookup[b & 0xF]; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + } + + return samples.ToArray(); + } + + static Utils() + { + NoiseFine = new BitArray(0x8_000); + int reg = 0x4_000; + for (int i = 0; i < NoiseFine.Length; i++) + { + if ((reg & 1) == 1) + { + reg >>= 1; + reg ^= 0x6_000; + NoiseFine[i] = true; + } + else + { + reg >>= 1; + NoiseFine[i] = false; + } + } + NoiseRough = new BitArray(0x80); + reg = 0x40; + for (int i = 0; i < NoiseRough.Length; i++) + { + if ((reg & 1) == 1) + { + reg >>= 1; + reg ^= 0x60; + NoiseRough[i] = true; + } + else + { + reg >>= 1; + NoiseRough[i] = false; + } + } + } + public static int Tri(int index) + { + index = (index - 64) & 0xFF; + return (index < 128) ? (index * 12) - 768 : 2_304 - (index * 12); + } + } +} diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 4bb8efe..a33fd80 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -1,24 +1,24 @@ -using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi; using NAudio.CoreAudioApi.Interfaces; using NAudio.Wave; using System; +using System.Diagnostics; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core; public abstract class Mixer : IAudioSessionEventsHandler, IDisposable { - public static event Action? VolumeChanged; + public static event Action? MixerVolumeChanged; public readonly bool[] Mutes; private IWavePlayer _out; private AudioSessionControl _appVolume; + private Process _appVol; private bool _shouldSendVolUpdateEvent = true; - protected WaveFileWriter? _waveWriter; - protected abstract WaveFormat WaveFormat { get; } - - protected Mixer() + protected Mixer() { Mutes = new bool[SongState.MAX_TRACKS]; } @@ -45,21 +45,34 @@ protected void Init(IWaveProvider waveProvider) _out.Play(); } - public void CreateWaveWriter(string fileName) - { - _waveWriter = new WaveFileWriter(fileName, WaveFormat); - } - public void CloseWaveWriter() - { - _waveWriter!.Dispose(); - _waveWriter = null; - } + // protected void Init(PortAudioOutputStream waveProvider) + // { + // _outStream = waveProvider; + //var dev = Configuration.DefaultOutputDevice; + // { + // var sessions = dev; + // int id = Environment.ProcessId; + // for (int i = 0; i < sessions; i++) + // { + // var sessionID = new int[i]; + // sessionID[i] = sessions; + // var session = Process.GetProcessById(sessionID[i]); + // if (session.SessionId == id) + // { + // _appVol = session; + // _appVolume.RegisterEventClient(this); + // break; + // } + // } + // } + // _outStream.StartStream(); + // } - public void OnVolumeChanged(float volume, bool isMuted) + public void OnVolumeChanged(float volume, bool isMuted) { if (_shouldSendVolUpdateEvent) { - VolumeChanged?.Invoke(volume); + MixerVolumeChanged?.Invoke(volume); } _shouldSendVolUpdateEvent = true; } @@ -103,4 +116,4 @@ public virtual void Dispose() _out.Dispose(); _appVolume.Dispose(); } -} +} \ No newline at end of file diff --git a/VG Music Studio - Core/NDS/DSE/Channel.cs b/VG Music Studio - Core/NDS/DSE/Channel.cs new file mode 100644 index 0000000..e97da44 --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Channel.cs @@ -0,0 +1,368 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal class Channel + { + public readonly byte Index; + + public Track? Owner; + public EnvelopeState State; + public byte RootKey; + public byte Key; + public byte NoteVelocity; + public sbyte Panpot; // Not necessary + public ushort BaseTimer; + public ushort Timer; + public uint NoteLength; + public byte Volume; + + private int _pos; + private short _prevLeft; + private short _prevRight; + + private int _envelopeTimeLeft; + private int _volumeIncrement; + private int _velocity; // From 0-0x3FFFFFFF ((128 << 23) - 1) + private byte _targetVolume; + + private byte _attackVolume; + private byte _attack; + private byte _decay; + private byte _sustain; + private byte _hold; + private byte _decay2; + private byte _release; + + // PCM8, PCM16, ADPCM + private SWD.SampleBlock _sample; + // PCM8, PCM16 + private int _dataOffset; + // ADPCM + private ADPCMDecoder _adpcmDecoder; + private short _adpcmLoopLastSample; + private short _adpcmLoopStepIndex; + + public Channel(byte i) + { + Index = i; + } + + public bool StartPCM(SWD localswd, SWD masterswd, byte voice, int key, uint noteLength) + { + SWD.IProgramInfo programInfo = localswd.Programs.ProgramInfos[voice]; + if (programInfo != null) + { + for (int i = 0; i < programInfo.SplitEntries.Length; i++) + { + SWD.ISplitEntry split = programInfo.SplitEntries[i]; + if (key >= split.LowKey && key <= split.HighKey) + { + _sample = masterswd.Samples[split.SampleId]; + Key = (byte)key; + RootKey = split.SampleRootKey; + BaseTimer = (ushort)(NDS.Utils.ARM7_CLOCK / _sample.WavInfo.SampleRate); + if (_sample.WavInfo.SampleFormat == SampleFormat.ADPCM) + { + _adpcmDecoder = new ADPCMDecoder(_sample.Data); + } + //attackVolume = sample.WavInfo.AttackVolume == 0 ? split.AttackVolume : sample.WavInfo.AttackVolume; + //attack = sample.WavInfo.Attack == 0 ? split.Attack : sample.WavInfo.Attack; + //decay = sample.WavInfo.Decay == 0 ? split.Decay : sample.WavInfo.Decay; + //sustain = sample.WavInfo.Sustain == 0 ? split.Sustain : sample.WavInfo.Sustain; + //hold = sample.WavInfo.Hold == 0 ? split.Hold : sample.WavInfo.Hold; + //decay2 = sample.WavInfo.Decay2 == 0 ? split.Decay2 : sample.WavInfo.Decay2; + //release = sample.WavInfo.Release == 0 ? split.Release : sample.WavInfo.Release; + //attackVolume = split.AttackVolume == 0 ? sample.WavInfo.AttackVolume : split.AttackVolume; + //attack = split.Attack == 0 ? sample.WavInfo.Attack : split.Attack; + //decay = split.Decay == 0 ? sample.WavInfo.Decay : split.Decay; + //sustain = split.Sustain == 0 ? sample.WavInfo.Sustain : split.Sustain; + //hold = split.Hold == 0 ? sample.WavInfo.Hold : split.Hold; + //decay2 = split.Decay2 == 0 ? sample.WavInfo.Decay2 : split.Decay2; + //release = split.Release == 0 ? sample.WavInfo.Release : split.Release; + _attackVolume = split.AttackVolume == 0 ? _sample.WavInfo.AttackVolume == 0 ? (byte)0x7F : _sample.WavInfo.AttackVolume : split.AttackVolume; + _attack = split.Attack == 0 ? _sample.WavInfo.Attack == 0 ? (byte)0x7F : _sample.WavInfo.Attack : split.Attack; + _decay = split.Decay == 0 ? _sample.WavInfo.Decay == 0 ? (byte)0x7F : _sample.WavInfo.Decay : split.Decay; + _sustain = split.Sustain == 0 ? _sample.WavInfo.Sustain == 0 ? (byte)0x7F : _sample.WavInfo.Sustain : split.Sustain; + _hold = split.Hold == 0 ? _sample.WavInfo.Hold == 0 ? (byte)0x7F : _sample.WavInfo.Hold : split.Hold; + _decay2 = split.Decay2 == 0 ? _sample.WavInfo.Decay2 == 0 ? (byte)0x7F : _sample.WavInfo.Decay2 : split.Decay2; + _release = split.Release == 0 ? _sample.WavInfo.Release == 0 ? (byte)0x7F : _sample.WavInfo.Release : split.Release; + DetermineEnvelopeStartingPoint(); + _pos = 0; + _prevLeft = _prevRight = 0; + NoteLength = noteLength; + return true; + } + } + } + return false; + } + + public void Stop() + { + if (Owner is not null) + { + Owner.Channels.Remove(this); + } + Owner = null; + Volume = 0; + } + + private bool CMDB1___sub_2074CA0() + { + bool b = true; + bool ge = _sample.WavInfo.EnvMult >= 0x7F; + bool ee = _sample.WavInfo.EnvMult == 0x7F; + if (_sample.WavInfo.EnvMult > 0x7F) + { + ge = _attackVolume >= 0x7F; + ee = _attackVolume == 0x7F; + } + if (!ee & ge + && _attack > 0x7F + && _decay > 0x7F + && _sustain > 0x7F + && _hold > 0x7F + && _decay2 > 0x7F + && _release > 0x7F) + { + b = false; + } + return b; + } + private void DetermineEnvelopeStartingPoint() + { + State = EnvelopeState.Two; // This isn't actually placed in this func + bool atLeastOneThingIsValid = CMDB1___sub_2074CA0(); // Neither is this + if (atLeastOneThingIsValid) + { + if (_attack != 0) + { + _velocity = _attackVolume << 23; + State = EnvelopeState.Hold; + UpdateEnvelopePlan(0x7F, _attack); + } + else + { + _velocity = 0x7F << 23; + if (_hold != 0) + { + UpdateEnvelopePlan(0x7F, _hold); + State = EnvelopeState.Decay; + } + else if (_decay != 0) + { + UpdateEnvelopePlan(_sustain, _decay); + State = EnvelopeState.Decay2; + } + else + { + UpdateEnvelopePlan(0, _release); + State = EnvelopeState.Six; + } + } + // Unk1E = 1 + } + else if (State != EnvelopeState.One) // What should it be? + { + State = EnvelopeState.Zero; + _velocity = 0x7F << 23; + } + } + public void SetEnvelopePhase7_2074ED8() + { + if (State != EnvelopeState.Zero) + { + UpdateEnvelopePlan(0, _release); + State = EnvelopeState.Seven; + } + } + public int StepEnvelope() + { + if (State > EnvelopeState.Two) + { + if (_envelopeTimeLeft != 0) + { + _envelopeTimeLeft--; + _velocity += _volumeIncrement; + if (_velocity < 0) + { + _velocity = 0; + } + else if (_velocity > 0x3FFFFFFF) + { + _velocity = 0x3FFFFFFF; + } + } + else + { + _velocity = _targetVolume << 23; + switch (State) + { + default: return _velocity >> 23; // case 8 + case EnvelopeState.Hold: + { + if (_hold == 0) + { + goto LABEL_6; + } + else + { + UpdateEnvelopePlan(0x7F, _hold); + State = EnvelopeState.Decay; + } + break; + } + case EnvelopeState.Decay: + LABEL_6: + { + if (_decay == 0) + { + _velocity = _sustain << 23; + goto LABEL_9; + } + else + { + UpdateEnvelopePlan(_sustain, _decay); + State = EnvelopeState.Decay2; + } + break; + } + case EnvelopeState.Decay2: + LABEL_9: + { + if (_decay2 == 0) + { + goto LABEL_11; + } + else + { + UpdateEnvelopePlan(0, _decay2); + State = EnvelopeState.Six; + } + break; + } + case EnvelopeState.Six: + LABEL_11: + { + UpdateEnvelopePlan(0, 0); + State = EnvelopeState.Two; + break; + } + case EnvelopeState.Seven: + { + State = EnvelopeState.Eight; + _velocity = 0; + _envelopeTimeLeft = 0; + break; + } + } + } + } + return _velocity >> 23; + } + private void UpdateEnvelopePlan(byte targetVolume, int envelopeParam) + { + if (envelopeParam == 0x7F) + { + _volumeIncrement = 0; + _envelopeTimeLeft = int.MaxValue; + } + else + { + _targetVolume = targetVolume; + _envelopeTimeLeft = _sample.WavInfo.EnvMult == 0 + ? Utils.Duration32[envelopeParam] * 1000 / 10000 + : Utils.Duration16[envelopeParam] * _sample.WavInfo.EnvMult * 1000 / 10000; + _volumeIncrement = _envelopeTimeLeft == 0 ? 0 : ((targetVolume << 23) - _velocity) / _envelopeTimeLeft; + } + } + + public void Process(out short left, out short right) + { + if (Timer != 0) + { + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + // prevLeft and prevRight are stored because numSamples can be 0. + for (int i = 0; i < numSamples; i++) + { + short samp; + switch (_sample.WavInfo.SampleFormat) + { + case SampleFormat.PCM8: + { + // If hit end + if (_dataOffset >= _sample.Data.Length) + { + if (_sample.WavInfo.Loop) + { + _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)((sbyte)_sample.Data[_dataOffset++] << 8); + break; + } + case SampleFormat.PCM16: + { + // If hit end + if (_dataOffset >= _sample.Data.Length) + { + if (_sample.WavInfo.Loop) + { + _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)(_sample.Data[_dataOffset++] | (_sample.Data[_dataOffset++] << 8)); + break; + } + case SampleFormat.ADPCM: + { + // If just looped + if (_adpcmDecoder.DataOffset == _sample.WavInfo.LoopStart * 4 && !_adpcmDecoder.OnSecondNibble) + { + _adpcmLoopLastSample = _adpcmDecoder.LastSample; + _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; + } + // If hit end + if (_adpcmDecoder.DataOffset >= _sample.Data.Length && !_adpcmDecoder.OnSecondNibble) + { + if (_sample.WavInfo.Loop) + { + _adpcmDecoder.DataOffset = (int)(_sample.WavInfo.LoopStart * 4); + _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; + _adpcmDecoder.LastSample = _adpcmLoopLastSample; + _adpcmDecoder.OnSecondNibble = false; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = _adpcmDecoder.GetSample(); + break; + } + default: samp = 0; break; + } + samp = (short)(samp * Volume / 0x7F); + _prevLeft = (short)(samp * (-Panpot + 0x40) / 0x80); + _prevRight = (short)(samp * (Panpot + 0x40) / 0x80); + } + } + left = _prevLeft; + right = _prevRight; + } + } +} diff --git a/VG Music Studio - Core/NDS/DSE/DSECommands.cs b/VG Music Studio - Core/NDS/DSE/Commands.cs similarity index 80% rename from VG Music Studio - Core/NDS/DSE/DSECommands.cs rename to VG Music Studio - Core/NDS/DSE/Commands.cs index e07ac3b..cc8ac62 100644 --- a/VG Music Studio - Core/NDS/DSE/DSECommands.cs +++ b/VG Music Studio - Core/NDS/DSE/Commands.cs @@ -4,7 +4,7 @@ namespace Kermalis.VGMusicStudio.Core.NDS.DSE; -internal sealed class ExpressionCommand : ICommand +internal class ExpressionCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Expression"; @@ -12,13 +12,13 @@ internal sealed class ExpressionCommand : ICommand public byte Expression { get; set; } } -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; public string Arguments => string.Empty; } -internal sealed class InvalidCommand : ICommand +internal class InvalidCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Invalid 0x{Command:X}"; @@ -26,7 +26,7 @@ internal sealed class InvalidCommand : ICommand public byte Command { get; set; } } -internal sealed class LoopStartCommand : ICommand +internal class LoopStartCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Loop Start"; @@ -34,7 +34,7 @@ internal sealed class LoopStartCommand : ICommand public long Offset { get; set; } } -internal sealed class NoteCommand : ICommand +internal class NoteCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -45,7 +45,7 @@ internal sealed class NoteCommand : ICommand public byte Velocity { get; set; } public uint Duration { get; set; } } -internal sealed class OctaveAddCommand : ICommand +internal class OctaveAddCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Add To Octave"; @@ -53,7 +53,7 @@ internal sealed class OctaveAddCommand : ICommand public sbyte OctaveChange { get; set; } } -internal sealed class OctaveSetCommand : ICommand +internal class OctaveSetCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Set Octave"; @@ -61,7 +61,7 @@ internal sealed class OctaveSetCommand : ICommand public byte Octave { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -69,7 +69,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -77,7 +77,7 @@ internal sealed class PitchBendCommand : ICommand public ushort Bend { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -85,7 +85,7 @@ internal sealed class RestCommand : ICommand public uint Rest { get; set; } } -internal sealed class SkipBytesCommand : ICommand +internal class SkipBytesCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Skip 0x{Command:X}"; @@ -94,7 +94,7 @@ internal sealed class SkipBytesCommand : ICommand public byte Command { get; set; } public byte[] SkippedBytes { get; set; } } -internal sealed class TempoCommand : ICommand +internal class TempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => $"Tempo {Command - 0xA3}"; // The two possible tempo commands are 0xA4 and 0xA5 @@ -103,7 +103,7 @@ internal sealed class TempoCommand : ICommand public byte Command { get; set; } public byte Tempo { get; set; } } -internal sealed class UnknownCommand : ICommand +internal class UnknownCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Unknown 0x{Command:X}"; @@ -112,7 +112,7 @@ internal sealed class UnknownCommand : ICommand public byte Command { get; set; } public byte[] Args { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -120,7 +120,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/NDS/DSE/DSEChannel.cs b/VG Music Studio - Core/NDS/DSE/DSEChannel.cs deleted file mode 100644 index 4b1b83f..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEChannel.cs +++ /dev/null @@ -1,375 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class DSEChannel -{ - public readonly byte Index; - - public DSETrack? Owner; - public EnvelopeState State; - public byte RootKey; - public byte Key; - public byte NoteVelocity; - public sbyte Panpot; // Not necessary - public ushort BaseTimer; - public ushort Timer; - public uint NoteLength; - public byte Volume; - - private int _pos; - private short _prevLeft; - private short _prevRight; - - private int _envelopeTimeLeft; - private int _volumeIncrement; - private int _velocity; // From 0-0x3FFFFFFF ((128 << 23) - 1) - private byte _targetVolume; - - private byte _attackVolume; - private byte _attack; - private byte _decay; - private byte _sustain; - private byte _hold; - private byte _decay2; - private byte _release; - - // PCM8, PCM16, ADPCM - private SWD.SampleBlock _sample; - // PCM8, PCM16 - private int _dataOffset; - // ADPCM - private ADPCMDecoder _adpcmDecoder; - private short _adpcmLoopLastSample; - private short _adpcmLoopStepIndex; - - public DSEChannel(byte i) - { - Index = i; - } - - public bool StartPCM(SWD localswd, SWD masterswd, byte voice, int key, uint noteLength) - { - SWD.IProgramInfo? programInfo = localswd.Programs.ProgramInfos[voice]; - if (programInfo is null) - { - return false; - } - - for (int i = 0; i < programInfo.SplitEntries.Length; i++) - { - SWD.ISplitEntry split = programInfo.SplitEntries[i]; - if (key < split.LowKey || key > split.HighKey) - { - continue; - } - - _sample = masterswd.Samples[split.SampleId]; - Key = (byte)key; - RootKey = split.SampleRootKey; - BaseTimer = (ushort)(NDSUtils.ARM7_CLOCK / _sample.WavInfo.SampleRate); - if (_sample.WavInfo.SampleFormat == SampleFormat.ADPCM) - { - _adpcmDecoder = new ADPCMDecoder(_sample.Data); - } - //attackVolume = sample.WavInfo.AttackVolume == 0 ? split.AttackVolume : sample.WavInfo.AttackVolume; - //attack = sample.WavInfo.Attack == 0 ? split.Attack : sample.WavInfo.Attack; - //decay = sample.WavInfo.Decay == 0 ? split.Decay : sample.WavInfo.Decay; - //sustain = sample.WavInfo.Sustain == 0 ? split.Sustain : sample.WavInfo.Sustain; - //hold = sample.WavInfo.Hold == 0 ? split.Hold : sample.WavInfo.Hold; - //decay2 = sample.WavInfo.Decay2 == 0 ? split.Decay2 : sample.WavInfo.Decay2; - //release = sample.WavInfo.Release == 0 ? split.Release : sample.WavInfo.Release; - //attackVolume = split.AttackVolume == 0 ? sample.WavInfo.AttackVolume : split.AttackVolume; - //attack = split.Attack == 0 ? sample.WavInfo.Attack : split.Attack; - //decay = split.Decay == 0 ? sample.WavInfo.Decay : split.Decay; - //sustain = split.Sustain == 0 ? sample.WavInfo.Sustain : split.Sustain; - //hold = split.Hold == 0 ? sample.WavInfo.Hold : split.Hold; - //decay2 = split.Decay2 == 0 ? sample.WavInfo.Decay2 : split.Decay2; - //release = split.Release == 0 ? sample.WavInfo.Release : split.Release; - _attackVolume = split.AttackVolume == 0 ? _sample.WavInfo.AttackVolume == 0 ? (byte)0x7F : _sample.WavInfo.AttackVolume : split.AttackVolume; - _attack = split.Attack == 0 ? _sample.WavInfo.Attack == 0 ? (byte)0x7F : _sample.WavInfo.Attack : split.Attack; - _decay = split.Decay == 0 ? _sample.WavInfo.Decay == 0 ? (byte)0x7F : _sample.WavInfo.Decay : split.Decay; - _sustain = split.Sustain == 0 ? _sample.WavInfo.Sustain == 0 ? (byte)0x7F : _sample.WavInfo.Sustain : split.Sustain; - _hold = split.Hold == 0 ? _sample.WavInfo.Hold == 0 ? (byte)0x7F : _sample.WavInfo.Hold : split.Hold; - _decay2 = split.Decay2 == 0 ? _sample.WavInfo.Decay2 == 0 ? (byte)0x7F : _sample.WavInfo.Decay2 : split.Decay2; - _release = split.Release == 0 ? _sample.WavInfo.Release == 0 ? (byte)0x7F : _sample.WavInfo.Release : split.Release; - DetermineEnvelopeStartingPoint(); - _pos = 0; - _prevLeft = _prevRight = 0; - NoteLength = noteLength; - return true; - } - return false; - } - - public void Stop() - { - if (Owner is not null) - { - Owner.Channels.Remove(this); - } - Owner = null; - Volume = 0; - } - - private bool CMDB1___sub_2074CA0() - { - bool b = true; - bool ge = _sample.WavInfo.EnvMult >= 0x7F; - bool ee = _sample.WavInfo.EnvMult == 0x7F; - if (_sample.WavInfo.EnvMult > 0x7F) - { - ge = _attackVolume >= 0x7F; - ee = _attackVolume == 0x7F; - } - if (!ee & ge - && _attack > 0x7F - && _decay > 0x7F - && _sustain > 0x7F - && _hold > 0x7F - && _decay2 > 0x7F - && _release > 0x7F) - { - b = false; - } - return b; - } - private void DetermineEnvelopeStartingPoint() - { - State = EnvelopeState.Two; // This isn't actually placed in this func - bool atLeastOneThingIsValid = CMDB1___sub_2074CA0(); // Neither is this - if (atLeastOneThingIsValid) - { - if (_attack != 0) - { - _velocity = _attackVolume << 23; - State = EnvelopeState.Hold; - UpdateEnvelopePlan(0x7F, _attack); - } - else - { - _velocity = 0x7F << 23; - if (_hold != 0) - { - UpdateEnvelopePlan(0x7F, _hold); - State = EnvelopeState.Decay; - } - else if (_decay != 0) - { - UpdateEnvelopePlan(_sustain, _decay); - State = EnvelopeState.Decay2; - } - else - { - UpdateEnvelopePlan(0, _release); - State = EnvelopeState.Six; - } - } - // Unk1E = 1 - } - else if (State != EnvelopeState.One) // What should it be? - { - State = EnvelopeState.Zero; - _velocity = 0x7F << 23; - } - } - public void SetEnvelopePhase7_2074ED8() - { - if (State != EnvelopeState.Zero) - { - UpdateEnvelopePlan(0, _release); - State = EnvelopeState.Seven; - } - } - public int StepEnvelope() - { - if (State > EnvelopeState.Two) - { - if (_envelopeTimeLeft != 0) - { - _envelopeTimeLeft--; - _velocity += _volumeIncrement; - if (_velocity < 0) - { - _velocity = 0; - } - else if (_velocity > 0x3FFFFFFF) - { - _velocity = 0x3FFFFFFF; - } - } - else - { - _velocity = _targetVolume << 23; - switch (State) - { - default: return _velocity >> 23; // case 8 - case EnvelopeState.Hold: - { - if (_hold == 0) - { - goto LABEL_6; - } - else - { - UpdateEnvelopePlan(0x7F, _hold); - State = EnvelopeState.Decay; - } - break; - } - case EnvelopeState.Decay: - LABEL_6: - { - if (_decay == 0) - { - _velocity = _sustain << 23; - goto LABEL_9; - } - else - { - UpdateEnvelopePlan(_sustain, _decay); - State = EnvelopeState.Decay2; - } - break; - } - case EnvelopeState.Decay2: - LABEL_9: - { - if (_decay2 == 0) - { - goto LABEL_11; - } - else - { - UpdateEnvelopePlan(0, _decay2); - State = EnvelopeState.Six; - } - break; - } - case EnvelopeState.Six: - LABEL_11: - { - UpdateEnvelopePlan(0, 0); - State = EnvelopeState.Two; - break; - } - case EnvelopeState.Seven: - { - State = EnvelopeState.Eight; - _velocity = 0; - _envelopeTimeLeft = 0; - break; - } - } - } - } - return _velocity >> 23; - } - private void UpdateEnvelopePlan(byte targetVolume, int envelopeParam) - { - if (envelopeParam == 0x7F) - { - _volumeIncrement = 0; - _envelopeTimeLeft = int.MaxValue; - } - else - { - _targetVolume = targetVolume; - _envelopeTimeLeft = _sample.WavInfo.EnvMult == 0 - ? DSEUtils.Duration32[envelopeParam] * 1_000 / 10_000 - : DSEUtils.Duration16[envelopeParam] * _sample.WavInfo.EnvMult * 1_000 / 10_000; - _volumeIncrement = _envelopeTimeLeft == 0 ? 0 : ((targetVolume << 23) - _velocity) / _envelopeTimeLeft; - } - } - - public void Process(out short left, out short right) - { - if (Timer == 0) - { - left = _prevLeft; - right = _prevRight; - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - // prevLeft and prevRight are stored because numSamples can be 0. - for (int i = 0; i < numSamples; i++) - { - short samp; - switch (_sample.WavInfo.SampleFormat) - { - case SampleFormat.PCM8: - { - // If hit end - if (_dataOffset >= _sample.Data.Length) - { - if (_sample.WavInfo.Loop) - { - _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)((sbyte)_sample.Data[_dataOffset++] << 8); - break; - } - case SampleFormat.PCM16: - { - // If hit end - if (_dataOffset >= _sample.Data.Length) - { - if (_sample.WavInfo.Loop) - { - _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)(_sample.Data[_dataOffset++] | (_sample.Data[_dataOffset++] << 8)); - break; - } - case SampleFormat.ADPCM: - { - // If just looped - if (_adpcmDecoder.DataOffset == _sample.WavInfo.LoopStart * 4 && !_adpcmDecoder.OnSecondNibble) - { - _adpcmLoopLastSample = _adpcmDecoder.LastSample; - _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; - } - // If hit end - if (_adpcmDecoder.DataOffset >= _sample.Data.Length && !_adpcmDecoder.OnSecondNibble) - { - if (_sample.WavInfo.Loop) - { - _adpcmDecoder.DataOffset = (int)(_sample.WavInfo.LoopStart * 4); - _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; - _adpcmDecoder.LastSample = _adpcmLoopLastSample; - _adpcmDecoder.OnSecondNibble = false; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = _adpcmDecoder.GetSample(); - break; - } - default: samp = 0; break; - } - samp = (short)(samp * Volume / 0x7F); - _prevLeft = (short)(samp * (-Panpot + 0x40) / 0x80); - _prevRight = (short)(samp * (Panpot + 0x40) / 0x80); - } - left = _prevLeft; - right = _prevRight; - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEConfig.cs b/VG Music Studio - Core/NDS/DSE/DSEConfig.cs index 6a68eed..69edd6c 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEConfig.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEConfig.cs @@ -1,7 +1,7 @@ using Kermalis.EndianBinaryIO; using Kermalis.VGMusicStudio.Core.Properties; -using System.Collections.Generic; using System.IO; +using System.Linq; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; @@ -19,17 +19,14 @@ internal DSEConfig(string bgmPath) throw new DSENoSequencesException(bgmPath); } - // TODO: Big endian files - var songs = new List(BGMFiles.Length); + var songs = new Song[BGMFiles.Length]; for (int i = 0; i < BGMFiles.Length; i++) { using (FileStream stream = File.OpenRead(BGMFiles[i])) { var r = new EndianBinaryReader(stream, ascii: true); SMD.Header header = r.ReadObject(); - char[] chars = header.Label.ToCharArray(); - EndianBinaryPrimitives.TrimNullTerminators(ref chars); - songs.Add(new Song(i, $"{Path.GetFileNameWithoutExtension(BGMFiles[i])} - {new string(chars)}")); + songs[i] = new Song(i, $"{Path.GetFileNameWithoutExtension(BGMFiles[i])} - {new string(header.Label.TakeWhile(c => c != '\0').ToArray())}"); } } Playlists.Add(new Playlist(Strings.PlaylistMusic, songs)); @@ -39,7 +36,7 @@ public override string GetGameName() { return "DSE"; } - public override string GetSongName(int index) + public override string GetSongName(long index) { return index < 0 || index >= BGMFiles.Length ? index.ToString() diff --git a/VG Music Studio - Core/NDS/DSE/DSEEnums.cs b/VG Music Studio - Core/NDS/DSE/DSEEnums.cs deleted file mode 100644 index 911c5f0..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEEnums.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal enum EnvelopeState : byte -{ - Zero = 0, - One = 1, - Two = 2, - Hold = 3, - Decay = 4, - Decay2 = 5, - Six = 6, - Seven = 7, - Eight = 8, -} - -internal enum SampleFormat : ushort -{ - PCM8 = 0x000, - PCM16 = 0x100, - ADPCM = 0x200, -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs deleted file mode 100644 index 8f7a943..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Kermalis.EndianBinaryIO; -using Kermalis.VGMusicStudio.Core.Util; -using System.Collections.Generic; -using System.IO; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong : ILoadedSong -{ - public List[] Events { get; } - public long MaxTicks { get; private set; } - public int LongestTrack; - - private readonly DSEPlayer _player; - private readonly SWD LocalSWD; - private readonly byte[] SMDFile; - public readonly DSETrack[] Tracks; - - public DSELoadedSong(DSEPlayer player, string bgm) - { - _player = player; - - LocalSWD = new SWD(Path.ChangeExtension(bgm, "swd")); - SMDFile = File.ReadAllBytes(bgm); - using (var stream = new MemoryStream(SMDFile)) - { - var r = new EndianBinaryReader(stream, ascii: true); - SMD.Header header = r.ReadObject(); - SMD.ISongChunk songChunk; - switch (header.Version) - { - case 0x402: - { - songChunk = r.ReadObject(); - break; - } - case 0x415: - { - songChunk = r.ReadObject(); - break; - } - default: throw new DSEInvalidHeaderVersionException(header.Version); - } - - Tracks = new DSETrack[songChunk.NumTracks]; - Events = new List[songChunk.NumTracks]; - for (byte trackIndex = 0; trackIndex < songChunk.NumTracks; trackIndex++) - { - long chunkStart = r.Stream.Position; - r.Stream.Position += 0x14; // Skip header - Tracks[trackIndex] = new DSETrack(trackIndex, (int)r.Stream.Position); - - AddTrackEvents(trackIndex, r); - - r.Stream.Position = chunkStart + 0xC; - uint chunkLength = r.ReadUInt32(); - r.Stream.Position += chunkLength; - r.Stream.Align(4); - } - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs deleted file mode 100644 index b37dde9..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs +++ /dev/null @@ -1,461 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex].Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex].Exists(e => e.Offset == cmdOffset); - } - - private void AddTrackEvents(byte trackIndex, EndianBinaryReader r) - { - Events[trackIndex] = new List(); - - uint lastNoteDuration = 0; - uint lastRest = 0; - bool cont = true; - while (cont) - { - long cmdOffset = r.Stream.Position; - byte cmd = r.ReadByte(); - if (cmd <= 0x7F) - { - byte arg = r.ReadByte(); - int numParams = (arg & 0xC0) >> 6; - int oct = ((arg & 0x30) >> 4) - 2; - int n = arg & 0xF; - if (n >= 12) - { - throw new DSEInvalidNoteException(trackIndex, (int)cmdOffset, n); - } - - uint duration; - if (numParams == 0) - { - duration = lastNoteDuration; - } - else // Big Endian reading of 8, 16, or 24 bits - { - duration = 0; - for (int b = 0; b < numParams; b++) - { - duration = (duration << 8) | r.ReadByte(); - } - lastNoteDuration = duration; - } - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteCommand { Note = (byte)n, OctaveChange = (sbyte)oct, Velocity = cmd, Duration = duration }); - } - } - else if (cmd >= 0x80 && cmd <= 0x8F) - { - lastRest = DSEUtils.FixedRests[cmd - 0x80]; - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - } - else // 0x90-0xFF - { - // TODO: 0x95 - a rest that may or may not repeat depending on some condition within channels - // TODO: 0x9E - may or may not jump somewhere else depending on an unknown structure - switch (cmd) - { - case 0x90: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x91: - { - lastRest = (uint)(lastRest + r.ReadSByte()); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x92: - { - lastRest = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x93: - { - lastRest = r.ReadUInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x94: - { - lastRest = (uint)(r.ReadByte() | (r.ReadByte() << 8) | (r.ReadByte() << 16)); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x96: - case 0x97: - case 0x9A: - case 0x9B: - case 0x9F: - case 0xA2: - case 0xA3: - case 0xA6: - case 0xA7: - case 0xAD: - case 0xAE: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBD: - case 0xC1: - case 0xC2: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD9: - case 0xDA: - case 0xDE: - case 0xE6: - case 0xEB: - case 0xEE: - case 0xF4: - case 0xF5: - case 0xF7: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new InvalidCommand { Command = cmd }); - } - break; - } - case 0x98: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand()); - } - cont = false; - break; - } - case 0x99: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopStartCommand { Offset = r.Stream.Position }); - } - break; - } - case 0xA0: - { - byte octave = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OctaveSetCommand { Octave = octave }); - } - break; - } - case 0xA1: - { - sbyte change = r.ReadSByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OctaveAddCommand { OctaveChange = change }); - } - break; - } - case 0xA4: - case 0xA5: // The code for these two is identical - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TempoCommand { Command = cmd, Tempo = tempoArg }); - } - break; - } - case 0xAB: - { - byte[] bytes = new byte[1]; - r.ReadBytes(bytes); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); - } - break; - } - case 0xAC: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xCB: - case 0xF8: - { - byte[] bytes = new byte[2]; - r.ReadBytes(bytes); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); - } - break; - } - case 0xD7: - { - ushort bend = r.ReadUInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = bend }); - } - break; - } - case 0xE0: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xE3: - { - byte expression = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ExpressionCommand { Expression = expression }); - } - break; - } - case 0xE8: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); - } - break; - } - case 0x9D: - case 0xB0: - case 0xC0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = Array.Empty() }); - } - break; - } - case 0x9C: - case 0xA9: - case 0xAA: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB5: - case 0xB6: - case 0xBC: - case 0xBE: - case 0xBF: - case 0xC3: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xDB: - case 0xDF: - case 0xE1: - case 0xE7: - case 0xE9: - case 0xEF: - case 0xF6: - { - byte[] args = new byte[1]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xA8: - case 0xB4: - case 0xD3: - case 0xD5: - case 0xD6: - case 0xD8: - case 0xF2: - { - byte[] args = new byte[2]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xAF: - case 0xD4: - case 0xE2: - case 0xEA: - case 0xF3: - { - byte[] args = new byte[3]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xDD: - case 0xE5: - case 0xED: - case 0xF1: - { - byte[] args = new byte[4]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xDC: - case 0xE4: - case 0xEC: - case 0xF0: - { - byte[] args = new byte[5]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - default: throw new DSEInvalidCMDException(trackIndex, (int)cmdOffset, cmd); - } - } - } - } - - public void SetTicks() - { - MaxTicks = 0; - for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) - { - List evs = Events[trackIndex]; - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - DSETrack track = Tracks[trackIndex]; - track.Init(); - - long elapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.CurOffset); - if (e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(elapsedTicks); - ExecuteNext(track); - if (track.Stopped) - { - break; - } - - elapsedTicks += track.Rest; - track.Rest = 0; - } - if (elapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = elapsedTicks; - } - track.StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - DSETrack track = Tracks[trackIndex]; - if (!track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < Tracks.Length; i++) - { - Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs deleted file mode 100644 index e07c497..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs +++ /dev/null @@ -1,288 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong -{ - public void UpdateSongState(SongState info) - { - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - Tracks[trackIndex].UpdateSongState(info.Tracks[trackIndex]); - } - } - - public void ExecuteNext(DSETrack track) - { - byte cmd = SMDFile[track.CurOffset++]; - if (cmd <= 0x7F) - { - byte arg = SMDFile[track.CurOffset++]; - int numParams = (arg & 0xC0) >> 6; - int oct = ((arg & 0x30) >> 4) - 2; - int n = arg & 0xF; - if (n >= 12) - { - throw new DSEInvalidNoteException(track.Index, track.CurOffset - 2, n); - } - - uint duration; - if (numParams == 0) - { - duration = track.LastNoteDuration; - } - else - { - duration = 0; - for (int b = 0; b < numParams; b++) - { - duration = (duration << 8) | SMDFile[track.CurOffset++]; - } - track.LastNoteDuration = duration; - } - DSEChannel? channel = _player.DMixer.AllocateChannel(); - if (channel is null) - { - throw new Exception("Not enough channels"); - } - - channel.Stop(); - track.Octave = (byte)(track.Octave + oct); - if (channel.StartPCM(LocalSWD, _player.MasterSWD, track.Voice, n + (12 * track.Octave), duration)) - { - channel.NoteVelocity = cmd; - channel.Owner = track; - track.Channels.Add(channel); - } - } - else if (cmd >= 0x80 && cmd <= 0x8F) - { - track.LastRest = DSEUtils.FixedRests[cmd - 0x80]; - track.Rest = track.LastRest; - } - else // 0x90-0xFF - { - // TODO: 0x95, 0x9E - switch (cmd) - { - case 0x90: - { - track.Rest = track.LastRest; - break; - } - case 0x91: - { - track.LastRest = (uint)(track.LastRest + (sbyte)SMDFile[track.CurOffset++]); - track.Rest = track.LastRest; - break; - } - case 0x92: - { - track.LastRest = SMDFile[track.CurOffset++]; - track.Rest = track.LastRest; - break; - } - case 0x93: - { - track.LastRest = (uint)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8)); - track.Rest = track.LastRest; - break; - } - case 0x94: - { - track.LastRest = (uint)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8) | (SMDFile[track.CurOffset++] << 16)); - track.Rest = track.LastRest; - break; - } - case 0x96: - case 0x97: - case 0x9A: - case 0x9B: - case 0x9F: - case 0xA2: - case 0xA3: - case 0xA6: - case 0xA7: - case 0xAD: - case 0xAE: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBD: - case 0xC1: - case 0xC2: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD9: - case 0xDA: - case 0xDE: - case 0xE6: - case 0xEB: - case 0xEE: - case 0xF4: - case 0xF5: - case 0xF7: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - { - track.Stopped = true; - break; - } - case 0x98: - { - if (track.LoopOffset == -1) - { - track.Stopped = true; - } - else - { - track.CurOffset = track.LoopOffset; - } - break; - } - case 0x99: - { - track.LoopOffset = track.CurOffset; - break; - } - case 0xA0: - { - track.Octave = SMDFile[track.CurOffset++]; - break; - } - case 0xA1: - { - track.Octave = (byte)(track.Octave + (sbyte)SMDFile[track.CurOffset++]); - break; - } - case 0xA4: - case 0xA5: - { - _player.Tempo = SMDFile[track.CurOffset++]; - break; - } - case 0xAB: - { - track.CurOffset++; - break; - } - case 0xAC: - { - track.Voice = SMDFile[track.CurOffset++]; - break; - } - case 0xCB: - case 0xF8: - { - track.CurOffset += 2; - break; - } - case 0xD7: - { - track.PitchBend = (ushort)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8)); - break; - } - case 0xE0: - { - track.Volume = SMDFile[track.CurOffset++]; - break; - } - case 0xE3: - { - track.Expression = SMDFile[track.CurOffset++]; - break; - } - case 0xE8: - { - track.Panpot = (sbyte)(SMDFile[track.CurOffset++] - 0x40); - break; - } - case 0x9D: - case 0xB0: - case 0xC0: - { - break; - } - case 0x9C: - case 0xA9: - case 0xAA: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB5: - case 0xB6: - case 0xBC: - case 0xBE: - case 0xBF: - case 0xC3: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xDB: - case 0xDF: - case 0xE1: - case 0xE7: - case 0xE9: - case 0xEF: - case 0xF6: - { - track.CurOffset++; - break; - } - case 0xA8: - case 0xB4: - case 0xD3: - case 0xD5: - case 0xD6: - case 0xD8: - case 0xF2: - { - track.CurOffset += 2; - break; - } - case 0xAF: - case 0xD4: - case 0xE2: - case 0xEA: - case 0xF3: - { - track.CurOffset += 3; - break; - } - case 0xDD: - case 0xE5: - case 0xED: - case 0xF1: - { - track.CurOffset += 4; - break; - } - case 0xDC: - case 0xE4: - case 0xEC: - case 0xF0: - { - track.CurOffset += 5; - break; - } - default: throw new DSEInvalidCMDException(track.Index, track.CurOffset - 1, cmd); - } - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs index 89f6c52..cbcf840 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs @@ -1,5 +1,4 @@ -using Kermalis.VGMusicStudio.Core.NDS.SDAT; -using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.Core.Util; using NAudio.Wave; using System; @@ -16,11 +15,9 @@ public sealed class DSEMixer : Mixer private float _fadePos; private float _fadeStepPerMicroframe; - private readonly DSEChannel[] _channels; + private readonly Channel[] _channels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - public DSEMixer() { // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. @@ -30,10 +27,10 @@ public DSEMixer() _samplesPerBuffer = 341; // TODO _samplesReciprocal = 1f / _samplesPerBuffer; - _channels = new DSEChannel[NUM_CHANNELS]; + _channels = new Channel[NUM_CHANNELS]; for (byte i = 0; i < NUM_CHANNELS; i++) { - _channels[i] = new DSEChannel(i); + _channels[i] = new Channel(i); } _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) @@ -44,17 +41,17 @@ public DSEMixer() Init(_buffer); } - internal DSEChannel? AllocateChannel() + internal Channel? AllocateChannel() { - static int GetScore(DSEChannel c) + static int GetScore(Channel c) { // Free channels should be used before releasing channels - return c.Owner is null ? -2 : DSEUtils.IsStateRemovable(c.State) ? -1 : 0; + return c.Owner is null ? -2 : Utils.IsStateRemovable(c.State) ? -1 : 0; } - DSEChannel? nChan = null; + Channel? nChan = null; for (int i = 0; i < NUM_CHANNELS; i++) { - DSEChannel c = _channels[i]; + Channel c = _channels[i]; if (nChan is null) { nChan = c; @@ -76,29 +73,29 @@ internal void ChannelTick() { for (int i = 0; i < NUM_CHANNELS; i++) { - DSEChannel chan = _channels[i]; + Channel chan = _channels[i]; if (chan.Owner is null) { continue; } chan.Volume = (byte)chan.StepEnvelope(); - if (chan.NoteLength == 0 && !DSEUtils.IsStateRemovable(chan.State)) + if (chan.NoteLength == 0 && !Utils.IsStateRemovable(chan.State)) { chan.SetEnvelopePhase7_2074ED8(); } - int vol = SDATUtils.SustainTable[chan.NoteVelocity] + SDATUtils.SustainTable[chan.Volume] + SDATUtils.SustainTable[chan.Owner.Volume] + SDATUtils.SustainTable[chan.Owner.Expression]; + int vol = SDAT.SDATUtils.SustainTable[chan.NoteVelocity] + SDAT.SDATUtils.SustainTable[chan.Volume] + SDAT.SDATUtils.SustainTable[chan.Owner.Volume] + SDAT.SDATUtils.SustainTable[chan.Owner.Expression]; //int pitch = ((chan.Key - chan.BaseKey) << 6) + chan.SweepMain() + chan.Owner.GetPitch(); // "<< 6" is "* 0x40" int pitch = (chan.Key - chan.RootKey) << 6; // "<< 6" is "* 0x40" - if (DSEUtils.IsStateRemovable(chan.State) && vol <= -92544) + if (Utils.IsStateRemovable(chan.State) && vol <= -92544) { chan.Stop(); } else { - chan.Volume = SDATUtils.GetChannelVolume(vol); + chan.Volume = SDAT.SDATUtils.GetChannelVolume(vol); chan.Panpot = chan.Owner.Panpot; - chan.Timer = SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); + chan.Timer = SDAT.SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); } } } @@ -131,6 +128,16 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } private readonly byte[] _b = new byte[4]; internal void Process(bool output, bool recording) { @@ -162,7 +169,7 @@ internal void Process(bool output, bool recording) right = 0; for (int j = 0; j < NUM_CHANNELS; j++) { - DSEChannel chan = _channels[j]; + Channel chan = _channels[j]; if (chan.Owner is null) { continue; diff --git a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs index bfdcda2..3eb9b59 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs @@ -1,135 +1,1046 @@ -using System.IO; +using Kermalis.EndianBinaryIO; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; -public sealed class DSEPlayer : Player +public sealed class DSEPlayer : IPlayer, ILoadedSong { - protected override string Name => "DSE Player"; - + private readonly DSEMixer _mixer; private readonly DSEConfig _config; - internal readonly DSEMixer DMixer; - internal readonly SWD MasterSWD; - private DSELoadedSong? _loadedSong; - - internal byte Tempo; - internal int TempoStack; + private readonly TimeBarrier _time; + private Thread? _thread; + private readonly SWD _masterSWD; + private SWD _localSWD; + private byte[] _smdFile; + private Track[] _tracks; + private byte _tempo; + private int _tempoStack; private long _elapsedLoops; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => DMixer; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; + + public PlayerState State { get; private set; } + public event Action? SongEnded; public DSEPlayer(DSEConfig config, DSEMixer mixer) - : base(192) { - DMixer = mixer; + _mixer = mixer; _config = config; + _masterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); - MasterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); + _time = new TimeBarrier(192); } - - public override void LoadSong(int index) + private void CreateThread() { - if (_loadedSong is not null) - { - _loadedSong = null; - } - - // If there's an exception, this will remain null - _loadedSong = new DSELoadedSong(this, _config.BGMFiles[index]); - _loadedSong.SetTicks(); + _thread = new Thread(Tick) { Name = "DSE Player Tick" }; + _thread.Start(); } - public override void UpdateSongState(SongState info) + private void WaitThread() { - info.Tempo = Tempo; - _loadedSong!.UpdateSongState(info); + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) + { + _thread.Join(); + } } - internal override void InitEmulation() + + private void InitEmulation() { - Tempo = 120; - TempoStack = 0; + _tempo = 120; + _tempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - DMixer.ResetFade(); - DSETrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + _mixer.ResetFade(); + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) { - tracks[i].Init(); + _tracks[trackIndex].Init(); } } - protected override void SetCurTick(long ticks) + private void SetTicks() { - _loadedSong!.SetCurTick(ticks); + MaxTicks = 0; + for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) + { + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = _tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.CurOffset); + if (e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + ExecuteNext(track); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.StopAllChannels(); + } } - protected override void OnStopped() + public void LoadSong(long index) { - DSETrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (_tracks != null) { - tracks[i].StopAllChannels(); + for (int i = 0; i < _tracks.Length; i++) + { + _tracks[i].StopAllChannels(); + } + _tracks = null; } - } - protected override bool Tick(bool playing, bool recording) + string bgm = _config.BGMFiles[index]; + _localSWD = new SWD(Path.ChangeExtension(bgm, "swd")); + _smdFile = File.ReadAllBytes(bgm); + using (var stream = new MemoryStream(_smdFile)) + { + var r = new EndianBinaryReader(stream, ascii: true); + SMD.Header header = r.ReadObject(); + SMD.ISongChunk songChunk; + switch (header.Version) + { + case 0x402: + { + songChunk = r.ReadObject(); + break; + } + case 0x415: + { + songChunk = r.ReadObject(); + break; + } + default: throw new DSEInvalidHeaderVersionException(header.Version); + } + + _tracks = new Track[songChunk.NumTracks]; + Events = new List[songChunk.NumTracks]; + for (byte trackIndex = 0; trackIndex < songChunk.NumTracks; trackIndex++) + { + Events[trackIndex] = new List(); + bool EventExists(long offset) + { + return Events[trackIndex].Any(e => e.Offset == offset); + } + + long chunkStart = r.Stream.Position; + r.Stream.Position += 0x14; // Skip header + _tracks[trackIndex] = new Track(trackIndex, (int)r.Stream.Position); + + uint lastNoteDuration = 0, lastRest = 0; + bool cont = true; + while (cont) + { + long offset = r.Stream.Position; + void AddEvent(ICommand command) + { + Events[trackIndex].Add(new SongEvent(offset, command)); + } + byte cmd = r.ReadByte(); + if (cmd <= 0x7F) + { + byte arg = r.ReadByte(); + int numParams = (arg & 0xC0) >> 6; + int oct = ((arg & 0x30) >> 4) - 2; + int n = arg & 0xF; + if (n >= 12) + { + throw new DSEInvalidNoteException(trackIndex, (int)offset, n); + } + + uint duration; + if (numParams == 0) + { + duration = lastNoteDuration; + } + else // Big Endian reading of 8, 16, or 24 bits + { + duration = 0; + for (int b = 0; b < numParams; b++) + { + duration = (duration << 8) | r.ReadByte(); + } + lastNoteDuration = duration; + } + if (!EventExists(offset)) + { + AddEvent(new NoteCommand { Note = (byte)n, OctaveChange = (sbyte)oct, Velocity = cmd, Duration = duration }); + } + } + else if (cmd >= 0x80 && cmd <= 0x8F) + { + lastRest = Utils.FixedRests[cmd - 0x80]; + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + } + else // 0x90-0xFF + { + // TODO: 0x95 - a rest that may or may not repeat depending on some condition within channels + // TODO: 0x9E - may or may not jump somewhere else depending on an unknown structure + switch (cmd) + { + case 0x90: + { + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x91: + { + lastRest = (uint)(lastRest + r.ReadSByte()); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x92: + { + lastRest = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x93: + { + lastRest = r.ReadUInt16(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x94: + { + lastRest = (uint)(r.ReadByte() | (r.ReadByte() << 8) | (r.ReadByte() << 16)); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x96: + case 0x97: + case 0x9A: + case 0x9B: + case 0x9F: + case 0xA2: + case 0xA3: + case 0xA6: + case 0xA7: + case 0xAD: + case 0xAE: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBD: + case 0xC1: + case 0xC2: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD9: + case 0xDA: + case 0xDE: + case 0xE6: + case 0xEB: + case 0xEE: + case 0xF4: + case 0xF5: + case 0xF7: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new InvalidCommand { Command = cmd }); + } + break; + } + case 0x98: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + cont = false; + break; + } + case 0x99: + { + if (!EventExists(offset)) + { + AddEvent(new LoopStartCommand { Offset = r.Stream.Position }); + } + break; + } + case 0xA0: + { + byte octave = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new OctaveSetCommand { Octave = octave }); + } + break; + } + case 0xA1: + { + sbyte change = r.ReadSByte(); + if (!EventExists(offset)) + { + AddEvent(new OctaveAddCommand { OctaveChange = change }); + } + break; + } + case 0xA4: + case 0xA5: // The code for these two is identical + { + byte tempoArg = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new TempoCommand { Command = cmd, Tempo = tempoArg }); + } + break; + } + case 0xAB: + { + byte[] bytes = new byte[1]; + r.ReadBytes(bytes); + if (!EventExists(offset)) + { + AddEvent(new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); + } + break; + } + case 0xAC: + { + byte voice = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = voice }); + } + break; + } + case 0xCB: + case 0xF8: + { + byte[] bytes = new byte[2]; + r.ReadBytes(bytes); + if (!EventExists(offset)) + { + AddEvent(new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); + } + break; + } + case 0xD7: + { + ushort bend = r.ReadUInt16(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = bend }); + } + break; + } + case 0xE0: + { + byte volume = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VolumeCommand { Volume = volume }); + } + break; + } + case 0xE3: + { + byte expression = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new ExpressionCommand { Expression = expression }); + } + break; + } + case 0xE8: + { + byte panArg = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); + } + break; + } + case 0x9D: + case 0xB0: + case 0xC0: + { + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = Array.Empty() }); + } + break; + } + case 0x9C: + case 0xA9: + case 0xAA: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB5: + case 0xB6: + case 0xBC: + case 0xBE: + case 0xBF: + case 0xC3: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xDB: + case 0xDF: + case 0xE1: + case 0xE7: + case 0xE9: + case 0xEF: + case 0xF6: + { + byte[] args = new byte[1]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xA8: + case 0xB4: + case 0xD3: + case 0xD5: + case 0xD6: + case 0xD8: + case 0xF2: + { + byte[] args = new byte[2]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xAF: + case 0xD4: + case 0xE2: + case 0xEA: + case 0xF3: + { + byte[] args = new byte[3]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xDD: + case 0xE5: + case 0xED: + case 0xF1: + { + byte[] args = new byte[4]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xDC: + case 0xE4: + case 0xEC: + case 0xF0: + { + byte[] args = new byte[5]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + default: throw new DSEInvalidCMDException(trackIndex, (int)offset, cmd); + } + } + } + r.Stream.Position = chunkStart + 0xC; + uint chunkLength = r.ReadUInt32(); + r.Stream.Position += chunkLength; + // Align 4 + while (r.Stream.Position % 4 != 0) + { + r.Stream.Position++; + } + } + SetTicks(); + } + } + public void SetCurrentPosition(long ticks) { - DSELoadedSong s = _loadedSong!; + if (_tracks is null) + { + SongEnded?.Invoke(); + return; + } - bool allDone = false; - while (!allDone && TempoStack >= 240) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - TempoStack -= 240; - allDone = true; - for (int i = 0; i < s.Tracks.Length; i++) + if (State == PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + while (true) { - TickTrack(s, s.Tracks[i], ref allDone); + if (ElapsedTicks == ticks) + { + goto finish; + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (!track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } + } + _tempoStack += _tempo; } - if (DMixer.IsFadeDone()) + finish: + for (int i = 0; i < _tracks.Length; i++) { - allDone = true; + _tracks[i].StopAllChannels(); } + Pause(); } - if (!allDone) + } + public void Play() + { + if (_tracks == null) { - TempoStack += Tempo; + SongEnded?.Invoke(); + return; + } + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) + { + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } - DMixer.ChannelTick(); - DMixer.Process(playing, recording); - return allDone; } - private void TickTrack(DSELoadedSong s, DSETrack track, ref bool allDone) + public void Pause() { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) + if (State == PlayerState.Playing) { - s.ExecuteNext(track); + State = PlayerState.Paused; + WaitThread(); } - if (track.Index == s.LongestTrack) + else if (State is PlayerState.Paused or PlayerState.Stopped) { - HandleTicksAndLoop(s, track); + State = PlayerState.Playing; + CreateThread(); } - if (!track.Stopped || track.Channels.Count != 0) + } + public void Stop() + { + if (State is PlayerState.Playing or PlayerState.Paused) { - allDone = false; + State = PlayerState.Stopped; + WaitThread(); } } - private void HandleTicksAndLoop(DSELoadedSong s, DSETrack track) + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() { - if (ElapsedTicks != s.MaxTicks) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - ElapsedTicks++; - return; + State = PlayerState.ShutDown; + WaitThread(); + } + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + SongState.Track tin = info.Tracks[trackIndex]; + tin.Position = track.CurOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.Type = "PCM"; + tin.Volume = track.Volume; + tin.PitchBend = track.PitchBend; + tin.Extra = track.Octave; + tin.Panpot = track.Panpot; + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + //tin.Type = string.Empty; + } + else + { + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (!Utils.IsStateRemovable(c.State)) + { + tin.Keys[numKeys++] = c.Key; + } + float a = (float)(-c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > left) + { + left = a; + } + a = (float)(c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > right) + { + right = a; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; + //tin.Type = string.Join(", ", channels.Select(c => c.State.ToString())); + } } + } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + private void ExecuteNext(Track track) + { + byte cmd = _smdFile[track.CurOffset++]; + if (cmd <= 0x7F) { - return; + byte arg = _smdFile[track.CurOffset++]; + int numParams = (arg & 0xC0) >> 6; + int oct = ((arg & 0x30) >> 4) - 2; + int n = arg & 0xF; + if (n >= 12) + { + throw new DSEInvalidNoteException(track.Index, track.CurOffset - 2, n); + } + + uint duration; + if (numParams == 0) + { + duration = track.LastNoteDuration; + } + else + { + duration = 0; + for (int b = 0; b < numParams; b++) + { + duration = (duration << 8) | _smdFile[track.CurOffset++]; + } + track.LastNoteDuration = duration; + } + Channel? channel = _mixer.AllocateChannel(); + if (channel is null) + { + throw new Exception("Not enough channels"); + } + + channel.Stop(); + track.Octave = (byte)(track.Octave + oct); + if (channel.StartPCM(_localSWD, _masterSWD, track.Voice, n + (12 * track.Octave), duration)) + { + channel.NoteVelocity = cmd; + channel.Owner = track; + track.Channels.Add(channel); + } } + else if (cmd >= 0x80 && cmd <= 0x8F) + { + track.LastRest = Utils.FixedRests[cmd - 0x80]; + track.Rest = track.LastRest; + } + else // 0x90-0xFF + { + // TODO: 0x95, 0x9E + switch (cmd) + { + case 0x90: + { + track.Rest = track.LastRest; + break; + } + case 0x91: + { + track.LastRest = (uint)(track.LastRest + (sbyte)_smdFile[track.CurOffset++]); + track.Rest = track.LastRest; + break; + } + case 0x92: + { + track.LastRest = _smdFile[track.CurOffset++]; + track.Rest = track.LastRest; + break; + } + case 0x93: + { + track.LastRest = (uint)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8)); + track.Rest = track.LastRest; + break; + } + case 0x94: + { + track.LastRest = (uint)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8) | (_smdFile[track.CurOffset++] << 16)); + track.Rest = track.LastRest; + break; + } + case 0x96: + case 0x97: + case 0x9A: + case 0x9B: + case 0x9F: + case 0xA2: + case 0xA3: + case 0xA6: + case 0xA7: + case 0xAD: + case 0xAE: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBD: + case 0xC1: + case 0xC2: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD9: + case 0xDA: + case 0xDE: + case 0xE6: + case 0xEB: + case 0xEE: + case 0xF4: + case 0xF5: + case 0xF7: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + { + track.Stopped = true; + break; + } + case 0x98: + { + if (track.LoopOffset == -1) + { + track.Stopped = true; + } + else + { + track.CurOffset = track.LoopOffset; + } + break; + } + case 0x99: + { + track.LoopOffset = track.CurOffset; + break; + } + case 0xA0: + { + track.Octave = _smdFile[track.CurOffset++]; + break; + } + case 0xA1: + { + track.Octave = (byte)(track.Octave + (sbyte)_smdFile[track.CurOffset++]); + break; + } + case 0xA4: + case 0xA5: + { + _tempo = _smdFile[track.CurOffset++]; + break; + } + case 0xAB: + { + track.CurOffset++; + break; + } + case 0xAC: + { + track.Voice = _smdFile[track.CurOffset++]; + break; + } + case 0xCB: + case 0xF8: + { + track.CurOffset += 2; + break; + } + case 0xD7: + { + track.PitchBend = (ushort)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8)); + break; + } + case 0xE0: + { + track.Volume = _smdFile[track.CurOffset++]; + break; + } + case 0xE3: + { + track.Expression = _smdFile[track.CurOffset++]; + break; + } + case 0xE8: + { + track.Panpot = (sbyte)(_smdFile[track.CurOffset++] - 0x40); + break; + } + case 0x9D: + case 0xB0: + case 0xC0: + { + break; + } + case 0x9C: + case 0xA9: + case 0xAA: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB5: + case 0xB6: + case 0xBC: + case 0xBE: + case 0xBF: + case 0xC3: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xDB: + case 0xDF: + case 0xE1: + case 0xE7: + case 0xE9: + case 0xEF: + case 0xF6: + { + track.CurOffset++; + break; + } + case 0xA8: + case 0xB4: + case 0xD3: + case 0xD5: + case 0xD6: + case 0xD8: + case 0xF2: + { + track.CurOffset += 2; + break; + } + case 0xAF: + case 0xD4: + case 0xE2: + case 0xEA: + case 0xF3: + { + track.CurOffset += 3; + break; + } + case 0xDD: + case 0xE5: + case 0xED: + case 0xF1: + { + track.CurOffset += 4; + break; + } + case 0xDC: + case 0xE4: + case 0xEC: + case 0xF0: + { + track.CurOffset += 5; + break; + } + default: throw new DSEInvalidCMDException(track.Index, track.CurOffset - 1, cmd); + } + } + } - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.CurOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !DMixer.IsFading()) + private void Tick() + { + _time.Start(); + while (true) { - DMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + bool allDone = true; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.CurOffset) + { + ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (!track.Stopped || track.Channels.Count != 0) + { + allDone = false; + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/NDS/DSE/DSETrack.cs b/VG Music Studio - Core/NDS/DSE/DSETrack.cs deleted file mode 100644 index a15e380..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSETrack.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class DSETrack -{ - public readonly byte Index; - private readonly int _startOffset; - public byte Octave; - public byte Voice; - public byte Expression; - public byte Volume; - public sbyte Panpot; - public uint Rest; - public ushort PitchBend; - public int CurOffset; - public int LoopOffset; - public bool Stopped; - public uint LastNoteDuration; - public uint LastRest; - - public readonly List Channels = new(0x10); - - public DSETrack(byte i, int startOffset) - { - Index = i; - _startOffset = startOffset; - } - - public void Init() - { - Expression = 0; - Voice = 0; - Volume = 0; - Octave = 4; - Panpot = 0; - Rest = 0; - PitchBend = 0; - CurOffset = _startOffset; - LoopOffset = -1; - Stopped = false; - LastNoteDuration = 0; - LastRest = 0; - StopAllChannels(); - } - - public void Tick() - { - if (Rest > 0) - { - Rest--; - } - for (int i = 0; i < Channels.Count; i++) - { - DSEChannel c = Channels[i]; - if (c.NoteLength > 0) - { - c.NoteLength--; - } - } - } - - public void StopAllChannels() - { - DSEChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - - public void UpdateSongState(SongState.Track tin) - { - tin.Position = CurOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.Type = "PCM"; - tin.Volume = Volume; - tin.PitchBend = PitchBend; - tin.Extra = Octave; - tin.Panpot = Panpot; - - DSEChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - //tin.Type = string.Empty; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - DSEChannel c = channels[j]; - if (!DSEUtils.IsStateRemovable(c.State)) - { - tin.Keys[numKeys++] = c.Key; - } - float a = (float)(-c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > left) - { - left = a; - } - a = (float)(c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > right) - { - right = a; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - //tin.Type = string.Join(", ", channels.Select(c => c.State.ToString())); - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEUtils.cs b/VG Music Studio - Core/NDS/DSE/DSEUtils.cs deleted file mode 100644 index 349c009..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEUtils.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal static class DSEUtils -{ - public static short[] Duration16 = new short[128] - { - 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, - 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, - 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, - 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, - 0x0020, 0x0023, 0x0028, 0x002D, 0x0033, 0x0039, 0x0040, 0x0048, - 0x0050, 0x0058, 0x0062, 0x006D, 0x0078, 0x0083, 0x0090, 0x009E, - 0x00AC, 0x00BC, 0x00CC, 0x00DE, 0x00F0, 0x0104, 0x0119, 0x012F, - 0x0147, 0x0160, 0x017A, 0x0196, 0x01B3, 0x01D2, 0x01F2, 0x0214, - 0x0238, 0x025E, 0x0285, 0x02AE, 0x02D9, 0x0307, 0x0336, 0x0367, - 0x039B, 0x03D1, 0x0406, 0x0442, 0x047E, 0x04C4, 0x0500, 0x0546, - 0x058C, 0x0622, 0x0672, 0x06CC, 0x071C, 0x0776, 0x07DA, 0x0834, - 0x0898, 0x0906, 0x096A, 0x09D8, 0x0A50, 0x0ABE, 0x0B40, 0x0BB8, - 0x0C3A, 0x0CBC, 0x0D48, 0x0DDE, 0x0E6A, 0x0F00, 0x0FA0, 0x1040, - 0x10EA, 0x1194, 0x123E, 0x12F2, 0x13B0, 0x146E, 0x1536, 0x15FE, - 0x16D0, 0x17A2, 0x187E, 0x195A, 0x1A40, 0x1B30, 0x1C20, 0x1D1A, - 0x1E1E, 0x1F22, 0x2030, 0x2148, 0x2260, 0x2382, 0x2710, 0x7FFF, - }; - public static int[] Duration32 = new int[128] - { - 0x00000000, 0x00000004, 0x00000007, 0x0000000A, 0x0000000F, 0x00000015, 0x0000001C, 0x00000024, - 0x0000002E, 0x0000003A, 0x00000048, 0x00000057, 0x00000068, 0x0000007B, 0x00000091, 0x000000A8, - 0x00000185, 0x000001BE, 0x000001FC, 0x0000023F, 0x00000288, 0x000002D6, 0x0000032A, 0x00000385, - 0x000003E5, 0x0000044C, 0x000004BA, 0x0000052E, 0x000005A9, 0x0000062C, 0x000006B5, 0x00000746, - 0x00000BCF, 0x00000CC0, 0x00000DBD, 0x00000EC6, 0x00000FDC, 0x000010FF, 0x0000122F, 0x0000136C, - 0x000014B6, 0x0000160F, 0x00001775, 0x000018EA, 0x00001A6D, 0x00001BFF, 0x00001DA0, 0x00001F51, - 0x00002C16, 0x00002E80, 0x00003100, 0x00003395, 0x00003641, 0x00003902, 0x00003BDB, 0x00003ECA, - 0x000041D0, 0x000044EE, 0x00004824, 0x00004B73, 0x00004ED9, 0x00005259, 0x000055F2, 0x000059A4, - 0x000074CC, 0x000079AB, 0x00007EAC, 0x000083CE, 0x00008911, 0x00008E77, 0x000093FF, 0x000099AA, - 0x00009F78, 0x0000A56A, 0x0000AB80, 0x0000B1BB, 0x0000B81A, 0x0000BE9E, 0x0000C547, 0x0000CC17, - 0x0000FD42, 0x000105CB, 0x00010E82, 0x00011768, 0x0001207E, 0x000129C4, 0x0001333B, 0x00013CE2, - 0x000146BB, 0x000150C5, 0x00015B02, 0x00016572, 0x00017015, 0x00017AEB, 0x000185F5, 0x00019133, - 0x0001E16D, 0x0001EF07, 0x0001FCE0, 0x00020AF7, 0x0002194F, 0x000227E6, 0x000236BE, 0x000245D7, - 0x00025532, 0x000264CF, 0x000274AE, 0x000284D0, 0x00029536, 0x0002A5E0, 0x0002B6CE, 0x0002C802, - 0x000341B0, 0x000355F8, 0x00036A90, 0x00037F79, 0x000394B4, 0x0003AA41, 0x0003C021, 0x0003D654, - 0x0003ECDA, 0x000403B5, 0x00041AE5, 0x0004326A, 0x00044A45, 0x00046277, 0x00047B00, 0x7FFFFFFF, - }; - public static readonly byte[] FixedRests = new byte[0x10] - { - 96, 72, 64, 48, 36, 32, 24, 18, 16, 12, 9, 8, 6, 4, 3, 2, - }; - - public static bool IsStateRemovable(EnvelopeState state) - { - return state == EnvelopeState.Two || state >= EnvelopeState.Seven; - } -} diff --git a/VG Music Studio - Core/NDS/DSE/Enums.cs b/VG Music Studio - Core/NDS/DSE/Enums.cs new file mode 100644 index 0000000..6cec60d --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Enums.cs @@ -0,0 +1,22 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal enum EnvelopeState : byte + { + Zero = 0, + One = 1, + Two = 2, + Hold = 3, + Decay = 4, + Decay2 = 5, + Six = 6, + Seven = 7, + Eight = 8 + } + + internal enum SampleFormat : ushort + { + PCM8 = 0x000, + PCM16 = 0x100, + ADPCM = 0x200 + } +} diff --git a/VG Music Studio - Core/NDS/DSE/SMD.cs b/VG Music Studio - Core/NDS/DSE/SMD.cs index 33cd44f..5383c4d 100644 --- a/VG Music Studio - Core/NDS/DSE/SMD.cs +++ b/VG Music Studio - Core/NDS/DSE/SMD.cs @@ -1,60 +1,61 @@ using Kermalis.EndianBinaryIO; -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class SMD +namespace Kermalis.VGMusicStudio.Core.NDS.DSE { - public sealed class Header // Size 0x40 + internal sealed class SMD { - [BinaryStringFixedLength(4)] - public string Type { get; set; } // "smdb" or "smdl" - [BinaryArrayFixedLength(4)] - public byte[] Unknown1 { get; set; } - public uint Length { get; set; } - public ushort Version { get; set; } - [BinaryArrayFixedLength(10)] - public byte[] Unknown2 { get; set; } - public ushort Year { get; set; } - public byte Month { get; set; } - public byte Day { get; set; } - public byte Hour { get; set; } - public byte Minute { get; set; } - public byte Second { get; set; } - public byte Centisecond { get; set; } - [BinaryStringFixedLength(16)] - public string Label { get; set; } - [BinaryArrayFixedLength(16)] - public byte[] Unknown3 { get; set; } - } + public sealed class Header + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } // "smdb" or "smdl" + [BinaryArrayFixedLength(4)] + public byte[] Unknown1 { get; set; } + public uint Length { get; set; } + public ushort Version { get; set; } + [BinaryArrayFixedLength(10)] + public byte[] Unknown2 { get; set; } + public ushort Year { get; set; } + public byte Month { get; set; } + public byte Day { get; set; } + public byte Hour { get; set; } + public byte Minute { get; set; } + public byte Second { get; set; } + public byte Centisecond { get; set; } + [BinaryStringFixedLength(16)] + public string Label { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown3 { get; set; } + } - public interface ISongChunk - { - byte NumTracks { get; } - } - public sealed class SongChunk_V402 : ISongChunk // Size 0x20 - { - [BinaryStringFixedLength(4)] - public string Type { get; set; } - [BinaryArrayFixedLength(16)] - public byte[] Unknown1 { get; set; } - public byte NumTracks { get; set; } - public byte NumChannels { get; set; } - [BinaryArrayFixedLength(4)] - public byte[] Unknown2 { get; set; } - public sbyte MasterVolume { get; set; } - public sbyte MasterPanpot { get; set; } - [BinaryArrayFixedLength(4)] - public byte[] Unknown3 { get; set; } - } - public sealed class SongChunk_V415 : ISongChunk // Size 0x40 - { - [BinaryStringFixedLength(4)] - public string Type { get; set; } - [BinaryArrayFixedLength(18)] - public byte[] Unknown1 { get; set; } - public byte NumTracks { get; set; } - public byte NumChannels { get; set; } - [BinaryArrayFixedLength(40)] - public byte[] Unknown2 { get; set; } + public interface ISongChunk + { + byte NumTracks { get; } + } + public sealed class SongChunk_V402 : ISongChunk + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown1 { get; set; } + public byte NumTracks { get; set; } + public byte NumChannels { get; set; } + [BinaryArrayFixedLength(4)] + public byte[] Unknown2 { get; set; } + public sbyte MasterVolume { get; set; } + public sbyte MasterPanpot { get; set; } + [BinaryArrayFixedLength(4)] + public byte[] Unknown3 { get; set; } + } + public sealed class SongChunk_V415 : ISongChunk + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } + [BinaryArrayFixedLength(18)] + public byte[] Unknown1 { get; set; } + public byte NumTracks { get; set; } + public byte NumChannels { get; set; } + [BinaryArrayFixedLength(40)] + public byte[] Unknown2 { get; set; } + } } } diff --git a/VG Music Studio - Core/NDS/DSE/SWD.cs b/VG Music Studio - Core/NDS/DSE/SWD.cs index 0b042fb..17c08ef 100644 --- a/VG Music Studio - Core/NDS/DSE/SWD.cs +++ b/VG Music Studio - Core/NDS/DSE/SWD.cs @@ -1,7 +1,5 @@ using Kermalis.EndianBinaryIO; -using Kermalis.VGMusicStudio.Core.Util; using System; -using System.Diagnostics; using System.IO; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; @@ -10,11 +8,11 @@ internal sealed class SWD { public interface IHeader { - // + } - private sealed class Header_V402 : IHeader // Size 0x40 + private class Header_V402 : IHeader { - [BinaryArrayFixedLength(8)] + [BinaryArrayFixedLength(10)] public byte[] Unknown1 { get; set; } public ushort Year { get; set; } public byte Month { get; set; } @@ -33,9 +31,9 @@ private sealed class Header_V402 : IHeader // Size 0x40 [BinaryArrayFixedLength(7)] public byte[] Padding { get; set; } } - private sealed class Header_V415 : IHeader // Size 0x40 + private class Header_V415 : IHeader { - [BinaryArrayFixedLength(8)] + [BinaryArrayFixedLength(10)] public byte[] Unknown1 { get; set; } public ushort Year { get; set; } public byte Month { get; set; } @@ -73,7 +71,7 @@ public interface ISplitEntry byte Decay2 { get; set; } byte Release { get; set; } } - public sealed class SplitEntry_V402 : ISplitEntry // Size 0x30 + public class SplitEntry_V402 : ISplitEntry { public ushort Id { get; set; } [BinaryArrayFixedLength(2)] @@ -107,10 +105,9 @@ public sealed class SplitEntry_V402 : ISplitEntry // Size 0x30 public byte Release { get; set; } public byte Unknown5 { get; set; } - [BinaryIgnore] int ISplitEntry.SampleId => SampleId; } - public sealed class SplitEntry_V415 : ISplitEntry // 0x30 + public class SplitEntry_V415 : ISplitEntry { public ushort Id { get; set; } [BinaryArrayFixedLength(2)] @@ -144,7 +141,6 @@ public sealed class SplitEntry_V415 : ISplitEntry // 0x30 public byte Release { get; set; } public byte Unknown5 { get; set; } - [BinaryIgnore] int ISplitEntry.SampleId => SampleId; } @@ -152,7 +148,7 @@ public interface IProgramInfo { ISplitEntry[] SplitEntries { get; } } - public sealed class ProgramInfo_V402 : IProgramInfo + public class ProgramInfo_V402 : IProgramInfo { public byte Id { get; set; } public byte NumSplits { get; set; } @@ -175,7 +171,7 @@ public sealed class ProgramInfo_V402 : IProgramInfo [BinaryIgnore] ISplitEntry[] IProgramInfo.SplitEntries => SplitEntries; } - public sealed class ProgramInfo_V415 : IProgramInfo + public class ProgramInfo_V415 : IProgramInfo { public ushort Id { get; set; } public ushort NumSplits { get; set; } @@ -199,7 +195,7 @@ public sealed class ProgramInfo_V415 : IProgramInfo public interface IWavInfo { - byte RootNote { get; } + byte RootKey { get; } sbyte Transpose { get; } SampleFormat SampleFormat { get; } bool Loop { get; } @@ -216,13 +212,13 @@ public interface IWavInfo byte Decay2 { get; } byte Release { get; } } - public sealed class WavInfo_V402 : IWavInfo // Size 0x40 + public class WavInfo_V402 : IWavInfo { public byte Unknown1 { get; set; } public byte Id { get; set; } [BinaryArrayFixedLength(2)] public byte[] Unknown2 { get; set; } - public byte RootNote { get; set; } + public byte RootKey { get; set; } public sbyte Transpose { get; set; } public byte Volume { get; set; } public sbyte Panpot { get; set; } @@ -249,14 +245,14 @@ public sealed class WavInfo_V402 : IWavInfo // Size 0x40 public byte Release { get; set; } public byte Unknown6 { get; set; } } - public sealed class WavInfo_V415 : IWavInfo // 0x40 + public class WavInfo_V415 : IWavInfo { [BinaryArrayFixedLength(2)] public byte[] Unknown1 { get; set; } public ushort Id { get; set; } [BinaryArrayFixedLength(2)] public byte[] Unknown2 { get; set; } - public byte RootNote { get; set; } + public byte RootKey { get; set; } public sbyte Transpose { get; set; } public byte Volume { get; set; } public sbyte Panpot { get; set; } @@ -297,38 +293,30 @@ public class SampleBlock } public class ProgramBank { - public IProgramInfo?[] ProgramInfos; + public IProgramInfo[] ProgramInfos; public KeyGroup[] KeyGroups; } - public class KeyGroup // Size 0x8 + public class KeyGroup { public ushort Id { get; set; } public byte Poly { get; set; } public byte Priority { get; set; } - public byte LowNote { get; set; } - public byte HighNote { get; set; } - public ushort Unknown { get; set; } + public byte Low { get; set; } + public byte High { get; set; } + [BinaryArrayFixedLength(2)] + public byte[] Unknown { get; set; } } - public sealed class LFOInfo + public class LFOInfo { - public byte Unknown1 { get; set; } - public byte HasData { get; set; } - public byte Type { get; set; } // LFOType enum - public byte CallbackType { get; set; } - public uint Unknown4 { get; set; } - public ushort Unknown8 { get; set; } - public ushort UnknownA { get; set; } - public ushort UnknownC { get; set; } - public byte UnknownE { get; set; } - public byte UnknownF { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown { get; set; } } public string Type; // "swdb" or "swdl" - public byte[] Unknown1; + public byte[] Unknown; public uint Length; public ushort Version; public IHeader Header; - public byte[] Unknown2; public ProgramBank Programs; public SampleBlock[] Samples; @@ -339,12 +327,10 @@ public SWD(string path) { var r = new EndianBinaryReader(stream, ascii: true); Type = r.ReadString_Count(4); - Unknown1 = new byte[4]; - r.ReadBytes(Unknown1); + Unknown = new byte[4]; + r.ReadBytes(Unknown); Length = r.ReadUInt32(); Version = r.ReadUInt16(); - Unknown2 = new byte[2]; - r.ReadBytes(Unknown2); switch (Version) { case 0x402: @@ -394,11 +380,14 @@ private static long FindChunk(EndianBinaryReader r, string chunk) } default: { - Debug.WriteLine($"Ignoring {str} chunk"); r.Stream.Position += 0x8; uint length = r.ReadUInt32(); r.Stream.Position += length; - r.Stream.Align(4); + // Align 4 + while (r.Stream.Position % 4 != 0) + { + r.Stream.Position++; + } break; } } @@ -449,7 +438,7 @@ private static long FindChunk(EndianBinaryReader r, string chunk) } chunkOffset += 0x10; - var programInfos = new IProgramInfo?[numPRGISlots]; + var programInfos = new IProgramInfo[numPRGISlots]; for (int i = 0; i < programInfos.Length; i++) { r.Stream.Position = chunkOffset + (2 * i); @@ -473,14 +462,16 @@ private static KeyGroup[] ReadKeyGroups(EndianBinaryReader r) { return Array.Empty(); } - - r.Stream.Position = chunkOffset + 0xC; - uint chunkLength = r.ReadUInt32(); - var keyGroups = new KeyGroup[chunkLength / 8]; // 8 is the size of a KeyGroup - for (int i = 0; i < keyGroups.Length; i++) + else { - keyGroups[i] = r.ReadObject(); + r.Stream.Position = chunkOffset + 0xC; + uint chunkLength = r.ReadUInt32(); + var keyGroups = new KeyGroup[chunkLength / 8]; // 8 is the size of a KeyGroup + for (int i = 0; i < keyGroups.Length; i++) + { + keyGroups[i] = r.ReadObject(); + } + return keyGroups; } - return keyGroups; } } diff --git a/VG Music Studio - Core/NDS/DSE/Track.cs b/VG Music Studio - Core/NDS/DSE/Track.cs new file mode 100644 index 0000000..ba0a7c6 --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Track.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.NDS.DSE; + +internal sealed class Track +{ + public readonly byte Index; + private readonly int _startOffset; + public byte Octave; + public byte Voice; + public byte Expression; + public byte Volume; + public sbyte Panpot; + public uint Rest; + public ushort PitchBend; + public int CurOffset; + public int LoopOffset; + public bool Stopped; + public uint LastNoteDuration; + public uint LastRest; + + public readonly List Channels = new(0x10); + + public Track(byte i, int startOffset) + { + Index = i; + _startOffset = startOffset; + } + + public void Init() + { + Expression = 0; + Voice = 0; + Volume = 0; + Octave = 4; + Panpot = 0; + Rest = 0; + PitchBend = 0; + CurOffset = _startOffset; + LoopOffset = -1; + Stopped = false; + LastNoteDuration = 0; + LastRest = 0; + StopAllChannels(); + } + + public void Tick() + { + if (Rest > 0) + { + Rest--; + } + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + if (c.NoteLength > 0) + { + c.NoteLength--; + } + } + } + + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } +} diff --git a/VG Music Studio - Core/NDS/DSE/Utils.cs b/VG Music Studio - Core/NDS/DSE/Utils.cs new file mode 100644 index 0000000..1f16b1a --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Utils.cs @@ -0,0 +1,53 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal static class Utils + { + public static short[] Duration16 = new short[128] + { + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, + 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, + 0x0020, 0x0023, 0x0028, 0x002D, 0x0033, 0x0039, 0x0040, 0x0048, + 0x0050, 0x0058, 0x0062, 0x006D, 0x0078, 0x0083, 0x0090, 0x009E, + 0x00AC, 0x00BC, 0x00CC, 0x00DE, 0x00F0, 0x0104, 0x0119, 0x012F, + 0x0147, 0x0160, 0x017A, 0x0196, 0x01B3, 0x01D2, 0x01F2, 0x0214, + 0x0238, 0x025E, 0x0285, 0x02AE, 0x02D9, 0x0307, 0x0336, 0x0367, + 0x039B, 0x03D1, 0x0406, 0x0442, 0x047E, 0x04C4, 0x0500, 0x0546, + 0x058C, 0x0622, 0x0672, 0x06CC, 0x071C, 0x0776, 0x07DA, 0x0834, + 0x0898, 0x0906, 0x096A, 0x09D8, 0x0A50, 0x0ABE, 0x0B40, 0x0BB8, + 0x0C3A, 0x0CBC, 0x0D48, 0x0DDE, 0x0E6A, 0x0F00, 0x0FA0, 0x1040, + 0x10EA, 0x1194, 0x123E, 0x12F2, 0x13B0, 0x146E, 0x1536, 0x15FE, + 0x16D0, 0x17A2, 0x187E, 0x195A, 0x1A40, 0x1B30, 0x1C20, 0x1D1A, + 0x1E1E, 0x1F22, 0x2030, 0x2148, 0x2260, 0x2382, 0x2710, 0x7FFF + }; + public static int[] Duration32 = new int[128] + { + 0x00000000, 0x00000004, 0x00000007, 0x0000000A, 0x0000000F, 0x00000015, 0x0000001C, 0x00000024, + 0x0000002E, 0x0000003A, 0x00000048, 0x00000057, 0x00000068, 0x0000007B, 0x00000091, 0x000000A8, + 0x00000185, 0x000001BE, 0x000001FC, 0x0000023F, 0x00000288, 0x000002D6, 0x0000032A, 0x00000385, + 0x000003E5, 0x0000044C, 0x000004BA, 0x0000052E, 0x000005A9, 0x0000062C, 0x000006B5, 0x00000746, + 0x00000BCF, 0x00000CC0, 0x00000DBD, 0x00000EC6, 0x00000FDC, 0x000010FF, 0x0000122F, 0x0000136C, + 0x000014B6, 0x0000160F, 0x00001775, 0x000018EA, 0x00001A6D, 0x00001BFF, 0x00001DA0, 0x00001F51, + 0x00002C16, 0x00002E80, 0x00003100, 0x00003395, 0x00003641, 0x00003902, 0x00003BDB, 0x00003ECA, + 0x000041D0, 0x000044EE, 0x00004824, 0x00004B73, 0x00004ED9, 0x00005259, 0x000055F2, 0x000059A4, + 0x000074CC, 0x000079AB, 0x00007EAC, 0x000083CE, 0x00008911, 0x00008E77, 0x000093FF, 0x000099AA, + 0x00009F78, 0x0000A56A, 0x0000AB80, 0x0000B1BB, 0x0000B81A, 0x0000BE9E, 0x0000C547, 0x0000CC17, + 0x0000FD42, 0x000105CB, 0x00010E82, 0x00011768, 0x0001207E, 0x000129C4, 0x0001333B, 0x00013CE2, + 0x000146BB, 0x000150C5, 0x00015B02, 0x00016572, 0x00017015, 0x00017AEB, 0x000185F5, 0x00019133, + 0x0001E16D, 0x0001EF07, 0x0001FCE0, 0x00020AF7, 0x0002194F, 0x000227E6, 0x000236BE, 0x000245D7, + 0x00025532, 0x000264CF, 0x000274AE, 0x000284D0, 0x00029536, 0x0002A5E0, 0x0002B6CE, 0x0002C802, + 0x000341B0, 0x000355F8, 0x00036A90, 0x00037F79, 0x000394B4, 0x0003AA41, 0x0003C021, 0x0003D654, + 0x0003ECDA, 0x000403B5, 0x00041AE5, 0x0004326A, 0x00044A45, 0x00046277, 0x00047B00, 0x7FFFFFFF + }; + public static readonly byte[] FixedRests = new byte[0x10] + { + 96, 72, 64, 48, 36, 32, 24, 18, 16, 12, 9, 8, 6, 4, 3, 2 + }; + + public static bool IsStateRemovable(EnvelopeState state) + { + return state == EnvelopeState.Two || state >= EnvelopeState.Seven; + } + } +} diff --git a/VG Music Studio - Core/NDS/NDSUtils.cs b/VG Music Studio - Core/NDS/NDSUtils.cs deleted file mode 100644 index 2bfd9b5..0000000 --- a/VG Music Studio - Core/NDS/NDSUtils.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS; - -internal static class NDSUtils -{ - public const int ARM7_CLOCK = 16_756_991; // (33.513982 MHz / 2) == 16.756991 MHz == 16,756,991 Hz -} diff --git a/VG Music Studio - Core/NDS/SDAT/Channel.cs b/VG Music Studio - Core/NDS/SDAT/Channel.cs new file mode 100644 index 0000000..742a839 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Channel.cs @@ -0,0 +1,391 @@ +using System; + +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal sealed class Channel + { + public readonly byte Index; + + public Track? Owner; + public InstrumentType Type; + public EnvelopeState State; + public bool AutoSweep; + public byte BaseNote; + public byte Note; + public byte NoteVelocity; + public sbyte StartingPan; + public sbyte Pan; + public int SweepCounter; + public int SweepLength; + public short SweepPitch; + public int Velocity; // The SEQ Player treats 0 as the 100% amplitude value and -92544 (-723*128) as the 0% amplitude value. The starting ampltitude is 0% (-92544). + public byte Volume; // From 0x00-0x7F (Calculated from Utils) + public ushort BaseTimer; + public ushort Timer; + public int NoteDuration; + + private byte _attack; + private int _sustain; + private ushort _decay; + private ushort _release; + public byte LFORange; + public byte LFOSpeed; + public byte LFODepth; + public ushort LFODelay; + public ushort LFOPhase; + public int LFOParam; + public ushort LFODelayCount; + public LFOType LFOType; + public byte Priority; + + private int _pos; + private short _prevLeft; + private short _prevRight; + + // PCM8, PCM16, ADPCM + private SWAR.SWAV _swav; + // PCM8, PCM16 + private int _dataOffset; + // ADPCM + private ADPCMDecoder _adpcmDecoder; + private short _adpcmLoopLastSample; + private short _adpcmLoopStepIndex; + // PSG + private byte _psgDuty; + private int _psgCounter; + // Noise + private ushort _noiseCounter; + + public Channel(byte i) + { + Index = i; + } + + public void StartPCM(SWAR.SWAV swav, int noteDuration) + { + Type = InstrumentType.PCM; + _dataOffset = 0; + _swav = swav; + if (swav.Format == SWAVFormat.ADPCM) + { + _adpcmDecoder = new ADPCMDecoder(swav.Samples); + } + BaseTimer = swav.Timer; + Start(noteDuration); + } + public void StartPSG(byte duty, int noteDuration) + { + Type = InstrumentType.PSG; + _psgCounter = 0; + _psgDuty = duty; + BaseTimer = 8006; + Start(noteDuration); + } + public void StartNoise(int noteLength) + { + Type = InstrumentType.Noise; + _noiseCounter = 0x7FFF; + BaseTimer = 8006; + Start(noteLength); + } + + private void Start(int noteDuration) + { + State = EnvelopeState.Attack; + Velocity = -92544; + _pos = 0; + _prevLeft = _prevRight = 0; + NoteDuration = noteDuration; + } + + public void Stop() + { + if (Owner is not null) + { + Owner.Channels.Remove(this); + } + Owner = null; + Volume = 0; + Priority = 0; + } + + public int SweepMain() + { + if (SweepPitch == 0 || SweepCounter >= SweepLength) + { + return 0; + } + + int sweep = (int)(Math.BigMul(SweepPitch, SweepLength - SweepCounter) / SweepLength); + if (AutoSweep) + { + SweepCounter++; + } + return sweep; + } + public void LFOTick() + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + else + { + int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; + if (LFOType == LFOType.Volume) + { + param = (param * 60) >> 14; + } + else + { + param >>= 8; + } + LFOParam = param; + int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" + while (counter >= 0x8000) + { + counter -= 0x8000; + } + LFOPhase = (ushort)counter; + } + } + + public void SetAttack(int a) + { + _attack = SDATUtils.AttackTable[a]; + } + public void SetDecay(int d) + { + _decay = SDATUtils.DecayTable[d]; + } + public void SetSustain(byte s) + { + _sustain = SDATUtils.SustainTable[s]; + } + public void SetRelease(int r) + { + _release = SDATUtils.DecayTable[r]; + } + public void StepEnvelope() + { + switch (State) + { + case EnvelopeState.Attack: + { + Velocity = _attack * Velocity / 0xFF; + if (Velocity == 0) + { + State = EnvelopeState.Decay; + } + break; + } + case EnvelopeState.Decay: + { + Velocity -= _decay; + if (Velocity <= _sustain) + { + State = EnvelopeState.Sustain; + Velocity = _sustain; + } + break; + } + case EnvelopeState.Release: + { + Velocity -= _release; + if (Velocity < -92544) + { + Velocity = -92544; + } + break; + } + } + } + + /// EmulateProcess doesn't care about samples that loop; it only cares about ones that force the track to wait for them to end + public void EmulateProcess() + { + if (Timer == 0) + { + return; + } + + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + for (int i = 0; i < numSamples; i++) + { + if (Type == InstrumentType.PCM && !_swav.DoesLoop) + { + switch (_swav.Format) + { + case SWAVFormat.PCM8: + { + if (_dataOffset >= _swav.Samples.Length) + { + Stop(); + } + else + { + _dataOffset++; + } + return; + } + case SWAVFormat.PCM16: + { + if (_dataOffset >= _swav.Samples.Length) + { + Stop(); + } + else + { + _dataOffset += 2; + } + return; + } + case SWAVFormat.ADPCM: + { + if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) + { + Stop(); + } + else + { + // This is a faster emulation of adpcmDecoder.GetSample() without caring about the sample + if (_adpcmDecoder.OnSecondNibble) + { + _adpcmDecoder.DataOffset++; + } + _adpcmDecoder.OnSecondNibble = !_adpcmDecoder.OnSecondNibble; + } + return; + } + } + } + } + } + public void Process(out short left, out short right) + { + if (Timer == 0) + { + left = _prevLeft; + right = _prevRight; + return; + } + + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + // numSamples can be 0 + for (int i = 0; i < numSamples; i++) + { + short samp; + switch (Type) + { + case InstrumentType.PCM: + { + switch (_swav.Format) + { + case SWAVFormat.PCM8: + { + // If hit end + if (_dataOffset >= _swav.Samples.Length) + { + if (_swav.DoesLoop) + { + _dataOffset = _swav.LoopOffset * 4; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)((sbyte)_swav.Samples[_dataOffset++] << 8); + break; + } + case SWAVFormat.PCM16: + { + // If hit end + if (_dataOffset >= _swav.Samples.Length) + { + if (_swav.DoesLoop) + { + _dataOffset = _swav.LoopOffset * 4; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)(_swav.Samples[_dataOffset++] | (_swav.Samples[_dataOffset++] << 8)); + break; + } + case SWAVFormat.ADPCM: + { + // If just looped + if (_swav.DoesLoop && _adpcmDecoder.DataOffset == _swav.LoopOffset * 4 && !_adpcmDecoder.OnSecondNibble) + { + _adpcmLoopLastSample = _adpcmDecoder.LastSample; + _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; + } + // If hit end + if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) + { + if (_swav.DoesLoop) + { + _adpcmDecoder.DataOffset = _swav.LoopOffset * 4; + _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; + _adpcmDecoder.LastSample = _adpcmLoopLastSample; + _adpcmDecoder.OnSecondNibble = false; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = _adpcmDecoder.GetSample(); + break; + } + default: samp = 0; break; + } + break; + } + case InstrumentType.PSG: + { + samp = _psgCounter <= _psgDuty ? short.MinValue : short.MaxValue; + _psgCounter++; + if (_psgCounter >= 8) + { + _psgCounter = 0; + } + break; + } + case InstrumentType.Noise: + { + if ((_noiseCounter & 1) != 0) + { + _noiseCounter = (ushort)((_noiseCounter >> 1) ^ 0x6000); + samp = -0x7FFF; + } + else + { + _noiseCounter = (ushort)(_noiseCounter >> 1); + samp = 0x7FFF; + } + break; + } + default: samp = 0; break; + } + samp = (short)(samp * Volume / 0x7F); + _prevLeft = (short)(samp * (-Pan + 0x40) / 0x80); + _prevRight = (short)(samp * (Pan + 0x40) / 0x80); + } + left = _prevLeft; + right = _prevRight; + } + } +} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATCommands.cs b/VG Music Studio - Core/NDS/SDAT/Commands.cs similarity index 100% rename from VG Music Studio - Core/NDS/SDAT/SDATCommands.cs rename to VG Music Studio - Core/NDS/SDAT/Commands.cs diff --git a/VG Music Studio - Core/NDS/SDAT/Enums.cs b/VG Music Studio - Core/NDS/SDAT/Enums.cs new file mode 100644 index 0000000..9f4aa42 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Enums.cs @@ -0,0 +1,40 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal enum EnvelopeState : byte + { + Attack, + Decay, + Sustain, + Release + } + internal enum ArgType : byte + { + None, + Byte, + Short, + VarLen, + Rand, + PlayerVar + } + + internal enum LFOType : byte + { + Pitch, + Volume, + Panpot + } + internal enum InstrumentType : byte + { + PCM = 0x1, + PSG = 0x2, + Noise = 0x3, + Drum = 0x10, + KeySplit = 0x11 + } + internal enum SWAVFormat : byte + { + PCM8, + PCM16, + ADPCM + } +} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs b/VG Music Studio - Core/NDS/SDAT/FileHeader.cs similarity index 87% rename from VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs rename to VG Music Studio - Core/NDS/SDAT/FileHeader.cs index dc742dc..638b4fd 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs +++ b/VG Music Studio - Core/NDS/SDAT/FileHeader.cs @@ -2,7 +2,7 @@ namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; -public sealed class SDATFileHeader +public sealed class FileHeader { public string FileType; public ushort FileEndianness; @@ -11,7 +11,7 @@ public sealed class SDATFileHeader public ushort HeaderSize; // 16 public ushort NumBlocks; - public SDATFileHeader(EndianBinaryReader er) + public FileHeader(EndianBinaryReader er) { FileType = er.ReadString_Count(4); er.Endianness = Endianness.BigEndian; diff --git a/VG Music Studio - Core/NDS/SDAT/SBNK.cs b/VG Music Studio - Core/NDS/SDAT/SBNK.cs index 953f065..2acd3a4 100644 --- a/VG Music Studio - Core/NDS/SDAT/SBNK.cs +++ b/VG Music Studio - Core/NDS/SDAT/SBNK.cs @@ -119,7 +119,7 @@ public Instrument(EndianBinaryReader er) } } - public SDATFileHeader FileHeader; // "SBNK" + public FileHeader FileHeader; // "SBNK" public string BlockType; // "DATA" public int BlockSize; public byte[] Padding; @@ -133,7 +133,7 @@ public SBNK(byte[] bytes) using (var stream = new MemoryStream(bytes)) { var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); + FileHeader = new FileHeader(er); BlockType = er.ReadString_Count(4); BlockSize = er.ReadInt32(); Padding = new byte[32]; diff --git a/VG Music Studio - Core/NDS/SDAT/SDAT.cs b/VG Music Studio - Core/NDS/SDAT/SDAT.cs index df2f861..85e4ff3 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDAT.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDAT.cs @@ -111,24 +111,6 @@ public sealed class SequenceInfo public byte PlayerNum { get; set; } public byte Unknown3 { get; set; } public byte Unknown4 { get; set; } - - internal SSEQ GetSSEQ(SDAT sdat) - { - return new SSEQ(sdat.FATBlock.Entries[FileId].Data); - } - internal SBNK GetSBNK(SDAT sdat) - { - BankInfo bankInfo = sdat.INFOBlock.BankInfos.Entries[Bank]!; - var sbnk = new SBNK(sdat.FATBlock.Entries[bankInfo.FileId].Data); - for (int i = 0; i < 4; i++) - { - if (bankInfo.SWARs[i] != 0xFFFF) - { - sbnk.SWARs[i] = new SWAR(sdat.FATBlock.Entries[sdat.INFOBlock.WaveArchiveInfos.Entries[bankInfo.SWARs[i]]!.FileId].Data); - } - } - return sbnk; - } } public sealed class BankInfo { @@ -224,7 +206,7 @@ public FAT(EndianBinaryReader er) } } - public SDATFileHeader FileHeader; // "SDAT" + public FileHeader FileHeader; // "SDAT" public int SYMBOffset; public int SYMBLength; public int INFOOffset; @@ -240,27 +222,30 @@ public FAT(EndianBinaryReader er) public FAT FATBlock; //FILEBlock - public SDAT(Stream stream) + public SDAT(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - SYMBOffset = er.ReadInt32(); - SYMBLength = er.ReadInt32(); - INFOOffset = er.ReadInt32(); - INFOLength = er.ReadInt32(); - FATOffset = er.ReadInt32(); - FATLength = er.ReadInt32(); - FILEOffset = er.ReadInt32(); - FILELength = er.ReadInt32(); - Padding = new byte[16]; - er.ReadBytes(Padding); - - if (SYMBOffset != 0 && SYMBLength != 0) + using (var stream = new MemoryStream(bytes)) { - SYMBBlock = new SYMB(er, SYMBOffset); + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + SYMBOffset = er.ReadInt32(); + SYMBLength = er.ReadInt32(); + INFOOffset = er.ReadInt32(); + INFOLength = er.ReadInt32(); + FATOffset = er.ReadInt32(); + FATLength = er.ReadInt32(); + FILEOffset = er.ReadInt32(); + FILELength = er.ReadInt32(); + Padding = new byte[16]; + er.ReadBytes(Padding); + + if (SYMBOffset != 0 && SYMBLength != 0) + { + SYMBBlock = new SYMB(er, SYMBOffset); + } + INFOBlock = new INFO(er, INFOOffset); + stream.Position = FATOffset; + FATBlock = new FAT(er); } - INFOBlock = new INFO(er, INFOOffset); - stream.Position = FATOffset; - FATBlock = new FAT(er); } } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs b/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs deleted file mode 100644 index 87fdf6d..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs +++ /dev/null @@ -1,394 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SDATChannel -{ - public readonly byte Index; - - public SDATTrack? Owner; - public InstrumentType Type; - public EnvelopeState State; - public bool AutoSweep; - public byte BaseNote; - public byte Note; - public byte NoteVelocity; - public sbyte StartingPan; - public sbyte Pan; - public int SweepCounter; - public int SweepLength; - public short SweepPitch; - /// The SEQ Player treats 0 as the 100% amplitude value and -92544 (-723*128) as the 0% amplitude value. The starting ampltitude is 0% (-92544) - public int Velocity; - /// From 0x00-0x7F (Calculated from Utils) - public byte Volume; - public ushort BaseTimer; - public ushort Timer; - public int NoteDuration; - - private byte _attack; - private int _sustain; - private ushort _decay; - private ushort _release; - public byte LFORange; - public byte LFOSpeed; - public byte LFODepth; - public ushort LFODelay; - public ushort LFOPhase; - public int LFOParam; - public ushort LFODelayCount; - public LFOType LFOType; - public byte Priority; - - private int _pos; - private short _prevLeft; - private short _prevRight; - - // PCM8, PCM16, ADPCM - private SWAR.SWAV? _swav; - // PCM8, PCM16 - private int _dataOffset; - // ADPCM - private ADPCMDecoder? _adpcmDecoder; - private short _adpcmLoopLastSample; - private short _adpcmLoopStepIndex; - // PSG - private byte _psgDuty; - private int _psgCounter; - // Noise - private ushort _noiseCounter; - - public SDATChannel(byte i) - { - Index = i; - } - - public void StartPCM(SWAR.SWAV swav, int noteDuration) - { - Type = InstrumentType.PCM; - _dataOffset = 0; - _swav = swav; - if (swav.Format == SWAVFormat.ADPCM) - { - _adpcmDecoder = new ADPCMDecoder(swav.Samples); - } - BaseTimer = swav.Timer; - Start(noteDuration); - } - public void StartPSG(byte duty, int noteDuration) - { - Type = InstrumentType.PSG; - _psgCounter = 0; - _psgDuty = duty; - BaseTimer = 8006; // NDSUtils.ARM7_CLOCK / 2093 - Start(noteDuration); - } - public void StartNoise(int noteLength) - { - Type = InstrumentType.Noise; - _noiseCounter = 0x7FFF; - BaseTimer = 8006; // NDSUtils.ARM7_CLOCK / 2093 - Start(noteLength); - } - - private void Start(int noteDuration) - { - State = EnvelopeState.Attack; - Velocity = -92544; - _pos = 0; - _prevLeft = _prevRight = 0; - NoteDuration = noteDuration; - } - - public void Stop() - { - if (Owner is not null) - { - Owner.Channels.Remove(this); - } - Owner = null; - Volume = 0; - Priority = 0; - } - - public int SweepMain() - { - if (SweepPitch == 0 || SweepCounter >= SweepLength) - { - return 0; - } - - int sweep = (int)(Math.BigMul(SweepPitch, SweepLength - SweepCounter) / SweepLength); - if (AutoSweep) - { - SweepCounter++; - } - return sweep; - } - public void LFOTick() - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - else - { - int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; - if (LFOType == LFOType.Volume) - { - param = (param * 60) >> 14; - } - else - { - param >>= 8; - } - LFOParam = param; - int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" - while (counter >= 0x8000) - { - counter -= 0x8000; - } - LFOPhase = (ushort)counter; - } - } - - public void SetAttack(int a) - { - _attack = SDATUtils.AttackTable[a]; - } - public void SetDecay(int d) - { - _decay = SDATUtils.DecayTable[d]; - } - public void SetSustain(byte s) - { - _sustain = SDATUtils.SustainTable[s]; - } - public void SetRelease(int r) - { - _release = SDATUtils.DecayTable[r]; - } - public void StepEnvelope() - { - switch (State) - { - case EnvelopeState.Attack: - { - Velocity = _attack * Velocity / 0xFF; - if (Velocity == 0) - { - State = EnvelopeState.Decay; - } - break; - } - case EnvelopeState.Decay: - { - Velocity -= _decay; - if (Velocity <= _sustain) - { - State = EnvelopeState.Sustain; - Velocity = _sustain; - } - break; - } - case EnvelopeState.Release: - { - Velocity -= _release; - if (Velocity < -92544) - { - Velocity = -92544; - } - break; - } - } - } - - /// EmulateProcess doesn't care about samples that loop; it only cares about ones that force the track to wait for them to end - public void EmulateProcess() - { - if (Timer == 0) - { - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - for (int i = 0; i < numSamples; i++) - { - if (Type != InstrumentType.PCM || _swav!.DoesLoop) - { - continue; - } - - switch (_swav.Format) - { - case SWAVFormat.PCM8: - { - if (_dataOffset >= _swav.Samples.Length) - { - Stop(); - } - else - { - _dataOffset++; - } - return; - } - case SWAVFormat.PCM16: - { - if (_dataOffset >= _swav.Samples.Length) - { - Stop(); - } - else - { - _dataOffset += 2; - } - return; - } - case SWAVFormat.ADPCM: - { - if (_adpcmDecoder!.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) - { - Stop(); - } - else - { - // This is a faster emulation of adpcmDecoder.GetSample() without caring about the sample - if (_adpcmDecoder.OnSecondNibble) - { - _adpcmDecoder.DataOffset++; - } - _adpcmDecoder.OnSecondNibble = !_adpcmDecoder.OnSecondNibble; - } - return; - } - } - } - } - public void Process(out short left, out short right) - { - if (Timer == 0) - { - left = _prevLeft; - right = _prevRight; - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - // numSamples can be 0 - for (int i = 0; i < numSamples; i++) - { - short samp; - switch (Type) - { - case InstrumentType.PCM: - { - switch (_swav!.Format) - { - case SWAVFormat.PCM8: - { - // If hit end - if (_dataOffset >= _swav.Samples.Length) - { - if (_swav.DoesLoop) - { - _dataOffset = _swav.LoopOffset * 4; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)((sbyte)_swav.Samples[_dataOffset++] << 8); - break; - } - case SWAVFormat.PCM16: - { - // If hit end - if (_dataOffset >= _swav.Samples.Length) - { - if (_swav.DoesLoop) - { - _dataOffset = _swav.LoopOffset * 4; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)(_swav.Samples[_dataOffset++] | (_swav.Samples[_dataOffset++] << 8)); - break; - } - case SWAVFormat.ADPCM: - { - // If just looped - if (_swav.DoesLoop && _adpcmDecoder!.DataOffset == _swav.LoopOffset * 4 && !_adpcmDecoder.OnSecondNibble) - { - _adpcmLoopLastSample = _adpcmDecoder.LastSample; - _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; - } - // If hit end - if (_adpcmDecoder!.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) - { - if (_swav.DoesLoop) - { - _adpcmDecoder.DataOffset = _swav.LoopOffset * 4; - _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; - _adpcmDecoder.LastSample = _adpcmLoopLastSample; - _adpcmDecoder.OnSecondNibble = false; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = _adpcmDecoder.GetSample(); - break; - } - default: samp = 0; break; - } - break; - } - case InstrumentType.PSG: - { - samp = _psgCounter <= _psgDuty ? short.MinValue : short.MaxValue; - _psgCounter++; - if (_psgCounter >= 8) - { - _psgCounter = 0; - } - break; - } - case InstrumentType.Noise: - { - if ((_noiseCounter & 1) != 0) - { - _noiseCounter = (ushort)((_noiseCounter >> 1) ^ 0x6000); - samp = -0x7FFF; - } - else - { - _noiseCounter = (ushort)(_noiseCounter >> 1); - samp = 0x7FFF; - } - break; - } - default: samp = 0; break; - } - samp = (short)(samp * Volume / 0x7F); - _prevLeft = (short)(samp * (-Pan + 0x40) / 0x80); - _prevRight = (short)(samp * (Pan + 0x40) / 0x80); - } - left = _prevLeft; - right = _prevRight; - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs b/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs index ce0c21c..c35a95a 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs @@ -31,7 +31,7 @@ public override string GetGameName() { return "SDAT"; } - public override string GetSongName(int index) + public override string GetSongName(long index) { return SDAT.SYMBBlock is null || index < 0 || index >= SDAT.SYMBBlock.SequenceSymbols.NumEntries ? index.ToString() diff --git a/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs b/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs deleted file mode 100644 index 62f10b9..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal enum EnvelopeState : byte -{ - Attack, - Decay, - Sustain, - Release, -} -internal enum ArgType : byte -{ - None, - Byte, - Short, - VarLen, - Rand, - PlayerVar, -} - -internal enum LFOType : byte -{ - Pitch, - Volume, - Panpot, -} -internal enum InstrumentType : byte -{ - PCM = 0x1, - PSG = 0x2, - Noise = 0x3, - Drum = 0x10, - KeySplit = 0x11, -} -internal enum SWAVFormat : byte -{ - PCM8, - PCM16, - ADPCM, -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs deleted file mode 100644 index ff00ed2..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong : ILoadedSong -{ - public List?[] Events { get; } - public long MaxTicks { get; internal set; } - public int LongestTrack; - - private readonly SDATPlayer _player; - private readonly int _randSeed; - private Random? _rand; - public readonly SDAT.INFO.SequenceInfo SEQInfo; // TODO: Not public - private readonly SSEQ _sseq; - private readonly SBNK _sbnk; - - public SDATLoadedSong(SDATPlayer player, SDAT.INFO.SequenceInfo seqInfo) - { - _player = player; - SEQInfo = seqInfo; - - SDAT sdat = player.Config.SDAT; - _sseq = seqInfo.GetSSEQ(sdat); - _sbnk = seqInfo.GetSBNK(sdat); - _randSeed = Random.Shared.Next(); - // Cannot set random seed without creating a new object which is dumb - - Events = new List[0x10]; - AddTrackEvents(0, 0); - } - - private static SDATInvalidCMDException Invalid(byte trackIndex, int cmdOffset, byte cmd) - { - return new SDATInvalidCMDException(trackIndex, cmdOffset, cmd); - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs deleted file mode 100644 index 66118b1..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs +++ /dev/null @@ -1,746 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, T command, ArgType argOverrideType) where T : SDATCommand, ICommand - { - command.RandMod = argOverrideType == ArgType.Rand; - command.VarMod = argOverrideType == ArgType.PlayerVar; - Events[trackIndex].Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex].Exists(e => e.Offset == cmdOffset); - } - - private int ReadArg(ref int dataOffset, ArgType type) - { - switch (type) - { - case ArgType.Byte: - { - return _sseq.Data[dataOffset++]; - } - case ArgType.Short: - { - short s = ReadInt16LittleEndian(_sseq.Data.AsSpan(dataOffset)); - dataOffset += 2; - return s; - } - case ArgType.VarLen: - { - int numRead = 0; - int value = 0; - byte b; - do - { - b = _sseq.Data[dataOffset++]; - value = (value << 7) | (b & 0x7F); - numRead++; - } - while (numRead < 4 && (b & 0x80) != 0); - return value; - } - case ArgType.Rand: - { - // Combine min and max into one int - int minMax = ReadInt32LittleEndian(_sseq.Data.AsSpan(dataOffset)); - dataOffset += 4; - return minMax; - } - case ArgType.PlayerVar: - { - return _sseq.Data[dataOffset++]; // Return var index - } - default: throw new Exception(); - } - } - - private void AddTrackEvents(byte trackIndex, int trackStartOffset) - { - ref List trackEvents = ref Events[trackIndex]; - trackEvents ??= new List(); - - int callStackDepth = 0; - AddEvents(trackIndex, trackStartOffset, ref callStackDepth); - } - private void AddEvents(byte trackIndex, int startOffset, ref int callStackDepth) - { - int dataOffset = startOffset; - bool cont = true; - while (cont) - { - bool @if = false; - int cmdOffset = dataOffset; - ArgType argOverrideType = ArgType.None; - again: - byte cmd = _sseq.Data[dataOffset++]; - - if (cmd <= 0x7F) - { - HandleNoteEvent(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); - } - else - { - switch (cmd & 0xF0) - { - case 0x80: HandleCmdGroup0x80(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0x90: HandleCmdGroup0x90(trackIndex, ref dataOffset, ref callStackDepth, cmdOffset, cmd, argOverrideType, ref @if, ref cont); break; - case 0xA0: - { - if (HandleCmdGroup0xA0(trackIndex, ref cmdOffset, cmd, ref argOverrideType, ref @if)) - { - goto again; - } - break; - } - case 0xB0: HandleCmdGroup0xB0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xC0: HandleCmdGroup0xC0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xD0: HandleCmdGroup0xD0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xE0: HandleCmdGroup0xE0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - default: HandleCmdGroup0xF0(trackIndex, ref dataOffset, ref callStackDepth, cmdOffset, cmd, argOverrideType, ref @if, ref cont); break; - } - } - } - } - - private void HandleNoteEvent(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - byte velocity = _sseq.Data[dataOffset++]; - int duration = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteComand { Note = cmd, Velocity = velocity, Duration = duration }, argOverrideType); - } - } - private void HandleCmdGroup0x80(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); - switch (cmd) - { - case 0x80: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = arg }, argOverrideType); - } - break; - } - case 0x81: // RAND PROGRAM: [BW2 (2249)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = arg }, argOverrideType); // TODO: Bank change - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0x90(byte trackIndex, ref int dataOffset, ref int callStackDepth, int cmdOffset, byte cmd, ArgType argOverrideType, ref bool @if, ref bool cont) - { - switch (cmd) - { - case 0x93: - { - byte openTrackIndex = _sseq.Data[dataOffset++]; - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OpenTrackCommand { Track = openTrackIndex, Offset = offset24bit }, argOverrideType); - AddTrackEvents(openTrackIndex, offset24bit); - } - break; - } - case 0x94: - { - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new JumpCommand { Offset = offset24bit }, argOverrideType); - if (!EventExists(trackIndex, offset24bit)) - { - AddEvents(trackIndex, offset24bit, ref callStackDepth); - } - } - if (!@if) - { - cont = false; - } - break; - } - case 0x95: - { - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new CallCommand { Offset = offset24bit }, argOverrideType); - } - if (callStackDepth < 3) - { - if (!EventExists(trackIndex, offset24bit)) - { - callStackDepth++; - AddEvents(trackIndex, offset24bit, ref callStackDepth); - } - } - else - { - throw new SDATTooManyNestedCallsException(trackIndex); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private bool HandleCmdGroup0xA0(byte trackIndex, ref int cmdOffset, byte cmd, ref ArgType argOverrideType, ref bool @if) - { - switch (cmd) - { - case 0xA0: // [New Super Mario Bros (BGM_AMB_CHIKA)] [BW2 (1917, 1918)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModRandCommand(), argOverrideType); - } - argOverrideType = ArgType.Rand; - cmdOffset++; - return true; - } - case 0xA1: // [New Super Mario Bros (BGM_AMB_SABAKU)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModVarCommand(), argOverrideType); - } - argOverrideType = ArgType.PlayerVar; - cmdOffset++; - return true; - } - case 0xA2: // [Mario Kart DS (75)] [BW2 (1917, 1918)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModIfCommand(), argOverrideType); - } - @if = true; - cmdOffset++; - return true; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xB0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - byte varIndex = _sseq.Data[dataOffset++]; - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); - switch (cmd) - { - case 0xB0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarSetCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarAddCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarSubCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarMulCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarDivCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarShiftCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB6: // [Mario Kart DS (75)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarRandCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB8: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpEECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB9: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpGECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBA: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpGGCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBB: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpLECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBC: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpLLCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpNECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xC0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); - switch (cmd) - { - case 0xC0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = arg }, argOverrideType); - } - break; - } - case 0xC1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackVolumeCommand { Volume = arg }, argOverrideType); - } - break; - } - case 0xC2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PlayerVolumeCommand { Volume = arg }, argOverrideType); - } - break; - } - case 0xC3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TransposeCommand { Transpose = arg }, argOverrideType); - } - break; - } - case 0xC4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = arg }, argOverrideType); - } - break; - } - case 0xC5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendRangeCommand { Range = arg }, argOverrideType); - } - break; - } - case 0xC6: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PriorityCommand { Priority = arg }, argOverrideType); - } - break; - } - case 0xC7: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new MonophonyCommand { Mono = arg }, argOverrideType); - } - break; - } - case 0xC8: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TieCommand { Tie = arg }, argOverrideType); - } - break; - } - case 0xC9: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoControlCommand { Portamento = arg }, argOverrideType); - } - break; - } - case 0xCA: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFODepthCommand { Depth = arg }, argOverrideType); - } - break; - } - case 0xCB: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFOSpeedCommand { Speed = arg }, argOverrideType); - } - break; - } - case 0xCC: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFOTypeCommand { Type = arg }, argOverrideType); - } - break; - } - case 0xCD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFORangeCommand { Range = arg }, argOverrideType); - } - break; - } - case 0xCE: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoToggleCommand { Portamento = arg }, argOverrideType); - } - break; - } - case 0xCF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoTimeCommand { Time = arg }, argOverrideType); - } - break; - } - } - } - private void HandleCmdGroup0xD0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); - switch (cmd) - { - case 0xD0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceAttackCommand { Attack = arg }, argOverrideType); - } - break; - } - case 0xD1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceDecayCommand { Decay = arg }, argOverrideType); - } - break; - } - case 0xD2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceSustainCommand { Sustain = arg }, argOverrideType); - } - break; - } - case 0xD3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceReleaseCommand { Release = arg }, argOverrideType); - } - break; - } - case 0xD4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopStartCommand { NumLoops = arg }, argOverrideType); - } - break; - } - case 0xD5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackExpressionCommand { Expression = arg }, argOverrideType); - } - break; - } - case 0xD6: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarPrintCommand { Variable = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xE0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); - switch (cmd) - { - case 0xE0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFODelayCommand { Delay = arg }, argOverrideType); - } - break; - } - case 0xE1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TempoCommand { Tempo = arg }, argOverrideType); - } - break; - } - case 0xE3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SweepPitchCommand { Pitch = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xF0(byte trackIndex, ref int dataOffset, ref int callStackDepth, int cmdOffset, byte cmd, ArgType argOverrideType, ref bool @if, ref bool cont) - { - switch (cmd) - { - case 0xFC: // [HGSS(1353)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopEndCommand(), argOverrideType); - } - break; - } - case 0xFD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ReturnCommand(), argOverrideType); - } - if (!@if && callStackDepth != 0) - { - cont = false; - callStackDepth--; - } - break; - } - case 0xFE: - { - ushort bits = (ushort)ReadArg(ref dataOffset, ArgType.Short); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new AllocTracksCommand { Tracks = bits }, argOverrideType); - } - break; - } - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand(), argOverrideType); - } - if (!@if) - { - cont = false; - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - - public void SetTicks() - { - // TODO: (NSMB 81) (Spirit Tracks 18) does not count all ticks because the songs keep jumping backwards while changing vars and then using ModIfCommand to change events - // Should evaluate all branches if possible - MaxTicks = 0; - for (int i = 0; i < 0x10; i++) - { - ref List? evs = ref Events[i]; - if (evs is not null) - { - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - } - } - _player.InitEmulation(); - - bool[] done = new bool[0x10]; // We use this instead of track.Stopped just to be certain that emulating Monophony works as intended - while (Array.Exists(_player.Tracks, t => t.Allocated && t.Enabled && !done[t.Index])) - { - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - SDATTrack track = _player.Tracks[trackIndex]; - List evs = Events[trackIndex]!; - if (!track.Enabled || track.Stopped) - { - continue; - } - - track.Tick(); - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - ExecuteNext(track); - if (done[trackIndex]) - { - continue; - } - - e.Ticks.Add(_player.ElapsedTicks); - bool b; - if (track.Stopped) - { - b = true; - } - else - { - SongEvent newE = evs.Single(ev => ev.Offset == track.DataOffset); - b = (track.CallStackDepth == 0 && newE.Ticks.Count > 0) // If we already counted the tick of this event and we're not looping/calling - || (track.CallStackDepth != 0 && track.CallStackLoops.All(l => l == 0) && newE.Ticks.Count > 0); // If we have "LoopStart (0)" and already counted the tick of this event - } - if (b) - { - done[trackIndex] = true; - if (_player.ElapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = _player.ElapsedTicks; - } - } - } - } - _player.ElapsedTicks++; - } - _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); - } - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - _player.Tracks[trackIndex].StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - SDATTrack track = _player.Tracks[trackIndex]; - if (track.Enabled && !track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) - { - ExecuteNext(track); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); - } - finish: - for (int i = 0; i < 0x10; i++) - { - _player.Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs deleted file mode 100644 index 7f00ca7..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs +++ /dev/null @@ -1,787 +0,0 @@ -using System; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong -{ - public void InitEmulation() - { - _player.Volume = SEQInfo.Volume; - _rand = new Random(_randSeed); - } - - public void UpdateInstrumentCache(byte voice, out string str) - { - if (_sbnk.NumInstruments <= voice) - { - str = "Empty"; - } - else - { - InstrumentType t = _sbnk.Instruments[voice].Type; - switch (t) - { - case InstrumentType.PCM: str = "PCM"; break; - case InstrumentType.PSG: str = "PSG"; break; - case InstrumentType.Noise: str = "Noise"; break; - case InstrumentType.Drum: str = "Drum"; break; - case InstrumentType.KeySplit: str = "Key Split"; break; - default: str = "Invalid {0}" + (byte)t; break; - } - } - } - - private int ReadArg(SDATTrack track, ArgType type) - { - if (track.ArgOverrideType != ArgType.None) - { - type = track.ArgOverrideType; - } - switch (type) - { - case ArgType.Byte: - { - return _sseq.Data[track.DataOffset++]; - } - case ArgType.Short: - { - return _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); - } - case ArgType.VarLen: - { - int read = 0, value = 0; - byte b; - do - { - b = _sseq.Data[track.DataOffset++]; - value = (value << 7) | (b & 0x7F); - read++; - } - while (read < 4 && (b & 0x80) != 0); - return value; - } - case ArgType.Rand: - { - short min = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); - short max = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); - return _rand!.Next(min, max + 1); - } - case ArgType.PlayerVar: - { - byte varIndex = _sseq.Data[track.DataOffset++]; - return _player.Vars[varIndex]; - } - default: throw new Exception(); - } - } - private void TryStartChannel(SBNK.InstrumentData inst, SDATTrack track, byte note, byte velocity, int duration, out SDATChannel? channel) - { - InstrumentType type = inst.Type; - channel = _player.SMixer.AllocateChannel(type, track); - if (channel is null) - { - return; - } - - if (track.Tie) - { - duration = -1; - } - SBNK.InstrumentData.DataParam param = inst.Param; - byte release = param.Release; - if (release == 0xFF) - { - duration = -1; - release = 0; - } - bool started = false; - switch (type) - { - case InstrumentType.PCM: - { - ushort[] info = param.Info; - SWAR.SWAV? swav = _sbnk.GetSWAV(info[1], info[0]); - if (swav is not null) - { - channel.StartPCM(swav, duration); - started = true; - } - break; - } - case InstrumentType.PSG: - { - channel.StartPSG((byte)param.Info[0], duration); - started = true; - break; - } - case InstrumentType.Noise: - { - channel.StartNoise(duration); - started = true; - break; - } - } - channel.Stop(); - if (!started) - { - return; - } - - channel.Note = note; - byte baseNote = param.BaseNote; - channel.BaseNote = type != InstrumentType.PCM && baseNote == 0x7F ? (byte)60 : baseNote; - channel.NoteVelocity = velocity; - channel.SetAttack(param.Attack); - channel.SetDecay(param.Decay); - channel.SetSustain(param.Sustain); - channel.SetRelease(release); - channel.StartingPan = (sbyte)(param.Pan - 0x40); - channel.Owner = track; - channel.Priority = track.Priority; - track.Channels.Add(channel); - } - private void PlayNote(SDATTrack track, byte note, byte velocity, int duration) - { - SDATChannel? channel = null; - if (track.Tie && track.Channels.Count != 0) - { - channel = track.Channels.Last(); - channel.Note = note; - channel.NoteVelocity = velocity; - } - else - { - SBNK.InstrumentData? inst = _sbnk.GetInstrumentData(track.Voice, note); - if (inst is not null) - { - TryStartChannel(inst, track, note, velocity, duration, out channel); - } - - if (channel is null) - { - return; - } - } - - if (track.Attack != 0xFF) - { - channel.SetAttack(track.Attack); - } - if (track.Decay != 0xFF) - { - channel.SetDecay(track.Decay); - } - if (track.Sustain != 0xFF) - { - channel.SetSustain(track.Sustain); - } - if (track.Release != 0xFF) - { - channel.SetRelease(track.Release); - } - channel.SweepPitch = track.SweepPitch; - if (track.Portamento) - { - channel.SweepPitch += (short)((track.PortamentoNote - note) << 6); // "<< 6" is "* 0x40" - } - if (track.PortamentoTime != 0) - { - channel.SweepLength = (track.PortamentoTime * track.PortamentoTime * Math.Abs(channel.SweepPitch)) >> 11; // ">> 11" is "/ 0x800" - channel.AutoSweep = true; - } - else - { - channel.SweepLength = duration; - channel.AutoSweep = false; - } - channel.SweepCounter = 0; - } - - internal void ExecuteNext(SDATTrack track) - { - bool resetOverride = true; - bool resetCmdWork = true; - byte cmd = _sseq.Data[track.DataOffset++]; - if (cmd < 0x80) - { - ExecuteNoteEvent(track, cmd); - } - else - { - switch (cmd & 0xF0) - { - case 0x80: ExecuteCmdGroup0x80(track, cmd); break; - case 0x90: ExecuteCmdGroup0x90(track, cmd); break; - case 0xA0: ExecuteCmdGroup0xA0(track, cmd, ref resetOverride, ref resetCmdWork); break; - case 0xB0: ExecuteCmdGroup0xB0(track, cmd); break; - case 0xC0: ExecuteCmdGroup0xC0(track, cmd); break; - case 0xD0: ExecuteCmdGroup0xD0(track, cmd); break; - case 0xE0: ExecuteCmdGroup0xE0(track, cmd); break; - default: ExecuteCmdGroup0xF0(track, cmd); break; - } - } - if (resetOverride) - { - track.ArgOverrideType = ArgType.None; - } - if (resetCmdWork) - { - track.DoCommandWork = true; - } - } - - private void ExecuteNoteEvent(SDATTrack track, byte cmd) - { - byte velocity = _sseq.Data[track.DataOffset++]; - int duration = ReadArg(track, ArgType.VarLen); - if (!track.DoCommandWork) - { - return; - } - - int n = cmd + track.Transpose; - if (n < 0) - { - n = 0; - } - else if (n > 0x7F) - { - n = 0x7F; - } - byte note = (byte)n; - PlayNote(track, note, velocity, duration); - track.PortamentoNote = note; - if (track.Mono) - { - track.Rest = duration; - if (duration == 0) - { - track.WaitingForNoteToFinishBeforeContinuingXD = true; - } - } - } - private void ExecuteCmdGroup0x80(SDATTrack track, byte cmd) - { - int arg = ReadArg(track, ArgType.VarLen); - - switch (cmd) - { - case 0x80: // Rest - { - if (track.DoCommandWork) - { - track.Rest = arg; - } - break; - } - case 0x81: // Program Change - { - if (track.DoCommandWork && arg <= byte.MaxValue) - { - track.Voice = (byte)arg; - } - break; - } - throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0x90(SDATTrack track, byte cmd) - { - switch (cmd) - { - case 0x93: // Open Track - { - int index = _sseq.Data[track.DataOffset++]; - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork && track.Index == 0) - { - SDATTrack other = _player.Tracks[index]; - if (other.Allocated && !other.Enabled) - { - other.Enabled = true; - other.DataOffset = offset24bit; - } - } - break; - } - case 0x94: // Jump - { - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork) - { - track.DataOffset = offset24bit; - } - break; - } - case 0x95: // Call - { - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork && track.CallStackDepth < 3) - { - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackLoops[track.CallStackDepth] = byte.MaxValue; // This is only necessary for SetTicks() to deal with LoopStart (0) - track.CallStackDepth++; - track.DataOffset = offset24bit; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private static void ExecuteCmdGroup0xA0(SDATTrack track, byte cmd, ref bool resetOverride, ref bool resetCmdWork) - { - switch (cmd) - { - case 0xA0: // Rand Mod - { - if (track.DoCommandWork) - { - track.ArgOverrideType = ArgType.Rand; - resetOverride = false; - } - break; - } - case 0xA1: // Var Mod - { - if (track.DoCommandWork) - { - track.ArgOverrideType = ArgType.PlayerVar; - resetOverride = false; - } - break; - } - case 0xA2: // If Mod - { - if (track.DoCommandWork) - { - track.DoCommandWork = track.VariableFlag; - resetCmdWork = false; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xB0(SDATTrack track, byte cmd) - { - byte varIndex = _sseq.Data[track.DataOffset++]; - short mathArg = (short)ReadArg(track, ArgType.Short); - switch (cmd) - { - case 0xB0: // VarSet - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] = mathArg; - } - break; - } - case 0xB1: // VarAdd - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] += mathArg; - } - break; - } - case 0xB2: // VarSub - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] -= mathArg; - } - break; - } - case 0xB3: // VarMul - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] *= mathArg; - } - break; - } - case 0xB4: // VarDiv - { - if (track.DoCommandWork && mathArg != 0) - { - _player.Vars[varIndex] /= mathArg; - } - break; - } - case 0xB5: // VarShift - { - if (track.DoCommandWork) - { - ref short v = ref _player.Vars[varIndex]; - v = mathArg < 0 ? (short)(v >> -mathArg) : (short)(v << mathArg); - } - break; - } - case 0xB6: // VarRand - { - if (track.DoCommandWork) - { - bool negate = false; - if (mathArg < 0) - { - negate = true; - mathArg = (short)-mathArg; - } - short val = (short)_rand!.Next(mathArg + 1); - if (negate) - { - val = (short)-val; - } - _player.Vars[varIndex] = val; - } - break; - } - case 0xB8: // VarCmpEE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] == mathArg; - } - break; - } - case 0xB9: // VarCmpGE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] >= mathArg; - } - break; - } - case 0xBA: // VarCmpGG - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] > mathArg; - } - break; - } - case 0xBB: // VarCmpLE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] <= mathArg; - } - break; - } - case 0xBC: // VarCmpLL - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] < mathArg; - } - break; - } - case 0xBD: // VarCmpNE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] != mathArg; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xC0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Byte); - switch (cmd) - { - case 0xC0: // Panpot - { - if (track.DoCommandWork) - { - track.Panpot = (sbyte)(cmdArg - 0x40); - } - break; - } - case 0xC1: // Track Volume - { - if (track.DoCommandWork) - { - track.Volume = (byte)cmdArg; - } - break; - } - case 0xC2: // Player Volume - { - if (track.DoCommandWork) - { - _player.Volume = (byte)cmdArg; - } - break; - } - case 0xC3: // Transpose - { - if (track.DoCommandWork) - { - track.Transpose = (sbyte)cmdArg; - } - break; - } - case 0xC4: // Pitch Bend - { - if (track.DoCommandWork) - { - track.PitchBend = (sbyte)cmdArg; - } - break; - } - case 0xC5: // Pitch Bend Range - { - if (track.DoCommandWork) - { - track.PitchBendRange = (byte)cmdArg; - } - break; - } - case 0xC6: // Priority - { - if (track.DoCommandWork) - { - track.Priority = (byte)(_player.Priority + (byte)cmdArg); - } - break; - } - case 0xC7: // Mono - { - if (track.DoCommandWork) - { - track.Mono = cmdArg == 1; - } - break; - } - case 0xC8: // Tie - { - if (track.DoCommandWork) - { - track.Tie = cmdArg == 1; - track.StopAllChannels(); - } - break; - } - case 0xC9: // Portamento Control - { - if (track.DoCommandWork) - { - int k = cmdArg + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.PortamentoNote = (byte)k; - track.Portamento = true; - } - break; - } - case 0xCA: // LFO Depth - { - if (track.DoCommandWork) - { - track.LFODepth = (byte)cmdArg; - } - break; - } - case 0xCB: // LFO Speed - { - if (track.DoCommandWork) - { - track.LFOSpeed = (byte)cmdArg; - } - break; - } - case 0xCC: // LFO Type - { - if (track.DoCommandWork) - { - track.LFOType = (LFOType)cmdArg; - } - break; - } - case 0xCD: // LFO Range - { - if (track.DoCommandWork) - { - track.LFORange = (byte)cmdArg; - } - break; - } - case 0xCE: // Portamento Toggle - { - if (track.DoCommandWork) - { - track.Portamento = cmdArg == 1; - } - break; - } - case 0xCF: // Portamento Time - { - if (track.DoCommandWork) - { - track.PortamentoTime = (byte)cmdArg; - } - break; - } - } - } - private void ExecuteCmdGroup0xD0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Byte); - switch (cmd) - { - case 0xD0: // Forced Attack - { - if (track.DoCommandWork) - { - track.Attack = (byte)cmdArg; - } - break; - } - case 0xD1: // Forced Decay - { - if (track.DoCommandWork) - { - track.Decay = (byte)cmdArg; - } - break; - } - case 0xD2: // Forced Sustain - { - if (track.DoCommandWork) - { - track.Sustain = (byte)cmdArg; - } - break; - } - case 0xD3: // Forced Release - { - if (track.DoCommandWork) - { - track.Release = (byte)cmdArg; - } - break; - } - case 0xD4: // Loop Start - { - if (track.DoCommandWork && track.CallStackDepth < 3) - { - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackLoops[track.CallStackDepth] = (byte)cmdArg; - track.CallStackDepth++; - } - break; - } - case 0xD5: // Track Expression - { - if (track.DoCommandWork) - { - track.Expression = (byte)cmdArg; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xE0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Short); - switch (cmd) - { - case 0xE0: // LFO Delay - { - if (track.DoCommandWork) - { - track.LFODelay = (ushort)cmdArg; - } - break; - } - case 0xE1: // Tempo - { - if (track.DoCommandWork) - { - _player.Tempo = (ushort)cmdArg; - } - break; - } - case 0xE3: // Sweep Pitch - { - if (track.DoCommandWork) - { - track.SweepPitch = (short)cmdArg; - } - break; - } - } - } - private void ExecuteCmdGroup0xF0(SDATTrack track, byte cmd) - { - switch (cmd) - { - case 0xFC: // Loop End - { - if (track.DoCommandWork && track.CallStackDepth != 0) - { - byte count = track.CallStackLoops[track.CallStackDepth - 1]; - if (count != 0) - { - count--; - track.CallStackLoops[track.CallStackDepth - 1] = count; - if (count == 0) - { - track.CallStackDepth--; - break; - } - } - track.DataOffset = track.CallStack[track.CallStackDepth - 1]; - } - break; - } - case 0xFD: // Return - { - if (track.DoCommandWork && track.CallStackDepth != 0) - { - track.CallStackDepth--; - track.DataOffset = track.CallStack[track.CallStackDepth]; - track.CallStackLoops[track.CallStackDepth] = 0; // This is only necessary for SetTicks() to deal with LoopStart (0) - } - break; - } - case 0xFE: // Alloc Tracks - { - // Must be in the beginning of the first track to work - if (track.DoCommandWork && track.Index == 0 && track.DataOffset == 1) // == 1 because we read cmd already - { - // Track 1 enabled = bit 1 set, Track 4 enabled = bit 4 set, etc - int trackBits = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); - for (int i = 0; i < 0x10; i++) - { - if ((trackBits & (1 << i)) != 0) - { - _player.Tracks[i].Allocated = true; - } - } - } - break; - } - case 0xFF: // Finish - { - if (track.DoCommandWork) - { - track.Stopped = true; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs index e516e15..9cbf17b 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs @@ -13,11 +13,9 @@ public sealed class SDATMixer : Mixer private float _fadePos; private float _fadeStepPerMicroframe; - internal SDATChannel[] Channels; + internal Channel[] Channels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal SDATMixer() { // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. @@ -27,10 +25,10 @@ internal SDATMixer() _samplesPerBuffer = 341; // TODO _samplesReciprocal = 1f / _samplesPerBuffer; - Channels = new SDATChannel[0x10]; + Channels = new Channel[0x10]; for (byte i = 0; i < 0x10; i++) { - Channels[i] = new SDATChannel(i); + Channels[i] = new Channel(i); } _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) @@ -44,7 +42,7 @@ internal SDATMixer() private static readonly int[] _pcmChanOrder = new int[] { 4, 5, 6, 7, 2, 0, 3, 1, 8, 9, 10, 11, 14, 12, 15, 13 }; private static readonly int[] _psgChanOrder = new int[] { 8, 9, 10, 11, 12, 13 }; private static readonly int[] _noiseChanOrder = new int[] { 14, 15 }; - internal SDATChannel? AllocateChannel(InstrumentType type, SDATTrack track) + internal Channel? AllocateChannel(InstrumentType type, Track track) { int[] allowedChannels; switch (type) @@ -54,10 +52,10 @@ internal SDATMixer() case InstrumentType.Noise: allowedChannels = _noiseChanOrder; break; default: return null; } - SDATChannel? nChan = null; + Channel? nChan = null; for (int i = 0; i < allowedChannels.Length; i++) { - SDATChannel c = Channels[allowedChannels[i]]; + Channel c = Channels[allowedChannels[i]]; if (nChan is not null && c.Priority >= nChan.Priority && (c.Priority != nChan.Priority || nChan.Volume <= c.Volume)) { continue; @@ -75,7 +73,7 @@ internal void ChannelTick() { for (int i = 0; i < 0x10; i++) { - SDATChannel chan = Channels[i]; + Channel chan = Channels[i]; if (chan.Owner is null) { continue; @@ -147,13 +145,23 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } internal void EmulateProcess() { for (int i = 0; i < _samplesPerBuffer; i++) { for (int j = 0; j < 0x10; j++) { - SDATChannel chan = Channels[j]; + Channel chan = Channels[j]; if (chan.Owner is not null) { chan.EmulateProcess(); @@ -192,7 +200,7 @@ internal void Process(bool output, bool recording) right = 0; for (int j = 0; j < 0x10; j++) { - SDATChannel chan = Channels[j]; + Channel chan = Channels[j]; if (chan.Owner is null) { continue; diff --git a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs index 97fb6ae..3699cc9 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs @@ -1,195 +1,1694 @@ +using Kermalis.VGMusicStudio.Core.Util; using System; using System.Collections.Generic; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; -public sealed class SDATPlayer : Player +public sealed class SDATPlayer : IPlayer, ILoadedSong { - protected override string Name => "SDAT Player"; - internal readonly byte Priority = 0x40; - internal readonly short[] Vars = new short[0x20]; // 16 player variables, then 16 global variables - internal readonly SDATTrack[] Tracks = new SDATTrack[0x10]; - private readonly string?[] _voiceTypeCache = new string?[256]; - internal readonly SDATConfig Config; - internal readonly SDATMixer SMixer; - private SDATLoadedSong? _loadedSong; - + private readonly short[] _vars = new short[0x20]; // 16 player variables, then 16 global variables + private readonly Track[] _tracks = new Track[0x10]; + private readonly SDATMixer _mixer; + private readonly SDATConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private int _randSeed; + private Random _rand; + private SDAT.INFO.SequenceInfo _seqInfo; + private SSEQ _sseq; + private SBNK _sbnk; internal byte Volume; - internal ushort Tempo; - internal int TempoStack; + private ushort _tempo; + private int _tempoStack; private long _elapsedLoops; - private ushort? _prevBank; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => SMixer; + public PlayerState State { get; private set; } + public event Action? SongEnded; internal SDATPlayer(SDATConfig config, SDATMixer mixer) - : base(192) { - Config = config; - SMixer = mixer; + _config = config; + _mixer = mixer; for (byte i = 0; i < 0x10; i++) { - Tracks[i] = new SDATTrack(i, this); + _tracks[i] = new Track(i, this); } - } - public override void LoadSong(int index) + _time = new TimeBarrier(192); + } + private void CreateThread() { - if (_loadedSong is not null) + _thread = new Thread(Tick) { Name = "SDAT Player Tick" }; + _thread.Start(); + } + private void WaitThread() + { + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) { - _loadedSong = null; + _thread.Join(); } + } - SDAT.INFO.SequenceInfo? seqInfo = Config.SDAT.INFOBlock.SequenceInfos.Entries[index]; - if (seqInfo is null) + private void InitEmulation() + { + _tempo = 120; // Confirmed: default tempo is 120 (MKDS 75) + _tempoStack = 0; + _elapsedLoops = 0; + ElapsedTicks = 0; + _mixer.ResetFade(); + Volume = _seqInfo.Volume; + _rand = new Random(_randSeed); + for (int i = 0; i < 0x10; i++) + { + _tracks[i].Init(); + } + // Initialize player and global variables. Global variables should not have a global effect in this program. + for (int i = 0; i < 0x20; i++) { + _vars[i] = i % 8 == 0 ? short.MaxValue : (short)0; + } + } + private void SetTicks() + { + // TODO: (NSMB 81) (Spirit Tracks 18) does not count all ticks because the songs keep jumping backwards while changing vars and then using ModIfCommand to change events + // Should evaluate all branches if possible + MaxTicks = 0; + for (int i = 0; i < 0x10; i++) + { + if (Events[i] != null) + { + Events[i] = Events[i].OrderBy(e => e.Offset).ToList(); + } + } + InitEmulation(); + bool[] done = new bool[0x10]; // We use this instead of track.Stopped just to be certain that emulating Monophony works as intended + while (_tracks.Any(t => t.Allocated && t.Enabled && !done[t.Index])) + { + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + List evs = Events[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + ExecuteNext(track); + if (!done[trackIndex]) + { + e.Ticks.Add(ElapsedTicks); + bool b; + if (track.Stopped) + { + b = true; + } + else + { + SongEvent newE = evs.Single(ev => ev.Offset == track.DataOffset); + b = (track.CallStackDepth == 0 && newE.Ticks.Count > 0) // If we already counted the tick of this event and we're not looping/calling + || (track.CallStackDepth != 0 && track.CallStackLoops.All(l => l == 0) && newE.Ticks.Count > 0); // If we have "LoopStart (0)" and already counted the tick of this event + } + if (b) + { + done[trackIndex] = true; + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + } + } + } + } + } + ElapsedTicks++; + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.EmulateProcess(); + } + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + _tracks[trackIndex].StopAllChannels(); + } + } + public void LoadSong(long index) + { + Stop(); + SDAT.INFO.SequenceInfo oldSeqInfo = _seqInfo; + _seqInfo = _config.SDAT.INFOBlock.SequenceInfos.Entries[index]; + if (_seqInfo == null) + { + _sseq = null; + _sbnk = null; + Events = null; return; } - // If there's an exception, this will remain null - _loadedSong = new SDATLoadedSong(this, seqInfo); - _loadedSong.SetTicks(); - - ushort? old = _prevBank; - ushort nu = _loadedSong.SEQInfo.Bank; - if (old != nu) + if (oldSeqInfo == null || _seqInfo.Bank != oldSeqInfo.Bank) { - _prevBank = nu; Array.Clear(_voiceTypeCache); } + _sseq = new SSEQ(_config.SDAT.FATBlock.Entries[_seqInfo.FileId].Data); + SDAT.INFO.BankInfo bankInfo = _config.SDAT.INFOBlock.BankInfos.Entries[_seqInfo.Bank]; + _sbnk = new SBNK(_config.SDAT.FATBlock.Entries[bankInfo.FileId].Data); + for (int i = 0; i < 4; i++) + { + if (bankInfo.SWARs[i] != 0xFFFF) + { + _sbnk.SWARs[i] = new SWAR(_config.SDAT.FATBlock.Entries[_config.SDAT.INFOBlock.WaveArchiveInfos.Entries[bankInfo.SWARs[i]].FileId].Data); + } + } + _randSeed = new Random().Next(); + + // RECURSION INCOMING + Events = new List[0x10]; + AddTrackEvents(0, 0); + void AddTrackEvents(byte i, int trackStartOffset) + { + if (Events[i] == null) + { + Events[i] = new List(); + } + int callStackDepth = 0; + AddEvents(trackStartOffset); + bool EventExists(long offset) + { + return Events[i].Any(e => e.Offset == offset); + } + void AddEvents(int startOffset) + { + int dataOffset = startOffset; + int ReadArg(ArgType type) + { + switch (type) + { + case ArgType.Byte: + { + return _sseq.Data[dataOffset++]; + } + case ArgType.Short: + { + return _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8); + } + case ArgType.VarLen: + { + int read = 0, value = 0; + byte b; + do + { + b = _sseq.Data[dataOffset++]; + value = (value << 7) | (b & 0x7F); + read++; + } + while (read < 4 && (b & 0x80) != 0); + return value; + } + case ArgType.Rand: + { + // Combine min and max into one int + return _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16) | (_sseq.Data[dataOffset++] << 24); + } + case ArgType.PlayerVar: + { + // Return var index + return _sseq.Data[dataOffset++]; + } + default: throw new Exception(); + } + } + bool cont = true; + while (cont) + { + bool @if = false; + int offset = dataOffset; + ArgType argOverrideType = ArgType.None; + again: + byte cmd = _sseq.Data[dataOffset++]; + void AddEvent(T command) where T : SDATCommand, ICommand + { + command.RandMod = argOverrideType == ArgType.Rand; + command.VarMod = argOverrideType == ArgType.PlayerVar; + Events[i].Add(new SongEvent(offset, command)); + } + void Invalid() + { + throw new SDATInvalidCMDException(i, offset, cmd); + } + + if (cmd <= 0x7F) + { + byte velocity = _sseq.Data[dataOffset++]; + int duration = ReadArg(argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); + if (!EventExists(offset)) + { + AddEvent(new NoteComand { Note = cmd, Velocity = velocity, Duration = duration }); + } + } + else + { + int cmdGroup = cmd & 0xF0; + if (cmdGroup == 0x80) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); + switch (cmd) + { + case 0x80: + { + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = arg }); + } + break; + } + case 0x81: // RAND PROGRAM: [BW2 (2249)] + { + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = arg }); // TODO: Bank change + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0x90) + { + switch (cmd) + { + case 0x93: + { + byte trackIndex = _sseq.Data[dataOffset++]; + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new OpenTrackCommand { Track = trackIndex, Offset = offset24bit }); + AddTrackEvents(trackIndex, offset24bit); + } + break; + } + case 0x94: + { + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new JumpCommand { Offset = offset24bit }); + if (!EventExists(offset24bit)) + { + AddEvents(offset24bit); + } + } + if (!@if) + { + cont = false; + } + break; + } + case 0x95: + { + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new CallCommand { Offset = offset24bit }); + } + if (callStackDepth < 3) + { + if (!EventExists(offset24bit)) + { + callStackDepth++; + AddEvents(offset24bit); + } + } + else + { + throw new SDATTooManyNestedCallsException(i); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xA0) + { + switch (cmd) + { + case 0xA0: // [New Super Mario Bros (BGM_AMB_CHIKA)] [BW2 (1917, 1918)] + { + if (!EventExists(offset)) + { + AddEvent(new ModRandCommand()); + } + argOverrideType = ArgType.Rand; + offset++; + goto again; + } + case 0xA1: // [New Super Mario Bros (BGM_AMB_SABAKU)] + { + if (!EventExists(offset)) + { + AddEvent(new ModVarCommand()); + } + argOverrideType = ArgType.PlayerVar; + offset++; + goto again; + } + case 0xA2: // [Mario Kart DS (75)] [BW2 (1917, 1918)] + { + if (!EventExists(offset)) + { + AddEvent(new ModIfCommand()); + } + @if = true; + offset++; + goto again; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xB0) + { + byte varIndex = _sseq.Data[dataOffset++]; + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); + switch (cmd) + { + case 0xB0: + { + if (!EventExists(offset)) + { + AddEvent(new VarSetCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB1: + { + if (!EventExists(offset)) + { + AddEvent(new VarAddCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB2: + { + if (!EventExists(offset)) + { + AddEvent(new VarSubCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB3: + { + if (!EventExists(offset)) + { + AddEvent(new VarMulCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB4: + { + if (!EventExists(offset)) + { + AddEvent(new VarDivCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB5: + { + if (!EventExists(offset)) + { + AddEvent(new VarShiftCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB6: // [Mario Kart DS (75)] + { + if (!EventExists(offset)) + { + AddEvent(new VarRandCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB8: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpEECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB9: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpGECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBA: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpGGCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBB: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpLECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBC: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpLLCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBD: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpNECommand { Variable = varIndex, Argument = arg }); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xC0 || cmdGroup == 0xD0) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); + switch (cmd) + { + case 0xC0: + { + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = arg }); + } + break; + } + case 0xC1: + { + if (!EventExists(offset)) + { + AddEvent(new TrackVolumeCommand { Volume = arg }); + } + break; + } + case 0xC2: + { + if (!EventExists(offset)) + { + AddEvent(new PlayerVolumeCommand { Volume = arg }); + } + break; + } + case 0xC3: + { + if (!EventExists(offset)) + { + AddEvent(new TransposeCommand { Transpose = arg }); + } + break; + } + case 0xC4: + { + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = arg }); + } + break; + } + case 0xC5: + { + if (!EventExists(offset)) + { + AddEvent(new PitchBendRangeCommand { Range = arg }); + } + break; + } + case 0xC6: + { + if (!EventExists(offset)) + { + AddEvent(new PriorityCommand { Priority = arg }); + } + break; + } + case 0xC7: + { + if (!EventExists(offset)) + { + AddEvent(new MonophonyCommand { Mono = arg }); + } + break; + } + case 0xC8: + { + if (!EventExists(offset)) + { + AddEvent(new TieCommand { Tie = arg }); + } + break; + } + case 0xC9: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoControlCommand { Portamento = arg }); + } + break; + } + case 0xCA: + { + if (!EventExists(offset)) + { + AddEvent(new LFODepthCommand { Depth = arg }); + } + break; + } + case 0xCB: + { + if (!EventExists(offset)) + { + AddEvent(new LFOSpeedCommand { Speed = arg }); + } + break; + } + case 0xCC: + { + if (!EventExists(offset)) + { + AddEvent(new LFOTypeCommand { Type = arg }); + } + break; + } + case 0xCD: + { + if (!EventExists(offset)) + { + AddEvent(new LFORangeCommand { Range = arg }); + } + break; + } + case 0xCE: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoToggleCommand { Portamento = arg }); + } + break; + } + case 0xCF: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoTimeCommand { Time = arg }); + } + break; + } + case 0xD0: + { + if (!EventExists(offset)) + { + AddEvent(new ForceAttackCommand { Attack = arg }); + } + break; + } + case 0xD1: + { + if (!EventExists(offset)) + { + AddEvent(new ForceDecayCommand { Decay = arg }); + } + break; + } + case 0xD2: + { + if (!EventExists(offset)) + { + AddEvent(new ForceSustainCommand { Sustain = arg }); + } + break; + } + case 0xD3: + { + if (!EventExists(offset)) + { + AddEvent(new ForceReleaseCommand { Release = arg }); + } + break; + } + case 0xD4: + { + if (!EventExists(offset)) + { + AddEvent(new LoopStartCommand { NumLoops = arg }); + } + break; + } + case 0xD5: + { + if (!EventExists(offset)) + { + AddEvent(new TrackExpressionCommand { Expression = arg }); + } + break; + } + case 0xD6: + { + if (!EventExists(offset)) + { + AddEvent(new VarPrintCommand { Variable = arg }); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xE0) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); + switch (cmd) + { + case 0xE0: + { + if (!EventExists(offset)) + { + AddEvent(new LFODelayCommand { Delay = arg }); + } + break; + } + case 0xE1: + { + if (!EventExists(offset)) + { + AddEvent(new TempoCommand { Tempo = arg }); + } + break; + } + case 0xE3: + { + if (!EventExists(offset)) + { + AddEvent(new SweepPitchCommand { Pitch = arg }); + } + break; + } + default: Invalid(); break; + } + } + else // if (cmdGroup == 0xF0) + { + switch (cmd) + { + case 0xFC: // [HGSS(1353)] + { + if (!EventExists(offset)) + { + AddEvent(new LoopEndCommand()); + } + break; + } + case 0xFD: + { + if (!EventExists(offset)) + { + AddEvent(new ReturnCommand()); + } + if (!@if && callStackDepth != 0) + { + cont = false; + callStackDepth--; + } + break; + } + case 0xFE: + { + ushort bits = (ushort)ReadArg(ArgType.Short); + if (!EventExists(offset)) + { + AddEvent(new AllocTracksCommand { Tracks = bits }); + } + break; + } + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + if (!@if) + { + cont = false; + } + break; + } + default: Invalid(); break; + } + } + } + } + } + } + SetTicks(); } - public override void UpdateSongState(SongState info) + + public void SetCurrentPosition(long ticks) { - info.Tempo = Tempo; - for (int i = 0; i < 0x10; i++) + if (_seqInfo is null) + { + SongEnded?.Invoke(); + return; + } + if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) + { + return; + } + + if (State is PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + while (true) { - SDATTrack track = Tracks[i]; - if (track.Enabled) + if (ElapsedTicks == ticks) { - track.UpdateSongState(info.Tracks[i], _loadedSong!, _voiceTypeCache); + goto finish; } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + ExecuteNext(track); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.EmulateProcess(); + } + finish: + for (int i = 0; i < 0x10; i++) + { + _tracks[i].StopAllChannels(); } + Pause(); } - internal override void InitEmulation() + public void Play() { - Tempo = 120; // Confirmed: default tempo is 120 (MKDS 75) - TempoStack = 0; - _elapsedLoops = 0; - ElapsedTicks = 0; - SMixer.ResetFade(); - _loadedSong!.InitEmulation(); - for (int i = 0; i < 0x10; i++) + if (_seqInfo == null) { - Tracks[i].Init(); + SongEnded?.Invoke(); + return; } - // Initialize player and global variables. Global variables should not have a global effect in this program. - for (int i = 0; i < 0x20; i++) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - Vars[i] = i % 8 == 0 ? short.MaxValue : (short)0; + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } } - protected override void SetCurTick(long ticks) + public void Pause() { - _loadedSong!.SetCurTick(ticks); + if (State == PlayerState.Playing) + { + State = PlayerState.Paused; + WaitThread(); + } + else if (State == PlayerState.Paused || State == PlayerState.Stopped) + { + State = PlayerState.Playing; + CreateThread(); + } } - protected override void OnStopped() + public void Stop() { - for (int i = 0; i < 0x10; i++) + if (State == PlayerState.Playing || State == PlayerState.Paused) { - Tracks[i].StopAllChannels(); + State = PlayerState.Stopped; + WaitThread(); } } - - protected override bool Tick(bool playing, bool recording) + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() + { + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) + { + State = PlayerState.ShutDown; + WaitThread(); + } + } + private readonly string?[] _voiceTypeCache = new string?[256]; + public void UpdateSongState(SongState info) { - bool allDone = false; - while (!allDone && TempoStack >= 240) + info.Tempo = _tempo; + for (int i = 0; i < 0x10; i++) { - TempoStack -= 240; - allDone = true; - for (int i = 0; i < 0x10; i++) + Track track = _tracks[i]; + if (!track.Enabled) + { + continue; + } + + SongState.Track tin = info.Tracks[i]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.LFO = track.LFODepth * track.LFORange; + ref string? cache = ref _voiceTypeCache[track.Voice]; + if (cache is null) { - TickTrack(i, ref allDone); + if (_sbnk.NumInstruments <= track.Voice) + { + cache = "Empty"; + } + else + { + InstrumentType t = _sbnk.Instruments[track.Voice].Type; + switch (t) + { + case InstrumentType.PCM: cache = "PCM"; break; + case InstrumentType.PSG: cache = "PSG"; break; + case InstrumentType.Noise: cache = "Noise"; break; + case InstrumentType.Drum: cache = "Drum"; break; + case InstrumentType.KeySplit: cache = "Key Split"; break; + default: cache = "Invalid {0}" + (byte)t; break; + } + } } - if (SMixer.IsFadeDone()) + tin.Type = cache; + tin.Volume = track.Volume; + tin.PitchBend = track.GetPitch(); + tin.Extra = track.Portamento ? track.PortamentoTime : (byte)0; + tin.Panpot = track.GetPan(); + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + } + else { - allDone = true; + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (c.State != EnvelopeState.Release) + { + tin.Keys[numKeys++] = c.Note; + } + float a = (float)(-c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > left) + { + left = a; + } + a = (float)(c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > right) + { + right = a; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; } } - if (!allDone) + } + + private void TryStartChannel(SBNK.InstrumentData inst, Track track, byte note, byte velocity, int duration, out Channel? channel) + { + InstrumentType type = inst.Type; + channel = _mixer.AllocateChannel(type, track); + if (channel is null) { - TempoStack += Tempo; + return; } - for (int i = 0; i < 0x10; i++) + + if (track.Tie) { - SDATTrack track = Tracks[i]; - if (track.Enabled) + duration = -1; + } + SBNK.InstrumentData.DataParam param = inst.Param; + byte release = param.Release; + if (release == 0xFF) + { + duration = -1; + release = 0; + } + bool started = false; + switch (type) + { + case InstrumentType.PCM: + { + ushort[] info = param.Info; + SWAR.SWAV? swav = _sbnk.GetSWAV(info[1], info[0]); + if (swav is not null) + { + channel.StartPCM(swav, duration); + started = true; + } + break; + } + case InstrumentType.PSG: { - track.UpdateChannels(); + channel.StartPSG((byte)param.Info[0], duration); + started = true; + break; + } + case InstrumentType.Noise: + { + channel.StartNoise(duration); + started = true; + break; } } - SMixer.ChannelTick(); - SMixer.Process(playing, recording); - return allDone; + channel.Stop(); + if (!started) + { + return; + } + + channel.Note = note; + byte baseNote = param.BaseNote; + channel.BaseNote = type != InstrumentType.PCM && baseNote == 0x7F ? (byte)60 : baseNote; + channel.NoteVelocity = velocity; + channel.SetAttack(param.Attack); + channel.SetDecay(param.Decay); + channel.SetSustain(param.Sustain); + channel.SetRelease(release); + channel.StartingPan = (sbyte)(param.Pan - 0x40); + channel.Owner = track; + channel.Priority = track.Priority; + track.Channels.Add(channel); } - private void TickTrack(int trackIndex, ref bool allDone) + internal void PlayNote(Track track, byte note, byte velocity, int duration) { - SDATTrack track = Tracks[trackIndex]; - if (!track.Enabled) + Channel? channel = null; + if (track.Tie && track.Channels.Count != 0) { - return; + channel = track.Channels.Last(); + channel.Note = note; + channel.NoteVelocity = velocity; + } + else + { + SBNK.InstrumentData? inst = _sbnk.GetInstrumentData(track.Voice, note); + if (inst is not null) + { + TryStartChannel(inst, track, note, velocity, duration, out channel); + } + + if (channel is null) + { + return; + } } - track.Tick(); - SDATLoadedSong s = _loadedSong!; - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + if (track.Attack != 0xFF) + { + channel.SetAttack(track.Attack); + } + if (track.Decay != 0xFF) + { + channel.SetDecay(track.Decay); + } + if (track.Sustain != 0xFF) + { + channel.SetSustain(track.Sustain); + } + if (track.Release != 0xFF) + { + channel.SetRelease(track.Release); + } + channel.SweepPitch = track.SweepPitch; + if (track.Portamento) { - s.ExecuteNext(track); + channel.SweepPitch += (short)((track.PortamentoKey - note) << 6); // "<< 6" is "* 0x40" } - if (trackIndex == s.LongestTrack) + if (track.PortamentoTime != 0) { - HandleTicksAndLoop(s, track); + channel.SweepLength = (track.PortamentoTime * track.PortamentoTime * Math.Abs(channel.SweepPitch)) >> 11; // ">> 11" is "/ 0x800" + channel.AutoSweep = true; } - if (!track.Stopped || track.Channels.Count != 0) + else { - allDone = false; + channel.SweepLength = duration; + channel.AutoSweep = false; } + channel.SweepCounter = 0; } - private void HandleTicksAndLoop(SDATLoadedSong s, SDATTrack track) + private void ExecuteNext(Track track) { - if (ElapsedTicks != s.MaxTicks) + int ReadArg(ArgType type) { - ElapsedTicks++; - return; + if (track.ArgOverrideType != ArgType.None) + { + type = track.ArgOverrideType; + } + switch (type) + { + case ArgType.Byte: + { + return _sseq.Data[track.DataOffset++]; + } + case ArgType.Short: + { + return _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); + } + case ArgType.VarLen: + { + int read = 0, value = 0; + byte b; + do + { + b = _sseq.Data[track.DataOffset++]; + value = (value << 7) | (b & 0x7F); + read++; + } + while (read < 4 && (b & 0x80) != 0); + return value; + } + case ArgType.Rand: + { + short min = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); + short max = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); + return _rand.Next(min, max + 1); + } + case ArgType.PlayerVar: + { + byte varIndex = _sseq.Data[track.DataOffset++]; + return _vars[varIndex]; + } + default: throw new Exception(); + } } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + bool resetOverride = true; + bool resetCmdWork = true; + byte cmd = _sseq.Data[track.DataOffset++]; + if (cmd < 0x80) // Notes { - return; + byte velocity = _sseq.Data[track.DataOffset++]; + int duration = ReadArg(ArgType.VarLen); + if (track.DoCommandWork) + { + int k = cmd + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + byte key = (byte)k; + PlayNote(track, key, velocity, duration); + track.PortamentoKey = key; + if (track.Mono) + { + track.Rest = duration; + if (duration == 0) + { + track.WaitingForNoteToFinishBeforeContinuingXD = true; + } + } + } } - - _elapsedLoops++; - //UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.DataOffset, track.Rest); // TODO - // Prevent crashes with songs that don't load all ticks yet (See SetTicks()) - List evs = s.Events[track.Index]!; - for (int i = 0; i < evs.Count; i++) + else { - SongEvent ev = evs[i]; - if (ev.Offset == track.DataOffset) + int cmdGroup = cmd & 0xF0; + switch (cmdGroup) { - //ElapsedTicks = ev.Ticks[0] - track.Rest; - ElapsedTicks = ev.Ticks.Count == 0 ? 0 : ev.Ticks[0] - track.Rest; - break; + case 0x80: + { + int arg = ReadArg(ArgType.VarLen); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0x80: // Rest + { + track.Rest = arg; + break; + } + case 0x81: // Program Change + { + if (arg <= byte.MaxValue) + { + track.Voice = (byte)arg; + } + break; + } + } + } + break; + } + case 0x90: + { + switch (cmd) + { + case 0x93: // Open Track + { + int index = _sseq.Data[track.DataOffset++]; + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork && track.Index == 0) + { + Track other = _tracks[index]; + if (other.Allocated && !other.Enabled) + { + other.Enabled = true; + other.DataOffset = offset24bit; + } + } + break; + } + case 0x94: // Jump + { + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork) + { + track.DataOffset = offset24bit; + } + break; + } + case 0x95: // Call + { + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork && track.CallStackDepth < 3) + { + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackLoops[track.CallStackDepth] = byte.MaxValue; // This is only necessary for SetTicks() to deal with LoopStart (0) + track.CallStackDepth++; + track.DataOffset = offset24bit; + } + break; + } + } + break; + } + case 0xA0: + { + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xA0: // Rand Mod + { + track.ArgOverrideType = ArgType.Rand; + resetOverride = false; + break; + } + case 0xA1: // Var Mod + { + track.ArgOverrideType = ArgType.PlayerVar; + resetOverride = false; + break; + } + case 0xA2: // If Mod + { + track.DoCommandWork = track.VariableFlag; + resetCmdWork = false; + break; + } + } + } + break; + } + case 0xB0: + { + byte varIndex = _sseq.Data[track.DataOffset++]; + short mathArg = (short)ReadArg(ArgType.Short); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xB0: // VarSet + { + _vars[varIndex] = mathArg; + break; + } + case 0xB1: // VarAdd + { + _vars[varIndex] += mathArg; + break; + } + case 0xB2: // VarSub + { + _vars[varIndex] -= mathArg; + break; + } + case 0xB3: // VarMul + { + _vars[varIndex] *= mathArg; + break; + } + case 0xB4: // VarDiv + { + if (mathArg != 0) + { + _vars[varIndex] /= mathArg; + } + break; + } + case 0xB5: // VarShift + { + _vars[varIndex] = mathArg < 0 ? (short)(_vars[varIndex] >> -mathArg) : (short)(_vars[varIndex] << mathArg); + break; + } + case 0xB6: // VarRand + { + bool negate = false; + if (mathArg < 0) + { + negate = true; + mathArg = (short)-mathArg; + } + short val = (short)_rand.Next(mathArg + 1); + if (negate) + { + val = (short)-val; + } + _vars[varIndex] = val; + break; + } + case 0xB8: // VarCmpEE + { + track.VariableFlag = _vars[varIndex] == mathArg; + break; + } + case 0xB9: // VarCmpGE + { + track.VariableFlag = _vars[varIndex] >= mathArg; + break; + } + case 0xBA: // VarCmpGG + { + track.VariableFlag = _vars[varIndex] > mathArg; + break; + } + case 0xBB: // VarCmpLE + { + track.VariableFlag = _vars[varIndex] <= mathArg; + break; + } + case 0xBC: // VarCmpLL + { + track.VariableFlag = _vars[varIndex] < mathArg; + break; + } + case 0xBD: // VarCmpNE + { + track.VariableFlag = _vars[varIndex] != mathArg; + break; + } + } + } + break; + } + case 0xC0: + case 0xD0: + { + int cmdArg = ReadArg(ArgType.Byte); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xC0: // Panpot + { + track.Panpot = (sbyte)(cmdArg - 0x40); + break; + } + case 0xC1: // Track Volume + { + track.Volume = (byte)cmdArg; + break; + } + case 0xC2: // Player Volume + { + Volume = (byte)cmdArg; + break; + } + case 0xC3: // Transpose + { + track.Transpose = (sbyte)cmdArg; + break; + } + case 0xC4: // Pitch Bend + { + track.PitchBend = (sbyte)cmdArg; + break; + } + case 0xC5: // Pitch Bend Range + { + track.PitchBendRange = (byte)cmdArg; + break; + } + case 0xC6: // Priority + { + track.Priority = (byte)(Priority + (byte)cmdArg); + break; + } + case 0xC7: // Mono + { + track.Mono = cmdArg == 1; + break; + } + case 0xC8: // Tie + { + track.Tie = cmdArg == 1; + track.StopAllChannels(); + break; + } + case 0xC9: // Portamento Control + { + int k = cmdArg + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.PortamentoKey = (byte)k; + track.Portamento = true; + break; + } + case 0xCA: // LFO Depth + { + track.LFODepth = (byte)cmdArg; + break; + } + case 0xCB: // LFO Speed + { + track.LFOSpeed = (byte)cmdArg; + break; + } + case 0xCC: // LFO Type + { + track.LFOType = (LFOType)cmdArg; + break; + } + case 0xCD: // LFO Range + { + track.LFORange = (byte)cmdArg; + break; + } + case 0xCE: // Portamento Toggle + { + track.Portamento = cmdArg == 1; + break; + } + case 0xCF: // Portamento Time + { + track.PortamentoTime = (byte)cmdArg; + break; + } + case 0xD0: // Forced Attack + { + track.Attack = (byte)cmdArg; + break; + } + case 0xD1: // Forced Decay + { + track.Decay = (byte)cmdArg; + break; + } + case 0xD2: // Forced Sustain + { + track.Sustain = (byte)cmdArg; + break; + } + case 0xD3: // Forced Release + { + track.Release = (byte)cmdArg; + break; + } + case 0xD4: // Loop Start + { + if (track.CallStackDepth < 3) + { + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackLoops[track.CallStackDepth] = (byte)cmdArg; + track.CallStackDepth++; + } + break; + } + case 0xD5: // Track Expression + { + track.Expression = (byte)cmdArg; + break; + } + } + } + break; + } + case 0xE0: + { + int cmdArg = ReadArg(ArgType.Short); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xE0: // LFO Delay + { + track.LFODelay = (ushort)cmdArg; + break; + } + case 0xE1: // Tempo + { + _tempo = (ushort)cmdArg; + break; + } + case 0xE3: // Sweep Pitch + { + track.SweepPitch = (short)cmdArg; + break; + } + } + } + break; + } + case 0xF0: + { + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xFC: // Loop End + { + if (track.CallStackDepth != 0) + { + byte count = track.CallStackLoops[track.CallStackDepth - 1]; + if (count != 0) + { + count--; + track.CallStackLoops[track.CallStackDepth - 1] = count; + if (count == 0) + { + track.CallStackDepth--; + break; + } + } + track.DataOffset = track.CallStack[track.CallStackDepth - 1]; + } + break; + } + case 0xFD: // Return + { + if (track.CallStackDepth != 0) + { + track.CallStackDepth--; + track.DataOffset = track.CallStack[track.CallStackDepth]; + track.CallStackLoops[track.CallStackDepth] = 0; // This is only necessary for SetTicks() to deal with LoopStart (0) + } + break; + } + case 0xFE: // Alloc Tracks + { + // Must be in the beginning of the first track to work + if (track.Index == 0 && track.DataOffset == 1) // == 1 because we read cmd already + { + // Track 1 enabled = bit 1 set, Track 4 enabled = bit 4 set, etc + int trackBits = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); + for (int i = 0; i < 0x10; i++) + { + if ((trackBits & (1 << i)) != 0) + { + _tracks[i].Allocated = true; + } + } + } + break; + } + case 0xFF: // Finish + { + track.Stopped = true; + break; + } + } + } + break; + } } } - if (ShouldFadeOut && _elapsedLoops > NumLoops && !SMixer.IsFading()) + if (resetOverride) + { + track.ArgOverrideType = ArgType.None; + } + if (resetCmdWork) + { + track.DoCommandWork = true; + } + } + + private void Tick() + { + _time.Start(); + while (true) { - SMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + void MixerProcess() + { + for (int i = 0; i < 0x10; i++) + { + Track track = _tracks[i]; + if (track.Enabled) + { + track.UpdateChannels(); + } + } + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + bool allDone = true; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (!track.Enabled) + { + continue; + } + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + ExecuteNext(track); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + //ElapsedTicks = ev.Ticks[0] - track.Rest; + ElapsedTicks = ev.Ticks.Count == 0 ? 0 : ev.Ticks[0] - track.Rest; // Prevent crashes with songs that don't load all ticks yet (See SetTicks()) + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (!track.Stopped || track.Channels.Count != 0) + { + allDone = false; + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + MixerProcess(); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + MixerProcess(); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs b/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs deleted file mode 100644 index 87be5b5..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SDATTrack -{ - public readonly byte Index; - private readonly SDATPlayer _player; - - public bool Allocated; - public bool Enabled; - public bool Stopped; - public bool Tie; - public bool Mono; - public bool Portamento; - public bool WaitingForNoteToFinishBeforeContinuingXD; // TODO: Is this necessary? - public byte Voice; - public byte Priority; - public byte Volume; - public byte Expression; - public byte PitchBendRange; - public byte LFORange; - public byte LFOSpeed; - public byte LFODepth; - public ushort LFODelay; - public ushort LFOPhase; - public int LFOParam; - public ushort LFODelayCount; - public LFOType LFOType; - public sbyte PitchBend; - public sbyte Panpot; - public sbyte Transpose; - public byte Attack; - public byte Decay; - public byte Sustain; - public byte Release; - public byte PortamentoNote; - public byte PortamentoTime; - public short SweepPitch; - public int Rest; - public readonly int[] CallStack; - public readonly byte[] CallStackLoops; - public byte CallStackDepth; - public int DataOffset; - public bool VariableFlag; // Set by variable commands (0xB0 - 0xBD) - public bool DoCommandWork; - public ArgType ArgOverrideType; - - public readonly List Channels = new(0x10); - - public SDATTrack(byte i, SDATPlayer player) - { - Index = i; - _player = player; - - CallStack = new int[3]; - CallStackLoops = new byte[3]; - } - public void Init() - { - Stopped = Tie = WaitingForNoteToFinishBeforeContinuingXD = Portamento = false; - Allocated = Enabled = Index == 0; - DataOffset = 0; - ArgOverrideType = ArgType.None; - Mono = VariableFlag = DoCommandWork = true; - CallStackDepth = 0; - Voice = LFODepth = 0; - PitchBend = Panpot = Transpose = 0; - LFOPhase = LFODelay = LFODelayCount = 0; - LFORange = 1; - LFOSpeed = 0x10; - Priority = (byte)(_player.Priority + 0x40); - Volume = Expression = 0x7F; - Attack = Decay = Sustain = Release = 0xFF; - PitchBendRange = 2; - PortamentoNote = 60; - PortamentoTime = 0; - SweepPitch = 0; - LFOType = LFOType.Pitch; - Rest = 0; - StopAllChannels(); - } - public void LFOTick() - { - if (Channels.Count == 0) - { - LFOPhase = 0; - LFOParam = 0; - LFODelayCount = LFODelay; - } - else - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - else - { - int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; - if (LFOType == LFOType.Volume) - { - param = (int)(((long)param * 60) >> 14); - } - else - { - param >>= 8; - } - LFOParam = param; - int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" - while (counter >= 0x8000) - { - counter -= 0x8000; - } - LFOPhase = (ushort)counter; - } - } - } - public void Tick() - { - if (Rest > 0) - { - Rest--; - } - if (Channels.Count != 0) - { - // TickNotes: - for (int i = 0; i < Channels.Count; i++) - { - SDATChannel c = Channels[i]; - if (c.NoteDuration > 0) - { - c.NoteDuration--; - } - if (!c.AutoSweep && c.SweepCounter < c.SweepLength) - { - c.SweepCounter++; - } - } - } - else - { - WaitingForNoteToFinishBeforeContinuingXD = false; - } - } - public void UpdateChannels() - { - for (int i = 0; i < Channels.Count; i++) - { - SDATChannel c = Channels[i]; - c.LFOType = LFOType; - c.LFOSpeed = LFOSpeed; - c.LFODepth = LFODepth; - c.LFORange = LFORange; - c.LFODelay = LFODelay; - } - } - - public void StopAllChannels() - { - SDATChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - - public int GetPitch() - { - //int lfo = LFOType == LFOType.Pitch ? LFOParam : 0; - int lfo = 0; - return (PitchBend * PitchBendRange / 2) + lfo; - } - public int GetVolume() - { - //int lfo = LFOType == LFOType.Volume ? LFOParam : 0; - int lfo = 0; - return SDATUtils.SustainTable[_player.Volume] + SDATUtils.SustainTable[Volume] + SDATUtils.SustainTable[Expression] + lfo; - } - public sbyte GetPan() - { - //int lfo = LFOType == LFOType.Panpot ? LFOParam : 0; - int lfo = 0; - int p = Panpot + lfo; - if (p < -0x40) - { - p = -0x40; - } - else if (p > 0x3F) - { - p = 0x3F; - } - return (sbyte)p; - } - - public void UpdateSongState(SongState.Track tin, SDATLoadedSong loadedSong, string?[] voiceTypeCache) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.LFO = LFODepth * LFORange; - ref string? cache = ref voiceTypeCache[Voice]; - if (cache is null) - { - loadedSong.UpdateInstrumentCache(Voice, out cache); - } - tin.Type = cache; - tin.Volume = Volume; - tin.PitchBend = GetPitch(); - tin.Extra = Portamento ? PortamentoTime : (byte)0; - tin.Panpot = GetPan(); - - SDATChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - SDATChannel c = channels[j]; - if (c.State != EnvelopeState.Release) - { - tin.Keys[numKeys++] = c.Note; - } - float a = (float)(-c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > left) - { - left = a; - } - a = (float)(c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > right) - { - right = a; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SSEQ.cs b/VG Music Studio - Core/NDS/SDAT/SSEQ.cs index 22068c7..ec3859c 100644 --- a/VG Music Studio - Core/NDS/SDAT/SSEQ.cs +++ b/VG Music Studio - Core/NDS/SDAT/SSEQ.cs @@ -1,30 +1,31 @@ using Kermalis.EndianBinaryIO; using System.IO; -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SSEQ +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT { - public SDATFileHeader FileHeader; // "SSEQ" - public string BlockType; // "DATA" - public int BlockSize; - public int DataOffset; + internal sealed class SSEQ + { + public FileHeader FileHeader; // "SSEQ" + public string BlockType; // "DATA" + public int BlockSize; + public int DataOffset; - public byte[] Data; + public byte[] Data; - public SSEQ(byte[] bytes) - { - using (var stream = new MemoryStream(bytes)) + public SSEQ(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - BlockType = er.ReadString_Count(4); - BlockSize = er.ReadInt32(); - DataOffset = er.ReadInt32(); + using (var stream = new MemoryStream(bytes)) + { + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + BlockType = er.ReadString_Count(4); + BlockSize = er.ReadInt32(); + DataOffset = er.ReadInt32(); - Data = new byte[FileHeader.FileSize - DataOffset]; - stream.Position = DataOffset; - er.ReadBytes(Data); + Data = new byte[FileHeader.FileSize - DataOffset]; + stream.Position = DataOffset; + er.ReadBytes(Data); + } } } } diff --git a/VG Music Studio - Core/NDS/SDAT/SWAR.cs b/VG Music Studio - Core/NDS/SDAT/SWAR.cs index 5a5e64d..2af20c3 100644 --- a/VG Music Studio - Core/NDS/SDAT/SWAR.cs +++ b/VG Music Studio - Core/NDS/SDAT/SWAR.cs @@ -1,64 +1,64 @@ using Kermalis.EndianBinaryIO; using System.IO; -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SWAR +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT { - public sealed class SWAV + internal sealed class SWAR { - public SWAVFormat Format; - public bool DoesLoop; - public ushort SampleRate; - /// / - public ushort Timer; - public ushort LoopOffset; - public int Length; + public sealed class SWAV + { + public SWAVFormat Format; + public bool DoesLoop; + public ushort SampleRate; + public ushort Timer; // (NDSUtils.ARM7_CLOCK / SampleRate) + public ushort LoopOffset; + public int Length; - public byte[] Samples; + public byte[] Samples; - public SWAV(EndianBinaryReader er) - { - Format = er.ReadEnum(); - DoesLoop = er.ReadBoolean(); - SampleRate = er.ReadUInt16(); - Timer = er.ReadUInt16(); - LoopOffset = er.ReadUInt16(); - Length = er.ReadInt32(); + public SWAV(EndianBinaryReader er) + { + Format = er.ReadEnum(); + DoesLoop = er.ReadBoolean(); + SampleRate = er.ReadUInt16(); + Timer = er.ReadUInt16(); + LoopOffset = er.ReadUInt16(); + Length = er.ReadInt32(); - Samples = new byte[(LoopOffset * 4) + (Length * 4)]; - er.ReadBytes(Samples); + Samples = new byte[(LoopOffset * 4) + (Length * 4)]; + er.ReadBytes(Samples); + } } - } - public SDATFileHeader FileHeader; // "SWAR" - public string BlockType; // "DATA" - public int BlockSize; - public byte[] Padding; - public int NumWaves; - public int[] WaveOffsets; + public FileHeader FileHeader; // "SWAR" + public string BlockType; // "DATA" + public int BlockSize; + public byte[] Padding; + public int NumWaves; + public int[] WaveOffsets; - public SWAV[] Waves; + public SWAV[] Waves; - public SWAR(byte[] bytes) - { - using (var stream = new MemoryStream(bytes)) + public SWAR(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - BlockType = er.ReadString_Count(4); - BlockSize = er.ReadInt32(); - Padding = new byte[32]; - er.ReadBytes(Padding); - NumWaves = er.ReadInt32(); - WaveOffsets = new int[NumWaves]; - er.ReadInt32s(WaveOffsets); - - Waves = new SWAV[NumWaves]; - for (int i = 0; i < NumWaves; i++) + using (var stream = new MemoryStream(bytes)) { - stream.Position = WaveOffsets[i]; - Waves[i] = new SWAV(er); + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + BlockType = er.ReadString_Count(4); + BlockSize = er.ReadInt32(); + Padding = new byte[32]; + er.ReadBytes(Padding); + NumWaves = er.ReadInt32(); + WaveOffsets = new int[NumWaves]; + er.ReadInt32s(WaveOffsets); + + Waves = new SWAV[NumWaves]; + for (int i = 0; i < NumWaves; i++) + { + stream.Position = WaveOffsets[i]; + Waves[i] = new SWAV(er); + } } } } diff --git a/VG Music Studio - Core/NDS/SDAT/Track.cs b/VG Music Studio - Core/NDS/SDAT/Track.cs new file mode 100644 index 0000000..43a1435 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Track.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal sealed class Track + { + public readonly byte Index; + private readonly SDATPlayer _player; + + public bool Allocated; + public bool Enabled; + public bool Stopped; + public bool Tie; + public bool Mono; + public bool Portamento; + public bool WaitingForNoteToFinishBeforeContinuingXD; // TODO: Is this necessary? + public byte Voice; + public byte Priority; + public byte Volume; + public byte Expression; + public byte PitchBendRange; + public byte LFORange; + public byte LFOSpeed; + public byte LFODepth; + public ushort LFODelay; + public ushort LFOPhase; + public int LFOParam; + public ushort LFODelayCount; + public LFOType LFOType; + public sbyte PitchBend; + public sbyte Panpot; + public sbyte Transpose; + public byte Attack; + public byte Decay; + public byte Sustain; + public byte Release; + public byte PortamentoKey; + public byte PortamentoTime; + public short SweepPitch; + public int Rest; + public readonly int[] CallStack; + public readonly byte[] CallStackLoops; + public byte CallStackDepth; + public int DataOffset; + public bool VariableFlag; // Set by variable commands (0xB0 - 0xBD) + public bool DoCommandWork; + public ArgType ArgOverrideType; + + public readonly List Channels = new(0x10); + + public Track(byte i, SDATPlayer player) + { + Index = i; + _player = player; + + CallStack = new int[3]; + CallStackLoops = new byte[3]; + } + public void Init() + { + Stopped = Tie = WaitingForNoteToFinishBeforeContinuingXD = Portamento = false; + Allocated = Enabled = Index == 0; + DataOffset = 0; + ArgOverrideType = ArgType.None; + Mono = VariableFlag = DoCommandWork = true; + CallStackDepth = 0; + Voice = LFODepth = 0; + PitchBend = Panpot = Transpose = 0; + LFOPhase = LFODelay = LFODelayCount = 0; + LFORange = 1; + LFOSpeed = 0x10; + Priority = (byte)(_player.Priority + 0x40); + Volume = Expression = 0x7F; + Attack = Decay = Sustain = Release = 0xFF; + PitchBendRange = 2; + PortamentoKey = 60; + PortamentoTime = 0; + SweepPitch = 0; + LFOType = LFOType.Pitch; + Rest = 0; + StopAllChannels(); + } + public void LFOTick() + { + if (Channels.Count == 0) + { + LFOPhase = 0; + LFOParam = 0; + LFODelayCount = LFODelay; + } + else + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + else + { + int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; + if (LFOType == LFOType.Volume) + { + param = (int)(((long)param * 60) >> 14); + } + else + { + param >>= 8; + } + LFOParam = param; + int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" + while (counter >= 0x8000) + { + counter -= 0x8000; + } + LFOPhase = (ushort)counter; + } + } + } + public void Tick() + { + if (Rest > 0) + { + Rest--; + } + if (Channels.Count != 0) + { + // TickNotes: + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + if (c.NoteDuration > 0) + { + c.NoteDuration--; + } + if (!c.AutoSweep && c.SweepCounter < c.SweepLength) + { + c.SweepCounter++; + } + } + } + else + { + WaitingForNoteToFinishBeforeContinuingXD = false; + } + } + public void UpdateChannels() + { + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + c.LFOType = LFOType; + c.LFOSpeed = LFOSpeed; + c.LFODepth = LFODepth; + c.LFORange = LFORange; + c.LFODelay = LFODelay; + } + } + + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } + + public int GetPitch() + { + //int lfo = LFOType == LFOType.Pitch ? LFOParam : 0; + int lfo = 0; + return (PitchBend * PitchBendRange / 2) + lfo; + } + public int GetVolume() + { + //int lfo = LFOType == LFOType.Volume ? LFOParam : 0; + int lfo = 0; + return SDATUtils.SustainTable[_player.Volume] + SDATUtils.SustainTable[Volume] + SDATUtils.SustainTable[Expression] + lfo; + } + public sbyte GetPan() + { + //int lfo = LFOType == LFOType.Panpot ? LFOParam : 0; + int lfo = 0; + int p = Panpot + lfo; + if (p < -0x40) + { + p = -0x40; + } + else if (p > 0x3F) + { + p = 0x3F; + } + return (sbyte)p; + } + } +} diff --git a/VG Music Studio - Core/NDS/Utils.cs b/VG Music Studio - Core/NDS/Utils.cs new file mode 100644 index 0000000..601e832 --- /dev/null +++ b/VG Music Studio - Core/NDS/Utils.cs @@ -0,0 +1,7 @@ +namespace Kermalis.VGMusicStudio.Core.NDS +{ + internal static class Utils + { + public const int ARM7_CLOCK = 16_756_991; // (33.513982 MHz / 2) == 16.756991 MHz == 16,756,991 Hz + } +} diff --git a/VG Music Studio - Core/Player.cs b/VG Music Studio - Core/Player.cs index 453af4b..adb8fc8 100644 --- a/VG Music Studio - Core/Player.cs +++ b/VG Music Studio - Core/Player.cs @@ -1,8 +1,5 @@ -using Kermalis.VGMusicStudio.Core.Util; -using System; +using System; using System.Collections.Generic; -using System.IO; -using System.Threading; namespace Kermalis.VGMusicStudio.Core; @@ -17,179 +14,25 @@ public enum PlayerState : byte public interface ILoadedSong { - List?[] Events { get; } + List[] Events { get; } long MaxTicks { get; } + long ElapsedTicks { get; } } -public abstract class Player : IDisposable +public interface IPlayer : IDisposable { - protected abstract string Name { get; } - protected abstract Mixer Mixer { get; } - - public abstract ILoadedSong? LoadedSong { get; } - public bool ShouldFadeOut { get; set; } - public long NumLoops { get; set; } - - public long ElapsedTicks { get; internal set; } - public PlayerState State { get; protected set; } - public event Action? SongEnded; - - private readonly TimeBarrier _time; - private Thread? _thread; - - protected Player(double ticksPerSecond) - { - _time = new TimeBarrier(ticksPerSecond); - } - - public abstract void LoadSong(int index); - public abstract void UpdateSongState(SongState info); - internal abstract void InitEmulation(); - protected abstract void SetCurTick(long ticks); - protected abstract void OnStopped(); - - protected abstract bool Tick(bool playing, bool recording); - - protected void CreateThread() - { - _thread = new Thread(TimerTick) { Name = Name + " Tick" }; - _thread.Start(); - } - protected void WaitThread() - { - if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) - { - _thread.Join(); - } - } - protected void UpdateElapsedTicksAfterLoop(List evs, long trackEventOffset, long trackRest) - { - for (int i = 0; i < evs.Count; i++) - { - SongEvent ev = evs[i]; - if (ev.Offset == trackEventOffset) - { - ElapsedTicks = ev.Ticks[0] - trackRest; - return; - } - } - throw new InvalidDataException("No loop point found"); - } - - public void Play() - { - if (LoadedSong is null) - { - SongEnded?.Invoke(); - return; - } - - if (State is not PlayerState.ShutDown) - { - Stop(); - InitEmulation(); - State = PlayerState.Playing; - CreateThread(); - } - } - public void TogglePlaying() - { - switch (State) - { - case PlayerState.Playing: - { - State = PlayerState.Paused; - WaitThread(); - break; - } - case PlayerState.Paused: - case PlayerState.Stopped: - { - State = PlayerState.Playing; - CreateThread(); - break; - } - } - } - public void Stop() - { - if (State is PlayerState.Playing or PlayerState.Paused) - { - State = PlayerState.Stopped; - WaitThread(); - OnStopped(); - } - } - public void Record(string fileName) - { - Mixer.CreateWaveWriter(fileName); - - InitEmulation(); - State = PlayerState.Recording; - CreateThread(); - WaitThread(); - - Mixer.CloseWaveWriter(); - } - public void SetSongPosition(long ticks) - { - if (LoadedSong is null) - { - SongEnded?.Invoke(); - return; - } - - if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) - { - return; - } - - if (State is PlayerState.Playing) - { - TogglePlaying(); - } - InitEmulation(); - SetCurTick(ticks); - TogglePlaying(); - } - - private void TimerTick() - { - _time.Start(); - while (true) - { - PlayerState state = State; - bool playing = state == PlayerState.Playing; - bool recording = state == PlayerState.Recording; - if (!playing && !recording) - { - break; - } - - bool allDone = Tick(playing, recording); - if (allDone) - { - // TODO: lock state - _time.Stop(); // TODO: Don't need timer if recording - State = PlayerState.Stopped; - SongEnded?.Invoke(); - return; - } - if (playing) - { - _time.Wait(); - } - } - _time.Stop(); - } - - public void Dispose() - { - if (State != PlayerState.ShutDown) - { - State = PlayerState.ShutDown; - WaitThread(); - } - SongEnded = null; - } + ILoadedSong? LoadedSong { get; } + bool ShouldFadeOut { get; set; } + long NumLoops { get; set; } + + PlayerState State { get; } + event Action? SongEnded; + + void LoadSong(long index); + void SetCurrentPosition(long ticks); + void Play(); + void Pause(); + void Stop(); + void Record(string fileName); + void UpdateSongState(SongState info); } diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index eea96fb..5cada93 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -19,7 +19,7 @@ namespace Kermalis.VGMusicStudio.Core.Properties { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Strings { @@ -141,6 +141,15 @@ public static string ErrorBoolParse { } } + /// + /// Looks up a localized string similar to Color {0} has an invalid key.. + /// + public static string ErrorConfigColorInvalidKey { + get { + return ResourceManager.GetString("ErrorConfigColorInvalidKey", resourceCulture); + } + } + /// /// Looks up a localized string similar to Color {0} is not defined.. /// @@ -519,6 +528,15 @@ public static string MenuSaveWAV { } } + /// + /// Looks up a localized string similar to C;C#;D;D#;E;F;F#;G;G#;A;A#;B. + /// + public static string Notes { + get { + return ResourceManager.GetString("Notes", resourceCulture); + } + } + /// /// Looks up a localized string similar to Next Song. /// @@ -636,15 +654,6 @@ public static string PlayPlaylistBody { } } - /// - /// Looks up a localized string similar to songs|0_0|song|1_1|songs|2_*|. - /// - public static string Song_s_ { - get { - return ResourceManager.GetString("Song(s)", resourceCulture); - } - } - /// /// Looks up a localized string similar to VoiceTable saved to {0}.. /// @@ -734,5 +743,82 @@ public static string TrackViewerTrackX { return ResourceManager.GetString("TrackViewerTrackX", resourceCulture); } } + + /// + /// Looks up a localized string similar to GBA Files. + /// + public static string GTKFilterOpenGBA + { + get + { + return ResourceManager.GetString("GTKFilterOpenGBA", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SDAT Files. + /// + public static string GTKFilterOpenSDAT + { + get + { + return ResourceManager.GetString("GTKFilterOpenSDAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DLS Files. + /// + public static string GTKFilterSaveDLS + { + get + { + return ResourceManager.GetString("GTKFilterSaveDLS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MIDI Files. + /// + public static string GTKFilterSaveMIDI + { + get + { + return ResourceManager.GetString("GTKFilterSaveMIDI", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SF2 Files. + /// + public static string GTKFilterSaveSF2 + { + get + { + return ResourceManager.GetString("GTKFilterSaveSF2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKFilterSaveWAV + { + get + { + return ResourceManager.GetString("GTKFilterSaveWAV", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKAllFiles + { + get + { + return ResourceManager.GetString("GTKAllFiles", resourceCulture); + } + } } } diff --git a/VG Music Studio - Core/Properties/Strings.es.resx b/VG Music Studio - Core/Properties/Strings.es.resx index c524dfd..d98bb26 100644 --- a/VG Music Studio - Core/Properties/Strings.es.resx +++ b/VG Music Studio - Core/Properties/Strings.es.resx @@ -118,10 +118,10 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - ¿Quisiera detener la Lista de Repoducción actual? + Quisiera detener la Lista de Reproducción actual? - Error al Cargar la Canción {0} + Error al Cargar Canción {0} Error al Abrir Carpeta DSE @@ -169,11 +169,14 @@ Abrir Archivo SDAT - Lista de Reproducción + Playlist Exportar Canción como MIDI + + Do;Do#;Re;Re#;Mi;Fa;Fa#;Sol;Sol#;La;La#;Si + Siguiente Canción @@ -211,7 +214,7 @@ Música - ¿Quisiera reproducir la siguiente Lista de Reproducción? + Quisiera reproducir la siguiente Lista de Reproducción? {0} MIDI guardado en {0}. @@ -240,6 +243,9 @@ "{0}" debe ser Verdadero o Falso. + + El color {0} tiene una clave inválida. + El color {0} no está definido. @@ -268,7 +274,7 @@ No hay ningún archivo "bgm(NNNN).smd". - Error al Cargar la Configuración Global + Error al Cargar Configuración Global No se puede copiar, el código del juego "{0}" es inválido. @@ -339,7 +345,4 @@ DLS guardado en {0}. - - canciones|0_0|canción|1_1|canciones|2_*| - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.fr.resx b/VG Music Studio - Core/Properties/Strings.fr.resx deleted file mode 100644 index 0befad5..0000000 --- a/VG Music Studio - Core/Properties/Strings.fr.resx +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Echec de chargement du titre {0} - - - Echec du chargement de la ROM GBA (AlphaDream) - - - Echec de l'exportation en MIDI - - - Fichiers GBA - - - Fichiers MIDI - - - Données - - - Fichier - - - Ouvrir ROM GBA (MP2K) - - - Exporter le titre en MIDI - - - Silence - - - Notes - - - Pause - - - Lecture - - - Position - - - Stop - - - Tempo - - - Type - - - Dé-pause - - - MIDI enregistré sous {0}. - - - Voulez-vous lancer la playlist suivante ?{0} - - - Titre suivant - - - Titre précédent - - - Voulez-vous arrêter la lecture de la playlist en cours ? - - - Echec de chargement du dossier DSE - - - Echec de chargement de la ROM GBA (MP2K) - - - Echec de lecture du fichier SDAT - - - Fichiers SDAT - - - Arrêter la playlist en cours - - - Ouvrir dossier DSE - - - Ouvrir ROM GBA (AlphaDream) - - - Ouvrir fichier SDAT - - - Playlist - - - Musique - - - Arguments - - - Event - - - Offset - - - Ticks - - - Visualiseur de pistes - - - Piste {0} - - - Clé {0} - - - "{0}" doit être Vrai ou Faux - - - La couleur {0} n'est pas définie. - - - La couleur {0} est définie plus d'une fois entre le décimal et l'hexadécimal. - - - "{0}" est invalide. - - - "{0}" est manquante. - - - "{0}" doit avoir au moins une entrée. - - - Version d'en-tête inconnue: 0x{0:X} - - - Clé invalide pour la piste {0} à l'adresse 0x{1:X}: {2} - - - Commande invalide pour la piste {0} à l'adresse 0x{1:X}: 0x{2:X} - - - Il n'y a pas de fichiers "bgm(NNNN).smd". - - - Echec du chargement de la configuration globale. - - - Impossible de copier le code de jeu invalide "{0}" - - - Le code de jeu "{0}" est manquant. - - - Erreur au parsage du code de jeu "{0}" dans "{1}"{2} - - - Le titre {1} de la playlist "{0}" est défini plus d'une fois entre le décimal et l'hexadécimal. - - - Le compte de "{0}" doit être identique au compte de "{1}". - - - Commande de statut de lecture invalide sur la piste {0} à l'adresse 0x{1:X}: 0x{2:X} - - - Trop d'events d'appel imbriqués sur la piste {0} - - - Echec du parsage de "{0}"{1} - - - Cet archive SDAT n'a pas de séquences. - - - "{0}" n'est pas un entier. - - - "{0}" doit être entre {1} et {2}. - - - Echec de l'exportation en WAV - - - Fichiers WAV - - - Exporter le titre en WAV - - - WAV sauvegardé sous {0}. - - - Echec de l'exportation en SF2 - - - Fichiers SF2 - - - Exporter la VoiceTable en SF2 - - - VoiceTable sauvegardée sous {0}. - - - Echec de l'exportation en DLS - - - Fichiers DLS - - - Exporter la VoiceTable en DLS - - - VoiceTable sauvegardée sous {0}. - - - titres|0_0|titre|1_1|titres|2_*| - - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.it.resx b/VG Music Studio - Core/Properties/Strings.it.resx index 6da605e..935f17e 100644 --- a/VG Music Studio - Core/Properties/Strings.it.resx +++ b/VG Music Studio - Core/Properties/Strings.it.resx @@ -144,6 +144,9 @@ Esporta Brano in MIDI + + Do;Do#;Re;Re#;Mi;Fa;Fa#;Sol;Sol#;La;La#;Si + Pausa @@ -240,6 +243,9 @@ "{0}" deve essere Vero o Falso. + + Il colore {0} non ha una chiave valida. + Il colore {0} non è definito. @@ -339,7 +345,4 @@ VoiceTable salvata in {0}. - - canzoni|0_0|canzone|1_1|canzoni|2_*| - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 916279d..c88d68c 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,16 +128,16 @@ Error Exporting MIDI - GBA Files + Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.* - MIDI Files + MIDI Files (*.mid, *.midi)|*.mid;*.midi - Data + _Data - File + _File Open GBA ROM (MP2K) @@ -145,6 +145,9 @@ Export Song as MIDI + + C;C#;D;D#;E;F;F#;G;G#;A;A#;B + Rest @@ -199,7 +202,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.* End Current Playlist @@ -246,6 +249,10 @@ "{0}" must be True or False. {0} is the value name. + + Color {0} has an invalid key. + {0} is the color number. + Color {0} is not defined. {0} is the color number. @@ -331,7 +338,7 @@ Error Exporting WAV - WAV Files + WAV Files (*.wav)|*.wav Export Song as WAV @@ -344,7 +351,7 @@ Error Exporting SF2 - SF2 Files + SF2 Files (*.sf2)|*.sf2 Export VoiceTable as SF2 @@ -357,7 +364,7 @@ Error Exporting DLS - DLS Files + DLS Files (*.dls)|*.dls Export VoiceTable as DLS @@ -366,7 +373,25 @@ VoiceTable saved to {0}. {0} is the file name. - - songs|0_0|song|1_1|songs|2_*| + + Game Boy Advance binary (*.gba, *.srl) + + + Nitro Soundmaker Sound Data (*.sdat) + + + DLS Soundfont Files (*.dls) + + + MIDI Sequence Files (*.mid, *.midi) + + + SF2 Soundfont Files (*.sf2) + + + Wave Audio Data (*.wav) + + + All files (*.*) \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.ru.resx b/VG Music Studio - Core/Properties/Strings.ru.resx deleted file mode 100644 index b35e074..0000000 --- a/VG Music Studio - Core/Properties/Strings.ru.resx +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Ошибка во время загрузки мелодии {0} - - - Ошибка во время загрузки GBA-ROMа (AlphaDream) - - - Ошибка во время экспорта MIDI - - - GBA-файлы - - - MIDI-файлы - - - Данные - - - Файл - - - Открыть GBA-ROM (MP2K) - - - Экспортировать мелодию в формате MIDI - - - Длительность - - - Ноты - - - Пауза - - - Проиграть - - - Адрес - - - Остановить - - - Темп - - - Тип - - - Продолжить - - - Мелодия успешно сохранена в MIDI-файл "{0}". - - - Хотите прослушать данный плейлист?{0} - - - Следующая мелодия - - - Предыдущая мелодия - - - Хотите прервать воспроизведение плейлиста? - - - При открытии DSE-папки произошла ошибка - - - При открытии GBA-ROMа (MP2K) произошла ошибка - - - При открытии SDAT-файла произошла ошибка - - - SDAT-файлы - - - Отключить плейлист - - - Открыть DSE-папку - - - Открыть GBA-ROM (AlphaDream) - - - Открыть SDAT-файл - - - Плейлист - - - Музыка - - - Аргументы - - - Событие - - - Адрес - - - Такты - - - Просмотр трека - - - Трек {0} - - - Родительский ключ {0} - - - "{0}" должно принимать значения True или False. - - - Цвет {0} не указан. - - - Цвет {0} указан несколько раз среди десятичных и шестнадцатеричных значений. - - - Родительский ключ "{0}" недопустим. - - - Родительский ключ "{0}" отсутствует. - - - Родительский ключ "{0}" должен содержать хотя бы одно значение. - - - Неизвестная версия заголовка: 0x{0:X} - - - Недопустимый родительский ключ в треке {0} по адресу 0x{1:X}: {2} - - - Недопустимая команда в треке {0} по адресу 0x{1:X}: 0x{2:X} - - - Файлы типа "bgm(NNNN).smd" отсутствуют. - - - Ошибка загрузки глобальной конфигурвции - - - Невозможно скопировать недопустимый игровой код "{0}" - - - Игровой код "{0}" отсутствует. - - - Ошибка во время анализа игрового кода "{0}" в файле "{1}"{2} - - - В плейлисте "{0}" содержится мелодия {1}, которая указана несколько раз среди десятичных и шестнадцатеричных значений. - - - Значения родительских ключей "{0}" и "{1}" должны совпадать. - - - Недопустимая команда состояния в треке {0} по адресу 0x{1:X}: 0x{2:X} - - - Слишком много случаев вызовов вложенных функций в треке {0} - - - Ошибка анализа файла "{0}"{1} - - - В указанном SDAT-архиве отсутствуют секвенции. - - - Значение "{0}" должно содержать целое число. - - - Значение "{0}" должно находиться в диапазоне от "{1}" до "{2}". - - - При экспорте WAV-файла произошла ошибка - - - WAV-файлы - - - Экспортировать мелодию в формате WAV - - - Мелодия успешно сохранена в WAV-файл "{0}". - - - При экспорте SF2-файла произошла ошибка - - - SF2-файлы - - - Экспортировать таблицу семплов в формате SF2 - - - Таблица семплов успешно сохранена в файл "{0}". - - - При экспорте DLS-файла произошла ошибка - - - DLS-файлы - - - Экспортировать таблицу семплов в формате DLS - - - Таблица семплов успешно сохранена в файл "{0}". - - - мелодий|0_0|мелодия|1_1|мелодии|2_4|мелодий|5_*| - - \ No newline at end of file diff --git a/VG Music Studio - Core/SongState.cs b/VG Music Studio - Core/SongState.cs index c3035a7..8987c14 100644 --- a/VG Music Studio - Core/SongState.cs +++ b/VG Music Studio - Core/SongState.cs @@ -1,70 +1,71 @@ -namespace Kermalis.VGMusicStudio.Core; - -public sealed class SongState +namespace Kermalis.VGMusicStudio.Core { - public sealed class Track + public sealed class SongState { - public long Position; - public byte Voice; - public byte Volume; - public int LFO; - public long Rest; - public sbyte Panpot; - public float LeftVolume; - public float RightVolume; - public int PitchBend; - public byte Extra; - public string Type; - public byte[] Keys; + public sealed class Track + { + public long Position; + public byte Voice; + public byte Volume; + public int LFO; + public long Rest; + public sbyte Panpot; + public float LeftVolume; + public float RightVolume; + public int PitchBend; + public byte Extra; + public string Type; + public byte[] Keys; - public int PreviousKeysTime; // TODO: Fix - public string PreviousKeys; + public int PreviousKeysTime; // TODO: Fix + public string PreviousKeys; - public Track() - { - Keys = new byte[MAX_KEYS]; - for (int i = 0; i < MAX_KEYS; i++) + public Track() { - Keys[i] = byte.MaxValue; + Keys = new byte[MAX_KEYS]; + for (int i = 0; i < MAX_KEYS; i++) + { + Keys[i] = byte.MaxValue; + } } - } - public void Reset() - { - Position = Rest = 0; - Voice = Volume = Extra = 0; - LFO = PitchBend = PreviousKeysTime = 0; - Panpot = 0; - LeftVolume = RightVolume = 0f; - Type = PreviousKeys = null; - for (int i = 0; i < MAX_KEYS; i++) + public void Reset() { - Keys[i] = byte.MaxValue; + Position = Rest = 0; + Voice = Volume = Extra = 0; + LFO = PitchBend = PreviousKeysTime = 0; + Panpot = 0; + LeftVolume = RightVolume = 0f; + Type = PreviousKeys = null; + for (int i = 0; i < MAX_KEYS; i++) + { + Keys[i] = byte.MaxValue; + } } } - } - public const int MAX_KEYS = 32 + 1; // DSE is currently set to use 32 channels - public const int MAX_TRACKS = 18; // PMD2 has a few songs with 18 tracks + public const int MAX_KEYS = 32 + 1; // DSE is currently set to use 32 channels + public const int MAX_TRACKS = 18; // PMD2 has a few songs with 18 tracks - public ushort Tempo; - public Track[] Tracks; + public ushort Tempo; + public Track[] Tracks; - public SongState() - { - Tracks = new Track[MAX_TRACKS]; - for (int i = 0; i < MAX_TRACKS; i++) + public SongState() { - Tracks[i] = new Track(); + Tracks = new Track[MAX_TRACKS]; + for (int i = 0; i < MAX_TRACKS; i++) + { + Tracks[i] = new Track(); + } } - } - public void Reset() - { - Tempo = 0; - for (int i = 0; i < MAX_TRACKS; i++) + public void Reset() { - Tracks[i].Reset(); + Tempo = 0; + for (int i = 0; i < MAX_TRACKS; i++) + { + Tracks[i].Reset(); + } } } } diff --git a/VG Music Studio - Core/Util/ConfigUtils.cs b/VG Music Studio - Core/Util/ConfigUtils.cs index af490fa..ff25770 100644 --- a/VG Music Studio - Core/Util/ConfigUtils.cs +++ b/VG Music Studio - Core/Util/ConfigUtils.cs @@ -10,9 +10,7 @@ namespace Kermalis.VGMusicStudio.Core.Util; public static class ConfigUtils { public const string PROGRAM_NAME = "VG Music Studio"; - private static readonly string[] _notes = new string[12] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; - private static readonly CultureInfo _enUS = new("en-US"); - private static readonly Dictionary _keyCache = new(128); + private static readonly string[] _notes = Strings.Notes.Split(';'); public static bool TryParseValue(string value, long minValue, long maxValue, out long outValue) { @@ -35,7 +33,8 @@ string GetMessage() return string.Format(Strings.ErrorValueParseRanged, valueName, minValue, maxValue); } - if (value.StartsWith("0x") && long.TryParse(value.AsSpan(2), NumberStyles.HexNumber, _enUS, out long hexp)) + var provider = new CultureInfo("en-US"); + if (value.StartsWith("0x") && long.TryParse(value.AsSpan(2), NumberStyles.HexNumber, provider, out long hexp)) { if (hexp < minValue || hexp > maxValue) { @@ -43,7 +42,7 @@ string GetMessage() } return hexp; } - else if (long.TryParse(value, NumberStyles.Integer, _enUS, out long dec)) + else if (long.TryParse(value, NumberStyles.Integer, provider, out long dec)) { if (dec < minValue || dec > maxValue) { @@ -51,7 +50,7 @@ string GetMessage() } return dec; } - else if (long.TryParse(value, NumberStyles.HexNumber, _enUS, out long hex)) + else if (long.TryParse(value, NumberStyles.HexNumber, provider, out long hex)) { if (hex < minValue || hex > maxValue) { @@ -110,28 +109,6 @@ public static TEnum GetValidEnum(this YamlMappingNode yamlNode, string ke return ParseEnum(key, yamlNode.Children.GetValue(key).ToString()); } - public static void TryCreateMasterPlaylist(List playlists) - { - if (playlists.Exists(p => p.Name == "Music")) - { - return; - } - - var songs = new List(); - foreach (Config.Playlist p in playlists) - { - foreach (Config.Song s in p.Songs) - { - if (!songs.Exists(s1 => s1.Index == s.Index)) - { - songs.Add(s); - } - } - } - songs.Sort((s1, s2) => s1.Index.CompareTo(s2.Index)); - playlists.Insert(0, new Config.Playlist(Strings.PlaylistMusic, songs)); - } - public static string CombineWithBaseDirectory(string path) { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path); @@ -141,13 +118,9 @@ public static string GetNoteName(int note) { return _notes[note]; } + // TODO: Cache results? public static string GetKeyName(int note) { - if (!_keyCache.TryGetValue(note, out string? str)) - { - str = _notes[note % 12] + ((note / 12) + (GlobalConfig.Instance.MiddleCOctave - 5)); - _keyCache.Add(note, str); - } - return str; + return _notes[note % 12] + ((note / 12) + (GlobalConfig.Instance.MiddleCOctave - 5)); } } diff --git a/VG Music Studio - Core/Util/DataUtils.cs b/VG Music Studio - Core/Util/DataUtils.cs deleted file mode 100644 index fe16180..0000000 --- a/VG Music Studio - Core/Util/DataUtils.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.IO; - -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class DataUtils -{ - public static void Align(this Stream s, int num) - { - while (s.Position % num != 0) - { - s.Position++; - } - } -} diff --git a/VG Music Studio - Core/Util/GlobalConfig.cs b/VG Music Studio - Core/Util/GlobalConfig.cs index 87ee284..106f805 100644 --- a/VG Music Studio - Core/Util/GlobalConfig.cs +++ b/VG Music Studio - Core/Util/GlobalConfig.cs @@ -58,9 +58,29 @@ private GlobalConfig() { throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorConfigColorRepeated, i))); } - - string valueName = string.Format(Strings.ConfigKeySubkey, string.Format("{0} {1}", nameof(Colors), i)); - var co = Color.FromArgb((int)(0xFF000000 + (uint)ConfigUtils.ParseValue(valueName, c.Value.ToString(), 0x000000, 0xFFFFFF))); + long h = 0, s = 0, l = 0; + foreach (KeyValuePair v in ((YamlMappingNode)c.Value).Children) + { + string key = v.Key.ToString(); + string valueName = string.Format(Strings.ConfigKeySubkey, string.Format("{0} {1}", nameof(Colors), i)); + if (key == "H") + { + h = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else if (key == "S") + { + s = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else if (key == "L") + { + l = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else + { + throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorConfigColorInvalidKey, i))); + } + } + var co = HSLColor.ToColor((int)h, (byte)s, (byte)l); Colors[i] = co; Colors[i + 128] = co; } diff --git a/VG Music Studio - Core/Util/HSLColor.cs b/VG Music Studio - Core/Util/HSLColor.cs index b2b7ee7..ab371dd 100644 --- a/VG Music Studio - Core/Util/HSLColor.cs +++ b/VG Music Studio - Core/Util/HSLColor.cs @@ -1,140 +1,144 @@ using System; +using System.Collections.Generic; using System.Drawing; +using System.Linq; namespace Kermalis.VGMusicStudio.Core.Util; -// https://www.rapidtables.com/convert/color/rgb-to-hsl.html -// https://www.rapidtables.com/convert/color/hsl-to-rgb.html -// Not really used right now, but will be very useful if we are going to use OpenGL public readonly struct HSLColor { - /// [0, 1) - public readonly double Hue; - /// [0, 1] - public readonly double Saturation; - /// [0, 1] - public readonly double Lightness; - - public HSLColor(double h, double s, double l) + public readonly int H; + public readonly byte S; + public readonly byte L; + + public HSLColor(int h, byte s, byte l) { - Hue = h; - Saturation = s; - Lightness = l; + H = h; + S = s; + L = l; } public HSLColor(in Color c) { - double nR = c.R / 255.0; - double nG = c.G / 255.0; - double nB = c.B / 255.0; - - double max = Math.Max(Math.Max(nR, nG), nB); - double min = Math.Min(Math.Min(nR, nG), nB); - double delta = max - min; + double modifiedR, modifiedG, modifiedB, min, max, delta, h, s, l; - Lightness = (min + max) * 0.5; + modifiedR = c.R / 255.0; + modifiedG = c.G / 255.0; + modifiedB = c.B / 255.0; - if (delta == 0) - { - Hue = 0; - } - else if (max == nR) - { - Hue = (nG - nB) / delta % 6 / 6; - } - else if (max == nG) - { - Hue = (((nB - nR) / delta) + 2) / 6; - } - else // max == nB - { - Hue = (((nR - nG) / delta) + 4) / 6; - } + min = new List(3) { modifiedR, modifiedG, modifiedB }.Min(); + max = new List(3) { modifiedR, modifiedG, modifiedB }.Max(); + delta = max - min; + l = (min + max) / 2; if (delta == 0) { - Saturation = 0; + h = 0; + s = 0; } else { - Saturation = delta / (1 - Math.Abs((2 * Lightness) - 1)); + s = (l <= 0.5) ? (delta / (min + max)) : (delta / (2 - max - min)); + + if (modifiedR == max) + { + h = (modifiedG - modifiedB) / 6 / delta; + } + else if (modifiedG == max) + { + h = (1.0 / 3) + ((modifiedB - modifiedR) / 6 / delta); + } + else + { + h = (2.0 / 3) + ((modifiedR - modifiedG) / 6 / delta); + } + + h = (h < 0) ? ++h : h; + h = (h > 1) ? --h : h; } + + H = (int)Math.Round(h * 360); + S = (byte)Math.Round(s * 100); + L = (byte)Math.Round(l * 100); } public Color ToColor() { - return ToColor(Hue, Saturation, Lightness); + return ToColor(H, S, L); } - public static void ToRGB(double h, double s, double l, out double r, out double g, out double b) + // https://github.com/iamartyom/ColorHelper/blob/master/ColorHelper/Converter/ColorConverter.cs + public static Color ToColor(int h, byte s, byte l) { - h *= 360; + double modifiedH, modifiedS, modifiedL, + r = 1, g = 1, b = 1, + q, p; - double c = (1 - Math.Abs((2 * l) - 1)) * s; - double x = c * (1 - Math.Abs((h / 60 % 2) - 1)); - double m = l - (c * 0.5); + modifiedH = h / 360.0; + modifiedS = s / 100.0; + modifiedL = l / 100.0; - if (h < 60) + q = (modifiedL < 0.5) ? modifiedL * (1 + modifiedS) : modifiedL + modifiedS - modifiedL * modifiedS; + p = 2 * modifiedL - q; + + if (modifiedL == 0) // If the lightness value is 0 it will always be black { - r = c; - g = x; + r = 0; + g = 0; b = 0; } - else if (h < 120) + else if (modifiedS != 0) { - r = x; - g = c; - b = 0; + r = GetHue(p, q, modifiedH + 1.0 / 3); + g = GetHue(p, q, modifiedH); + b = GetHue(p, q, modifiedH - 1.0 / 3); } - else if (h < 180) + + return Color.FromArgb(255, (byte)Math.Round(r * 255), (byte)Math.Round(g * 255), (byte)Math.Round(b * 255)); + } + private static double GetHue(double p, double q, double t) + { + double value = p; + + if (t < 0) { - r = 0; - g = c; - b = x; + t++; } - else if (h < 240) + else if (t > 1) { - r = 0; - g = x; - b = c; + t--; } - else if (h < 300) + + if (t < 1.0 / 6) { - r = x; - g = 0; - b = c; + value = p + (q - p) * 6 * t; } - else // h < 360 + else if (t < 1.0 / 2) { - r = c; - g = 0; - b = x; + value = q; + } + else if (t < 2.0 / 3) + { + value = p + (q - p) * (2.0 / 3 - t) * 6; } - r += m; - g += m; - b += m; - } - public static Color ToColor(double h, double s, double l) - { - ToRGB(h, s, l, out double r, out double g, out double b); - return Color.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255)); + return value; } public override bool Equals(object? obj) { if (obj is HSLColor other) { - return Hue == other.Hue && Saturation == other.Saturation && Lightness == other.Lightness; + return H == other.H && S == other.S && L == other.L; } return false; } public override int GetHashCode() { - return HashCode.Combine(Hue, Saturation, Lightness); + return HashCode.Combine(H, S, L); } public override string ToString() { - return $"{Hue * 360}° {Saturation:P} {Lightness:P}"; + return $"{H}° {S}% {L}%"; } public static bool operator ==(HSLColor left, HSLColor right) diff --git a/VG Music Studio - Core/Util/LanguageUtils.cs b/VG Music Studio - Core/Util/LanguageUtils.cs deleted file mode 100644 index ad1bc50..0000000 --- a/VG Music Studio - Core/Util/LanguageUtils.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class LanguageUtils -{ - // Try to handle lang strings like "мелодий|0_0|мелодия|1_1|мелодии|2_4|мелодий|5_*|" - public static string HandlePlural(int count, string str) - { - string[] split = str.Split('|', StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < split.Length; i += 2) - { - string text = split[i]; - string range = split[i + 1]; - - int rangeSplit = range.IndexOf('_'); - int rangeStart = GetPluralRangeValue(range.AsSpan(0, rangeSplit), int.MinValue); - int rangeEnd = GetPluralRangeValue(range.AsSpan(rangeSplit + 1), int.MaxValue); - if (count >= rangeStart && count <= rangeEnd) - { - return text; - } - } - throw new ArgumentOutOfRangeException(nameof(str), str, "Could not find plural entry"); - } - private static int GetPluralRangeValue(ReadOnlySpan chars, int star) - { - return chars.Length == 1 && chars[0] == '*' ? star : int.Parse(chars); - } -} diff --git a/VG Music Studio - Core/Util/SampleUtils.cs b/VG Music Studio - Core/Util/SampleUtils.cs index cbce3fb..057499e 100644 --- a/VG Music Studio - Core/Util/SampleUtils.cs +++ b/VG Music Studio - Core/Util/SampleUtils.cs @@ -1,15 +1,19 @@ using System; -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class SampleUtils +namespace Kermalis.VGMusicStudio.Core.Util { - public static void PCMU8ToPCM16(ReadOnlySpan src, Span dest) + internal static class SampleUtils { - for (int i = 0; i < src.Length; i++) + // TODO: Span output? + public static short[] PCMU8ToPCM16(ReadOnlySpan data) { - byte b = src[i]; - dest[i] = (short)((b - 0x80) << 8); + short[] ret = new short[data.Length]; + for (int i = 0; i < data.Length; i++) + { + byte b = data[i]; + ret[i] = (short)((b - 0x80) << 8); + } + return ret; } } } diff --git a/VG Music Studio - Core/Util/TimeBarrier.cs b/VG Music Studio - Core/Util/TimeBarrier.cs index 5379357..fab0ae5 100644 --- a/VG Music Studio - Core/Util/TimeBarrier.cs +++ b/VG Music Studio - Core/Util/TimeBarrier.cs @@ -13,9 +13,9 @@ internal sealed class TimeBarrier private double _lastTimeStamp; private bool _started; - public TimeBarrier(double ticksPerSecond) + public TimeBarrier(double framesPerSecond) { - _waitInterval = 1.0 / ticksPerSecond; + _waitInterval = 1.0 / framesPerSecond; _started = false; _sw = new Stopwatch(); _timerInterval = 1.0 / Stopwatch.Frequency; diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index f82177d..c60a0f8 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -14,13 +14,17 @@ - + + + + + Dependencies\DLS2.dll - Dependencies\SoundFont2.dll + Dependencies\SoundFont2.dll @@ -39,16 +43,4 @@ - - - True - True - Strings.resx - - - PublicResXFileCodeGenerator - Strings.Designer.cs - - - diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..01921eb --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,875 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal sealed class MainWindow : Window + { + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + #endregion + + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + + _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + { + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + } + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + if (Engine.Instance != null) + { + DisposeEngine(); + } + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; + _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..0f13fcc --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..f18377e --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,16 @@ + + + + Exe + net6.0 + + + + + + + + + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..d151b67 --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1369 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; + +using Application = Adw.Application; +using Window = Adw.Window; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class MainWindow : Window +{ + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + private int _duration = 0; + private int _position = 0; + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private readonly Adjustment _volumeAdjustment, _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; + + // Sound Sequence List + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); + _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + //_volumeScale.OnValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + //_positionScale.SetRange(0, double.MaxValue); + _positionGestureClick = GestureClick.New(); + //if (_positionGestureClick.Button == 1) + // { + // _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + // _positionScale.OnValueChanged += PositionScale_MouseButtonPress; + // } + //_positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + + SetContent(_mainBox); + + Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance!.Player.SetCurrentPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + //_positionScale.Adjustment!.Upper = double.MaxValue; + _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); + _positionScale.SetRange(0, _duration); + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; + _positionScale.Show(); + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ enableds; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); + return; + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + _timer.Start(); + Show(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + Show(); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + if (ticks < _duration) + { + // TODO: Implement GStreamer functions to replace Gtk.Adjustment + //_positionScale.SetRange(0, _duration); + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues + } + else + { + return; + } + } + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..a99da5f --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,48 @@ +using Adw; +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..1fd8cf1 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..621175f --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..6d21dc2 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..6077bf9 --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..64ba658 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,281 @@ + + + + Exe + net6.0 + enable + true + + + + + + + + + + + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + + diff --git a/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs b/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs index 63eb0b5..8e21ee2 100644 --- a/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs +++ b/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs @@ -55,8 +55,8 @@ internal MIDITrackChunk(uint size, EndianBinaryReader r) byte channel = (byte)(cmd & 0xF); switch (cmd & ~0xF) { - case 0x80: Insert(ticks, new NoteOffMessage(r, channel)); break; - case 0x90: Insert(ticks, new NoteOnMessage(r, channel)); break; + case 0x80: Insert(ticks, new NoteOnMessage(r, channel)); break; + case 0x90: Insert(ticks, new NoteOffMessage(r, channel)); break; case 0xA0: Insert(ticks, new PolyphonicPressureMessage(r, channel)); break; case 0xB0: Insert(ticks, new ControllerMessage(r, channel)); break; case 0xC0: Insert(ticks, new ProgramChangeMessage(r, channel)); break; @@ -239,11 +239,8 @@ internal override void Write(EndianBinaryWriter w) } // Update size now - long endOffset = w.Stream.Position; - uint size = (uint)(endOffset - sizeOffset - 4); + uint size = (uint)(w.Stream.Position - sizeOffset + 4); w.Stream.Position = sizeOffset; w.WriteUInt32(size); - - w.Stream.Position = endOffset; // Go back to the end } } diff --git a/VG Music Studio - MIDI/Events/NoteOffMessage.cs b/VG Music Studio - MIDI/Events/NoteOffMessage.cs index 4408b89..15adc01 100644 --- a/VG Music Studio - MIDI/Events/NoteOffMessage.cs +++ b/VG Music Studio - MIDI/Events/NoteOffMessage.cs @@ -50,7 +50,7 @@ public NoteOffMessage(byte channel, MIDINote note, byte velocity) internal override byte GetCMDByte() { - return (byte)(0x80 + Channel); + return (byte)(0x90 + Channel); } internal override void Write(EndianBinaryWriter w) diff --git a/VG Music Studio - MIDI/Events/NoteOnMessage.cs b/VG Music Studio - MIDI/Events/NoteOnMessage.cs index 2ad63be..629cfed 100644 --- a/VG Music Studio - MIDI/Events/NoteOnMessage.cs +++ b/VG Music Studio - MIDI/Events/NoteOnMessage.cs @@ -50,7 +50,7 @@ public NoteOnMessage(byte channel, MIDINote note, byte velocity) internal override byte GetCMDByte() { - return (byte)(0x90 + Channel); + return (byte)(0x80 + Channel); } internal override void Write(EndianBinaryWriter w) diff --git a/VG Music Studio - MIDI/MIDINote.cs b/VG Music Studio - MIDI/MIDINote.cs index f680f33..e7de7bc 100644 --- a/VG Music Studio - MIDI/MIDINote.cs +++ b/VG Music Studio - MIDI/MIDINote.cs @@ -62,7 +62,6 @@ public enum MIDINote : byte A_3, Bb_3, B_3, - /// Middle C C_4, Db_4, D_4, diff --git a/VG Music Studio - WinForms/MainForm.cs b/VG Music Studio - WinForms/MainForm.cs index 8820c08..43c381d 100644 --- a/VG Music Studio - WinForms/MainForm.cs +++ b/VG Music Studio - WinForms/MainForm.cs @@ -7,7 +7,6 @@ using Kermalis.VGMusicStudio.Core.Util; using Kermalis.VGMusicStudio.WinForms.Properties; using Kermalis.VGMusicStudio.WinForms.Util; -using Microsoft.WindowsAPICodePack.Taskbar; using System; using System.Collections.Generic; using System.ComponentModel; @@ -28,14 +27,15 @@ internal sealed class MainForm : ThemedForm public readonly bool[] PianoTracks; - private PlayingPlaylist? _playlist; - private int _curSong = -1; + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSongs; + private readonly List _remainingSongs; private TrackViewer? _trackViewer; - private bool _songEnded = false; - private bool _positionBarFree = true; - private bool _autoplay = false; + private bool _stopUI = false; #region Controls @@ -51,19 +51,21 @@ internal sealed class MainForm : ThemedForm private readonly ColorSlider _volumeBar, _positionBar; private readonly SongInfoControl _songInfo; private readonly ImageComboBox _songsComboBox; - private readonly TaskbarPlayerButtons? _taskbar; #endregion private MainForm() { + _playedSongs = new List(); + _remainingSongs = new List(); + PianoTracks = new bool[SongState.MAX_TRACKS]; for (int i = 0; i < SongState.MAX_TRACKS; i++) { PianoTracks[i] = true; } - Mixer.VolumeChanged += Mixer_VolumeChanged; + Mixer.MixerVolumeChanged += SetVolumeBarValue; // File Menu _openDSEItem = new ToolStripMenuItem { Text = Strings.MenuOpenDSE }; @@ -103,11 +105,11 @@ private MainForm() // Buttons _playButton = new ThemedButton { Enabled = false, ForeColor = Color.MediumSpringGreen, Text = Strings.PlayerPlay }; - _playButton.Click += PlayButton_Click; + _playButton.Click += (o, e) => Play(); _pauseButton = new ThemedButton { Enabled = false, ForeColor = Color.DeepSkyBlue, Text = Strings.PlayerPause }; - _pauseButton.Click += PauseButton_Click; + _pauseButton.Click += (o, e) => Pause(); _stopButton = new ThemedButton { Enabled = false, ForeColor = Color.MediumVioletRed, Text = Strings.PlayerStop }; - _stopButton.Click += StopButton_Click; + _stopButton.Click += (o, e) => Stop(); // Numerical _songNumerical = new ThemedNumeric { Enabled = false, Minimum = 0, Visible = false }; @@ -115,7 +117,7 @@ private MainForm() // Timer _timer = new Timer(); - _timer.Tick += Timer_Tick; + _timer.Tick += UpdateUI; // Piano _piano = new PianoControl(); @@ -149,112 +151,152 @@ private MainForm() Resize += OnResize; Text = ConfigUtils.PROGRAM_NAME; - // Taskbar Buttons - if (TaskbarManager.IsPlatformSupported) + OnResize(null, null); + } + + private void VolumeBar_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume(_volumeBar.Value / (float)_volumeBar.Maximum); + } + public void SetVolumeBarValue(float volume) + { + _volumeBar.ValueChanged -= VolumeBar_ValueChanged; + _volumeBar.Value = (int)(volume * _volumeBar.Maximum); + _volumeBar.ValueChanged += VolumeBar_ValueChanged; + } + private bool _positionBarFree = true; + private void PositionBar_MouseUp(object? sender, MouseEventArgs? e) + { + if (e.Button == MouseButtons.Left) { - _taskbar = new TaskbarPlayerButtons(Handle); + Engine.Instance.Player.SetCurrentPosition(_positionBar.Value); + _positionBarFree = true; + LetUIKnowPlayerIsPlaying(); + } + } + private void PositionBar_MouseDown(object? sender, MouseEventArgs? e) + { + if (e.Button == MouseButtons.Left) + { + _positionBarFree = false; } - - OnResize(null, EventArgs.Empty); } - private void SongNumerical_ValueChanged(object? sender, EventArgs e) + private bool _autoplay = false; + private void SongNumerical_ValueChanged(object? sender, EventArgs? e) { _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; - int index = (int)_songNumerical.Value; + long index = (long)_songNumerical.Value; Stop(); Text = ConfigUtils.PROGRAM_NAME; _songsComboBox.SelectedIndex = 0; _songInfo.Reset(); - - Player player = Engine.Instance!.Player; - Config cfg = Engine.Instance.Config; + bool success; try { - player.LoadSong(index); + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) } catch (Exception ex) { - FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, cfg.GetSongName(index))); + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; } _trackViewer?.UpdateTracks(); - ILoadedSong? loadedSong = player.LoadedSong; // LoadedSong is still null when there are no tracks - if (loadedSong is not null) + if (success) { - List songs = cfg.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 - int songIndex = songs.FindIndex(s => s.Index == index); - if (songIndex != -1) + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) { - Text = $"{ConfigUtils.PROGRAM_NAME} ― {songs[songIndex].Name}"; // TODO: Make this a func - _songsComboBox.SelectedIndex = songIndex + 1; // + 1 because the "Music" playlist is first in the combobox + Text = $"{ConfigUtils.PROGRAM_NAME} ― {song.Name}"; // TODO: Make this a func + _songsComboBox.SelectedIndex = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - _positionBar.Maximum = loadedSong.MaxTicks; + _positionBar.Maximum = Engine.Instance!.Player.LoadedSong!.MaxTicks; _positionBar.LargeChange = _positionBar.Maximum / 10; _positionBar.SmallChange = _positionBar.LargeChange / 4; - _songInfo.SetNumTracks(loadedSong.Events.Length); + _songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) { Play(); } - _positionBar.Enabled = true; - _exportWAVItem.Enabled = true; - _exportMIDIItem.Enabled = MP2KEngine.MP2KInstance is not null; - _exportDLSItem.Enabled = _exportSF2Item.Enabled = AlphaDreamEngine.AlphaDreamInstance is not null; } else { _songInfo.SetNumTracks(0); - _positionBar.Enabled = false; - _exportWAVItem.Enabled = false; - _exportMIDIItem.Enabled = false; - _exportDLSItem.Enabled = false; - _exportSF2Item.Enabled = false; } + _positionBar.Enabled = _exportWAVItem.Enabled = success; + _exportMIDIItem.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Enabled = _exportSF2Item.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; _autoplay = true; _songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; } - private void SongsComboBox_SelectedIndexChanged(object? sender, EventArgs e) + private void SongsComboBox_SelectedIndexChanged(object? sender, EventArgs? e) { var item = (ImageComboBoxItem)_songsComboBox.SelectedItem; - switch (item.Item) + if (item.Item is Config.Song song) { - case Config.Song song: + SetAndLoadSong(song.Index); + } + else if (item.Item is Config.Playlist playlist) + { + if (playlist.Songs.Count > 0 + && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) { - SetAndLoadSong(song.Index); - break; + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endPlaylistItem.Enabled = true; + SetAndLoadNextPlaylistSong(); } - case Config.Playlist playlist: + } + } + private void SetAndLoadSong(long index) + { + _curSong = index; + if (_songNumerical.Value == index) + { + SongNumerical_ValueChanged(null, null); + } + else + { + _songNumerical.Value = index; + } + } + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSongs.Count == 0) + { + _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) { - if (playlist.Songs.Count > 0 - && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) - { - ResetPlaylistStuff(false); - Engine.Instance!.Player.ShouldFadeOut = true; - Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; - _endPlaylistItem.Enabled = true; - _playlist = new PlayingPlaylist(playlist); - _playlist.SetAndLoadNextSong(); - } - break; + _remainingSongs.Shuffle(); } } + long nextSong = _remainingSongs[0]; + _remainingSongs.RemoveAt(0); + SetAndLoadSong(nextSong); } - private void ResetPlaylistStuff(bool numericalAndComboboxEnabled) + private void ResetPlaylistStuff(bool enableds) { - if (Engine.Instance is not null) + if (Engine.Instance != null) { Engine.Instance.Player.ShouldFadeOut = false; } + _playlistPlaying = false; + _curPlaylist = null; _curSong = -1; - _playlist = null; + _remainingSongs.Clear(); + _playedSongs.Clear(); _endPlaylistItem.Enabled = false; - _songNumerical.Enabled = numericalAndComboboxEnabled; - _songsComboBox.Enabled = numericalAndComboboxEnabled; + _songNumerical.Enabled = _songsComboBox.Enabled = enableds; } - private void EndCurrentPlaylist(object? sender, EventArgs e) + private void EndCurrentPlaylist(object? sender, EventArgs? e) { if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) { @@ -262,7 +304,7 @@ private void EndCurrentPlaylist(object? sender, EventArgs e) } } - private void OpenDSE(object? sender, EventArgs e) + private void OpenDSE(object? sender, EventArgs? e) { var d = new FolderBrowserDialog { @@ -292,10 +334,16 @@ private void OpenDSE(object? sender, EventArgs e) _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; } - private void OpenAlphaDream(object? sender, EventArgs e) + private void OpenAlphaDream(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".gba", Strings.MenuOpenAlphaDream, Strings.FilterOpenGBA + " (*.gba)|*.gba"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenAlphaDream, + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -303,7 +351,7 @@ private void OpenAlphaDream(object? sender, EventArgs e) DisposeEngine(); try { - _ = new AlphaDreamEngine(File.ReadAllBytes(inFile)); + _ = new AlphaDreamEngine(File.ReadAllBytes(d.FileName)); } catch (Exception ex) { @@ -318,10 +366,16 @@ private void OpenAlphaDream(object? sender, EventArgs e) _exportMIDIItem.Visible = false; _exportSF2Item.Visible = true; } - private void OpenMP2K(object? sender, EventArgs e) + private void OpenMP2K(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".gba", Strings.MenuOpenMP2K, Strings.FilterOpenGBA + " (*.gba)|*.gba"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenMP2K, + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -329,7 +383,7 @@ private void OpenMP2K(object? sender, EventArgs e) DisposeEngine(); try { - _ = new MP2KEngine(File.ReadAllBytes(inFile)); + _ = new MP2KEngine(File.ReadAllBytes(d.FileName)); } catch (Exception ex) { @@ -344,10 +398,16 @@ private void OpenMP2K(object? sender, EventArgs e) _exportMIDIItem.Visible = true; _exportSF2Item.Visible = false; } - private void OpenSDAT(object? sender, EventArgs e) + private void OpenSDAT(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".sdat", Strings.MenuOpenSDAT, Strings.FilterOpenSDAT + " (*.sdat)|*.sdat"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenSDAT, + Filter = Strings.FilterOpenSDAT, + FilterIndex = 1, + DefaultExt = ".sdat", + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -355,10 +415,7 @@ private void OpenSDAT(object? sender, EventArgs e) DisposeEngine(); try { - using (FileStream stream = File.OpenRead(inFile)) - { - _ = new SDATEngine(new SDAT(stream)); - } + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.FileName))); } catch (Exception ex) { @@ -374,81 +431,114 @@ private void OpenSDAT(object? sender, EventArgs e) _exportSF2Item.Visible = false; } - private void ExportDLS(object? sender, EventArgs e) + private void ExportDLS(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - string? outFile = WinFormsUtils.CreateSaveDialog(cfg.GetGameName(), ".dls", Strings.MenuSaveDLS, Strings.FilterSaveDLS + " (*.dls)|*.dls"); - if (outFile is null) + + var d = new SaveFileDialog + { + FileName = cfg.GetGameName(), + DefaultExt = ".dls", + ValidateNames = true, + Title = Strings.MenuSaveDLS, + Filter = Strings.FilterSaveDLS, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } try { - AlphaDreamSoundFontSaver_DLS.Save(cfg, outFile); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, outFile), Text); + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); } } - private void ExportMIDI(object? sender, EventArgs e) + private void ExportMIDI(object? sender, EventArgs? e) { - string songName = Engine.Instance!.Config.GetSongName((int)_songNumerical.Value); - string? outFile = WinFormsUtils.CreateSaveDialog(songName, ".mid", Strings.MenuSaveMIDI, Strings.FilterSaveMIDI + " (*.mid;*.midi)|*.mid;*.midi"); - if (outFile is null) + var d = new SaveFileDialog + { + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".mid", + ValidateNames = true, + Title = Strings.MenuSaveMIDI, + Filter = Strings.FilterSaveMIDI, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; - var args = new MIDISaveArgs(true, false, new (int AbsoluteTick, (byte Numerator, byte Denominator))[] + var args = new MIDISaveArgs { - (0, (4, 4)), - }); + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; try { - p.SaveAsMIDI(outFile, args); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, outFile), Text); + p.SaveAsMIDI(d.FileName, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); } } - private void ExportSF2(object? sender, EventArgs e) + private void ExportSF2(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - string? outFile = WinFormsUtils.CreateSaveDialog(cfg.GetGameName(), ".sf2", Strings.MenuSaveSF2, Strings.FilterSaveSF2 + " (*.sf2)|*.sf2"); - if (outFile is null) + + var d = new SaveFileDialog + { + FileName = cfg.GetGameName(), + DefaultExt = ".sf2", + ValidateNames = true, + Title = Strings.MenuSaveSF2, + Filter = Strings.FilterSaveSF2, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } try { - AlphaDreamSoundFontSaver_SF2.Save(outFile, cfg); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, outFile), Text); + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); } } - private void ExportWAV(object? sender, EventArgs e) + private void ExportWAV(object? sender, EventArgs? e) { - string songName = Engine.Instance!.Config.GetSongName((int)_songNumerical.Value); - string? outFile = WinFormsUtils.CreateSaveDialog(songName, ".wav", Strings.MenuSaveWAV, Strings.FilterSaveWAV + " (*.wav)|*.wav"); - if (outFile is null) + var d = new SaveFileDialog + { + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".wav", + ValidateNames = true, + Title = Strings.MenuSaveWAV, + Filter = Strings.FilterSaveWAV, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } Stop(); - Player player = Engine.Instance.Player; + IPlayer player = Engine.Instance.Player; bool oldFade = player.ShouldFadeOut; long oldLoops = player.NumLoops; player.ShouldFadeOut = true; @@ -456,8 +546,8 @@ private void ExportWAV(object? sender, EventArgs e) try { - player.Record(outFile); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, outFile), Text); + player.Record(d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, d.FileName), Text); } catch (Exception ex) { @@ -466,9 +556,21 @@ private void ExportWAV(object? sender, EventArgs e) player.ShouldFadeOut = oldFade; player.NumLoops = oldLoops; - _songEnded = false; // Don't make UI do anything about the song ended event + _stopUI = false; } + public void LetUIKnowPlayerIsPlaying() + { + if (_timer.Enabled) + { + return; + } + + _pauseButton.Enabled = _stopButton.Enabled = true; + _pauseButton.Text = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + _timer.Start(); + } private void Play() { Engine.Instance!.Player.Play(); @@ -476,7 +578,7 @@ private void Play() } private void Pause() { - Engine.Instance!.Player.TogglePlaying(); + Engine.Instance!.Player.Pause(); if (Engine.Instance.Player.State == PlayerState.Paused) { _pauseButton.Text = Strings.PlayerUnpause; @@ -487,26 +589,58 @@ private void Pause() _pauseButton.Text = Strings.PlayerPause; _timer.Start(); } - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); } private void Stop() { Engine.Instance!.Player.Stop(); - _pauseButton.Enabled = false; - _stopButton.Enabled = false; + _pauseButton.Enabled = _stopButton.Enabled = false; _pauseButton.Text = Strings.PlayerPause; _timer.Stop(); _songInfo.Reset(); _piano.UpdateKeys(_songInfo.Info.Tracks, PianoTracks); UpdatePositionIndicators(0L); - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSong(object? sender, EventArgs? e) + { + long prevSong; + if (_playlistPlaying) + { + int index = _playedSongs.Count - 1; + prevSong = _playedSongs[index]; + _playedSongs.RemoveAt(index); + _remainingSongs.Insert(0, _curSong); + } + else + { + prevSong = (long)_songNumerical.Value - 1; + } + SetAndLoadSong(prevSong); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSongs.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSong((long)_songNumerical.Value + 1); + } } private void FinishLoading(long numSongs) { - Engine.Instance!.Player.SongEnded += Player_SongEnded; + Engine.Instance!.Player.SongEnded += SongEnded; foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) { _songsComboBox.Items.Add(new ImageComboBoxItem(playlist, Resources.IconPlaylist, 0)); @@ -519,7 +653,6 @@ private void FinishLoading(long numSongs) _autoplay = false; SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = true; - UpdateTaskbarButtons(); } private void DisposeEngine() { @@ -529,116 +662,71 @@ private void DisposeEngine() Engine.Instance.Dispose(); } - Text = ConfigUtils.PROGRAM_NAME; _trackViewer?.UpdateTracks(); - _taskbar?.DisableAll(); - _songsComboBox.Enabled = false; - _songNumerical.Enabled = false; - _playButton.Enabled = false; - _volumeBar.Enabled = false; - _positionBar.Enabled = false; + Text = ConfigUtils.PROGRAM_NAME; _songInfo.SetNumTracks(0); _songInfo.ResetMutes(); ResetPlaylistStuff(false); UpdatePositionIndicators(0L); - TaskbarPlayerButtons.UpdateState(); - _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged -= SongNumerical_ValueChanged; - _songNumerical.Visible = false; + _songNumerical.Value = _songNumerical.Maximum = 0; _songsComboBox.SelectedItem = null; _songsComboBox.Items.Clear(); - _songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged += SongNumerical_ValueChanged; } - private void UpdatePositionIndicators(long ticks) + private void UpdateUI(object? sender, EventArgs? e) { - if (_positionBarFree) + if (_stopUI) { - _positionBar.Value = ticks; + _stopUI = false; + if (_playlistPlaying) + { + _playedSongs.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + Stop(); + } } - if (GlobalConfig.Instance.TaskbarProgress && TaskbarManager.IsPlatformSupported) + else { - TaskbarManager.Instance.SetProgressValue((int)ticks, (int)_positionBar.Maximum); + if (WindowState != FormWindowState.Minimized) + { + SongState info = _songInfo.Info; + Engine.Instance!.Player.UpdateSongState(info); + _piano.UpdateKeys(info.Tracks, PianoTracks); + _songInfo.Invalidate(); + } + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); } } - private void UpdateTaskbarButtons() + private void SongEnded() { - _taskbar?.UpdateButtons(_playlist, _curSong, (int)_songNumerical.Maximum); + _stopUI = true; } - - private void OpenTrackViewer(object? sender, EventArgs e) + private void UpdatePositionIndicators(long ticks) { - if (_trackViewer is not null) + if (_positionBarFree) { - _trackViewer.Focus(); - return; + _positionBar.Value = ticks; } - - _trackViewer = new TrackViewer { Owner = this }; - _trackViewer.FormClosed += TrackViewer_FormClosed; - _trackViewer.Show(); } - public void TogglePlayback() - { - switch (Engine.Instance!.Player.State) - { - case PlayerState.Stopped: Play(); break; - case PlayerState.Paused: - case PlayerState.Playing: Pause(); break; - } - } - public void PlayPreviousSong() + private void OpenTrackViewer(object? sender, EventArgs? e) { - if (_playlist is not null) - { - _playlist.UndoThenSetAndLoadPrevSong(_curSong); - } - else - { - SetAndLoadSong((int)_songNumerical.Value - 1); - } - } - public void PlayNextSong() - { - if (_playlist is not null) - { - _playlist.AdvanceThenSetAndLoadNextSong(_curSong); - } - else - { - SetAndLoadSong((int)_songNumerical.Value + 1); - } - } - public void LetUIKnowPlayerIsPlaying() - { - if (_timer.Enabled) + if (_trackViewer is not null) { + _trackViewer.Focus(); return; } - _pauseButton.Enabled = true; - _stopButton.Enabled = true; - _pauseButton.Text = Strings.PlayerPause; - _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); - _timer.Start(); - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); - } - public void SetAndLoadSong(int index) - { - _curSong = index; - if (_songNumerical.Value == index) - { - SongNumerical_ValueChanged(null, EventArgs.Empty); - } - else - { - _songNumerical.Value = index; - } + _trackViewer = new TrackViewer { Owner = this }; + _trackViewer.FormClosed += (o, s) => _trackViewer = null; + _trackViewer.Show(); } protected override void OnFormClosing(FormClosingEventArgs e) @@ -646,7 +734,7 @@ protected override void OnFormClosing(FormClosingEventArgs e) DisposeEngine(); base.OnFormClosing(e); } - private void OnResize(object? sender, EventArgs e) + private void OnResize(object? sender, EventArgs? e) { if (WindowState == FormWindowState.Minimized) { @@ -693,7 +781,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Space && _playButton.Enabled && !_songsComboBox.Focused) { - TogglePlayback(); + TogglePlayback(null, null); return true; } return base.ProcessCmdKey(ref msg, keyData); @@ -707,78 +795,4 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } - - private void Timer_Tick(object? sender, EventArgs e) - { - if (_songEnded) - { - _songEnded = false; - if (_playlist is not null) - { - _playlist.AdvanceThenSetAndLoadNextSong(_curSong); - } - else - { - Stop(); - } - } - else - { - Player player = Engine.Instance!.Player; - if (WindowState != FormWindowState.Minimized) - { - SongState info = _songInfo.Info; - player.UpdateSongState(info); - _piano.UpdateKeys(info.Tracks, PianoTracks); - _songInfo.Invalidate(); - } - UpdatePositionIndicators(player.ElapsedTicks); - } - } - private void Mixer_VolumeChanged(float volume) - { - _volumeBar.ValueChanged -= VolumeBar_ValueChanged; - _volumeBar.Value = (int)(volume * _volumeBar.Maximum); - _volumeBar.ValueChanged += VolumeBar_ValueChanged; - } - private void Player_SongEnded() - { - _songEnded = true; - } - private void VolumeBar_ValueChanged(object? sender, EventArgs e) - { - Engine.Instance!.Mixer.SetVolume(_volumeBar.Value / (float)_volumeBar.Maximum); - } - private void PositionBar_MouseUp(object? sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - Engine.Instance!.Player.SetSongPosition(_positionBar.Value); - _positionBarFree = true; - LetUIKnowPlayerIsPlaying(); - } - } - private void PositionBar_MouseDown(object? sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - _positionBarFree = false; - } - } - private void PlayButton_Click(object? sender, EventArgs e) - { - Play(); - } - private void PauseButton_Click(object? sender, EventArgs e) - { - Pause(); - } - private void StopButton_Click(object? sender, EventArgs e) - { - Stop(); - } - private void TrackViewer_FormClosed(object? sender, FormClosedEventArgs e) - { - _trackViewer = null; - } } diff --git a/VG Music Studio - WinForms/PianoControl.cs b/VG Music Studio - WinForms/PianoControl.cs index 81075ae..e7947a3 100644 --- a/VG Music Studio - WinForms/PianoControl.cs +++ b/VG Music Studio - WinForms/PianoControl.cs @@ -38,7 +38,7 @@ internal sealed class PianoControl : Control private enum KeyType : byte { Black, - White, + White } private const double BLACK_KEY_SCALE = 2.0 / 3; @@ -64,23 +64,23 @@ public PianoKey(byte k) SetStyle(ControlStyles.Selectable, false); OnBrush = new(Color.Transparent); - byte c; + byte l; if (KeyTypeTable[k % 12] == KeyType.White) { if (k / 12 % 2 == 0) { - c = 255; + l = 240; } else { - c = 127; + l = 120; } } else { - c = 0; + l = 0; } - _offBrush = new SolidBrush(Color.FromArgb(c, c, c)); + _offBrush = new SolidBrush(HSLColor.ToColor(160, 0, l)); } protected override void Dispose(bool disposing) diff --git a/VG Music Studio - WinForms/PlayingPlaylist.cs b/VG Music Studio - WinForms/PlayingPlaylist.cs deleted file mode 100644 index 100f88f..0000000 --- a/VG Music Studio - WinForms/PlayingPlaylist.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Kermalis.VGMusicStudio.Core; -using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Util; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.WinForms; - -internal sealed class PlayingPlaylist -{ - public readonly List _playedSongs; - public readonly List _remainingSongs; - public readonly Config.Playlist _curPlaylist; - - public PlayingPlaylist(Config.Playlist play) - { - _playedSongs = new List(); - _remainingSongs = new List(); - _curPlaylist = play; - } - - public void AdvanceThenSetAndLoadNextSong(int curSong) - { - _playedSongs.Add(curSong); - SetAndLoadNextSong(); - } - public void UndoThenSetAndLoadPrevSong(int curSong) - { - int prevIndex = _playedSongs.Count - 1; - int prevSong = _playedSongs[prevIndex]; - _playedSongs.RemoveAt(prevIndex); - _remainingSongs.Insert(0, curSong); - MainForm.Instance.SetAndLoadSong(prevSong); - } - public void SetAndLoadNextSong() - { - if (_remainingSongs.Count == 0) - { - _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); - if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) - { - _remainingSongs.Shuffle(); - } - } - int nextSong = _remainingSongs[0]; - _remainingSongs.RemoveAt(0); - MainForm.Instance.SetAndLoadSong(nextSong); - } -} diff --git a/VG Music Studio - WinForms/Program.cs b/VG Music Studio - WinForms/Program.cs index 24f9e89..c207096 100644 --- a/VG Music Studio - WinForms/Program.cs +++ b/VG Music Studio - WinForms/Program.cs @@ -12,11 +12,6 @@ internal static class Program private static void Main() { #if DEBUG - //VGMSDebug.SimulateLanguage("en"); - //VGMSDebug.SimulateLanguage("es"); - //VGMSDebug.SimulateLanguage("fr"); - //VGMSDebug.SimulateLanguage("it"); - //VGMSDebug.SimulateLanguage("ru"); //VGMSDebug.GBAGameCodeScan(@"C:\Users\Kermalis\Documents\Emulation\GBA\Games"); #endif try diff --git a/VG Music Studio - WinForms/SongInfoControl.cs b/VG Music Studio - WinForms/SongInfoControl.cs index b2bc0b7..9b2c9f2 100644 --- a/VG Music Studio - WinForms/SongInfoControl.cs +++ b/VG Music Studio - WinForms/SongInfoControl.cs @@ -289,19 +289,12 @@ private void DrawVerticalBars(Graphics g, SongState.Track track, int vBarY1, int _barHeight); if (rect.Width > 0) { - float velocity = track.LeftVolume + track.RightVolume; - int alpha; - if (velocity >= 2f) + float velocity = (track.LeftVolume + track.RightVolume) * 2f; + if (velocity > 1f) { - alpha = 255; + velocity = 1f; } - else - { - const int DELTA = 125; - alpha = (int)WinFormsUtils.Lerp(velocity * 0.5f, 0f, DELTA); - alpha += 255 - DELTA; - } - _solidBrush.Color = Color.FromArgb(alpha, color); + _solidBrush.Color = Color.FromArgb((int)WinFormsUtils.Lerp(velocity, 20f, 255f), color); g.FillRectangle(_solidBrush, rect); g.DrawRectangle(_pen, rect); //_solidBrush.Color = color; diff --git a/VG Music Studio - WinForms/TaskbarPlayerButtons.cs b/VG Music Studio - WinForms/TaskbarPlayerButtons.cs deleted file mode 100644 index d6185e4..0000000 --- a/VG Music Studio - WinForms/TaskbarPlayerButtons.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Kermalis.VGMusicStudio.Core; -using Kermalis.VGMusicStudio.Core.Properties; -using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Properties; -using Microsoft.WindowsAPICodePack.Taskbar; -using System; - -namespace Kermalis.VGMusicStudio.WinForms; - -internal sealed class TaskbarPlayerButtons -{ - private readonly ThumbnailToolBarButton _prevTButton, _toggleTButton, _nextTButton; - - public TaskbarPlayerButtons(IntPtr handle) - { - _prevTButton = new ThumbnailToolBarButton(Resources.IconPrevious, Strings.PlayerPreviousSong); - _prevTButton.Click += PrevTButton_Click; - _toggleTButton = new ThumbnailToolBarButton(Resources.IconPlay, Strings.PlayerPlay); - _toggleTButton.Click += ToggleTButton_Click; - _nextTButton = new ThumbnailToolBarButton(Resources.IconNext, Strings.PlayerNextSong); - _nextTButton.Click += NextTButton_Click; - _prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = false; - TaskbarManager.Instance.ThumbnailToolBars.AddButtons(handle, _prevTButton, _toggleTButton, _nextTButton); - } - - private void PrevTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.PlayPreviousSong(); - } - private void ToggleTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.TogglePlayback(); - } - private void NextTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.PlayNextSong(); - } - - public void DisableAll() - { - _prevTButton.Enabled = false; - _toggleTButton.Enabled = false; - _nextTButton.Enabled = false; - } - public void UpdateButtons(PlayingPlaylist? playlist, int curSong, int maxSong) - { - if (playlist is not null) - { - _prevTButton.Enabled = playlist._playedSongs.Count > 0; - _nextTButton.Enabled = true; - } - else - { - _prevTButton.Enabled = curSong > 0; - _nextTButton.Enabled = curSong < maxSong; - } - switch (Engine.Instance!.Player.State) - { - case PlayerState.Stopped: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerPlay; break; - case PlayerState.Playing: _toggleTButton.Icon = Resources.IconPause; _toggleTButton.Tooltip = Strings.PlayerPause; break; - case PlayerState.Paused: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerUnpause; break; - } - _toggleTButton.Enabled = true; - } - public static void UpdateState() - { - if (!GlobalConfig.Instance.TaskbarProgress || !TaskbarManager.IsPlatformSupported) - { - return; - } - - TaskbarProgressBarState state; - switch (Engine.Instance?.Player.State) - { - case PlayerState.Playing: state = TaskbarProgressBarState.Normal; break; - case PlayerState.Paused: state = TaskbarProgressBarState.Paused; break; - default: state = TaskbarProgressBarState.NoProgress; break; - } - TaskbarManager.Instance.SetProgressState(state); - } -} diff --git a/VG Music Studio - WinForms/Theme.cs b/VG Music Studio - WinForms/Theme.cs index c8803e6..0652802 100644 --- a/VG Music Studio - WinForms/Theme.cs +++ b/VG Music Studio - WinForms/Theme.cs @@ -24,7 +24,7 @@ public static readonly Color public static Color DrainColor(Color c) { var hsl = new HSLColor(c); - return HSLColor.ToColor(hsl.Hue, hsl.Saturation / 2.5, hsl.Lightness); + return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); } } diff --git a/VG Music Studio - WinForms/TrackViewer.cs b/VG Music Studio - WinForms/TrackViewer.cs index 81520cc..80949f3 100644 --- a/VG Music Studio - WinForms/TrackViewer.cs +++ b/VG Music Studio - WinForms/TrackViewer.cs @@ -72,7 +72,7 @@ private void ListView_ItemActivate(object? sender, EventArgs e) List list = ((SongEvent)_listView.SelectedItem.RowObject).Ticks; if (list.Count > 0) { - Engine.Instance!.Player.SetSongPosition(list[0]); + Engine.Instance?.Player.SetCurrentPosition(list[0]); MainForm.Instance.LetUIKnowPlayerIsPlaying(); } } diff --git a/VG Music Studio - WinForms/Util/ColorSlider.cs b/VG Music Studio - WinForms/Util/ColorSlider.cs index fba1516..fa6171e 100644 --- a/VG Music Studio - WinForms/Util/ColorSlider.cs +++ b/VG Music Studio - WinForms/Util/ColorSlider.cs @@ -25,6 +25,7 @@ #endregion + using System; using System.ComponentModel; using System.Drawing; @@ -34,9 +35,9 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; [DesignerCategory(""), ToolboxBitmap(typeof(TrackBar))] -internal sealed class ColorSlider : Control +internal class ColorSlider : Control { - private const int THUMB_SIZE = 14; + private const int thumbSize = 14; private Rectangle thumbRect; private long _value = 0L; @@ -45,13 +46,16 @@ public long Value get => _value; set { - if (value < _minimum || value > _maximum) + if (value >= _minimum && value <= _maximum) + { + _value = value; + ValueChanged?.Invoke(this, EventArgs.Empty); + Invalidate(); + } + else { throw new ArgumentOutOfRangeException(nameof(Value), $"{nameof(Value)} must be between {nameof(Minimum)} and {nameof(Maximum)}."); } - _value = value; - ValueChanged?.Invoke(this, EventArgs.Empty); - Invalidate(); } } private long _minimum = 0L; @@ -60,17 +64,20 @@ public long Minimum get => _minimum; set { - if (value > _maximum) + if (value <= _maximum) { - throw new ArgumentOutOfRangeException(nameof(Minimum), $"{nameof(Minimum)} cannot be higher than {nameof(Maximum)}."); + _minimum = value; + if (_value < _minimum) + { + _value = _minimum; + ValueChanged?.Invoke(this, new EventArgs()); + } + Invalidate(); } - _minimum = value; - if (_value < _minimum) + else { - _value = _minimum; - ValueChanged?.Invoke(this, new EventArgs()); + throw new ArgumentOutOfRangeException(nameof(Minimum), $"{nameof(Minimum)} cannot be higher than {nameof(Maximum)}."); } - Invalidate(); } } private long _maximum = 10L; @@ -79,17 +86,20 @@ public long Maximum get => _maximum; set { - if (value < _minimum) + if (value >= _minimum) { - throw new ArgumentOutOfRangeException(nameof(Maximum), $"{nameof(Maximum)} cannot be lower than {nameof(Minimum)}."); + _maximum = value; + if (_value > _maximum) + { + _value = _maximum; + ValueChanged?.Invoke(this, new EventArgs()); + } + Invalidate(); } - _maximum = value; - if (_value > _maximum) + else { - _value = _maximum; - ValueChanged?.Invoke(this, new EventArgs()); + throw new ArgumentOutOfRangeException(nameof(Maximum), $"{nameof(Maximum)} cannot be lower than {nameof(Minimum)}."); } - Invalidate(); } } private long _smallChange = 1L; @@ -98,11 +108,14 @@ public long SmallChange get => _smallChange; set { - if (value < 0) + if (value >= 0) + { + _smallChange = value; + } + else { throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); } - _smallChange = value; } } private long _largeChange = 5L; @@ -111,11 +124,14 @@ public long LargeChange get => _largeChange; set { - if (value < 0) + if (value >= 0) + { + _largeChange = value; + } + else { throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); } - _largeChange = value; } } private bool _acceptKeys = true; @@ -129,7 +145,7 @@ public bool AcceptKeys } } - public event EventHandler? ValueChanged; + public event EventHandler ValueChanged; private readonly Color _thumbOuterColor = Color.White; private readonly Color _thumbInnerColor = Color.White; @@ -216,12 +232,12 @@ private void Draw(PaintEventArgs e, } long a = _maximum - _minimum; - long x = a == 0 ? 0 : (_value - _minimum) * (ClientRectangle.Width - THUMB_SIZE) / a; - thumbRect = new Rectangle((int)x, ClientRectangle.Y + ClientRectangle.Height / 2 - THUMB_SIZE / 2, THUMB_SIZE, THUMB_SIZE); + long x = a == 0 ? 0 : (_value - _minimum) * (ClientRectangle.Width - thumbSize) / a; + thumbRect = new Rectangle((int)x, ClientRectangle.Y + ClientRectangle.Height / 2 - thumbSize / 2, thumbSize, thumbSize); Rectangle barRect = ClientRectangle; barRect.Inflate(-1, -barRect.Height / 3); Rectangle elapsedRect = barRect; - elapsedRect.Width = thumbRect.Left + THUMB_SIZE / 2; + elapsedRect.Width = thumbRect.Left + thumbSize / 2; pen.Color = barInnerColorPaint; e.Graphics.DrawLine(pen, barRect.X, barRect.Y + barRect.Height / 2, barRect.X + barRect.Width, barRect.Y + barRect.Height / 2); @@ -248,7 +264,7 @@ private void Draw(PaintEventArgs e, newthumbOuterColorPaint = Color.FromArgb(175, thumbOuterColorPaint); newthumbInnerColorPaint = Color.FromArgb(175, thumbInnerColorPaint); } - using (GraphicsPath thumbPath = CreateRoundRectPath(thumbRect, THUMB_SIZE)) + using (GraphicsPath thumbPath = CreateRoundRectPath(thumbRect, thumbSize)) { using (var lgbThumb = new LinearGradientBrush(thumbRect, newthumbOuterColorPaint, newthumbInnerColorPaint, LinearGradientMode.Vertical) { WrapMode = WrapMode.TileFlipXY }) { @@ -289,7 +305,7 @@ private void Draw(PaintEventArgs e, private void SetValueFromPoint(Point p) { int x = p.X; - int margin = THUMB_SIZE / 2; + int margin = thumbSize / 2; x -= margin; _value = (long)(x * ((_maximum - _minimum) / (ClientSize.Width - 2f * margin)) + _minimum); if (_value < _minimum) diff --git a/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs b/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs index 5a073ff..ed3a13c 100644 --- a/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs +++ b/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs @@ -1,5 +1,4 @@ -using Kermalis.VGMusicStudio.WinForms.Properties; -using System; +using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; @@ -81,7 +80,7 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; * - Initial Version */ -internal sealed class FlexibleMessageBox +internal class FlexibleMessageBox { #region Public statics @@ -167,13 +166,13 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, #region Internal form class - private sealed class FlexibleMessageBoxForm : ThemedForm + class FlexibleMessageBoxForm : ThemedForm { - IContainer components; + IContainer components = null; protected override void Dispose(bool disposing) { - if (disposing && components is not null) + if (disposing && components != null) { components.Dispose(); } @@ -285,7 +284,7 @@ void InitializeComponent() Controls.Add(panel1); Controls.Add(button1); DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); - Icon = Resources.Icon; + Icon = Properties.Resources.Icon; MaximizeBox = false; MinimizeBox = false; MinimumSize = new Size(276, 140); @@ -351,7 +350,7 @@ private FlexibleMessageBoxForm() #region Private helper functions - static string[]? GetStringRows(string message) + static string[] GetStringRows(string message) { if (string.IsNullOrEmpty(message)) { @@ -394,10 +393,10 @@ static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) return workingAreaFactor; } - static void SetDialogStartPosition(FlexibleMessageBoxForm flexibleMessageBoxForm, IWin32Window? owner) + static void SetDialogStartPosition(FlexibleMessageBoxForm flexibleMessageBoxForm, IWin32Window owner) { - // If no owner given: Center on current screen - if (owner is null) + //If no owner given: Center on current screen + if (owner == null) { var screen = Screen.FromPoint(Cursor.Position); flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; @@ -413,8 +412,8 @@ static void SetDialogSizes(FlexibleMessageBoxForm flexibleMessageBoxForm, string Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); //Get rows. Exit if there are no rows to render... - string[]? stringRows = GetStringRows(text); - if (stringRows is null) + string[] stringRows = GetStringRows(text); + if (stringRows == null) { return; } @@ -564,7 +563,7 @@ static void SetDialogButtons(FlexibleMessageBoxForm flexibleMessageBoxForm, Mess #region Private event handlers - void FlexibleMessageBoxForm_Shown(object? sender, EventArgs e) + void FlexibleMessageBoxForm_Shown(object sender, EventArgs e) { int buttonIndexToFocus = 1; Button buttonToFocus; @@ -605,7 +604,7 @@ void FlexibleMessageBoxForm_Shown(object? sender, EventArgs e) buttonToFocus.Focus(); } - void LinkClicked(object? sender, LinkClickedEventArgs e) + void LinkClicked(object sender, LinkClickedEventArgs e) { try { @@ -614,7 +613,7 @@ void LinkClicked(object? sender, LinkClickedEventArgs e) } catch (Exception) { - // Let the caller of FlexibleMessageBoxForm decide what to do with this exception... + //Let the caller of FlexibleMessageBoxForm decide what to do with this exception... throw; } finally @@ -623,7 +622,7 @@ void LinkClicked(object? sender, LinkClickedEventArgs e) } } - void FlexibleMessageBoxForm_KeyUp(object? sender, KeyEventArgs e) + void FlexibleMessageBoxForm_KeyUp(object sender, KeyEventArgs e) { //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) @@ -657,7 +656,7 @@ void FlexibleMessageBoxForm_KeyUp(object? sender, KeyEventArgs e) #region Public show function - public static DialogResult Show(IWin32Window? owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { //Create a new instance of the FlexibleMessageBox form var flexibleMessageBoxForm = new FlexibleMessageBoxForm diff --git a/VG Music Studio - WinForms/Util/ImageComboBox.cs b/VG Music Studio - WinForms/Util/ImageComboBox.cs index 48826e3..45bca24 100644 --- a/VG Music Studio - WinForms/Util/ImageComboBox.cs +++ b/VG Music Studio - WinForms/Util/ImageComboBox.cs @@ -4,7 +4,7 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; -internal sealed class ImageComboBox : ComboBox +internal class ImageComboBox : ComboBox { private const int _imgSize = 15; private bool _open = false; @@ -41,7 +41,7 @@ protected override void OnDropDownClosed(EventArgs e) base.OnDropDownClosed(e); } } -internal sealed class ImageComboBoxItem +internal class ImageComboBoxItem { public object Item { get; } public Image Image { get; } diff --git a/VG Music Studio - WinForms/Util/VGMSDebug.cs b/VG Music Studio - WinForms/Util/VGMSDebug.cs index ab222a0..1c7bd11 100644 --- a/VG Music Studio - WinForms/Util/VGMSDebug.cs +++ b/VG Music Studio - WinForms/Util/VGMSDebug.cs @@ -3,10 +3,8 @@ using Kermalis.VGMusicStudio.Core; using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; -using System.Threading; namespace Kermalis.VGMusicStudio.WinForms.Util; @@ -50,12 +48,11 @@ public static void EventScan(List songs, bool showIndexes) { Console.WriteLine($"{nameof(EventScan)} started."); var scans = new Dictionary>(); - Player player = Engine.Instance!.Player; foreach (Config.Song song in songs) { try { - player.LoadSong(song.Index); + Engine.Instance.Player.LoadSong(song.Index); } catch (Exception ex) { @@ -63,19 +60,21 @@ public static void EventScan(List songs, bool showIndexes) continue; } - if (player.LoadedSong is null) + if (Engine.Instance.Player.LoadedSong is null) { continue; } - foreach (string cmd in player.LoadedSong.Events.Where(ev => ev is not null).SelectMany(ev => ev).Select(ev => ev.Command.Label).Distinct()) + foreach (string cmd in Engine.Instance.Player.LoadedSong.Events.Where(ev => ev != null).SelectMany(ev => ev).Select(ev => ev.Command.Label).Distinct()) { - if (!scans.TryGetValue(cmd, out List? list)) + if (scans.ContainsKey(cmd)) { - list = new List(); - scans.Add(cmd, list); + scans[cmd].Add(song); + } + else + { + scans.Add(cmd, new List { song }); } - list.Add(song); } } foreach (KeyValuePair> kvp in scans.OrderBy(k => k.Key)) @@ -119,10 +118,5 @@ public static void GBAGameCodeScan(string path) } Console.WriteLine($"{nameof(GBAGameCodeScan)} ended."); } - - public static void SimulateLanguage(string lang) - { - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang); - } } #endif \ No newline at end of file diff --git a/VG Music Studio - WinForms/Util/WinFormsUtils.cs b/VG Music Studio - WinForms/Util/WinFormsUtils.cs index 33a0766..0c64c71 100644 --- a/VG Music Studio - WinForms/Util/WinFormsUtils.cs +++ b/VG Music Studio - WinForms/Util/WinFormsUtils.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Windows.Forms; namespace Kermalis.VGMusicStudio.WinForms.Util; @@ -37,40 +36,4 @@ public static float Lerp(float value, float a1, float a2, float b1, float b2) { return b1 + ((value - a1) / (a2 - a1) * (b2 - b1)); } - - public static string? CreateLoadDialog(string extension, string title, string filter) - { - var d = new OpenFileDialog - { - DefaultExt = extension, - ValidateNames = true, - CheckFileExists = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } - public static string? CreateSaveDialog(string fileName, string extension, string title, string filter) - { - var d = new SaveFileDialog - { - FileName = fileName, - DefaultExt = extension, - AddExtension = true, - ValidateNames = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } } diff --git a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj index 1e811e9..bf42797 100644 --- a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj +++ b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj @@ -7,24 +7,20 @@ Kermalis.VGMusicStudio.WinForms enable true - true + true ..\Build Kermalis Kermalis - VG Music Studio - VG Music Studio - VG Music Studio + VGMusicStudio + VGMusicStudio + VGMusicStudio 0.3.0 - Properties\Icon.ico - False - - - - + + diff --git a/VG Music Studio - WinForms/ValueTextBox.cs b/VG Music Studio - WinForms/ValueTextBox.cs index f05190f..8a69ae5 100644 --- a/VG Music Studio - WinForms/ValueTextBox.cs +++ b/VG Music Studio - WinForms/ValueTextBox.cs @@ -6,8 +6,6 @@ namespace Kermalis.VGMusicStudio.WinForms; internal sealed class ValueTextBox : ThemedTextBox { - public event EventHandler? ValueChanged; - private bool _hex = false; public bool Hexadecimal { @@ -93,8 +91,14 @@ protected override void OnTextChanged(EventArgs e) Value = old; } + private EventHandler _onValueChanged = null; + public event EventHandler ValueChanged + { + add => _onValueChanged += value; + remove => _onValueChanged -= value; + } private void OnValueChanged(EventArgs e) { - ValueChanged?.Invoke(this, e); + _onValueChanged?.Invoke(this, e); } } diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 0f1fbff..37b7672 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -9,6 +9,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "V EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - MIDI", "VG Music Studio - MIDI\VG Music Studio - MIDI.csproj", "{6756ED81-71F6-457D-AD23-9C03B6C934E4}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{A171BF23-4281-46CD-AE0B-ED6CD118744E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,6 +33,18 @@ Global {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.Build.0 = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From f274d74ad66f67447b081585196ecb048b1aa245 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Sun, 19 Nov 2023 21:37:26 +1100 Subject: [PATCH 12/20] Another sync with net-6 branch (didn't realise it wasn't up to date) --- .gitignore | 3 +- .vscode/launch.json | 26 + .vscode/tasks.json | 41 + .../CellEditing/CellEditKeyEngine.cs | 520 + ObjectListView/CellEditing/CellEditors.cs | 325 + ObjectListView/CellEditing/EditorRegistry.cs | 213 + ObjectListView/CustomDictionary.xml | 46 + ObjectListView/DataListView.cs | 240 + ObjectListView/DataTreeListView.cs | 240 + ObjectListView/DragDrop/DragSource.cs | 219 + ObjectListView/DragDrop/DropSink.cs | 1562 +++ ObjectListView/DragDrop/OLVDataObject.cs | 185 + ObjectListView/FastDataListView.cs | 169 + ObjectListView/FastObjectListView.cs | 422 + ObjectListView/Filtering/Cluster.cs | 125 + .../Filtering/ClusteringStrategy.cs | 189 + .../Filtering/ClustersFromGroupsStrategy.cs | 70 + .../Filtering/DateTimeClusteringStrategy.cs | 187 + ObjectListView/Filtering/FilterMenuBuilder.cs | 369 + ObjectListView/Filtering/Filters.cs | 489 + .../Filtering/FlagClusteringStrategy.cs | 160 + ObjectListView/Filtering/ICluster.cs | 56 + .../Filtering/IClusteringStrategy.cs | 80 + ObjectListView/Filtering/TextMatchFilter.cs | 642 + ObjectListView/FullClassDiagram.cd | 1261 ++ ObjectListView/Implementation/Attributes.cs | 335 + ObjectListView/Implementation/Comparers.cs | 330 + .../Implementation/DataSourceAdapter.cs | 628 + ObjectListView/Implementation/Delegates.cs | 168 + ObjectListView/Implementation/DragSource.cs | 407 + ObjectListView/Implementation/DropSink.cs | 1402 ++ ObjectListView/Implementation/Enums.cs | 104 + ObjectListView/Implementation/Events.cs | 2514 ++++ .../Implementation/GroupingParameters.cs | 204 + ObjectListView/Implementation/Groups.cs | 761 ++ ObjectListView/Implementation/Munger.cs | 568 + .../Implementation/NativeMethods.cs | 1223 ++ .../Implementation/NullableDictionary.cs | 87 + ObjectListView/Implementation/OLVListItem.cs | 325 + .../Implementation/OLVListSubItem.cs | 173 + .../Implementation/OlvListViewHitTestInfo.cs | 388 + .../Implementation/TreeDataSourceAdapter.cs | 262 + .../Implementation/VirtualGroups.cs | 341 + .../Implementation/VirtualListDataSource.cs | 349 + ObjectListView/OLVColumn.cs | 1909 +++ ObjectListView/ObjectListView.DesignTime.cs | 550 + ObjectListView/ObjectListView.FxCop | 3521 +++++ ObjectListView/ObjectListView.cs | 10924 ++++++++++++++++ ObjectListView/ObjectListView.shfb | 47 + ObjectListView/ObjectListView2019.csproj | 54 + ObjectListView/ObjectListView2019.nuspec | 22 + ObjectListView/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 113 + ObjectListView/Properties/Resources.resx | 137 + ObjectListView/Rendering/Adornments.cs | 743 ++ ObjectListView/Rendering/Decorations.cs | 973 ++ ObjectListView/Rendering/Overlays.cs | 302 + ObjectListView/Rendering/Renderers.cs | 3887 ++++++ ObjectListView/Rendering/Styles.cs | 400 + ObjectListView/Rendering/TreeRenderer.cs | 309 + ObjectListView/Resources/clear-filter.png | Bin 0 -> 1381 bytes ObjectListView/Resources/coffee.jpg | Bin 0 -> 73464 bytes ObjectListView/Resources/filter-icons3.png | Bin 0 -> 1305 bytes ObjectListView/Resources/filter.png | Bin 0 -> 1331 bytes ObjectListView/Resources/sort-ascending.png | Bin 0 -> 1364 bytes ObjectListView/Resources/sort-descending.png | Bin 0 -> 1371 bytes ObjectListView/SubControls/GlassPanelForm.cs | 459 + ObjectListView/SubControls/HeaderControl.cs | 1230 ++ .../SubControls/ToolStripCheckedListBox.cs | 189 + ObjectListView/SubControls/ToolTipControl.cs | 699 + ObjectListView/TreeListView.cs | 2269 ++++ .../Utilities/ColumnSelectionForm.Designer.cs | 190 + .../Utilities/ColumnSelectionForm.cs | 263 + .../Utilities/ColumnSelectionForm.resx | 120 + ObjectListView/Utilities/Generator.cs | 563 + ObjectListView/Utilities/OLVExporter.cs | 277 + .../Utilities/TypedObjectListView.cs | 561 + ObjectListView/VirtualObjectListView.cs | 1255 ++ ObjectListView/olv-keyfile.snk | Bin 0 -> 596 bytes README.md | 129 +- VG Music Studio - Core/ADPCMDecoder.cs | 26 +- VG Music Studio - Core/Assembler.cs | 28 +- VG Music Studio - Core/Config.cs | 58 +- VG Music Studio - Core/Config.yaml | 258 +- .../Dependencies/KMIDI.deps.json | 41 - VG Music Studio - Core/Dependencies/KMIDI.dll | Bin 49664 -> 0 bytes VG Music Studio - Core/Dependencies/KMIDI.xml | 77 - VG Music Studio - Core/Engine.cs | 2 +- .../GBA/AlphaDream/AlphaDreamChannel.cs | 241 + .../GBA/AlphaDream/AlphaDreamConfig.cs | 18 +- .../GBA/AlphaDream/AlphaDreamEngine.cs | 4 +- .../GBA/AlphaDream/AlphaDreamEnums.cs | 15 - .../GBA/AlphaDream/AlphaDreamLoadedSong.cs | 41 - .../AlphaDream/AlphaDreamLoadedSong_Events.cs | 266 - .../AlphaDreamLoadedSong_Runtime.cs | 160 - .../GBA/AlphaDream/AlphaDreamMixer.cs | 18 +- .../GBA/AlphaDream/AlphaDreamPlayer.cs | 733 +- .../AlphaDreamSoundFontSaver_DLS.cs | 11 +- .../AlphaDreamSoundFontSaver_SF2.cs | 48 +- .../GBA/AlphaDream/AlphaDreamStructs.cs | 67 - .../GBA/AlphaDream/AlphaDreamTrack.cs | 92 - .../AlphaDream/Channels/AlphaDreamChannel.cs | 41 - .../Channels/AlphaDreamPCMChannel.cs | 110 - .../Channels/AlphaDreamSquareChannel.cs | 96 - .../{AlphaDreamCommands.cs => Commands.cs} | 26 +- .../GBA/AlphaDream/Enums.cs | 16 + .../GBA/AlphaDream/Structs.cs | 40 + .../GBA/AlphaDream/Track.cs | 69 + VG Music Studio - Core/GBA/GBAUtils.cs | 12 +- VG Music Studio - Core/GBA/MP2K/Channel.cs | 787 ++ .../GBA/MP2K/Channels/MP2KChannel.cs | 62 - .../GBA/MP2K/Channels/MP2KNoiseChannel.cs | 69 - .../GBA/MP2K/Channels/MP2KPCM4Channel.cs | 51 - .../GBA/MP2K/Channels/MP2KPCM8Channel.cs | 294 - .../GBA/MP2K/Channels/MP2KPSGChannel.cs | 282 - .../GBA/MP2K/Channels/MP2KSquareChannel.cs | 57 - .../GBA/MP2K/{MP2KCommands.cs => Commands.cs} | 46 +- VG Music Studio - Core/GBA/MP2K/Enums.cs | 76 + VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs | 35 +- VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs | 4 +- VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs | 75 - .../GBA/MP2K/MP2KLoadedSong.cs | 527 +- .../GBA/MP2K/MP2KLoadedSong_Events.cs | 546 - .../GBA/MP2K/MP2KLoadedSong_MIDI.cs | 78 +- .../GBA/MP2K/MP2KLoadedSong_Runtime.cs | 458 - VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 136 +- VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs | 797 +- .../GBA/MP2K/MP2KStructs.cs | 187 - VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs | 224 - VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs | 122 - .../GBA/MP2K/MP2KUtils_PkmnCompress.cs | 58 - VG Music Studio - Core/GBA/MP2K/Structs.cs | 80 + VG Music Studio - Core/GBA/MP2K/Track.cs | 174 + VG Music Studio - Core/GBA/MP2K/Utils.cs | 175 + VG Music Studio - Core/MP2K.yaml | 153 - VG Music Studio - Core/Mixer.cs | 52 +- VG Music Studio - Core/NDS/DSE/Channel.cs | 368 + .../NDS/DSE/{DSECommands.cs => Commands.cs} | 34 +- VG Music Studio - Core/NDS/DSE/DSEChannel.cs | 373 - VG Music Studio - Core/NDS/DSE/DSEConfig.cs | 11 +- VG Music Studio - Core/NDS/DSE/DSEEnums.cs | 21 - .../NDS/DSE/DSELoadedSong.cs | 62 - .../NDS/DSE/DSELoadedSong_Events.cs | 461 - .../NDS/DSE/DSELoadedSong_Runtime.cs | 285 - VG Music Studio - Core/NDS/DSE/DSEMixer.cs | 45 +- VG Music Studio - Core/NDS/DSE/DSEPlayer.cs | 1063 +- VG Music Studio - Core/NDS/DSE/DSETrack.cs | 120 - VG Music Studio - Core/NDS/DSE/DSEUtils.cs | 54 - VG Music Studio - Core/NDS/DSE/Enums.cs | 22 + VG Music Studio - Core/NDS/DSE/SMD.cs | 107 +- VG Music Studio - Core/NDS/DSE/SWD.cs | 188 +- VG Music Studio - Core/NDS/DSE/Track.cs | 71 + VG Music Studio - Core/NDS/DSE/Utils.cs | 53 + VG Music Studio - Core/NDS/NDSUtils.cs | 6 - VG Music Studio - Core/NDS/SDAT/Channel.cs | 391 + .../NDS/SDAT/{SDATCommands.cs => Commands.cs} | 0 VG Music Studio - Core/NDS/SDAT/Enums.cs | 40 + .../SDAT/{SDATFileHeader.cs => FileHeader.cs} | 4 +- VG Music Studio - Core/NDS/SDAT/SBNK.cs | 4 +- VG Music Studio - Core/NDS/SDAT/SDAT.cs | 63 +- .../NDS/SDAT/SDATChannel.cs | 391 - VG Music Studio - Core/NDS/SDAT/SDATConfig.cs | 2 +- VG Music Studio - Core/NDS/SDAT/SDATEnums.cs | 39 - .../NDS/SDAT/SDATLoadedSong.cs | 38 - .../NDS/SDAT/SDATLoadedSong_Events.cs | 744 -- .../NDS/SDAT/SDATLoadedSong_Runtime.cs | 787 -- VG Music Studio - Core/NDS/SDAT/SDATMixer.cs | 30 +- VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs | 1713 ++- VG Music Studio - Core/NDS/SDAT/SDATTrack.cs | 248 - VG Music Studio - Core/NDS/SDAT/SDATUtils.cs | 28 +- VG Music Studio - Core/NDS/SDAT/SSEQ.cs | 39 +- VG Music Studio - Core/NDS/SDAT/SWAR.cs | 94 +- VG Music Studio - Core/NDS/SDAT/Track.cs | 196 + VG Music Studio - Core/NDS/Utils.cs | 7 + VG Music Studio - Core/Player.cs | 194 +- .../Properties/Strings.Designer.cs | 106 +- .../Properties/Strings.es.resx | 19 +- .../Properties/Strings.fr.resx | 345 - .../Properties/Strings.it.resx | 9 +- .../Properties/Strings.resx | 45 +- .../Properties/Strings.ru.resx | 345 - VG Music Studio - Core/SongState.cs | 104 +- VG Music Studio - Core/Util/ConfigUtils.cs | 53 +- VG Music Studio - Core/Util/DataUtils.cs | 14 - VG Music Studio - Core/Util/GlobalConfig.cs | 26 +- VG Music Studio - Core/Util/HSLColor.cs | 164 +- VG Music Studio - Core/Util/LanguageUtils.cs | 30 - VG Music Studio - Core/Util/SampleUtils.cs | 18 +- VG Music Studio - Core/Util/TimeBarrier.cs | 4 +- .../VG Music Studio - Core.csproj | 37 +- VG Music Studio - GTK3/MainWindow.cs | 875 ++ VG Music Studio - GTK3/Program.cs | 23 + .../VG Music Studio - GTK3.csproj | 16 + .../ExtraLibBindings/Gtk.cs | 199 + .../ExtraLibBindings/GtkInternal.cs | 425 + VG Music Studio - GTK4/MainWindow.cs | 1369 ++ VG Music Studio - GTK4/Program.cs | 48 + VG Music Studio - GTK4/Theme.cs | 224 + .../Util/FlexibleMessageBox.cs | 763 ++ VG Music Studio - GTK4/Util/ScaleControl.cs | 86 + .../Util/SoundSequenceList.cs | 156 + .../VG Music Studio - GTK4.csproj | 281 + VG Music Studio - MIDI/Chunks/MIDIChunk.cs | 22 + .../Chunks/MIDIHeaderChunk.cs | 79 + .../Chunks/MIDITrackChunk.cs | 246 + .../Chunks/MIDIUnsupportedChunk.cs | 30 + .../Events/ChannelPressureMessage.cs | 48 + .../Events/ControllerMessage.cs | 141 + .../Events/EscapeMessage.cs | 39 + VG Music Studio - MIDI/Events/MIDIEvent.cs | 18 + VG Music Studio - MIDI/Events/MIDIMessage.cs | 10 + VG Music Studio - MIDI/Events/MetaMessage.cs | 122 + .../Events/NoteOffMessage.cs | 61 + .../Events/NoteOnMessage.cs | 61 + .../Events/PitchBendMessage.cs | 61 + .../Events/PolyphonicPressureMessage.cs | 53 + .../Events/ProgramChangeMessage.cs | 181 + .../Events/SysExContinuationMessage.cs | 47 + VG Music Studio - MIDI/Events/SysExMessage.cs | 47 + VG Music Studio - MIDI/MIDIFile.cs | 173 + VG Music Studio - MIDI/MIDINote.cs | 134 + VG Music Studio - MIDI/TimeDivisionValue.cs | 63 + .../VG Music Studio - MIDI.csproj | 15 + VG Music Studio - WinForms/MainForm.cs | 558 +- VG Music Studio - WinForms/PianoControl.cs | 66 +- .../PianoControl_PianoKey.cs | 86 - VG Music Studio - WinForms/PlayingPlaylist.cs | 49 - VG Music Studio - WinForms/Program.cs | 5 - VG Music Studio - WinForms/SongInfoControl.cs | 27 +- .../TaskbarPlayerButtons.cs | 81 - VG Music Studio - WinForms/Theme.cs | 2 +- VG Music Studio - WinForms/TrackViewer.cs | 2 +- .../Util/ColorSlider.cs | 76 +- .../Util/FlexibleMessageBox.cs | 56 +- .../Util/ImageComboBox.cs | 12 +- VG Music Studio - WinForms/Util/VGMSDebug.cs | 40 +- .../Util/WinFormsUtils.cs | 37 - .../VG Music Studio - WinForms.csproj | 42 +- VG Music Studio - WinForms/ValueTextBox.cs | 10 +- VG Music Studio.sln | 24 + 240 files changed, 65513 insertions(+), 10249 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json create mode 100644 ObjectListView/CellEditing/CellEditKeyEngine.cs create mode 100644 ObjectListView/CellEditing/CellEditors.cs create mode 100644 ObjectListView/CellEditing/EditorRegistry.cs create mode 100644 ObjectListView/CustomDictionary.xml create mode 100644 ObjectListView/DataListView.cs create mode 100644 ObjectListView/DataTreeListView.cs create mode 100644 ObjectListView/DragDrop/DragSource.cs create mode 100644 ObjectListView/DragDrop/DropSink.cs create mode 100644 ObjectListView/DragDrop/OLVDataObject.cs create mode 100644 ObjectListView/FastDataListView.cs create mode 100644 ObjectListView/FastObjectListView.cs create mode 100644 ObjectListView/Filtering/Cluster.cs create mode 100644 ObjectListView/Filtering/ClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ClustersFromGroupsStrategy.cs create mode 100644 ObjectListView/Filtering/DateTimeClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/FilterMenuBuilder.cs create mode 100644 ObjectListView/Filtering/Filters.cs create mode 100644 ObjectListView/Filtering/FlagClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/ICluster.cs create mode 100644 ObjectListView/Filtering/IClusteringStrategy.cs create mode 100644 ObjectListView/Filtering/TextMatchFilter.cs create mode 100644 ObjectListView/FullClassDiagram.cd create mode 100644 ObjectListView/Implementation/Attributes.cs create mode 100644 ObjectListView/Implementation/Comparers.cs create mode 100644 ObjectListView/Implementation/DataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/Delegates.cs create mode 100644 ObjectListView/Implementation/DragSource.cs create mode 100644 ObjectListView/Implementation/DropSink.cs create mode 100644 ObjectListView/Implementation/Enums.cs create mode 100644 ObjectListView/Implementation/Events.cs create mode 100644 ObjectListView/Implementation/GroupingParameters.cs create mode 100644 ObjectListView/Implementation/Groups.cs create mode 100644 ObjectListView/Implementation/Munger.cs create mode 100644 ObjectListView/Implementation/NativeMethods.cs create mode 100644 ObjectListView/Implementation/NullableDictionary.cs create mode 100644 ObjectListView/Implementation/OLVListItem.cs create mode 100644 ObjectListView/Implementation/OLVListSubItem.cs create mode 100644 ObjectListView/Implementation/OlvListViewHitTestInfo.cs create mode 100644 ObjectListView/Implementation/TreeDataSourceAdapter.cs create mode 100644 ObjectListView/Implementation/VirtualGroups.cs create mode 100644 ObjectListView/Implementation/VirtualListDataSource.cs create mode 100644 ObjectListView/OLVColumn.cs create mode 100644 ObjectListView/ObjectListView.DesignTime.cs create mode 100644 ObjectListView/ObjectListView.FxCop create mode 100644 ObjectListView/ObjectListView.cs create mode 100644 ObjectListView/ObjectListView.shfb create mode 100644 ObjectListView/ObjectListView2019.csproj create mode 100644 ObjectListView/ObjectListView2019.nuspec create mode 100644 ObjectListView/Properties/AssemblyInfo.cs create mode 100644 ObjectListView/Properties/Resources.Designer.cs create mode 100644 ObjectListView/Properties/Resources.resx create mode 100644 ObjectListView/Rendering/Adornments.cs create mode 100644 ObjectListView/Rendering/Decorations.cs create mode 100644 ObjectListView/Rendering/Overlays.cs create mode 100644 ObjectListView/Rendering/Renderers.cs create mode 100644 ObjectListView/Rendering/Styles.cs create mode 100644 ObjectListView/Rendering/TreeRenderer.cs create mode 100644 ObjectListView/Resources/clear-filter.png create mode 100644 ObjectListView/Resources/coffee.jpg create mode 100644 ObjectListView/Resources/filter-icons3.png create mode 100644 ObjectListView/Resources/filter.png create mode 100644 ObjectListView/Resources/sort-ascending.png create mode 100644 ObjectListView/Resources/sort-descending.png create mode 100644 ObjectListView/SubControls/GlassPanelForm.cs create mode 100644 ObjectListView/SubControls/HeaderControl.cs create mode 100644 ObjectListView/SubControls/ToolStripCheckedListBox.cs create mode 100644 ObjectListView/SubControls/ToolTipControl.cs create mode 100644 ObjectListView/TreeListView.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.Designer.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.cs create mode 100644 ObjectListView/Utilities/ColumnSelectionForm.resx create mode 100644 ObjectListView/Utilities/Generator.cs create mode 100644 ObjectListView/Utilities/OLVExporter.cs create mode 100644 ObjectListView/Utilities/TypedObjectListView.cs create mode 100644 ObjectListView/VirtualObjectListView.cs create mode 100644 ObjectListView/olv-keyfile.snk delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.deps.json delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.dll delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.xml create mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs delete mode 100644 VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs rename VG Music Studio - Core/GBA/AlphaDream/{AlphaDreamCommands.cs => Commands.cs} (77%) create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Enums.cs create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Structs.cs create mode 100644 VG Music Studio - Core/GBA/AlphaDream/Track.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Channel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs rename VG Music Studio - Core/GBA/MP2K/{MP2KCommands.cs => Commands.cs} (79%) create mode 100644 VG Music Studio - Core/GBA/MP2K/Enums.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs delete mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KUtils_PkmnCompress.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Structs.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Track.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/Utils.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Channel.cs rename VG Music Studio - Core/NDS/DSE/{DSECommands.cs => Commands.cs} (78%) delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEChannel.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEEnums.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSETrack.cs delete mode 100644 VG Music Studio - Core/NDS/DSE/DSEUtils.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Enums.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Track.cs create mode 100644 VG Music Studio - Core/NDS/DSE/Utils.cs delete mode 100644 VG Music Studio - Core/NDS/NDSUtils.cs create mode 100644 VG Music Studio - Core/NDS/SDAT/Channel.cs rename VG Music Studio - Core/NDS/SDAT/{SDATCommands.cs => Commands.cs} (100%) create mode 100644 VG Music Studio - Core/NDS/SDAT/Enums.cs rename VG Music Studio - Core/NDS/SDAT/{SDATFileHeader.cs => FileHeader.cs} (87%) delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATChannel.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATEnums.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs delete mode 100644 VG Music Studio - Core/NDS/SDAT/SDATTrack.cs create mode 100644 VG Music Studio - Core/NDS/SDAT/Track.cs create mode 100644 VG Music Studio - Core/NDS/Utils.cs delete mode 100644 VG Music Studio - Core/Properties/Strings.fr.resx delete mode 100644 VG Music Studio - Core/Properties/Strings.ru.resx delete mode 100644 VG Music Studio - Core/Util/DataUtils.cs delete mode 100644 VG Music Studio - Core/Util/LanguageUtils.cs create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj create mode 100644 VG Music Studio - MIDI/Chunks/MIDIChunk.cs create mode 100644 VG Music Studio - MIDI/Chunks/MIDIHeaderChunk.cs create mode 100644 VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs create mode 100644 VG Music Studio - MIDI/Chunks/MIDIUnsupportedChunk.cs create mode 100644 VG Music Studio - MIDI/Events/ChannelPressureMessage.cs create mode 100644 VG Music Studio - MIDI/Events/ControllerMessage.cs create mode 100644 VG Music Studio - MIDI/Events/EscapeMessage.cs create mode 100644 VG Music Studio - MIDI/Events/MIDIEvent.cs create mode 100644 VG Music Studio - MIDI/Events/MIDIMessage.cs create mode 100644 VG Music Studio - MIDI/Events/MetaMessage.cs create mode 100644 VG Music Studio - MIDI/Events/NoteOffMessage.cs create mode 100644 VG Music Studio - MIDI/Events/NoteOnMessage.cs create mode 100644 VG Music Studio - MIDI/Events/PitchBendMessage.cs create mode 100644 VG Music Studio - MIDI/Events/PolyphonicPressureMessage.cs create mode 100644 VG Music Studio - MIDI/Events/ProgramChangeMessage.cs create mode 100644 VG Music Studio - MIDI/Events/SysExContinuationMessage.cs create mode 100644 VG Music Studio - MIDI/Events/SysExMessage.cs create mode 100644 VG Music Studio - MIDI/MIDIFile.cs create mode 100644 VG Music Studio - MIDI/MIDINote.cs create mode 100644 VG Music Studio - MIDI/TimeDivisionValue.cs create mode 100644 VG Music Studio - MIDI/VG Music Studio - MIDI.csproj delete mode 100644 VG Music Studio - WinForms/PianoControl_PianoKey.cs delete mode 100644 VG Music Studio - WinForms/PlayingPlaylist.cs delete mode 100644 VG Music Studio - WinForms/TaskbarPlayerButtons.cs diff --git a/.gitignore b/.gitignore index 80921d3..1bbfb2e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,5 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..23ffcc2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/VG Music Studio - GTK4/bin/Debug/net6.0/VG Music Studio - GTK4.dll", + "args": [], + "cwd": "${workspaceFolder}/VG Music Studio - GTK4", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..bf93855 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/ObjectListView/CellEditing/CellEditKeyEngine.cs b/ObjectListView/CellEditing/CellEditKeyEngine.cs new file mode 100644 index 0000000..a0d67b6 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditKeyEngine.cs @@ -0,0 +1,520 @@ +/* + * CellEditKeyEngine - A engine that allows the behaviour of arbitrary keys to be configured + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * v2.8 + * 2014-05-30 JPP - When a row is disabled, skip over it when looking for another cell to edit + * v2.5 + * 2012-04-14 JPP - Fixed bug where, on a OLV with only a single editable column, tabbing + * to change rows would edit the cell above rather than the cell below + * the cell being edited. + * 2.5 + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using BrightIdeasSoftware; + +namespace BrightIdeasSoftware { + /// + /// Indicates the behavior of a key when a cell "on the edge" is being edited. + /// and the normal behavior of that key would exceed the edge. For example, + /// for a key that normally moves one column to the left, the "edge" would be + /// the left most column, since the normal action of the key cannot be taken + /// (since there are no more columns to the left). + /// + public enum CellEditAtEdgeBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will result in the cell editing wrapping to the + /// cell on the opposite edge. + /// + Wrap, + + /// + /// The key press will wrap, but the column will be changed to the + /// appropriate adjacent column. This only makes sense for keys where + /// the normal action is ChangeRow. + /// + ChangeColumn, + + /// + /// The key press will wrap, but the row will be changed to the + /// appropriate adjacent row. This only makes sense for keys where + /// the normal action is ChangeColumn. + /// + ChangeRow, + + /// + /// The key will result in the current edit operation being ended. + /// + EndEdit + }; + + /// + /// Indicates the normal behaviour of a key when used during a cell edit + /// operation. + /// + public enum CellEditCharacterBehaviour { + /// + /// The key press will be ignored + /// + Ignore, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the left. + /// + ChangeColumnLeft, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the next editable cell to the right. + /// + ChangeColumnRight, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row above. + /// + ChangeRowUp, + + /// + /// The key press will end the current edit and begin an edit + /// operation on the row below + /// + ChangeRowDown, + + /// + /// The key press will cancel the current edit + /// + CancelEdit, + + /// + /// The key press will finish the current edit operation + /// + EndEdit, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb1, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb2, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb3, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb4, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb5, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb6, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb7, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb8, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb9, + + /// + /// Custom verb that can be used for specialized actions. + /// + CustomVerb10, + }; + + /// + /// Instances of this class handle key presses during a cell edit operation. + /// + public class CellEditKeyEngine { + + #region Public interface + + /// + /// Sets the behaviour of a given key + /// + /// + /// + /// + public virtual void SetKeyBehaviour(Keys key, CellEditCharacterBehaviour normalBehaviour, CellEditAtEdgeBehaviour atEdgeBehaviour) { + this.CellEditKeyMap[key] = normalBehaviour; + this.CellEditKeyAtEdgeBehaviourMap[key] = atEdgeBehaviour; + } + + /// + /// Handle a key press + /// + /// + /// + /// True if the key was completely handled. + public virtual bool HandleKey(ObjectListView olv, Keys keyData) { + if (olv == null) throw new ArgumentNullException("olv"); + + CellEditCharacterBehaviour behaviour; + if (!CellEditKeyMap.TryGetValue(keyData, out behaviour)) + return false; + + this.ListView = olv; + + switch (behaviour) { + case CellEditCharacterBehaviour.Ignore: + break; + case CellEditCharacterBehaviour.CancelEdit: + this.HandleCancelEdit(); + break; + case CellEditCharacterBehaviour.EndEdit: + this.HandleEndEdit(); + break; + case CellEditCharacterBehaviour.ChangeColumnLeft: + case CellEditCharacterBehaviour.ChangeColumnRight: + this.HandleColumnChange(keyData, behaviour); + break; + case CellEditCharacterBehaviour.ChangeRowDown: + case CellEditCharacterBehaviour.ChangeRowUp: + this.HandleRowChange(keyData, behaviour); + break; + default: + return this.HandleCustomVerb(keyData, behaviour); + }; + + return true; + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the ObjectListView on which the current key is being handled. + /// This cannot be null. + /// + protected ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the row of the cell that is currently being edited + /// + protected OLVListItem ItemBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? null : this.ListView.CellEditEventArgs.ListViewItem; + } + } + + /// + /// Gets the index of the column of the cell that is being edited + /// + protected int SubItemIndexBeingEdited { + get { + return (this.ListView == null || this.ListView.CellEditEventArgs == null) ? -1 : this.ListView.CellEditEventArgs.SubItemIndex; + } + } + + /// + /// Gets or sets the map that remembers the normal behaviour of keys + /// + protected IDictionary CellEditKeyMap { + get { + if (cellEditKeyMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyMap; + } + set { + cellEditKeyMap = value; + } + } + private IDictionary cellEditKeyMap; + + /// + /// Gets or sets the map that remembers the desired behaviour of keys + /// on edge cases. + /// + protected IDictionary CellEditKeyAtEdgeBehaviourMap { + get { + if (cellEditKeyAtEdgeBehaviourMap == null) + this.InitializeCellEditKeyMaps(); + return cellEditKeyAtEdgeBehaviourMap; + } + set { + cellEditKeyAtEdgeBehaviourMap = value; + } + } + private IDictionary cellEditKeyAtEdgeBehaviourMap; + + #endregion + + #region Initialization + + /// + /// Setup the default key mapping + /// + protected virtual void InitializeCellEditKeyMaps() { + this.cellEditKeyMap = new Dictionary(); + this.cellEditKeyMap[Keys.Escape] = CellEditCharacterBehaviour.CancelEdit; + this.cellEditKeyMap[Keys.Return] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Enter] = CellEditCharacterBehaviour.EndEdit; + this.cellEditKeyMap[Keys.Tab] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Tab | Keys.Shift] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Left | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnLeft; + this.cellEditKeyMap[Keys.Right | Keys.Alt] = CellEditCharacterBehaviour.ChangeColumnRight; + this.cellEditKeyMap[Keys.Up | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowUp; + this.cellEditKeyMap[Keys.Down | Keys.Alt] = CellEditCharacterBehaviour.ChangeRowDown; + + this.cellEditKeyAtEdgeBehaviourMap = new Dictionary(); + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Tab | Keys.Shift] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Left | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Right | Keys.Alt] = CellEditAtEdgeBehaviour.Wrap; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Up | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + this.cellEditKeyAtEdgeBehaviourMap[Keys.Down | Keys.Alt] = CellEditAtEdgeBehaviour.ChangeColumn; + } + + #endregion + + #region Command handling + + /// + /// Handle the end edit command + /// + protected virtual void HandleEndEdit() { + this.ListView.PossibleFinishCellEditing(); + } + + /// + /// Handle the cancel edit command + /// + protected virtual void HandleCancelEdit() { + this.ListView.CancelCellEdit(); + } + + /// + /// Placeholder that subclasses can override to handle any custom verbs + /// + /// + /// + /// + protected virtual bool HandleCustomVerb(Keys keyData, CellEditCharacterBehaviour behaviour) { + return false; + } + + /// + /// Handle a change row command + /// + /// + /// + protected virtual void HandleRowChange(Keys keyData, CellEditCharacterBehaviour behaviour) { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + OLVListItem olvi = this.ItemBeingEdited; + int subItemIndex = this.SubItemIndexBeingEdited; + bool isGoingUp = behaviour == CellEditCharacterBehaviour.ChangeRowUp; + + // Try to find a row above (or below) the currently edited cell + // If we find one, start editing it and we're done. + OLVListItem adjacentOlvi = this.GetAdjacentItemOrNull(olvi, isGoingUp); + if (adjacentOlvi != null) { + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + return; + } + + // There is no adjacent row in the direction we want, so we must be on an edge. + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) { + case CellEditAtEdgeBehaviour.Ignore: + break; + case CellEditAtEdgeBehaviour.EndEdit: + this.ListView.PossibleFinishCellEditing(); + break; + case CellEditAtEdgeBehaviour.Wrap: + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + case CellEditAtEdgeBehaviour.ChangeColumn: + // Figure out the next editable column + List editableColumnsInDisplayOrder = this.EditableColumnsInDisplayOrder; + int displayIndex = Math.Max(0, editableColumnsInDisplayOrder.IndexOf(this.ListView.GetColumn(subItemIndex))); + if (isGoingUp) + displayIndex = (editableColumnsInDisplayOrder.Count + displayIndex - 1) % editableColumnsInDisplayOrder.Count; + else + displayIndex = (displayIndex + 1) % editableColumnsInDisplayOrder.Count; + subItemIndex = editableColumnsInDisplayOrder[displayIndex].Index; + + // Wrap to the next row and start the cell edit + adjacentOlvi = this.GetAdjacentItemOrNull(null, isGoingUp); + this.StartCellEditIfDifferent(adjacentOlvi, subItemIndex); + break; + } + } + + /// + /// Handle a change column command + /// + /// + /// + protected virtual void HandleColumnChange(Keys keyData, CellEditCharacterBehaviour behaviour) + { + // If we couldn't finish editing the current cell, don't try to move it + if (!this.ListView.PossibleFinishCellEditing()) + return; + + // Changing columns only works in details mode + if (this.ListView.View != View.Details) + return; + + List editableColumns = this.EditableColumnsInDisplayOrder; + OLVListItem olvi = this.ItemBeingEdited; + int displayIndex = Math.Max(0, + editableColumns.IndexOf(this.ListView.GetColumn(this.SubItemIndexBeingEdited))); + bool isGoingLeft = behaviour == CellEditCharacterBehaviour.ChangeColumnLeft; + + // Are we trying to continue past one of the edges? + if ((isGoingLeft && displayIndex == 0) || + (!isGoingLeft && displayIndex == editableColumns.Count - 1)) + { + // Yes, so figure out our at edge behaviour + CellEditAtEdgeBehaviour atEdgeBehaviour; + if (!this.CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour)) + atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap; + switch (atEdgeBehaviour) + { + case CellEditAtEdgeBehaviour.Ignore: + return; + case CellEditAtEdgeBehaviour.EndEdit: + this.HandleEndEdit(); + return; + case CellEditAtEdgeBehaviour.ChangeRow: + case CellEditAtEdgeBehaviour.Wrap: + if (atEdgeBehaviour == CellEditAtEdgeBehaviour.ChangeRow) + olvi = GetAdjacentItem(olvi, isGoingLeft && displayIndex == 0); + if (isGoingLeft) + displayIndex = editableColumns.Count - 1; + else + displayIndex = 0; + break; + } + } + else + { + if (isGoingLeft) + displayIndex -= 1; + else + displayIndex += 1; + } + + int subItemIndex = editableColumns[displayIndex].Index; + this.StartCellEditIfDifferent(olvi, subItemIndex); + } + + #endregion + + #region Utilities + + /// + /// Start editing the indicated cell if that cell is not already being edited + /// + /// The row to edit + /// The cell within that row to edit + protected void StartCellEditIfDifferent(OLVListItem olvi, int subItemIndex) { + if (this.ItemBeingEdited == olvi && this.SubItemIndexBeingEdited == subItemIndex) + return; + + this.ListView.EnsureVisible(olvi.Index); + this.ListView.StartCellEdit(olvi, subItemIndex); + } + + /// + /// Gets the adjacent item to the given item in the given direction. + /// If that item is disabled, continue in that direction until an enabled item is found. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more enabled items in that direction. + protected OLVListItem GetAdjacentItemOrNull(OLVListItem olvi, bool up) { + OLVListItem item = up ? this.ListView.GetPreviousItem(olvi) : this.ListView.GetNextItem(olvi); + while (item != null && !item.Enabled) + item = up ? this.ListView.GetPreviousItem(item) : this.ListView.GetNextItem(item); + return item; + } + + /// + /// Gets the adjacent item to the given item in the given direction, wrapping if needed. + /// + /// The row whose neighbour is sought + /// The direction of the adjacentness + /// An OLVListView adjacent to the given item, or null if there are no more items in that direction. + protected OLVListItem GetAdjacentItem(OLVListItem olvi, bool up) { + return this.GetAdjacentItemOrNull(olvi, up) ?? this.GetAdjacentItemOrNull(null, up); + } + + /// + /// Gets a collection of columns that are editable in the order they are shown to the user + /// + protected List EditableColumnsInDisplayOrder { + get { + List editableColumnsInDisplayOrder = new List(); + foreach (OLVColumn x in this.ListView.ColumnsInDisplayOrder) + if (x.IsEditable) + editableColumnsInDisplayOrder.Add(x); + return editableColumnsInDisplayOrder; + } + } + + #endregion + } +} diff --git a/ObjectListView/CellEditing/CellEditors.cs b/ObjectListView/CellEditing/CellEditors.cs new file mode 100644 index 0000000..4314021 --- /dev/null +++ b/ObjectListView/CellEditing/CellEditors.cs @@ -0,0 +1,325 @@ +/* + * CellEditors - Several slightly modified controls that are used as cell editors within ObjectListView. + * + * Author: Phillip Piper + * Date: 20/10/2008 5:15 PM + * + * Change log: + * 2018-05-05 JPP - Added ControlUtilities.AutoResizeDropDown() + * v2.6 + * 2012-08-02 JPP - Make most editors public so they can be reused/subclassed + * v2.3 + * 2009-08-13 JPP - Standardized code formatting + * v2.2.1 + * 2008-01-18 JPP - Added special handling for enums + * 2008-01-16 JPP - Added EditorRegistry + * v2.0.1 + * 2008-10-20 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An interface that allows cell editors to specifically handle getting and setting + /// values from ObjectListView + /// + public interface IOlvEditor { + object Value { get; set; } + } + + public static class ControlUtilities { + + /// + /// Configure the given ComboBox so that the dropped down menu is auto-sized to + /// be wide enough to show the widest item. + /// + /// + public static void AutoResizeDropDown(ComboBox dropDown) { + if (dropDown == null) + throw new ArgumentNullException("dropDown"); + + dropDown.DropDown += delegate(object sender, EventArgs args) { + + // Calculate the maximum width of the drop down items + int newWidth = 0; + foreach (object item in dropDown.Items) { + newWidth = Math.Max(newWidth, TextRenderer.MeasureText(item.ToString(), dropDown.Font).Width); + } + + int vertScrollBarWidth = dropDown.Items.Count > dropDown.MaxDropDownItems ? SystemInformation.VerticalScrollBarWidth : 0; + dropDown.DropDownWidth = newWidth + vertScrollBarWidth; + }; + } + } + + /// + /// These items allow combo boxes to remember a value and its description. + /// + public class ComboBoxItem + { + /// + /// + /// + /// + /// + public ComboBoxItem(Object key, String description) { + this.key = key; + this.description = description; + } + private readonly String description; + + /// + /// + /// + public Object Key { + get { return key; } + } + private readonly Object key; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return this.description; + } + } + + //----------------------------------------------------------------------- + // Cell editors + // These classes are simple cell editors that make it easier to get and set + // the value that the control is showing. + // In many cases, you can intercept the CellEditStarting event to + // change the characteristics of the editor. For example, changing + // the acceptable range for a numeric editor or changing the strings + // that represent true and false values for a boolean editor. + + /// + /// This editor shows and auto completes values from the given listview column. + /// + [ToolboxItem(false)] + public class AutoCompleteCellEditor : ComboBox + { + /// + /// Create an AutoCompleteCellEditor + /// + /// + /// + public AutoCompleteCellEditor(ObjectListView lv, OLVColumn column) { + this.DropDownStyle = ComboBoxStyle.DropDown; + + Dictionary alreadySeen = new Dictionary(); + for (int i = 0; i < Math.Min(lv.GetItemCount(), 1000); i++) { + String str = column.GetStringValue(lv.GetModelObject(i)); + if (!alreadySeen.ContainsKey(str)) { + this.Items.Add(str); + alreadySeen[str] = true; + } + } + + this.Sorted = true; + this.AutoCompleteSource = AutoCompleteSource.ListItems; + this.AutoCompleteMode = AutoCompleteMode.Append; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This combo box is specialized to allow editing of an enum. + /// + [ToolboxItem(false)] + public class EnumCellEditor : ComboBox + { + /// + /// + /// + /// + public EnumCellEditor(Type type) { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + foreach (object value in Enum.GetValues(type)) + values.Add(new ComboBoxItem(value, Enum.GetName(type, value))); + + this.DataSource = values; + + ControlUtilities.AutoResizeDropDown(this); + } + } + + /// + /// This editor simply shows and edits integer values. + /// + [ToolboxItem(false)] + public class IntUpDown : NumericUpDown + { + /// + /// + /// + public IntUpDown() { + this.DecimalPlaces = 0; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new int Value { + get { return Decimal.ToInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits unsigned integer values. + /// + /// This class can't be made public because unsigned int is not a + /// CLS-compliant type. If you want to use, just copy the code to this class + /// into your project and use it from there. + [ToolboxItem(false)] + internal class UintUpDown : NumericUpDown + { + public UintUpDown() { + this.DecimalPlaces = 0; + this.Minimum = 0; + this.Maximum = 9999999; + } + + public new uint Value { + get { return Decimal.ToUInt32(base.Value); } + set { base.Value = new Decimal(value); } + } + } + + /// + /// This editor simply shows and edits boolean values. + /// + [ToolboxItem(false)] + public class BooleanCellEditor : ComboBox + { + /// + /// + /// + public BooleanCellEditor() { + this.DropDownStyle = ComboBoxStyle.DropDownList; + this.ValueMember = "Key"; + + ArrayList values = new ArrayList(); + values.Add(new ComboBoxItem(false, "False")); + values.Add(new ComboBoxItem(true, "True")); + + this.DataSource = values; + } + } + + /// + /// This editor simply shows and edits boolean values using a checkbox + /// + [ToolboxItem(false)] + public class BooleanCellEditor2 : CheckBox + { + /// + /// Gets or sets the value shown by this editor + /// + public bool? Value { + get { + switch (this.CheckState) { + case CheckState.Checked: return true; + case CheckState.Indeterminate: return null; + case CheckState.Unchecked: + default: return false; + } + } + set { + if (value.HasValue) + this.CheckState = value.Value ? CheckState.Checked : CheckState.Unchecked; + else + this.CheckState = CheckState.Indeterminate; + } + } + + /// + /// Gets or sets how the checkbox will be aligned + /// + public new HorizontalAlignment TextAlign { + get { + switch (this.CheckAlign) { + case ContentAlignment.MiddleRight: return HorizontalAlignment.Right; + case ContentAlignment.MiddleCenter: return HorizontalAlignment.Center; + case ContentAlignment.MiddleLeft: + default: return HorizontalAlignment.Left; + } + } + set { + switch (value) { + case HorizontalAlignment.Left: + this.CheckAlign = ContentAlignment.MiddleLeft; + break; + case HorizontalAlignment.Center: + this.CheckAlign = ContentAlignment.MiddleCenter; + break; + case HorizontalAlignment.Right: + this.CheckAlign = ContentAlignment.MiddleRight; + break; + } + } + } + } + + /// + /// This editor simply shows and edits floating point values. + /// + /// You can intercept the CellEditStarting event if you want + /// to change the characteristics of the editor. For example, by increasing + /// the number of decimal places. + [ToolboxItem(false)] + public class FloatCellEditor : NumericUpDown + { + /// + /// + /// + public FloatCellEditor() { + this.DecimalPlaces = 2; + this.Minimum = -9999999; + this.Maximum = 9999999; + } + + /// + /// Gets or sets the value shown by this editor + /// + public new double Value { + get { return Convert.ToDouble(base.Value); } + set { base.Value = Convert.ToDecimal(value); } + } + } +} diff --git a/ObjectListView/CellEditing/EditorRegistry.cs b/ObjectListView/CellEditing/EditorRegistry.cs new file mode 100644 index 0000000..f92854f --- /dev/null +++ b/ObjectListView/CellEditing/EditorRegistry.cs @@ -0,0 +1,213 @@ +/* + * EditorRegistry - A registry mapping types to cell editors. + * + * Author: Phillip Piper + * Date: 6-March-2011 7:53 am + * + * Change log: + * 2011-03-31 JPP - Use OLVColumn.DataType if the value to be edited is null + * 2011-03-06 JPP - Separated from CellEditors.cs + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; + +namespace BrightIdeasSoftware { + + /// + /// A delegate that creates an editor for the given value + /// + /// The model from which that value came + /// The column for which the editor is being created + /// A representative value of the type to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A control which can edit the given value + public delegate Control EditorCreatorDelegate(Object model, OLVColumn column, Object value); + + /// + /// An editor registry gives a way to decide what cell editor should be used to edit + /// the value of a cell. Programmers can register non-standard types and the control that + /// should be used to edit instances of that type. + /// + /// + /// All ObjectListViews share the same editor registry. + /// + public class EditorRegistry { + #region Initializing + + /// + /// Create an EditorRegistry + /// + public EditorRegistry() { + this.InitializeStandardTypes(); + } + + private void InitializeStandardTypes() { + this.Register(typeof(Boolean), typeof(BooleanCellEditor)); + this.Register(typeof(Int16), typeof(IntUpDown)); + this.Register(typeof(Int32), typeof(IntUpDown)); + this.Register(typeof(Int64), typeof(IntUpDown)); + this.Register(typeof(UInt16), typeof(UintUpDown)); + this.Register(typeof(UInt32), typeof(UintUpDown)); + this.Register(typeof(UInt64), typeof(UintUpDown)); + this.Register(typeof(Single), typeof(FloatCellEditor)); + this.Register(typeof(Double), typeof(FloatCellEditor)); + this.Register(typeof(DateTime), delegate(Object model, OLVColumn column, Object value) { + DateTimePicker c = new DateTimePicker(); + c.Format = DateTimePickerFormat.Short; + return c; + }); + this.Register(typeof(Boolean), delegate(Object model, OLVColumn column, Object value) { + CheckBox c = new BooleanCellEditor2(); + c.ThreeState = column.TriStateCheckBoxes; + return c; + }); + } + + #endregion + + #region Registering + + /// + /// Register that values of 'type' should be edited by instances of 'controlType'. + /// + /// The type of value to be edited + /// The type of the Control that will edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), typeof(MySpecialColorEditor)); + /// + public void Register(Type type, Type controlType) { + this.Register(type, delegate(Object model, OLVColumn column, Object value) { + return controlType.InvokeMember("", BindingFlags.CreateInstance, null, null, null) as Control; + }); + } + + /// + /// Register the given delegate so that it is called to create editors + /// for values of the given type + /// + /// The type of value to be edited + /// The delegate that will create a control that can edit values of 'type' + /// + /// ObjectListView.EditorRegistry.Register(typeof(Color), CreateColorEditor); + /// ... + /// public Control CreateColorEditor(Object model, OLVColumn column, Object value) + /// { + /// return new MySpecialColorEditor(); + /// } + /// + public void Register(Type type, EditorCreatorDelegate creator) { + this.creatorMap[type] = creator; + } + + /// + /// Register a delegate that will be called to create an editor for values + /// that have not been handled. + /// + /// The delegate that will create a editor for all other types + public void RegisterDefault(EditorCreatorDelegate creator) { + this.defaultCreator = creator; + } + + /// + /// Register a delegate that will be given a chance to create a control + /// before any other option is considered. + /// + /// The delegate that will create a control + public void RegisterFirstChance(EditorCreatorDelegate creator) { + this.firstChanceCreator = creator; + } + + /// + /// Remove the registered handler for the given type + /// + /// Does nothing if the given type doesn't exist + /// The type whose registration is to be removed + public void Unregister(Type type) { + if (this.creatorMap.ContainsKey(type)) + this.creatorMap.Remove(type); + } + + #endregion + + #region Accessing + + /// + /// Create and return an editor that is appropriate for the given value. + /// Return null if no appropriate editor can be found. + /// + /// The model involved + /// The column to be edited + /// The value to be edited. This value may not be the exact + /// value for the column/model combination. It could be simply representative of + /// the appropriate type of value. + /// A Control that can edit the given type of values + public Control GetEditor(Object model, OLVColumn column, Object value) { + Control editor; + + // Give the first chance delegate a chance to decide + if (this.firstChanceCreator != null) { + editor = this.firstChanceCreator(model, column, value); + if (editor != null) + return editor; + } + + // Try to find a creator based on the type of the value (or the column) + Type type = value == null ? column.DataType : value.GetType(); + if (type != null && this.creatorMap.ContainsKey(type)) { + editor = this.creatorMap[type](model, column, value); + if (editor != null) + return editor; + } + + // Enums without other processing get a special editor + if (value != null && value.GetType().IsEnum) + return this.CreateEnumEditor(value.GetType()); + + // Give any default creator a final chance + if (this.defaultCreator != null) + return this.defaultCreator(model, column, value); + + return null; + } + + /// + /// Create and return an editor that will edit values of the given type + /// + /// A enum type + protected Control CreateEnumEditor(Type type) { + return new EnumCellEditor(type); + } + + #endregion + + #region Private variables + + private EditorCreatorDelegate firstChanceCreator; + private EditorCreatorDelegate defaultCreator; + private Dictionary creatorMap = new Dictionary(); + + #endregion + } +} diff --git a/ObjectListView/CustomDictionary.xml b/ObjectListView/CustomDictionary.xml new file mode 100644 index 0000000..f2cf5b9 --- /dev/null +++ b/ObjectListView/CustomDictionary.xml @@ -0,0 +1,46 @@ + + + + + br + Canceled + Center + Color + Colors + f + fmt + g + gdi + hti + i + lightbox + lv + lvi + lvsi + m + multi + Munger + n + olv + olvi + p + parms + r + Renderer + s + SubItem + Unapply + Unpause + x + y + + + ComPlus + + + + + OLV + + + diff --git a/ObjectListView/DataListView.cs b/ObjectListView/DataListView.cs new file mode 100644 index 0000000..2961d04 --- /dev/null +++ b/ObjectListView/DataListView.cs @@ -0,0 +1,240 @@ +/* + * DataListView - A data-bindable listview + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2011-02-27 JPP - Moved most of the logic to DataSourceAdapter (where it + * can be used by FastDataListView too) + * v2.3 + * 2009-01-18 JPP - Boolean columns are now handled as checkboxes + * - Auto-generated columns would fail if the data source was + * reseated, even to the same data source + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-10-03 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + + /// + /// A DataListView is a ListView that can be bound to a datasource (which would normally be a DataTable or DataView). + /// + /// + /// This listview keeps itself in sync with its source datatable by listening for change events. + /// The DataListView will automatically create columns to show all of the data source's columns/properties, if there is not already + /// a column showing that property. This allows you to define one or two columns in the designer and then have the others generated automatically. + /// If you don't want any column to be auto generated, set to false. + /// These generated columns will be only the simplest view of the world, and would look more interesting with a few delegates installed. + /// This listview will also automatically generate missing aspect getters to fetch the values from the data view. + /// Changing data sources is possible, but error prone. Before changing data sources, the programmer is responsible for modifying/resetting + /// the column collection to be valid for the new data source. + /// Internally, a CurrencyManager controls keeping the data source in-sync with other users of the data source (as per normal .NET + /// behavior). This means that the model objects in the DataListView are DataRowView objects. If you write your own AspectGetters/Setters, + /// they will be given DataRowView objects. + /// + public class DataListView : ObjectListView + { + #region Life and death + + /// + /// Make a DataListView + /// + public DataListView() + { + this.Adapter = new DataSourceAdapter(this); + } + + /// + /// + /// + /// + protected override void Dispose(bool disposing) { + this.Adapter.Dispose(); + base.Dispose(disposing); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// When a DataSource is set, the control will create OLVColumns to show any + /// data source columns that are not already shown. + /// If the DataSource is changed, you will have to remove any previously + /// created columns, since they will be configured for the previous DataSource. + /// . + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource + { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember + { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + /// + /// Adaptors cannot be shared between controls. Each DataListView needs its own adapter. + /// + protected DataSourceAdapter Adapter { + get { + Debug.Assert(adapter != null, "Data adapter should not be null"); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Object manipulations + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void AddObjects(ICollection modelObjects) + { + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// Remove the given collection of model objects from this control. + /// + /// This is a no-op for data lists, since the data + /// is controlled by the DataSource. Manipulate the data source + /// rather than this view of the data source. + public override void RemoveObjects(ICollection modelObjects) + { + } + + #endregion + + #region Event Handlers + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + /// + /// Handles parent binding context changes + /// + /// Unused EventArgs. + protected override void OnParentBindingContextChanged(EventArgs e) + { + base.OnParentBindingContextChanged(e); + + // BindingContext is an ambient property - by default it simply picks + // up the parent control's context (unless something has explicitly + // given us our own). So we must respond to changes in our parent's + // binding context in the same way we would changes to our own + // binding context. + + // THINK: Do we need to forward this to the adapter? + } + + #endregion + } +} diff --git a/ObjectListView/DataTreeListView.cs b/ObjectListView/DataTreeListView.cs new file mode 100644 index 0000000..65179a9 --- /dev/null +++ b/ObjectListView/DataTreeListView.cs @@ -0,0 +1,240 @@ +/* + * DataTreeListView - A data bindable TreeListView + * + * Author: Phillip Piper + * Date: 05/05/2012 3:26 PM + * + * Change log: + + * 2012-05-05 JPP Initial version + * + * TO DO: + + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A DataTreeListView is a TreeListView that calculates its hierarchy based on + /// information in the data source. + /// + /// + /// Like a , a DataTreeListView sources all its information + /// from a combination of and . + /// can be a DataTable, DataSet, + /// or anything that implements . + /// + /// + /// To function properly, the DataTreeListView requires: + /// + /// the table to have a column which holds a unique for the row. The name of this column must be set in . + /// the table to have a column which holds id of the hierarchical parent of the row. The name of this column must be set in . + /// a value which identifies which rows are the roots of the tree (). + /// + /// The hierarchy structure is determined finding all the rows where the parent key is equal to . These rows + /// become the root objects of the hierarchy. + /// + /// Like a TreeListView, the hierarchy must not contain cycles. Bad things will happen if the data is cyclic. + /// + public partial class DataTreeListView : TreeListView + { + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + /// The DataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// DataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of a row"), + DefaultValue(null)] + public virtual string KeyAspectName { + get { return this.Adapter.KeyAspectName; } + set { this.Adapter.KeyAspectName = value; } + } + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + [Category("Data"), + Description("The name of the property/column that holds the key of the parent of a row"), + DefaultValue(null)] + public virtual string ParentKeyAspectName { + get { return this.Adapter.ParentKeyAspectName; } + set { this.Adapter.ParentKeyAspectName = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. Actually, it can be any value that can + /// be compared for equality against a basic type. + /// If this is set to the wrong value (i.e. to a value that no row + /// has in the parent id column), the list will be empty. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual object RootKeyValue { + get { return this.Adapter.RootKeyValue; } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets the value that identifies a row as a root object. + /// . The RootKeyValue can be of any type, + /// but the IDE cannot sensibly represent a value of any type, + /// so this is a typed wrapper around that property. + /// + /// + /// If you want the root value to be something other than a string, + /// you will have set it yourself. + /// + [Category("Data"), + Description("The parent id value that identifies a row as a root object"), + DefaultValue(null)] + public virtual string RootKeyValueString { + get { return Convert.ToString(this.Adapter.RootKeyValue); } + set { this.Adapter.RootKeyValue = value; } + } + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + [Category("Data"), + Description("Should the keys columns (id and parent id) be shown to the user?"), + DefaultValue(true)] + public virtual bool ShowKeyColumns { + get { return this.Adapter.ShowKeyColumns; } + set { this.Adapter.ShowKeyColumns = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected TreeDataSourceAdapter Adapter { + get { + if (this.adapter == null) + this.adapter = new TreeDataSourceAdapter(this); + return adapter; + } + set { adapter = value; } + } + private TreeDataSourceAdapter adapter; + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DragSource.cs b/ObjectListView/DragDrop/DragSource.cs new file mode 100644 index 0000000..1abf13b --- /dev/null +++ b/ObjectListView/DragDrop/DragSource.cs @@ -0,0 +1,219 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2011-03-29 JPP - Separate OLVDataObject.cs + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. The data + /// object will normally include all the selected objects. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All operations are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshes the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + return new OLVDataObject(olv); + } + + #endregion + } +} diff --git a/ObjectListView/DragDrop/DropSink.cs b/ObjectListView/DragDrop/DropSink.cs new file mode 100644 index 0000000..c82bd67 --- /dev/null +++ b/ObjectListView/DragDrop/DropSink.cs @@ -0,0 +1,1562 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2018-04-26 JPP - Implemented LeftOfItem and RightOfItem target locations + * - Added support for rearranging on non-Detail views. + * v2.9 + * 2015-07-08 JPP - Added SimpleDropSink.EnableFeedback to allow all the pretty and helpful + * user feedback during drags to be turned off + * v2.7 + * 2011-04-20 JPP - Rewrote how ModelDropEventArgs.RefreshObjects() works on TreeListViews + * v2.4.1 + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it should be called CleverDropSink -- it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists. Defaults to true. + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. Defaults to true. + /// + /// AutoScroll does not scroll horizontally. + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Gets or sets whether the drop sink should draw feedback onto the given list + /// during the drag operation. Defaults to true. + /// + /// If this is false, you will have to give the user feedback in some + /// other fashion, like cursor changes + public bool EnableFeedback { + get { return enableFeedback; } + set { enableFeedback = value; } + } + private bool enableFeedback = true; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + /// + /// Gets or sets whether the drop sink will automatically use cursors + /// based on the drop effect. By default, this is true. If this is + /// set to false, you must set the Cursor yourself. + /// + public bool UseDefaultCursors { + get { return useDefaultCursors; } + set { useDefaultCursors = value; } + } + private bool useDefaultCursors = true; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* settings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + if (this.EnableFeedback) { + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + case DropTargetLocation.LeftOfItem: + this.DrawFeedbackLeftOfItemTarget(g, bounds); + break; + case DropTargetLocation.RightOfItem: + this.DrawFeedbackRightOfItemTarget(g, bounds); + break; + } + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.dropEventArgs.DragEventArgs = args; + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementors should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DragEventArgs = args; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + public override void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = this.UseDefaultCursors; + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.dropEventArgs.DragEventArgs = args; + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continue while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined). + // If the view is Details or List, then "between" is considered vertically. + // If the view is SmallIcon, LargeIcon or Tile, then "between" is considered horizontally. + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + switch (this.ListView.View) { + case View.LargeIcon: + case View.Tile: + case View.SmallIcon: + // If the mouse is over an item, check to see if it is near the left or right edge. + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : info.Item.Bounds.Width / 2; + if (pt.X <= info.Item.Bounds.Left + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else if (pt.X >= info.Item.Bounds.Right - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } else { + // Is there an item a little to the *right* of the mouse? + // If so, we say the drop point is *left* that item + int probeWidth = SMALL_VALUE * 2; + info = this.ListView.OlvHitTest(pt.X + probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.LeftOfItem; + } else { + // Is there an item a little to the left of the mouse? + info = this.ListView.OlvHitTest(pt.X - probeWidth, pt.Y); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.RightOfItem; + } + } + } + break; + case View.Details: + case View.List: + // If the mouse is over an item, check to see if it is near the top or bottom + if (info.Item != null) { + int delta = this.CanDropOnItem ? SMALL_VALUE : this.ListView.RowHeightEffective / 2; + + if (pt.Y <= info.Item.Bounds.Top + delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else if (pt.Y >= info.Item.Bounds.Bottom - delta) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the left of target + /// + /// + /// + protected virtual void DrawFeedbackLeftOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Left, r.Bottom); + } + + /// + /// Draw the feedback that shows the drop will occur to the right of target + /// + /// + /// + protected virtual void DrawFeedbackRightOfItemTarget(Graphics g, Rectangle bounds) + { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Right, r.Top, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * item.IndentCount; + r.X += indentWidth; + r.Width -= indentWidth; + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + if (y1 == y2) { + // Put right and left arrow on a horizontal line + DrawClosedFigure(g, b, RightPointingArrow(x1, y1)); + DrawClosedFigure(g, b, LeftPointingArrow(x2, y2)); + } else { + // Put up and down arrows on a vertical line + DrawClosedFigure(g, b, DownPointingArrow(x1, y1)); + DrawClosedFigure(g, b, UpPointingArrow(x2, y2)); + } + } + + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + private const int ARROW_SIZE = 6; + + private static void DrawClosedFigure(Graphics g, Brush b, Point[] pts) { + using (GraphicsPath gp = new GraphicsPath()) { + gp.StartFigure(); + gp.AddLines(pts); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + + private static Point[] RightPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x + ARROW_SIZE, y) + }; + } + + private static Point[] LeftPointingArrow(int x, int y) { + return new Point[] { + new Point(x, y - ARROW_SIZE), + new Point(x, y + ARROW_SIZE), + new Point(x - ARROW_SIZE, y) + }; + } + + private static Point[] DownPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y + ARROW_SIZE) + }; + } + + private static Point[] UpPointingArrow(int x, int y) { + return new Point[] { + new Point(x - ARROW_SIZE, y), + new Point(x + ARROW_SIZE, y), + new Point(x, y - ARROW_SIZE) + }; + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amongst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging the same list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + case DropTargetLocation.LeftOfItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + case DropTargetLocation.RightOfItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + + // Some views have to be "encouraged" to show the changes + switch (this.ListView.View) { + case View.LargeIcon: + case View.SmallIcon: + case View.Tile: + this.ListView.BuildList(); + break; + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occurred, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the original drag-drop event args + /// + public DragEventArgs DragEventArgs + { + get { return this.dragEventArgs; } + internal set { this.dragEventArgs = value; } + } + private DragEventArgs dragEventArgs; + + /// + /// Get the data object that is being dragged + /// + public object DataObject + { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + + toBeRefreshed.AddRange(this.SourceModels); + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv == null) + this.SourceListView.RefreshObjects(toBeRefreshed); + else + tlv.RebuildAll(true); + + TreeListView tlv2 = this.ListView as TreeListView; + if (tlv2 == null) + this.ListView.RefreshObject(this.TargetModel); + else + tlv2.RebuildAll(true); + } + } +} diff --git a/ObjectListView/DragDrop/OLVDataObject.cs b/ObjectListView/DragDrop/OLVDataObject.cs new file mode 100644 index 0000000..116861b --- /dev/null +++ b/ObjectListView/DragDrop/OLVDataObject.cs @@ -0,0 +1,185 @@ +/* + * OLVDataObject.cs - An OLE DataObject that knows how to convert rows of an OLV to text and HTML + * + * Author: Phillip Piper + * Date: 2011-03-29 3:34PM + * + * Change log: + * v2.8 + * 2014-05-02 JPP - When the listview is completely empty, don't try to set CSV text in the clipboard. + * v2.6 + * 2012-08-08 JPP - Changed to use OLVExporter. + * - Added CSV to formats exported to Clipboard + * v2.4 + * 2011-03-29 JPP - Initial version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) + : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + this.CreateTextFormats(); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private readonly bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + } + private readonly bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private readonly ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private readonly IList modelObjects; + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + + OLVExporter exporter = this.CreateExporter(); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(exporter.ExportTo(OLVExporter.ExportFormat.TabSeparated)); + string exportTo = exporter.ExportTo(OLVExporter.ExportFormat.CSV); + if (!String.IsNullOrEmpty(exportTo)) + this.SetText(exportTo, TextDataFormat.CommaSeparatedValue); + this.SetText(ConvertToHtmlFragment(exporter.ExportTo(OLVExporter.ExportFormat.HTML)), TextDataFormat.Html); + } + + /// + /// Create an exporter for the data contained in this object + /// + /// + protected OLVExporter CreateExporter() { + OLVExporter exporter = new OLVExporter(this.ListView); + exporter.IncludeColumnHeaders = this.IncludeColumnHeaders; + exporter.IncludeHiddenColumns = this.IncludeHiddenColumns; + exporter.ModelObjects = this.ModelObjects; + return exporter; + } + + /// + /// Make a HTML representation of our model objects + /// + [Obsolete("Use OLVExporter directly instead", false)] + public string CreateHtml() { + OLVExporter exporter = this.CreateExporter(); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognised as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + const string SOURCE = "http://www.codeproject.com/Articles/16009/A-Much-Easier-to-Use-ListView"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, SOURCE, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment, StringComparison.Ordinal); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, SOURCE, html); + } + } +} diff --git a/ObjectListView/FastDataListView.cs b/ObjectListView/FastDataListView.cs new file mode 100644 index 0000000..8b30d2b --- /dev/null +++ b/ObjectListView/FastDataListView.cs @@ -0,0 +1,169 @@ +/* + * FastDataListView - A data bindable listview that has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 22/09/2010 8:11 AM + * + * Change log: + * 2015-02-02 JPP - Made Unfreezing more efficient by removing a redundant BuildList() call + * v2.6 + * 2010-09-22 JPP - Initial version + * + * Copyright (C) 2006-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing.Design; + +namespace BrightIdeasSoftware +{ + /// + /// A FastDataListView virtualizes the display of data from a DataSource. It operates on + /// DataSets and DataTables in the same way as a DataListView, but does so much more efficiently. + /// + /// + /// + /// A FastDataListView still has to load all its data from the DataSource. If you have SQL statement + /// that returns 1 million rows, all 1 million rows will still need to read from the database. + /// However, once the rows are loaded, the FastDataListView will only build rows as they are displayed. + /// + /// + public class FastDataListView : FastObjectListView + { + /// + /// + /// + /// + protected override void Dispose(bool disposing) + { + if (this.adapter != null) { + this.adapter.Dispose(); + this.adapter = null; + } + + base.Dispose(disposing); + } + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + [Category("Data"), + Description("Should the control automatically generate columns from the DataSource"), + DefaultValue(true)] + public bool AutoGenerateColumns + { + get { return this.Adapter.AutoGenerateColumns; } + set { this.Adapter.AutoGenerateColumns = value; } + } + + /// + /// Get or set the VirtualListDataSource that will be displayed in this list view. + /// + /// The VirtualListDataSource should implement either , , + /// or . Some common examples are the following types of objects: + /// + /// + /// + /// + /// + /// + /// + /// When binding to a list container (i.e. one that implements the + /// interface, such as ) + /// you must also set the property in order + /// to identify which particular list you would like to display. You + /// may also set the property even when + /// VirtualListDataSource refers to a list, since can + /// also be used to navigate relations between lists. + /// + [Category("Data"), + TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] + public virtual Object DataSource { + get { return this.Adapter.DataSource; } + set { this.Adapter.DataSource = value; } + } + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + [Category("Data"), + Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), + DefaultValue("")] + public virtual string DataMember { + get { return this.Adapter.DataMember; } + set { this.Adapter.DataMember = value; } + } + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the DataSourceAdaptor that does the bulk of the work needed + /// for data binding. + /// + protected DataSourceAdapter Adapter { + get { + if (adapter == null) + adapter = this.CreateDataSourceAdapter(); + return adapter; + } + set { adapter = value; } + } + private DataSourceAdapter adapter; + + #endregion + + #region Implementation + + /// + /// Create the DataSourceAdapter that this control will use. + /// + /// A DataSourceAdapter configured for this list + /// Subclasses should override this to create their + /// own specialized adapters + protected virtual DataSourceAdapter CreateDataSourceAdapter() { + return new DataSourceAdapter(this); + } + + /// + /// Change the Unfreeze behaviour + /// + protected override void DoUnfreeze() + { + + // Copied from base method, but we don't need to BuildList() since we know that our + // data adaptor is going to do that immediately after this method exits. + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + // this.BuildList(); + } + + #endregion + } +} diff --git a/ObjectListView/FastObjectListView.cs b/ObjectListView/FastObjectListView.cs new file mode 100644 index 0000000..0c5fe30 --- /dev/null +++ b/ObjectListView/FastObjectListView.cs @@ -0,0 +1,422 @@ +/* + * FastObjectListView - A listview that behaves like an ObjectListView but has the speed of a virtual list + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2014-10-15 JPP - Fire Filter event when applying filters + * v2.8 + * 2012-06-11 JPP - Added more efficient version of FilteredObjects + * v2.5.1 + * 2011-04-25 JPP - Fixed problem with removing objects from filtered or sorted list + * v2.4 + * 2010-04-05 JPP - Added filtering + * v2.3 + * 2009-08-27 JPP - Added GroupingStrategy + * - Added optimized Objects property + * v2.2.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A FastObjectListView trades function for speed. + /// + /// + /// On my mid-range laptop, this view builds a list of 10,000 objects in 0.1 seconds, + /// as opposed to a normal ObjectListView which takes 10-15 seconds. Lists of up to 50,000 items should be + /// able to be handled with sub-second response times even on low end machines. + /// + /// A FastObjectListView is implemented as a virtual list with many of the virtual modes limits (e.g. no sorting) + /// fixed through coding. There are some functions that simply cannot be provided. Specifically, a FastObjectListView cannot: + /// + /// use Tile view + /// show groups on XP + /// + /// + /// + public class FastObjectListView : VirtualObjectListView + { + /// + /// Make a FastObjectListView + /// + public FastObjectListView() { + this.VirtualListDataSource = new FastObjectListDataSource(this); + this.GroupingStrategy = new FastListGroupingStrategy(); + } + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).FilteredObjectList; + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + // This is much faster than the base method + return ((FastObjectListDataSource)this.VirtualListDataSource).ObjectList; + } + set { base.Objects = value; } + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public override void MoveObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.MoveObjects(index, modelObjects); }); + return; + } + + // If any object that is going to be moved is before the point where the insertion + // will occur, then we have to reduce the location of our insertion point + int displacedObjectCount = 0; + foreach (object modelObject in modelObjects) { + int i = this.IndexOf(modelObject); + if (i >= 0 && i <= index) + displacedObjectCount++; + } + index -= displacedObjectCount; + + this.BeginUpdate(); + try { + this.RemoveObjects(modelObjects); + this.InsertObjects(index, modelObjects); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + /// To be really honest, Unsort() doesn't work on FastObjectListViews since + /// the original ordering of model objects is lost when Sort() is called. So this method + /// effectively just turns off sorting. + public override void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.SetObjects(this.Objects); + } + } + + /// + /// Provide a data source for a FastObjectListView + /// + /// + /// This class isn't intended to be used directly, but it is left as a public + /// class just in case someone wants to subclass it. + /// + public class FastObjectListDataSource : AbstractVirtualListDataSource + { + /// + /// Create a FastObjectListDataSource + /// + /// + public FastObjectListDataSource(FastObjectListView listView) + : base(listView) { + } + + #region IVirtualListDataSource Members + + /// + /// Get n'th object + /// + /// + /// + public override object GetNthObject(int n) { + if (n >= 0 && n < this.filteredObjectList.Count) + return this.filteredObjectList[n]; + + return null; + } + + /// + /// How many items are in the data source + /// + /// + public override int GetObjectCount() { + return this.filteredObjectList.Count; + } + + /// + /// Get the index of the given model + /// + /// + /// + public override int GetObjectIndex(object model) { + int index; + + if (model != null && this.objectsToIndexMap.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.listView.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// + /// + /// + /// + public override void Sort(OLVColumn column, SortOrder sortOrder) { + if (sortOrder != SortOrder.None) { + ModelObjectComparer comparer = new ModelObjectComparer(column, sortOrder, this.listView.SecondarySortColumn, this.listView.SecondarySortOrder); + this.fullObjectList.Sort(comparer); + this.filteredObjectList.Sort(comparer); + } + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void AddObjects(ICollection modelObjects) { + foreach (object modelObject in modelObjects) { + if (modelObject != null) + this.fullObjectList.Add(modelObject); + } + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + /// + public override void InsertObjects(int index, ICollection modelObjects) { + this.fullObjectList.InsertRange(index, modelObjects); + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Remove the given collection of models from this source. + /// + /// + public override void RemoveObjects(ICollection modelObjects) { + + // We have to unselect any object that is about to be deleted + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + int i = this.GetObjectIndex(modelObject); + if (i >= 0) + indicesToRemove.Add(i); + } + + // Sort the indices from highest to lowest so that we + // remove latter ones before earlier ones. In this way, the + // indices of the rows doesn't change after the deletes. + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + + foreach (int i in indicesToRemove) + this.listView.SelectedIndices.Remove(i); + + // Remove the objects from the unfiltered list + foreach (object modelObject in modelObjects) + this.fullObjectList.Remove(modelObject); + + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// + /// + /// + public override void SetObjects(IEnumerable collection) { + ArrayList newObjects = ObjectListView.EnumerableToArray(collection, true); + + this.fullObjectList = newObjects; + this.FilterObjects(); + this.RebuildIndexMap(); + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public override void UpdateObject(int index, object modelObject) { + if (index < 0 || index >= this.filteredObjectList.Count) + return; + + int i = this.fullObjectList.IndexOf(this.filteredObjectList[index]); + if (i < 0) + return; + + if (ReferenceEquals(this.fullObjectList[i], modelObject)) + return; + + this.fullObjectList[i] = modelObject; + this.filteredObjectList[index] = modelObject; + this.objectsToIndexMap[modelObject] = index; + } + + private ArrayList fullObjectList = new ArrayList(); + private ArrayList filteredObjectList = new ArrayList(); + private IModelFilter modelFilter; + private IListFilter listFilter; + + #endregion + + #region IFilterableDataSource Members + + /// + /// Apply the given filters to this data source. One or both may be null. + /// + /// + /// + public override void ApplyFilters(IModelFilter iModelFilter, IListFilter iListFilter) { + this.modelFilter = iModelFilter; + this.listFilter = iListFilter; + this.SetObjects(this.fullObjectList); + } + + #endregion + + #region Implementation + + /// + /// Gets the full list of objects being used for this fast list. + /// This list is unfiltered. + /// + public ArrayList ObjectList { + get { return fullObjectList; } + } + + /// + /// Gets the list of objects from ObjectList which survive any installed filters. + /// + public ArrayList FilteredObjectList { + get { return filteredObjectList; } + } + + /// + /// Rebuild the map that remembers which model object is displayed at which line + /// + protected void RebuildIndexMap() { + this.objectsToIndexMap.Clear(); + for (int i = 0; i < this.filteredObjectList.Count; i++) + this.objectsToIndexMap[this.filteredObjectList[i]] = i; + } + readonly Dictionary objectsToIndexMap = new Dictionary(); + + /// + /// Build our filtered list from our full list. + /// + protected void FilterObjects() { + + // If this list isn't filtered, we don't need to do anything else + if (!this.listView.UseFiltering) { + this.filteredObjectList = new ArrayList(this.fullObjectList); + return; + } + + // Tell the world to filter the objects. If they do so, don't do anything else + // ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(this.fullObjectList); + this.listView.OnFilter(args); + if (args.FilteredObjects != null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(args.FilteredObjects, false); + return; + } + + IEnumerable objects = (this.listFilter == null) ? + this.fullObjectList : this.listFilter.Filter(this.fullObjectList); + + // Apply the object filter if there is one + if (this.modelFilter == null) { + this.filteredObjectList = ObjectListView.EnumerableToArray(objects, false); + } else { + this.filteredObjectList = new ArrayList(); + foreach (object model in objects) { + if (this.modelFilter.Filter(model)) + this.filteredObjectList.Add(model); + } + } + } + + #endregion + } + +} diff --git a/ObjectListView/Filtering/Cluster.cs b/ObjectListView/Filtering/Cluster.cs new file mode 100644 index 0000000..f90a84d --- /dev/null +++ b/ObjectListView/Filtering/Cluster.cs @@ -0,0 +1,125 @@ +/* + * Cluster - Implements a simple cluster + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// Concrete implementation of the ICluster interface. + /// + public class Cluster : ICluster { + + #region Life and death + + /// + /// Create a cluster + /// + /// The key for the cluster + public Cluster(object key) { + this.Count = 1; + this.ClusterKey = key; + } + + #endregion + + #region Public overrides + + /// + /// Return a string representation of this cluster + /// + /// + public override string ToString() { + return this.DisplayLabel ?? "[empty]"; + } + + #endregion + + #region Implementation of ICluster + + /// + /// Gets or sets how many items belong to this cluster + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + public string DisplayLabel { + get { return displayLabel; } + set { displayLabel = value; } + } + private string displayLabel; + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + public object ClusterKey { + get { return clusterKey; } + set { clusterKey = value; } + } + private object clusterKey; + + #endregion + + #region Implementation of IComparable + + /// + /// Return an indication of the ordering between this object and the given one + /// + /// + /// + public int CompareTo(object other) { + if (other == null || other == System.DBNull.Value) + return 1; + + ICluster otherCluster = other as ICluster; + if (otherCluster == null) + return 1; + + string keyAsString = this.ClusterKey as string; + if (keyAsString != null) + return String.Compare(keyAsString, otherCluster.ClusterKey as string, StringComparison.CurrentCultureIgnoreCase); + + IComparable keyAsComparable = this.ClusterKey as IComparable; + if (keyAsComparable != null) + return keyAsComparable.CompareTo(otherCluster.ClusterKey); + + return -1; + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClusteringStrategy.cs b/ObjectListView/Filtering/ClusteringStrategy.cs new file mode 100644 index 0000000..b2380f0 --- /dev/null +++ b/ObjectListView/Filtering/ClusteringStrategy.cs @@ -0,0 +1,189 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 3-March-2011 10:53 pm + * + * Change log: + * 2011-03-03 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class provides a useful base implementation of a clustering + /// strategy where the clusters are grouped around the value of a given column. + /// + public class ClusteringStrategy : IClusteringStrategy { + + #region Static properties + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is null. It is exposed so it can be localized. + /// + static public string NULL_LABEL = "[null]"; + + /// + /// This field is the text that will be shown to the user when a cluster + /// key is empty (i.e. a string of zero length). It is exposed so it can be localized. + /// + static public string EMPTY_LABEL = "[empty]"; + + /// + /// Gets or sets the format that will be used by default for clusters that only + /// contain 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + static public string DefaultDisplayLabelFormatSingular { + get { return defaultDisplayLabelFormatSingular; } + set { defaultDisplayLabelFormatSingular = value; } + } + static private string defaultDisplayLabelFormatSingular = "{0} ({1} item)"; + + /// + /// Gets or sets the format that will be used by default for clusters that + /// contain 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + static public string DefaultDisplayLabelFormatPlural { + get { return defaultDisplayLabelFormatPural; } + set { defaultDisplayLabelFormatPural = value; } + } + static private string defaultDisplayLabelFormatPural = "{0} ({1} items)"; + + #endregion + + #region Life and death + + /// + /// Create a clustering strategy + /// + public ClusteringStrategy() { + this.DisplayLabelFormatSingular = DefaultDisplayLabelFormatSingular; + this.DisplayLabelFormatPlural = DefaultDisplayLabelFormatPlural; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets the column upon which this strategy is operating + /// + public OLVColumn Column { + get { return column; } + set { column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains only 1 item. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster (always 1 in this case) + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatSingular will be used + public string DisplayLabelFormatSingular { + get { return displayLabelFormatSingular; } + set { displayLabelFormatSingular = value; } + } + private string displayLabelFormatSingular; + + /// + /// Gets or sets the format that will be used when the cluster + /// contains 0 or two or more items. The format string must accept two placeholders: + /// - {0} is the cluster key converted to a string + /// - {1} is the number of items in the cluster + /// + /// If this is not set, the value from + /// ClusteringStrategy.DefaultDisplayLabelFormatPlural will be used + public string DisplayLabelFormatPlural { + get { return displayLabelFormatPural; } + set { displayLabelFormatPural = value; } + } + private string displayLabelFormatPural; + + #endregion + + #region ICluster implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + virtual public object GetClusterKey(object model) { + return this.Column.GetValue(model); + } + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + virtual public ICluster CreateCluster(object clusterKey) { + return new Cluster(clusterKey); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + virtual public string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ValueToString(cluster.ClusterKey) ?? NULL_LABEL; + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + virtual public IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new OneOfFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + /// + /// Create a label that combines the string representation of the cluster + /// key with a format string that holds an "X [N items in cluster]" type layout. + /// + /// + /// + /// + virtual protected string ApplyDisplayFormat(ICluster cluster, string s) { + string format = (cluster.Count == 1) ? this.DisplayLabelFormatSingular : this.DisplayLabelFormatPlural; + return String.IsNullOrEmpty(format) ? s : String.Format(format, s, cluster.Count); + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs new file mode 100644 index 0000000..ca95ecf --- /dev/null +++ b/ObjectListView/Filtering/ClustersFromGroupsStrategy.cs @@ -0,0 +1,70 @@ +/* + * ClusteringStrategy - Implements a simple clustering strategy + * + * Author: Phillip Piper + * Date: 1-April-2011 8:12am + * + * Change log: + * 2011-04-01 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// This class calculates clusters from the groups that the column uses. + /// + /// + /// + /// This is the default strategy for all non-date, filterable columns. + /// + /// + /// This class does not strictly mimic the groups created by the given column. + /// In particular, if the programmer changes the default grouping technique + /// by listening for grouping events, this class will not mimic that behaviour. + /// + /// + public class ClustersFromGroupsStrategy : ClusteringStrategy { + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + return this.Column.GetGroupKey(model); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + string s = this.Column.ConvertGroupKeyToTitle(cluster.ClusterKey); + if (String.IsNullOrEmpty(s)) + s = EMPTY_LABEL; + return this.ApplyDisplayFormat(cluster, s); + } + } +} diff --git a/ObjectListView/Filtering/DateTimeClusteringStrategy.cs b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs new file mode 100644 index 0000000..e0a864b --- /dev/null +++ b/ObjectListView/Filtering/DateTimeClusteringStrategy.cs @@ -0,0 +1,187 @@ +/* + * DateTimeClusteringStrategy - A strategy to cluster objects by a date time + * + * Author: Phillip Piper + * Date: 30-March-2011 9:40am + * + * Change log: + * 2011-03-30 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// This enum is used to indicate various portions of a datetime + /// + [Flags] + public enum DateTimePortion { + /// + /// Year + /// + Year = 0x01, + + /// + /// Month + /// + Month = 0x02, + + /// + /// Day of the month + /// + Day = 0x04, + + /// + /// Hour + /// + Hour = 0x08, + + /// + /// Minute + /// + Minute = 0x10, + + /// + /// Second + /// + Second = 0x20 + } + + /// + /// This class implements a strategy where the model objects are clustered + /// according to some portion of the datetime value in the configured column. + /// + /// To create a strategy that grouped people who were born in + /// the same month, you would create a strategy that extracted just + /// the month, and formatted it to show just the month's name. Like this: + /// + /// + /// someColumn.ClusteringStrategy = new DateTimeClusteringStrategy(DateTimePortion.Month, "MMMM"); + /// + public class DateTimeClusteringStrategy : ClusteringStrategy { + #region Life and death + + /// + /// Create a strategy that clusters by month/year + /// + public DateTimeClusteringStrategy() + : this(DateTimePortion.Year | DateTimePortion.Month, "MMMM yyyy") { + } + + /// + /// Create a strategy that clusters around the given parts + /// + /// + /// + public DateTimeClusteringStrategy(DateTimePortion portions, string format) { + this.Portions = portions; + this.Format = format; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the format string that will be used to create a user-presentable + /// version of the cluster key. + /// + /// The format should use the date/time format strings, as documented + /// in the Windows SDK. Both standard formats and custom format will work. + /// "D" - long date pattern + /// "MMMM, yyyy" - "January, 1999" + public string Format { + get { return format; } + set { format = value; } + } + private string format; + + /// + /// Gets or sets the parts of the DateTime that will be extracted when + /// determining the clustering key for an object. + /// + public DateTimePortion Portions { + get { return portions; } + set { portions = value; } + } + private DateTimePortion portions = DateTimePortion.Year | DateTimePortion.Month; + + #endregion + + #region IClusterStrategy implementation + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + // Get the data attribute we want from the given model + // Make sure the returned value is a DateTime + DateTime? dateTime = this.Column.GetValue(model) as DateTime?; + if (!dateTime.HasValue) + return null; + + // Extract the parts of the datetime that we are interested in. + // Even if we aren't interested in a particular portion, we still have to give it a reasonable default + // otherwise we won't be able to build a DateTime object for it + int year = ((this.Portions & DateTimePortion.Year) == DateTimePortion.Year) ? dateTime.Value.Year : 1; + int month = ((this.Portions & DateTimePortion.Month) == DateTimePortion.Month) ? dateTime.Value.Month : 1; + int day = ((this.Portions & DateTimePortion.Day) == DateTimePortion.Day) ? dateTime.Value.Day : 1; + int hour = ((this.Portions & DateTimePortion.Hour) == DateTimePortion.Hour) ? dateTime.Value.Hour : 0; + int minute = ((this.Portions & DateTimePortion.Minute) == DateTimePortion.Minute) ? dateTime.Value.Minute : 0; + int second = ((this.Portions & DateTimePortion.Second) == DateTimePortion.Second) ? dateTime.Value.Second : 0; + + return new DateTime(year, month, day, hour, minute, second); + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + DateTime? dateTime = cluster.ClusterKey as DateTime?; + + return this.ApplyDisplayFormat(cluster, dateTime.HasValue ? this.DateToString(dateTime.Value) : NULL_LABEL); + } + + /// + /// Convert the given date into a user presentable string + /// + /// + /// + protected virtual string DateToString(DateTime dateTime) { + if (String.IsNullOrEmpty(this.Format)) + return dateTime.ToString(CultureInfo.CurrentUICulture); + + try { + return dateTime.ToString(this.Format); + } + catch (FormatException) { + return String.Format("Bad format string '{0}' for value '{1}'", this.Format, dateTime); + } + } + + #endregion + } +} diff --git a/ObjectListView/Filtering/FilterMenuBuilder.cs b/ObjectListView/Filtering/FilterMenuBuilder.cs new file mode 100644 index 0000000..e91614a --- /dev/null +++ b/ObjectListView/Filtering/FilterMenuBuilder.cs @@ -0,0 +1,369 @@ +/* + * FilterMenuBuilder - Responsible for creating a Filter menu + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-20 JPP - Allow the same model object to be in multiple clusters + * Useful for xor'ed flag fields, and multi-value strings + * (e.g. hobbies that are stored as comma separated values). + * v2.5.1 + * 2012-04-14 JPP - Fixed rare bug with clustering an empty list (SF #3445118) + * v2.5 + * 2011-04-12 JPP - Added some images to menu + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Collections; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class know how to build a Filter menu. + /// It is responsible for clustering the values in the target column, + /// build a menu that shows those clusters, and then constructing + /// a filter that will enact the users choices. + /// + /// + /// Almost all of the methods in this class are declared as "virtual protected" + /// so that subclasses can provide alternative behaviours. + /// + public class FilterMenuBuilder { + + #region Static properties + + /// + /// Gets or sets the string that labels the Apply button. + /// Exposed so it can be localized. + /// + static public string APPLY_LABEL = "Apply"; + + /// + /// Gets or sets the string that labels the Clear All menu item. + /// Exposed so it can be localized. + /// + static public string CLEAR_ALL_FILTERS_LABEL = "Clear All Filters"; + + /// + /// Gets or sets the string that labels the Filtering menu as a whole.. + /// Exposed so it can be localized. + /// + static public string FILTERING_LABEL = "Filtering"; + + /// + /// Gets or sets the string that represents Select All values. + /// If this is set to null or empty, no Select All option will be included. + /// Exposed so it can be localized. + /// + static public string SELECT_ALL_LABEL = "Select All"; + + /// + /// Gets or sets the image that will be placed next to the Clear Filtering menu item + /// + static public Bitmap ClearFilteringImage = BrightIdeasSoftware.Properties.Resources.ClearFiltering; + + /// + /// Gets or sets the image that will be placed next to all "Apply" menu items on the filtering menu + /// + static public Bitmap FilteringImage = BrightIdeasSoftware.Properties.Resources.Filtering; + + #endregion + + #region Public properties + + /// + /// Gets or sets whether null should be considered as a valid data value. + /// If this is true (the default), then a cluster will null as a key will be allow. + /// If this is false, object that return a cluster key of null will ignored. + /// + public bool TreatNullAsDataValue { + get { return treatNullAsDataValue; } + set { treatNullAsDataValue = value; } + } + private bool treatNullAsDataValue = true; + + /// + /// Gets or sets the maximum number of objects that the clustering strategy + /// will consider. This should be large enough to collect all unique clusters, + /// but small enough to finish in a reasonable time. + /// + /// The default value is 10,000. This should be perfectly + /// acceptable for almost all lists. + public int MaxObjectsToConsider { + get { return maxObjectsToConsider; } + set { maxObjectsToConsider = value; } + } + private int maxObjectsToConsider = 10000; + + #endregion + + /// + /// Create a Filter menu on the given tool tip for the given column in the given ObjectListView. + /// + /// This is the main entry point into this class. + /// + /// + /// + /// The strip that should be shown to the user + virtual public ToolStripDropDown MakeFilterMenu(ToolStripDropDown strip, ObjectListView listView, OLVColumn column) { + if (strip == null) throw new ArgumentNullException("strip"); + if (listView == null) throw new ArgumentNullException("listView"); + if (column == null) throw new ArgumentNullException("column"); + + if (!column.UseFiltering || column.ClusteringStrategy == null || listView.Objects == null) + return strip; + + List clusters = this.Cluster(column.ClusteringStrategy, listView, column); + if (clusters.Count > 0) { + this.SortClusters(column.ClusteringStrategy, clusters); + strip.Items.Add(this.CreateFilteringMenuItem(column, clusters)); + } + + return strip; + } + + /// + /// Create a collection of clusters that should be presented to the user + /// + /// + /// + /// + /// + virtual protected List Cluster(IClusteringStrategy strategy, ObjectListView listView, OLVColumn column) { + // Build a map that correlates cluster key to clusters + NullableDictionary map = new NullableDictionary(); + int count = 0; + foreach (object model in listView.ObjectsForClustering) { + this.ClusterOneModel(strategy, map, model); + + if (count++ > this.MaxObjectsToConsider) + break; + } + + // Now that we know exactly how many items are in each cluster, create a label for it + foreach (ICluster cluster in map.Values) + cluster.DisplayLabel = strategy.GetClusterDisplayLabel(cluster); + + return new List(map.Values); + } + + private void ClusterOneModel(IClusteringStrategy strategy, NullableDictionary map, object model) { + object clusterKey = strategy.GetClusterKey(model); + + // If the returned value is an IEnumerable, that means the given model can belong to more than one cluster + IEnumerable keyEnumerable = clusterKey as IEnumerable; + if (clusterKey is string || keyEnumerable == null) + keyEnumerable = new object[] {clusterKey}; + + // Deal with nulls and DBNulls + ArrayList nullCorrected = new ArrayList(); + foreach (object key in keyEnumerable) { + if (key == null || key == System.DBNull.Value) { + if (this.TreatNullAsDataValue) + nullCorrected.Add(null); + } else nullCorrected.Add(key); + } + + // Group by key + foreach (object key in nullCorrected) { + if (map.ContainsKey(key)) + map[key].Count += 1; + else + map[key] = strategy.CreateCluster(key); + } + } + + /// + /// Order the given list of clusters in the manner in which they should be presented to the user. + /// + /// + /// + virtual protected void SortClusters(IClusteringStrategy strategy, List clusters) { + clusters.Sort(); + } + + /// + /// Do the work of making a menu that shows the clusters to the users + /// + /// + /// + /// + virtual protected ToolStripMenuItem CreateFilteringMenuItem(OLVColumn column, List clusters) { + ToolStripCheckedListBox checkedList = new ToolStripCheckedListBox(); + checkedList.Tag = column; + foreach (ICluster cluster in clusters) + checkedList.AddItem(cluster, column.ValuesChosenForFiltering.Contains(cluster.ClusterKey)); + if (!String.IsNullOrEmpty(SELECT_ALL_LABEL)) { + int checkedCount = checkedList.CheckedItems.Count; + if (checkedCount == 0) + checkedList.AddItem(SELECT_ALL_LABEL, CheckState.Unchecked); + else + checkedList.AddItem(SELECT_ALL_LABEL, checkedCount == clusters.Count ? CheckState.Checked : CheckState.Indeterminate); + } + checkedList.ItemCheck += new ItemCheckEventHandler(HandleItemCheckedWrapped); + + ToolStripMenuItem clearAll = new ToolStripMenuItem(CLEAR_ALL_FILTERS_LABEL, ClearFilteringImage, delegate(object sender, EventArgs args) { + this.ClearAllFilters(column); + }); + ToolStripMenuItem apply = new ToolStripMenuItem(APPLY_LABEL, FilteringImage, delegate(object sender, EventArgs args) { + this.EnactFilter(checkedList, column); + }); + ToolStripMenuItem subMenu = new ToolStripMenuItem(FILTERING_LABEL, null, new ToolStripItem[] { + clearAll, new ToolStripSeparator(), checkedList, apply }); + return subMenu; + } + + /// + /// Wrap a protected section around the real HandleItemChecked method, so that if + /// that method tries to change a "checkedness" of an item, we don't get a recursive + /// stack error. Effectively, this ensure that HandleItemChecked is only called + /// in response to a user action. + /// + /// + /// + private void HandleItemCheckedWrapped(object sender, ItemCheckEventArgs e) { + if (alreadyInHandleItemChecked) + return; + + try { + alreadyInHandleItemChecked = true; + this.HandleItemChecked(sender, e); + } + finally { + alreadyInHandleItemChecked = false; + } + } + bool alreadyInHandleItemChecked = false; + + /// + /// Handle a user-generated ItemCheck event + /// + /// + /// + virtual protected void HandleItemChecked(object sender, ItemCheckEventArgs e) { + + ToolStripCheckedListBox checkedList = sender as ToolStripCheckedListBox; + if (checkedList == null) return; + OLVColumn column = checkedList.Tag as OLVColumn; + if (column == null) return; + ObjectListView listView = column.ListView as ObjectListView; + if (listView == null) return; + + // Deal with the "Select All" item if there is one + int selectAllIndex = checkedList.Items.IndexOf(SELECT_ALL_LABEL); + if (selectAllIndex >= 0) + HandleSelectAllItem(e, checkedList, selectAllIndex); + } + + /// + /// Handle any checking/unchecking of the Select All option, and keep + /// its checkedness in sync with everything else that is checked. + /// + /// + /// + /// + virtual protected void HandleSelectAllItem(ItemCheckEventArgs e, ToolStripCheckedListBox checkedList, int selectAllIndex) { + // Did they check/uncheck the "Select All"? + if (e.Index == selectAllIndex) { + if (e.NewValue == CheckState.Checked) + checkedList.CheckAll(); + if (e.NewValue == CheckState.Unchecked) + checkedList.UncheckAll(); + return; + } + + // OK. The user didn't check/uncheck SelectAll. Now we have to update it's + // checkedness to reflect the state of everything else + // If all clusters are checked, we check the Select All. + // If no clusters are checked, the uncheck the Select All. + // For everything else, Select All is set to indeterminate. + + // How many items are currently checked? + int count = checkedList.CheckedItems.Count; + + // First complication. + // The value of the Select All itself doesn't count + if (checkedList.GetItemCheckState(selectAllIndex) != CheckState.Unchecked) + count -= 1; + + // Another complication. + // CheckedItems does not yet know about the item the user has just + // clicked, so we have to adjust the count of checked items to what + // it is going to be + if (e.NewValue != e.CurrentValue) { + if (e.NewValue == CheckState.Checked) + count += 1; + else + count -= 1; + } + + // Update the state of the Select All item + if (count == 0) + checkedList.SetItemState(selectAllIndex, CheckState.Unchecked); + else if (count == checkedList.Items.Count - 1) + checkedList.SetItemState(selectAllIndex, CheckState.Checked); + else + checkedList.SetItemState(selectAllIndex, CheckState.Indeterminate); + } + + /// + /// Clear all the filters that are applied to the given column + /// + /// The column from which filters are to be removed + virtual protected void ClearAllFilters(OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + olv.ResetColumnFiltering(); + } + + /// + /// Apply the selected values from the given list as a filter on the given column + /// + /// A list in which the checked items should be used as filters + /// The column for which a filter should be generated + virtual protected void EnactFilter(ToolStripCheckedListBox checkedList, OLVColumn column) { + + ObjectListView olv = column.ListView as ObjectListView; + if (olv == null || olv.IsDisposed) + return; + + // Collect all the checked values + ArrayList chosenValues = new ArrayList(); + foreach (object x in checkedList.CheckedItems) { + ICluster cluster = x as ICluster; + if (cluster != null) { + chosenValues.Add(cluster.ClusterKey); + } + } + column.ValuesChosenForFiltering = chosenValues; + + olv.UpdateColumnFiltering(); + } + } +} diff --git a/ObjectListView/Filtering/Filters.cs b/ObjectListView/Filtering/Filters.cs new file mode 100644 index 0000000..db69a62 --- /dev/null +++ b/ObjectListView/Filtering/Filters.cs @@ -0,0 +1,489 @@ +/* + * Filters - Filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 03/03/2010 17:00 + * + * Change log: + * 2011-03-01 JPP Added CompositeAllFilter, CompositeAnyFilter and OneOfFilter + * v2.4.1 + * 2010-06-23 JPP Extended TextMatchFilter to handle regular expressions and string prefix matching. + * v2.4 + * 2010-03-03 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Drawing; + +namespace BrightIdeasSoftware +{ + /// + /// Interface for model-by-model filtering + /// + public interface IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + bool Filter(object modelObject); + } + + /// + /// Interface for whole list filtering + /// + public interface IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + IEnumerable Filter(IEnumerable modelObjects); + } + + /// + /// Base class for model-by-model filters + /// + public class AbstractModelFilter : IModelFilter + { + /// + /// Should the given model be included when this filter is installed + /// + /// The model object to consider + /// Returns true if the model will be included by the filter + virtual public bool Filter(object modelObject) { + return true; + } + } + + /// + /// This filter calls a given Predicate to decide if a model object should be included + /// + public class ModelFilter : IModelFilter + { + /// + /// Create a filter based on the given predicate + /// + /// The function that will filter objects + public ModelFilter(Predicate predicate) { + this.Predicate = predicate; + } + + /// + /// Gets or sets the predicate used to filter model objects + /// + protected Predicate Predicate { + get { return predicate; } + set { predicate = value; } + } + private Predicate predicate; + + /// + /// Should the given model object be included? + /// + /// + /// + virtual public bool Filter(object modelObject) { + return this.Predicate == null ? true : this.Predicate(modelObject); + } + } + + /// + /// A CompositeFilter joins several other filters together. + /// If there are no filters, all model objects are included + /// + abstract public class CompositeFilter : IModelFilter { + + /// + /// Create an empty filter + /// + public CompositeFilter() { + } + + /// + /// Create a composite filter from the given list of filters + /// + /// A list of filters + public CompositeFilter(IEnumerable filters) { + foreach (IModelFilter filter in filters) { + if (filter != null) + Filters.Add(filter); + } + } + + /// + /// Gets or sets the filters used by this composite + /// + public IList Filters { + get { return filters; } + set { filters = value; } + } + private IList filters = new List(); + + /// + /// Get the sub filters that are text match filters + /// + public IEnumerable TextFilters { + get { + foreach (IModelFilter filter in this.Filters) { + TextMatchFilter textFilter = filter as TextMatchFilter; + if (textFilter != null) + yield return textFilter; + } + } + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// + /// True if the object is included by the filter + virtual public bool Filter(object modelObject) { + if (this.Filters == null || this.Filters.Count == 0) + return true; + + return this.FilterObject(modelObject); + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + abstract public bool FilterObject(object modelObject); + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must satisfy all filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAllFilter : CompositeFilter { + + /// + /// Create a filter + /// + /// + public CompositeAllFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (!filter.Filter(modelObject)) + return false; + + return true; + } + } + + /// + /// A CompositeAllFilter joins several other filters together. + /// A model object must only satisfy one of the filters to be included. + /// If there are no filters, all model objects are included + /// + public class CompositeAnyFilter : CompositeFilter { + + /// + /// Create a filter from the given filters + /// + /// + public CompositeAnyFilter(List filters) + : base(filters) { + } + + /// + /// Decide whether or not the given model should be included by the filter + /// + /// Filters is guaranteed to be non-empty when this method is called + /// The model object under consideration + /// True if the object is included by the filter + override public bool FilterObject(object modelObject) { + foreach (IModelFilter filter in this.Filters) + if (filter.Filter(modelObject)) + return true; + + return false; + } + } + + /// + /// Instances of this class extract a value from the model object + /// and compare that value to a list of fixed values. The model + /// object is included if the extracted value is in the list + /// + /// If there is no delegate installed or there are + /// no values to match, no model objects will be matched + public class OneOfFilter : IModelFilter { + + /// + /// Create a filter that will use the given delegate to extract values + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter) : + this(valueGetter, new ArrayList()) { + } + + /// + /// Create a filter that will extract values using the given delegate + /// and compare them to the values in the given list. + /// + /// + /// + public OneOfFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) { + this.ValueGetter = valueGetter; + this.PossibleValues = new ArrayList(possibleValues); + } + + /// + /// Gets or sets the delegate that will be used to extract values + /// from model objects + /// + virtual public AspectGetterDelegate ValueGetter { + get { return valueGetter; } + set { valueGetter = value; } + } + private AspectGetterDelegate valueGetter; + + /// + /// Gets or sets the list of values that the value extracted from + /// the model object must match in order to be included. + /// + virtual public IList PossibleValues { + get { return possibleValues; } + set { possibleValues = value; } + } + private IList possibleValues; + + /// + /// Should the given model object be included? + /// + /// + /// + public virtual bool Filter(object modelObject) { + if (this.ValueGetter == null || this.PossibleValues == null || this.PossibleValues.Count == 0) + return false; + + object result = this.ValueGetter(modelObject); + IEnumerable enumerable = result as IEnumerable; + if (result is string || enumerable == null) + return this.DoesValueMatch(result); + + foreach (object x in enumerable) { + if (this.DoesValueMatch(x)) + return true; + } + return false; + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected virtual bool DoesValueMatch(object result) { + return this.PossibleValues.Contains(result); + } + } + + /// + /// Instances of this class match a property of a model objects against + /// a list of bit flags. The property should be an xor-ed collection + /// of bits flags. + /// + /// Both the property compared and the list of possible values + /// must be convertible to ulongs. + public class FlagBitSetFilter : OneOfFilter { + + /// + /// Create an instance + /// + /// + /// + public FlagBitSetFilter(AspectGetterDelegate valueGetter, ICollection possibleValues) : base(valueGetter, possibleValues) { + this.ConvertPossibleValues(); + } + + /// + /// Gets or sets the collection of values that will be matched. + /// These must be ulongs (or convertible to ulongs). + /// + public override IList PossibleValues { + get { return base.PossibleValues; } + set { + base.PossibleValues = value; + this.ConvertPossibleValues(); + } + } + + private void ConvertPossibleValues() { + this.possibleValuesAsUlongs = new List(); + foreach (object x in this.PossibleValues) + this.possibleValuesAsUlongs.Add(Convert.ToUInt64(x)); + } + + /// + /// Decides if the given property is a match for the values in the PossibleValues collection + /// + /// + /// + protected override bool DoesValueMatch(object result) { + try { + UInt64 value = Convert.ToUInt64(result); + foreach (ulong flag in this.possibleValuesAsUlongs) { + if ((value & flag) == flag) + return true; + } + return false; + } + catch (InvalidCastException) { + return false; + } + catch (FormatException) { + return false; + } + } + + private List possibleValuesAsUlongs = new List(); + } + + /// + /// Base class for whole list filters + /// + public class AbstractListFilter : IListFilter + { + /// + /// Return a subset of the given list of model objects as the new + /// contents of the ObjectListView + /// + /// The collection of model objects that the list will possibly display + /// The filtered collection that holds the model objects that will be displayed. + virtual public IEnumerable Filter(IEnumerable modelObjects) { + return modelObjects; + } + } + + /// + /// Instance of this class implement delegate based whole list filtering + /// + public class ListFilter : AbstractListFilter + { + /// + /// A delegate that filters on a whole list + /// + /// + /// + public delegate IEnumerable ListFilterDelegate(IEnumerable rowObjects); + + /// + /// Create a ListFilter + /// + /// + public ListFilter(ListFilterDelegate function) { + this.Function = function; + } + + /// + /// Gets or sets the delegate that will filter the list + /// + public ListFilterDelegate Function { + get { return function; } + set { function = value; } + } + private ListFilterDelegate function; + + /// + /// Do the actual work of filtering + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Function == null) + return modelObjects; + + return this.Function(modelObjects); + } + } + + /// + /// Filter the list so only the last N entries are displayed + /// + public class TailFilter : AbstractListFilter + { + /// + /// Create a no-op tail filter + /// + public TailFilter() { + } + + /// + /// Create a filter that includes on the last N model objects + /// + /// + public TailFilter(int numberOfObjects) { + this.Count = numberOfObjects; + } + + /// + /// Gets or sets the number of model objects that will be + /// returned from the tail of the list + /// + public int Count { + get { return count; } + set { count = value; } + } + private int count; + + /// + /// Return the last N subset of the model objects + /// + /// + /// + public override IEnumerable Filter(IEnumerable modelObjects) { + if (this.Count <= 0) + return modelObjects; + + ArrayList list = ObjectListView.EnumerableToArray(modelObjects, false); + + if (this.Count > list.Count) + return list; + + object[] tail = new object[this.Count]; + list.CopyTo(list.Count - this.Count, tail, 0, this.Count); + return new ArrayList(tail); + } + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/FlagClusteringStrategy.cs b/ObjectListView/Filtering/FlagClusteringStrategy.cs new file mode 100644 index 0000000..519ce89 --- /dev/null +++ b/ObjectListView/Filtering/FlagClusteringStrategy.cs @@ -0,0 +1,160 @@ +/* + * FlagClusteringStrategy - Implements a clustering strategy for a field which is a single integer + * containing an XOR'ed collection of bit flags + * + * Author: Phillip Piper + * Date: 23-March-2012 8:33 am + * + * Change log: + * 2012-03-23 JPP - First version + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class cluster model objects on the basis of a + /// property that holds an xor-ed collection of bit flags. + /// + public class FlagClusteringStrategy : ClusteringStrategy + { + #region Life and death + + /// + /// Create a clustering strategy that operates on the flags of the given enum + /// + /// + public FlagClusteringStrategy(Type enumType) { + if (enumType == null) throw new ArgumentNullException("enumType"); + if (!enumType.IsEnum) throw new ArgumentException("Type must be enum", "enumType"); + if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false) == null) throw new ArgumentException("Type must have [Flags] attribute", "enumType"); + + List flags = new List(); + foreach (object x in Enum.GetValues(enumType)) + flags.Add(Convert.ToInt64(x)); + + List flagLabels = new List(); + foreach (string x in Enum.GetNames(enumType)) + flagLabels.Add(x); + + this.SetValues(flags.ToArray(), flagLabels.ToArray()); + } + + /// + /// Create a clustering strategy around the given collections of flags and their display labels. + /// There must be the same number of elements in both collections. + /// + /// The list of flags. + /// + public FlagClusteringStrategy(long[] values, string[] labels) { + this.SetValues(values, labels); + } + + #endregion + + #region Implementation + + /// + /// Gets the value that will be xor-ed to test for the presence of a particular value. + /// + public long[] Values { + get { return this.values; } + private set { this.values = value; } + } + private long[] values; + + /// + /// Gets the labels that will be used when the corresponding Value is XOR present in the data. + /// + public string[] Labels { + get { return this.labels; } + private set { this.labels = value; } + } + private string[] labels; + + private void SetValues(long[] flags, string[] flagLabels) { + if (flags == null || flags.Length == 0) throw new ArgumentNullException("flags"); + if (flagLabels == null || flagLabels.Length == 0) throw new ArgumentNullException("flagLabels"); + if (flags.Length != flagLabels.Length) throw new ArgumentException("values and labels must have the same number of entries", "flags"); + + this.Values = flags; + this.Labels = flagLabels; + } + + #endregion + + #region Implementation of IClusteringStrategy + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// + /// + public override object GetClusterKey(object model) { + List flags = new List(); + try { + long modelValue = Convert.ToInt64(this.Column.GetValue(model)); + foreach (long x in this.Values) { + if ((x & modelValue) == x) + flags.Add(x); + } + return flags; + } + catch (InvalidCastException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + catch (FormatException ex) { + System.Diagnostics.Debug.Write(ex); + return flags; + } + } + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + public override string GetClusterDisplayLabel(ICluster cluster) { + long clusterKeyAsUlong = Convert.ToInt64(cluster.ClusterKey); + for (int i = 0; i < this.Values.Length; i++ ) { + if (clusterKeyAsUlong == this.Values[i]) + return this.ApplyDisplayFormat(cluster, this.Labels[i]); + } + return this.ApplyDisplayFormat(cluster, clusterKeyAsUlong.ToString(CultureInfo.CurrentUICulture)); + } + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + public override IModelFilter CreateFilter(IList valuesChosenForFiltering) { + return new FlagBitSetFilter(this.GetClusterKey, valuesChosenForFiltering); + } + + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Filtering/ICluster.cs b/ObjectListView/Filtering/ICluster.cs new file mode 100644 index 0000000..3196595 --- /dev/null +++ b/ObjectListView/Filtering/ICluster.cs @@ -0,0 +1,56 @@ +/* + * ICluster - A cluster is a group of objects that can be included or excluded as a whole + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + /// + /// A cluster is a like collection of objects that can be usefully filtered + /// as whole using the filtering UI provided by the ObjectListView. + /// + public interface ICluster : IComparable { + /// + /// Gets or sets how many items belong to this cluster + /// + int Count { get; set; } + + /// + /// Gets or sets the label that will be shown to the user to represent + /// this cluster + /// + string DisplayLabel { get; set; } + + /// + /// Gets or sets the actual data object that all members of this cluster + /// have commonly returned. + /// + object ClusterKey { get; set; } + } +} diff --git a/ObjectListView/Filtering/IClusteringStrategy.cs b/ObjectListView/Filtering/IClusteringStrategy.cs new file mode 100644 index 0000000..fb6a4e2 --- /dev/null +++ b/ObjectListView/Filtering/IClusteringStrategy.cs @@ -0,0 +1,80 @@ +/* + * IClusterStrategy - Encapsulates the ability to create a list of clusters from an ObjectListView + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2012-05-23 JPP - Added CreateFilter() method to interface to allow the strategy + * to control the actual model filter that is created. + * v2.5 + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware{ + + /// + /// Implementation of this interface control the selecting of cluster keys + /// and how those clusters will be presented to the user + /// + public interface IClusteringStrategy { + + /// + /// Gets or sets the column upon which this strategy will operate + /// + OLVColumn Column { get; set; } + + /// + /// Get the cluster key by which the given model will be partitioned by this strategy + /// + /// If the returned value is an IEnumerable, the given model is considered + /// to belong to multiple clusters + /// + /// + object GetClusterKey(object model); + + /// + /// Create a cluster to hold the given cluster key + /// + /// + /// + ICluster CreateCluster(object clusterKey); + + /// + /// Gets the display label that the given cluster should use + /// + /// + /// + string GetClusterDisplayLabel(ICluster cluster); + + /// + /// Create a filter that will include only model objects that + /// match one or more of the given values. + /// + /// + /// + IModelFilter CreateFilter(IList valuesChosenForFiltering); + } +} diff --git a/ObjectListView/Filtering/TextMatchFilter.cs b/ObjectListView/Filtering/TextMatchFilter.cs new file mode 100644 index 0000000..8df3719 --- /dev/null +++ b/ObjectListView/Filtering/TextMatchFilter.cs @@ -0,0 +1,642 @@ +/* + * TextMatchFilter - Text based filtering on ObjectListViews + * + * Author: Phillip Piper + * Date: 31/05/2011 7:45am + * + * Change log: + * 2018-05-01 JPP - Added ITextMatchFilter to allow for alternate implementations + * - Made several classes public so they can be subclassed + * v2.6 + * 2012-10-13 JPP Allow filtering to consider additional columns + * v2.5.1 + * 2011-06-22 JPP Handle searching for empty strings + * v2.5.0 + * 2011-05-31 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using System.Drawing; + +namespace BrightIdeasSoftware { + + public interface ITextMatchFilter: IModelFilter { + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + IEnumerable FindAllMatchedRanges(string cellText); + } + + /// + /// Instances of this class include only those rows of the listview + /// that match one or more given strings. + /// + /// This class can match strings by prefix, regex, or simple containment. + /// There are factory methods for each of these matching strategies. + public class TextMatchFilter : AbstractModelFilter, ITextMatchFilter { + + #region Life and death + + /// + /// Create a text filter that will include rows where any cell matches + /// any of the given regex expressions. + /// + /// + /// + /// + /// Any string that is not a valid regex expression will be ignored. + public static TextMatchFilter Regex(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.RegexStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell begins with one of the given strings + /// + /// + /// + /// + public static TextMatchFilter Prefix(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.PrefixStrings = texts; + return filter; + } + + /// + /// Create a text filter that includes rows where any cell contains any of the given strings. + /// + /// + /// + /// + public static TextMatchFilter Contains(ObjectListView olv, params string[] texts) { + TextMatchFilter filter = new TextMatchFilter(olv); + filter.ContainsStrings = texts; + return filter; + } + + /// + /// Create a TextFilter + /// + /// + public TextMatchFilter(ObjectListView olv) { + this.ListView = olv; + } + + /// + /// Create a TextFilter that finds the given string + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + } + + /// + /// Create a TextFilter that finds the given string using the given comparison + /// + /// + /// + /// + public TextMatchFilter(ObjectListView olv, string text, StringComparison comparison) { + this.ListView = olv; + this.ContainsStrings = new string[] { text }; + this.StringComparison = comparison; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets which columns will be used for the comparisons? If this is null, all columns will be used + /// + public OLVColumn[] Columns { + get { return columns; } + set { columns = value; } + } + private OLVColumn[] columns; + + /// + /// Gets or sets additional columns which will be used in the comparison. These will be used + /// in addition to either the Columns property or to all columns taken from the control. + /// + public OLVColumn[] AdditionalColumns { + get { return additionalColumns; } + set { additionalColumns = value; } + } + private OLVColumn[] additionalColumns; + + /// + /// Gets or sets the collection of strings that will be used for + /// contains matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable ContainsStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextContainsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets whether or not this filter has any search criteria + /// + public bool HasComponents { + get { + return this.MatchingStrategies.Count > 0; + } + } + + /// + /// Gets or set the ObjectListView upon which this filter will work + /// + /// + /// You cannot really rebase a filter after it is created, so do not change this value. + /// It is included so that it can be set in an object initialiser. + /// + public ObjectListView ListView { + get { return listView; } + set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the collection of strings that will be used for + /// prefix matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable PrefixStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextBeginsMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + /// + /// This is only used when doing Regex matching (obviously). + /// If this is not set specifically, the appropriate options are chosen to match the + /// StringComparison setting (culture invariant, case sensitive). + /// + public RegexOptions RegexOptions { + get { + if (!regexOptions.HasValue) { + switch (this.StringComparison) { + case StringComparison.CurrentCulture: + regexOptions = RegexOptions.None; + break; + case StringComparison.CurrentCultureIgnoreCase: + regexOptions = RegexOptions.IgnoreCase; + break; + case StringComparison.Ordinal: + case StringComparison.InvariantCulture: + regexOptions = RegexOptions.CultureInvariant; + break; + case StringComparison.OrdinalIgnoreCase: + case StringComparison.InvariantCultureIgnoreCase: + regexOptions = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + break; + default: + regexOptions = RegexOptions.None; + break; + } + } + return regexOptions.Value; + } + set { + regexOptions = value; + } + } + private RegexOptions? regexOptions; + + /// + /// Gets or sets the collection of strings that will be used for + /// regex pattern matching. Setting this replaces all previous texts + /// of any kind. + /// + public IEnumerable RegexStrings { + get { + foreach (TextMatchingStrategy component in this.MatchingStrategies) + yield return component.Text; + } + set { + this.MatchingStrategies = new List(); + if (value != null) { + foreach (string text in value) + this.MatchingStrategies.Add(new TextRegexMatchingStrategy(this, text)); + } + } + } + + /// + /// Gets or sets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.stringComparison; } + set { this.stringComparison = value; } + } + private StringComparison stringComparison = StringComparison.InvariantCultureIgnoreCase; + + #endregion + + #region Implementation + + /// + /// Loop over the columns that are being considering by the filter + /// + /// + protected virtual IEnumerable IterateColumns() { + if (this.Columns == null) { + foreach (OLVColumn column in this.ListView.Columns) + yield return column; + } else { + foreach (OLVColumn column in this.Columns) + yield return column; + } + if (this.AdditionalColumns != null) { + foreach (OLVColumn column in this.AdditionalColumns) + yield return column; + } + } + + #endregion + + #region Public interface + + /// + /// Do the actual work of filtering + /// + /// + /// + public override bool Filter(object modelObject) { + if (this.ListView == null || !this.HasComponents) + return true; + + foreach (OLVColumn column in this.IterateColumns()) { + if (column.IsVisible && column.Searchable) { + string[] cellTexts = column.GetSearchValues(modelObject); + if (cellTexts != null && cellTexts.Length > 0) { + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (String.IsNullOrEmpty(filter.Text)) + return true; + foreach (string cellText in cellTexts) { + if (filter.MatchesText(cellText)) + return true; + } + } + } + } + } + + return false; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted + /// + /// A list of character ranges indicating the matched substrings + public IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + foreach (TextMatchingStrategy filter in this.MatchingStrategies) { + if (!String.IsNullOrEmpty(filter.Text)) + ranges.AddRange(filter.FindAllMatchedRanges(cellText)); + } + + return ranges; + } + + /// + /// Is the given column one of the columns being used by this filter? + /// + /// + /// + public bool IsIncluded(OLVColumn column) { + if (this.Columns == null) { + return column.ListView == this.ListView; + } + + foreach (OLVColumn x in this.Columns) { + if (x == column) + return true; + } + + return false; + } + + #endregion + + #region Implementation members + + protected List MatchingStrategies = new List(); + + #endregion + + #region Components + + /// + /// Base class for the various types of string matching that TextMatchFilter provides + /// + public abstract class TextMatchingStrategy { + + /// + /// Gets how the filter will match text + /// + public StringComparison StringComparison { + get { return this.TextFilter.StringComparison; } + } + + /// + /// Gets the text filter to which this component belongs + /// + public TextMatchFilter TextFilter { + get { return textFilter; } + set { textFilter = value; } + } + private TextMatchFilter textFilter; + + /// + /// Gets or sets the text that will be matched + /// + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public abstract IEnumerable FindAllMatchedRanges(string cellText); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public abstract bool MatchesText(string cellText); + } + + /// + /// This component provides text contains matching strategy. + /// + public class TextContainsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text contains strategy + /// + /// + /// + public TextContainsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.IndexOf(this.Text, this.StringComparison) != -1; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + int matchIndex = cellText.IndexOf(this.Text, this.StringComparison); + while (matchIndex != -1) { + ranges.Add(new CharacterRange(matchIndex, this.Text.Length)); + matchIndex = cellText.IndexOf(this.Text, matchIndex + this.Text.Length, this.StringComparison); + } + + return ranges; + } + } + + /// + /// This component provides text begins with matching strategy. + /// + public class TextBeginsMatchingStrategy : TextMatchingStrategy { + + /// + /// Create a text begins strategy + /// + /// + /// + public TextBeginsMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + return cellText.StartsWith(this.Text, this.StringComparison); + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (cellText.StartsWith(this.Text, this.StringComparison)) + ranges.Add(new CharacterRange(0, this.Text.Length)); + + return ranges; + } + + } + + /// + /// This component provides regex matching strategy. + /// + public class TextRegexMatchingStrategy : TextMatchingStrategy { + + /// + /// Creates a regex strategy + /// + /// + /// + public TextRegexMatchingStrategy(TextMatchFilter filter, string text) { + this.TextFilter = filter; + this.Text = text; + } + + /// + /// Gets or sets the options that will be used when compiling the regular expression. + /// + public RegexOptions RegexOptions { + get { + return this.TextFilter.RegexOptions; + } + } + + /// + /// Gets or sets a compiled regular expression, based on our current Text and RegexOptions. + /// + /// + /// If Text fails to compile as a regular expression, this will return a Regex object + /// that will match all strings. + /// + protected Regex Regex { + get { + if (this.regex == null) { + try { + this.regex = new Regex(this.Text, this.RegexOptions); + } + catch (ArgumentException) { + this.regex = TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + return this.regex; + } + set { + this.regex = value; + } + } + private Regex regex; + + /// + /// Gets whether or not our current regular expression is a valid regex + /// + protected bool IsRegexInvalid { + get { + return this.Regex == TextRegexMatchingStrategy.InvalidRegexMarker; + } + } + private static Regex InvalidRegexMarker = new Regex(".*"); + + /// + /// Does the given text match the filter + /// + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// Return true if the given cellText matches our strategy + public override bool MatchesText(string cellText) { + if (this.IsRegexInvalid) + return true; + return this.Regex.Match(cellText).Success; + } + + /// + /// Find all the ways in which this filter matches the given string. + /// + /// + /// + /// This is used by the renderer to decide which bits of + /// the string should be highlighted. + /// + /// this.Text will not be null or empty when this is called. + /// + /// The text of the cell we want to search + /// A list of character ranges indicating the matched substrings + public override IEnumerable FindAllMatchedRanges(string cellText) { + List ranges = new List(); + + if (!this.IsRegexInvalid) { + foreach (Match match in this.Regex.Matches(cellText)) { + if (match.Length > 0) + ranges.Add(new CharacterRange(match.Index, match.Length)); + } + } + + return ranges; + } + } + + #endregion + } +} diff --git a/ObjectListView/FullClassDiagram.cd b/ObjectListView/FullClassDiagram.cd new file mode 100644 index 0000000..3126de2 --- /dev/null +++ b/ObjectListView/FullClassDiagram.cd @@ -0,0 +1,1261 @@ + + + + + + AQCABIAAAIAhAACgAAAAAIAMAAAECAAggAIAIIAAAEA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAAAAAAAAAAQEIAAEAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + CellEditing\CellEditors.cs + + + + + + AAAAAAQIAAABAQAAQAAgAAAAAAABAIAAAAQAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + ABgAAAAAAAAAAgIhAAACAAAEAAAAAAAAAAAAAAAAAAA= + DataListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + BAAAAAAAAAAAAAAAAQAAAAAQAAAQEAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAMAAAAA= + DragDrop\DropSink.cs + + + + + + + ZS0gAiQEBAoQDA8YQBMAMCAFgwQHBALcAEBEiEAAAQA= + DragDrop\DropSink.cs + + + + + + BYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + IACgGiAAIBoAAAAAAAAAAAAAAALAAAAKgAQECIAEgAA= + DragDrop\DropSink.cs + + + + + + BAEAAAAAAAAAAAAAAAEQAAAAAAAAAAIAAAAAgAQAAEA= + DragDrop\DropSink.cs + + + + + + AQAAEAEABAAAAAAAEAAAAAAAAAIAAgACgAAAAAAAQBA= + DragDrop\OLVDataObject.cs + + + + + + AAAAAAAAAAAAAgIAAAACAAAEQAAAAAAAAAAAAAAAAAA= + FastDataListView.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEQAAAAAAAAAAA= + FastObjectListView.cs + + + + + + ABAAAAgAQAQAABAgAAASQ4AQAAIEAAAAAAAAAEIAgAA= + FastObjectListView.cs + + + + + + AAAAAAAQAAAAEAQEBAAAAAQAgAAAAIAAAAAAAAAAAAA= + Filtering\Cluster.cs + + + + + + + AAAAAAAEAAAAAAAAAhBABAgAQAAIKAQBAQAAAAAAoIA= + Filtering\ClusteringStrategy.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQBAAAAAAAAAAA= + Filtering\ClustersFromGroupsStrategy.cs + + + + + + AAAAAAIAAAACAAAAAAAACAAAAQgAAAQBAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + SAEAADAQgEEAAQAIAAgQIAAAAFQAAAAAAAAAoAAAAAE= + Filtering\FilterMenuBuilder.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAEAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAIAAAACAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + + AAAAAAAAAAAAAAAAAgAAAAIAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAABAAAAAQAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAgAAACAAAABAAABAAgAQACABABAAAAyEIAAIgSgAA= + Filtering\TextMatchFilter.cs + + + + + + EgAAQTAAZAEgWGAASFwIIEYECGBGAQKAQEEGAQJAAEE= + Implementation\Attributes.cs + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAA= + Implementation\Comparers.cs + + + + + + + AAIAAAAAAAQAAAAAAAAAAAAAQAAAAAAAAABQAAAAAAA= + Implementation\Comparers.cs + + + + + + + AZggAAAwAGAAAgACQAYCBCAEICACACUEhAEAQKBAgQg= + Implementation\DataSourceAdapter.cs + + + + + + + 5/7+//3///fX/+//+///f/3//f/37N////+//7+///8= + Implementation\Enums.cs + + + + + + + ASgQyXBAABICBAAAAIAAACCEMAKBQAOAABDAgAUpAQA= + Implementation\Events.cs + + + + + + ABEAEAAFQAAAABAABABQEAQAQAAAECAAAAAgAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAABAAAIAAAAAAAAAEAAAQAAAAABAAAAAAAABAAIAA= + Implementation\Events.cs + + + + + + AAQABAAAAAQQAAAAAAEAAAQAAAAABAAAAAAgABQAIAE= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAEAAAAAAAAAAAAEAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAEAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAQAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAgAAAAIAAAAAAAAAAAAgAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAQAAAIAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAEA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAQAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAMABAAAAQgAZAFAAGUARAAAAAgAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + CAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAQAAAAAAAEGAAAAAAAAAAAgAACAIAAAACAAHAAA= + Implementation\Events.cs + + + + + + AAAgAAAAMAAAAAAAgARABAAEUAQIAAAAiAgAAIAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAABAAAAAQAAAAAAIiAgACIAIAAA= + Implementation\Events.cs + + + + + + AEAAAAAAAAAAAAAAgAQAAAAEAAAAAQAAgAkEAIAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAEAAAAAAAAABABAAAUAQAAAAAAAgAAAAAAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAA= + Implementation\Events.cs + + + + + + AAIgAAAGJACRCAAEEABEAAAAJACBAAAAAAgIAAAAAAA= + Implementation\Events.cs + + + + + + QAAAEAAAAAAAABAABABQEAQAQAAAEAAAAAAAAEAAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAgAAAAIAAAAAAAAAAAIAAAACAAAA= + Implementation\Events.cs + + + + + + QAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Events.cs + + + + + + QAAAgEAACggAgAAIAAAAAEAAAIAAAAAAAAAAAAAAAII= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAgAAAAIAAA= + Implementation\Events.cs + + + + + + AAAAAAAAIMAAAACBEAEAoQAAAKAACAAUhAAgRIQAIAE= + Implementation\GroupingParameters.cs + + + + + + bEYChOwmAAQgiCQEQBgEAMwAEAAMAEQMgEFAFODAGhM= + Implementation\Groups.cs + + + + + + AAAAgAAAJAAAAAQEABCAAAAAhAAAAACAAAAAAAIAAAE= + Implementation\Munger.cs + + + + + + AAAIACAAJAAAgAAEACAAAAAABAAAIAAAAAEAAAAAEAA= + Implementation\Munger.cs + + + + + + AAEAAAAAAAAAAAAAIAAAACAAAAAAAAAAAAAAAAABAAA= + Implementation\Munger.cs + + + + + + cChxFKmMjlNGI/LfZWKToPLMK45gioYxDANnzL7yfN4= + Implementation\NativeMethods.cs + + + + + + AAEAAAAAAAAEAAAACAAAAAAAQAAAAAAAAAAAAAAAAAA= + Implementation\NullableDictionary.cs + + + + + + ABAAAAAAAABEAACAAAAAAAAQABAAEgAQAAIAASAAAgE= + Implementation\OLVListItem.cs + + + + + + AAAAAAAAAAAEAAAAAAAAAAAAABAIAAAQCAgACSAAAAk= + Implementation\OLVListSubItem.cs + + + + + + AAAAgEAAEAgAAABEAAZABAAGAAQAEAAAgAAAAAAIAAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + + AAAAABAAAAAAAACAAAAAAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEACAAA= + Implementation\VirtualGroups.cs + + + + + + + ABAAAAAAgAAAAAAgAAASQgAQAAAEAAAAAAAAAIAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + + AABAAAAAAAAAAAAAAABCAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + MgARTxAAJEcEWCbkoNwJbE6WTnSOEnOKQhSWGDJgsFk= + OLVColumn.cs + + + + + + AACgAIAABAAAAIABACCiAIAgAACAAgAAABAIAAAAgAE= + Rendering\Adornments.cs + + + + + + ABAAAAAAAIAAAAAAAEAAAAAAEAAAABAAAEABAAAAAAA= + Rendering\Adornments.cs + + + + + + QAIggAAEIAAgBIAIAAIASEACIABAACIIAAMACCADAsA= + Rendering\Adornments.cs + + + + + + AAEAAAAAAAABAgAAAQAABAAAAAQBAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AgAAAAAAEAAAAgAAAAAAAAAAAAAAAAAAAAAQAAIAAAA= + Rendering\Decorations.cs + + + + + + YAgAgCABAAAgA4AAAAIAgAAAAAAAAAAAAAIAACBIgAA= + Rendering\Decorations.cs + + + + + + AAAAgAAgAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAAIA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA= + Rendering\Decorations.cs + + + + + + QAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAEAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAABAgAAAQAABAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAAIAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAIAAAgAAAAAAABAAAAAQAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + + AAAAAAAAAAAAAgAAAAIAAAACAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + + AAABAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AxLAQSEQZQhhAmA5IRBAASSQUhQgkFAAgJDGAAMDE8I= + Rendering\Renderers.cs + + + + + + QAggCAEAAEAAAIAwAAKAEAIQABAAEAAAAAAAAAAKAAA= + Rendering\Renderers.cs + + + + + + AAIAEBAAAQAAAAgAABAAEAAAAAAAAAAAABAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAAQBIAAAAAAAAAAAAAAAAAAAAAAACBAAAAIAAAA= + Rendering\Renderers.cs + + + + + + AAAgAAAAAAAAAAAAAIAAAAAgIAAAAABBABAAAAAEIAA= + Rendering\Renderers.cs + + + + + + AAIAAQAAAAEAAgAAEAIAABAAAAAAAAAAIAEAACADAAA= + Rendering\Styles.cs + + + + + + + AAIAAQAAAAEAAgAAAAIAAAAAAAAAAAAAAAEAAAADAAA= + Rendering\Styles.cs + + + + + + + AAAAAAAAQAiAAAAAgAIAAAAAAAAIBAAgAAAAAAAAAAA= + Rendering\Styles.cs + + + + + + AAIAAQAAAAEAAAAAAAAAAAACACAAAgAgAAEAAAADAAA= + Rendering\Styles.cs + + + + + + AAAAAAAQAAgAAAAAAAAAAICAAIAIAAAABAAAAQAEAAA= + Rendering\Styles.cs + + + + + + BgCkgAAARAoAAEAyEAAAAAIAAAAIAhCAAQIERAgAASA= + SubControls\GlassPanelForm.cs + + + + + + MAAIOQAUABAAAACQiBQCKRgAACECAAoAwAAQxJAACaE= + SubControls\HeaderControl.cs + + + + + + AkAACAgAACCACAAAAAAAAIAAwAAIAAQCAAAAAAAAAAA= + SubControls\ToolStripCheckedListBox.cs + + + + + + CkoAByAwQQAggEvSAAIQiIWIBELAYOIpiAKQUIQDqEA= + SubControls\ToolTipControl.cs + + + + + + AAAAAEAAFDAAQTAUAACIBAoWEAAAAAAoAAAAAIEAAgA= + Utilities\ColumnSelectionForm.cs + + + + + + AAABAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAACAAAAAA= + Utilities\Generator.cs + + + + + + AAAAwABEAAAAAACIAIAQEAABEAAAAAEEggAAAAACQAA= + Utilities\TypedObjectListView.cs + + + + + + AAAACAAAAEAEAABAAEAQCAAAQAAEAEAAAAgAAAAAAAA= + Utilities\TypedObjectListView.cs + + + + + + AVkQQAAAAGIEAQAkKkHAEAgRH4gBgAGOCCEigAAgIAQ= + VirtualObjectListView.cs + + + + + + AAEAAAABACAEAQAEAAAAAAAgAQCAAAAAAAMIQAABEAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAABAAAABAAAAAAAAQAAAAAAAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAIAAAAAAAA= + ObjectListView.DesignTime.cs + + + + + + AAAAAAAAAAAAAAIAAAABEAAAgQAAAAAAAAAAQAIAAIg= + + + + + + AAAAAAAAAAAAAgIAAAACAAEGAAAAAEAAAAAAABAAQAA= + DataTreeListView.cs + + + + + + BAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAQAA= + DragDrop\DragSource.cs + + + + + + AAAAAAAAAAAQQAAAAAIAEAAAAAEFAAAAgAAAAAAAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA= + Filtering\Filters.cs + + + + + + AAAAAAAQAAAAAAAAAAAAAAQAgAAAAAAAAAAAAAAAAAA= + Filtering\ICluster.cs + + + + + + AAAAAAAAAAAAAAAAABBAAAAAAAAAAAQBAQAAAAAAAAA= + Filtering\IClusteringStrategy.cs + + + + + + AAAAAAAAAAAAAACAAAAEAAAAAAAAAAAEAAAACAAAAAA= + Implementation\VirtualGroups.cs + + + + + + AIAAAAAAAAAAAAAAAAAAAgAIAAAQAAAAAAAEAEAAAAA= + Implementation\VirtualGroups.cs + + + + + + ABAAAAAAAAAAAAAgAAASAgAQAAAEAAAAAAAAAAAAgAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA= + Implementation\VirtualListDataSource.cs + + + + + + AAAAAAAAAAAAAAAAAQAAAAAAAAQAAAAAAAAAAAAAAAA= + Rendering\Decorations.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAA= + Rendering\Overlays.cs + + + + + + AAAAAQAAAABAAAAAABAAAAAAAAAAABAAAAAAAAAAAAA= + Rendering\Renderers.cs + + + + + + AAAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAA= + Rendering\Styles.cs + + + + + + AAAgAAAACAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAAA= + CellEditing\CellEditKeyEngine.cs + + + + + + gAEAAAAQCAIAAAAAAIAAAAAAAUAQIABAAEAgAAAgACA= + CellEditing\CellEditKeyEngine.cs + + + + + + AAAAAQAAAAABAAAAAAAAAAAEAAQBBAAAAAIgAAEAAAA= + DragDrop\DropSink.cs + + + + + + AAAAAAAAJAAAAAAAAAAAAAIAAAAAACIEAAAAAAAAAAA= + Filtering\DateTimeClusteringStrategy.cs + + + + + + AEAAAAAAAAAAABAAEAQAARAAIQAAAAQAAAAAAEAAAAA= + Implementation\Groups.cs + + + + + + AgAAgAAAwABAAAAAAAUAAAIAgQAAAAAEACAgAAAFAAA= + Implementation\Groups.cs + + + + + + AAAAAAQAAAAAAAAAAAAAAQAAAAAAEAAAAIAAAAAAAAA= + Implementation\Groups.cs + + + + + + ASAAEEAAAAAAAAQAEAAAAAAAAAAAABAAAAAACAAAEAA= + Implementation\OlvListViewHitTestInfo.cs + + + + + + AAAEAAAAAAAAAAAAAAAAAAAQAAAABAAAAAAAAAAAAAA= + CellEditing\EditorRegistry.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAQAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAgAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAEAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAQABgAAAAACAQAAAAAAAAAAAAAAAAAAAAAAgAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAABAAAACAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAABAAAAAAgACAAAAACAAAAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + Implementation\Delegates.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAABAAAAAAAAAA= + Implementation\Events.cs + + + + \ No newline at end of file diff --git a/ObjectListView/Implementation/Attributes.cs b/ObjectListView/Implementation/Attributes.cs new file mode 100644 index 0000000..fd8df36 --- /dev/null +++ b/ObjectListView/Implementation/Attributes.cs @@ -0,0 +1,335 @@ +/* + * Attributes - Attributes that can be attached to properties of models to allow columns to be + * built from them directly + * + * Author: Phillip Piper + * Date: 15/08/2009 22:01 + * + * Change log: + * v2.6 + * 2012-08-16 JPP - Added [OLVChildren] and [OLVIgnore] + * - OLV attributes can now only be set on properties + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This attribute is used to mark a property of a model + /// class that should be noticed by Generator class. + /// + /// + /// All the attributes of this class match their equivalent properties on OLVColumn. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVColumnAttribute : Attribute + { + #region Constructor + + // There are several property where we actually want nullable value (bool?, int?), + // but it seems attribute properties can't be nullable types. + // So we explicitly track if those properties have been set. + + /// + /// Create a new OLVColumnAttribute + /// + public OLVColumnAttribute() { + } + + /// + /// Create a new OLVColumnAttribute with the given title + /// + /// The title of the column + public OLVColumnAttribute(string title) { + this.Title = title; + } + + #endregion + + #region Public properties + + /// + /// + /// + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// + /// + public bool CheckBoxes { + get { return checkBoxes; } + set { + checkBoxes = value; + this.IsCheckBoxesSet = true; + } + } + private bool checkBoxes; + internal bool IsCheckBoxesSet = false; + + /// + /// + /// + public int DisplayIndex { + get { return displayIndex; } + set { displayIndex = value; } + } + private int displayIndex = -1; + + /// + /// + /// + public bool FillsFreeSpace { + get { return fillsFreeSpace; } + set { fillsFreeSpace = value; } + } + private bool fillsFreeSpace; + + /// + /// + /// + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { + freeSpaceProportion = value; + IsFreeSpaceProportionSet = true; + } + } + private int freeSpaceProportion; + internal bool IsFreeSpaceProportionSet = false; + + /// + /// An array of IComparables that mark the cutoff points for values when + /// grouping on this column. + /// + public object[] GroupCutoffs { + get { return groupCutoffs; } + set { groupCutoffs = value; } + } + private object[] groupCutoffs; + + /// + /// + /// + public string[] GroupDescriptions { + get { return groupDescriptions; } + set { groupDescriptions = value; } + } + private string[] groupDescriptions; + + /// + /// + /// + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// + /// + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// + /// + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// + /// + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// + /// + public bool IsEditable { + get { return isEditable; } + set { + isEditable = value; + this.IsEditableSet = true; + } + } + private bool isEditable = true; + internal bool IsEditableSet = false; + + /// + /// + /// + public bool IsVisible { + get { return isVisible; } + set { isVisible = value; } + } + private bool isVisible = true; + + /// + /// + /// + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// + /// + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + private int maximumWidth = -1; + + /// + /// + /// + public int MinimumWidth { + get { return minimumWidth; } + set { minimumWidth = value; } + } + private int minimumWidth = -1; + + /// + /// + /// + public String Name { + get { return name; } + set { name = value; } + } + private String name; + + /// + /// + /// + public HorizontalAlignment TextAlign { + get { return this.textAlign; } + set { + this.textAlign = value; + IsTextAlignSet = true; + } + } + private HorizontalAlignment textAlign = HorizontalAlignment.Left; + internal bool IsTextAlignSet = false; + + /// + /// + /// + public String Tag { + get { return tag; } + set { tag = value; } + } + private String tag; + + /// + /// + /// + public String Title { + get { return title; } + set { title = value; } + } + private String title; + + /// + /// + /// + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// + /// + public bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + this.IsTriStateCheckBoxesSet = true; + } + } + private bool triStateCheckBoxes; + internal bool IsTriStateCheckBoxesSet = false; + + /// + /// + /// + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// + /// + public int Width { + get { return width; } + set { width = value; } + } + private int width = 150; + + #endregion + } + + /// + /// Properties marked with [OLVChildren] will be used as the children source in a TreeListView. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVChildrenAttribute : Attribute + { + + } + + /// + /// Properties marked with [OLVIgnore] will not have columns generated for them. + /// + [AttributeUsage(AttributeTargets.Property)] + public class OLVIgnoreAttribute : Attribute + { + + } +} diff --git a/ObjectListView/Implementation/Comparers.cs b/ObjectListView/Implementation/Comparers.cs new file mode 100644 index 0000000..1ec33d0 --- /dev/null +++ b/ObjectListView/Implementation/Comparers.cs @@ -0,0 +1,330 @@ +/* + * Comparers - Various Comparer classes used within ObjectListView + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * v2.8.1 + * 2014-12-03 JPP - Added StringComparer + * v2.3 + * 2009-08-24 JPP - Added OLVGroupComparer + * 2009-06-01 JPP - ModelObjectComparer would crash if secondary sort column was null. + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-11-25 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// ColumnComparer is the workhorse for all comparison between two values of a particular column. + /// If the column has a specific comparer, use that to compare the values. Otherwise, do + /// a case insensitive string compare of the string representations of the values. + /// + /// This class inherits from both IComparer and its generic counterpart + /// so that it can be used on untyped and typed collections. + /// This is used by normal (non-virtual) ObjectListViews. Virtual lists use + /// ModelObjectComparer + /// + public class ColumnComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column + /// + /// The column whose values will be compared + /// The ordering for column values + public ColumnComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a ColumnComparer that will order the rows in a list view according + /// to the values in a given column, and by a secondary column if the primary + /// column is equal. + /// + /// The column whose values will be compared + /// The ordering for column values + /// The column whose values will be compared for secondary sorting + /// The ordering for secondary column values + public ColumnComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2) + this.secondComparer = new ColumnComparer(col2, order2); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(object x, object y) + { + return this.Compare((OLVListItem)x, (OLVListItem)y); + } + + /// + /// Compare two rows + /// + /// row1 + /// row2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVListItem x, OLVListItem y) + { + if (this.sortOrder == SortOrder.None) + return 0; + + int result = 0; + object x1 = this.column.GetValue(x.RowObject); + object y1 = this.column.GetValue(y.RowObject); + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values to be used for sorting + /// + /// The aspect extracted from the first row + /// The aspect extracted from the second row + /// An ordering indication: -1, 0, 1 + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xAsString = x as String; + if (xAsString != null) + return CompareStrings(xAsString, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ColumnComparer secondComparer; + } + + + /// + /// This comparer sort list view groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + public class OLVGroupComparer : IComparer + { + /// + /// Create a group comparer + /// + /// The ordering for column values + public OLVGroupComparer(SortOrder order) { + this.sortOrder = order; + } + + /// + /// Compare the two groups. OLVGroups have a "SortValue" property, + /// which is used if present. Otherwise, the titles of the groups will be compared. + /// + /// group1 + /// group2 + /// An ordering indication: -1, 0, 1 + public int Compare(OLVGroup x, OLVGroup y) { + // If we can compare the sort values, do that. + // Otherwise do a case insensitive compare on the group header. + int result; + if (x.SortValue != null && y.SortValue != null) + result = x.SortValue.CompareTo(y.SortValue); + else + result = String.Compare(x.Header, y.Header, StringComparison.CurrentCultureIgnoreCase); + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + return result; + } + + private SortOrder sortOrder; + } + + /// + /// This comparer can be used to sort a collection of model objects by a given column + /// + /// + /// This is used by virtual ObjectListViews. Non-virtual lists use + /// ColumnComparer + /// + public class ModelObjectComparer : IComparer, IComparer + { + /// + /// Gets or sets the method that will be used to compare two strings. + /// The default is to compare on the current culture, case-insensitive + /// + public static StringCompareDelegate StringComparer + { + get { return stringComparer; } + set { stringComparer = value; } + } + private static StringCompareDelegate stringComparer; + + /// + /// Create a model object comparer + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order) + { + this.column = col; + this.sortOrder = order; + } + + /// + /// Create a model object comparer with a secondary sorting column + /// + /// + /// + /// + /// + public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) + : this(col, order) + { + // There is no point in secondary sorting on the same column + if (col != col2 && col2 != null && order2 != SortOrder.None) + this.secondComparer = new ModelObjectComparer(col2, order2); + } + + /// + /// Compare the two model objects + /// + /// + /// + /// + public int Compare(object x, object y) + { + int result = 0; + object x1 = this.column.GetValue(x); + object y1 = this.column.GetValue(y); + + if (this.sortOrder == SortOrder.None) + return 0; + + // Handle nulls. Null values come last + bool xIsNull = (x1 == null || x1 == System.DBNull.Value); + bool yIsNull = (y1 == null || y1 == System.DBNull.Value); + if (xIsNull || yIsNull) { + if (xIsNull && yIsNull) + result = 0; + else + result = (xIsNull ? -1 : 1); + } else { + result = this.CompareValues(x1, y1); + } + + if (this.sortOrder == SortOrder.Descending) + result = 0 - result; + + // If the result was equality, use the secondary comparer to resolve it + if (result == 0 && this.secondComparer != null) + result = this.secondComparer.Compare(x, y); + + return result; + } + + /// + /// Compare the actual values + /// + /// + /// + /// + public int CompareValues(object x, object y) + { + // Force case insensitive compares on strings + String xStr = x as String; + if (xStr != null) + return CompareStrings(xStr, y as String); + + IComparable comparable = x as IComparable; + return comparable != null ? comparable.CompareTo(y) : 0; + } + + private static int CompareStrings(string x, string y) + { + if (StringComparer == null) + return String.Compare(x, y, StringComparison.CurrentCultureIgnoreCase); + else + return StringComparer(x, y); + } + + private OLVColumn column; + private SortOrder sortOrder; + private ModelObjectComparer secondComparer; + + #region IComparer Members + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/Implementation/DataSourceAdapter.cs b/ObjectListView/Implementation/DataSourceAdapter.cs new file mode 100644 index 0000000..80f6da3 --- /dev/null +++ b/ObjectListView/Implementation/DataSourceAdapter.cs @@ -0,0 +1,628 @@ +/* + * DataSourceAdapter - A helper class that translates DataSource events for an ObjectListView + * + * Author: Phillip Piper + * Date: 20/09/2010 7:42 AM + * + * Change log: + * 2018-04-30 JPP - Sanity check upper limit against CurrencyManager rather than ListView just in + * case the CurrencyManager has gotten ahead of the ListView's contents. + * v2.9 + * 2015-10-31 JPP - Put back sanity check on upper limit of source items + * 2015-02-02 JPP - Made CreateColumnsFromSource() only rebuild columns when new ones were added + * v2.8.1 + * 2014-11-23 JPP - Honour initial CurrencyManager.Position when setting DataSource. + * 2014-10-27 JPP - Fix issue where SelectedObject was not sync'ed with CurrencyManager.Position (SF #129) + * v2.6 + * 2012-08-16 JPP - Unify common column creation functionality with Generator when possible + * + * 2010-09-20 JPP - Initial version + * + * Copyright (C) 2010-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Data; +using System.Windows.Forms; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A helper class that translates DataSource events for an ObjectListView + /// + public class DataSourceAdapter : IDisposable + { + #region Life and death + + /// + /// Make a DataSourceAdapter + /// + public DataSourceAdapter(ObjectListView olv) { + if (olv == null) throw new ArgumentNullException("olv"); + + this.ListView = olv; + // ReSharper disable once DoNotCallOverridableMethodsInConstructor + this.BindListView(this.ListView); + } + + /// + /// Finalize this object + /// + ~DataSourceAdapter() { + this.Dispose(false); + } + + /// + /// Release all the resources used by this instance + /// + public void Dispose() { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Release all the resources used by this instance + /// + public virtual void Dispose(bool fromUser) { + this.UnbindListView(this.ListView); + this.UnbindDataSource(); + } + + #endregion + + #region Public Properties + + /// + /// Gets or sets whether or not columns will be automatically generated to show the + /// columns when the DataSource is set. + /// + /// This must be set before the DataSource is set. It has no effect afterwards. + public bool AutoGenerateColumns { + get { return this.autoGenerateColumns; } + set { this.autoGenerateColumns = value; } + } + private bool autoGenerateColumns = true; + + /// + /// Get or set the DataSource that will be displayed in this list view. + /// + public virtual Object DataSource { + get { return dataSource; } + set { + dataSource = value; + this.RebindDataSource(true); + } + } + private Object dataSource; + + /// + /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. + /// + /// If the data source is not a DataSet or DataViewManager, this property has no effect + public virtual string DataMember { + get { return dataMember; } + set { + if (dataMember != value) { + dataMember = value; + RebindDataSource(); + } + } + } + private string dataMember = ""; + + /// + /// Gets the ObjectListView upon which this adaptor will operate + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + #endregion + + #region Implementation properties + + /// + /// Gets or sets the currency manager which is handling our binding context + /// + protected CurrencyManager CurrencyManager { + get { return currencyManager; } + set { currencyManager = value; } + } + private CurrencyManager currencyManager; + + #endregion + + #region Binding and unbinding + + /// + /// + /// + /// + protected virtual void BindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing += new EventHandler(HandleListViewFreezing); + olv.SelectionChanged += new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged += new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + /// + protected virtual void UnbindListView(ObjectListView olv) { + if (olv == null) + return; + + olv.Freezing -= new EventHandler(HandleListViewFreezing); + olv.SelectionChanged -= new EventHandler(HandleListViewSelectionChanged); + olv.BindingContextChanged -= new EventHandler(HandleListViewBindingContextChanged); + } + + /// + /// + /// + protected virtual void BindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged += new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged += new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged += new ListChangedEventHandler(CurrencyManagerListChanged); + } + + /// + /// + /// + protected virtual void UnbindDataSource() { + if (this.CurrencyManager == null) + return; + + this.CurrencyManager.MetaDataChanged -= new EventHandler(HandleCurrencyManagerMetaDataChanged); + this.CurrencyManager.PositionChanged -= new EventHandler(HandleCurrencyManagerPositionChanged); + this.CurrencyManager.ListChanged -= new ListChangedEventHandler(CurrencyManagerListChanged); + } + + #endregion + + #region Initialization + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource() { + RebindDataSource(false); + } + + /// + /// Our data source has changed. Figure out how to handle the new source + /// + protected virtual void RebindDataSource(bool forceDataInitialization) { + + CurrencyManager tempCurrencyManager = null; + if (this.ListView != null && this.ListView.BindingContext != null && this.DataSource != null) { + tempCurrencyManager = this.ListView.BindingContext[this.DataSource, this.DataMember] as CurrencyManager; + } + + // Has our currency manager changed? + if (this.CurrencyManager != tempCurrencyManager) { + this.UnbindDataSource(); + this.CurrencyManager = tempCurrencyManager; + this.BindDataSource(); + + // Our currency manager has changed so we have to initialize a new data source + forceDataInitialization = true; + } + + if (forceDataInitialization) + InitializeDataSource(); + } + + /// + /// The data source for this control has changed. Reconfigure the control for the new source + /// + protected virtual void InitializeDataSource() { + if (this.ListView.Frozen || this.CurrencyManager == null) + return; + + this.CreateColumnsFromSource(); + this.CreateMissingAspectGettersAndPutters(); + this.SetListContents(); + this.ListView.AutoSizeColumns(); + + // Fake a position change event so that the control matches any initial Position + this.HandleCurrencyManagerPositionChanged(null, null); + } + + /// + /// Take the contents of the currently bound list and put them into the control + /// + protected virtual void SetListContents() { + this.ListView.Objects = this.CurrencyManager.List; + } + + /// + /// Create columns for the listview based on what properties are available in the data source + /// + /// + /// This method will create columns if there is not already a column displaying that property. + /// + protected virtual void CreateColumnsFromSource() { + if (this.CurrencyManager == null) + return; + + // Don't generate any columns in design mode. If we do, the user will see them, + // but the Designer won't know about them and won't persist them, which is very confusing + if (this.ListView.IsDesignMode) + return; + + // Don't create columns if we've been told not to + if (!this.AutoGenerateColumns) + return; + + // Use a Generator to create columns + Generator generator = Generator.Instance as Generator ?? new Generator(); + + PropertyDescriptorCollection properties = this.CurrencyManager.GetItemProperties(); + if (properties.Count == 0) + return; + + bool wereColumnsAdded = false; + foreach (PropertyDescriptor property in properties) { + + if (!this.ShouldCreateColumn(property)) + continue; + + // Create a column + OLVColumn column = generator.MakeColumnFromPropertyDescriptor(property); + this.ConfigureColumn(column, property); + + // Add it to our list + this.ListView.AllColumns.Add(column); + wereColumnsAdded = true; + } + + if (wereColumnsAdded) + generator.PostCreateColumns(this.ListView); + } + + /// + /// Decide if a new column should be added to the control to display + /// the given property + /// + /// + /// + protected virtual bool ShouldCreateColumn(PropertyDescriptor property) { + + // Is there a column that already shows this property? If so, we don't show it again + if (this.ListView.AllColumns.Exists(delegate(OLVColumn x) { return x.AspectName == property.Name; })) + return false; + + // Relationships to other tables turn up as IBindibleLists. Don't make columns to show them. + // CHECK: Is this always true? What other things could be here? Constraints? Triggers? + if (property.PropertyType == typeof(IBindingList)) + return false; + + // Ignore anything marked with [OLVIgnore] + return property.Attributes[typeof(OLVIgnoreAttribute)] == null; + } + + /// + /// Configure the given column to show the given property. + /// The title and aspect name of the column are already filled in. + /// + /// + /// + protected virtual void ConfigureColumn(OLVColumn column, PropertyDescriptor property) { + + column.LastDisplayIndex = this.ListView.AllColumns.Count; + + // If our column is a BLOB, it could be an image, so assign a renderer to draw it. + // CONSIDER: Is this a common enough case to warrant this code? + if (property.PropertyType == typeof(System.Byte[])) + column.Renderer = new ImageRenderer(); + } + + /// + /// Generate aspect getters and putters for any columns that are missing them (and for which we have + /// enough information to actually generate a getter) + /// + protected virtual void CreateMissingAspectGettersAndPutters() { + foreach (OLVColumn x in this.ListView.AllColumns) { + OLVColumn column = x; // stack based variable accessible from closures + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectGetter = delegate(object row) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + return column.GetAspectByName(row); + return (drv.Row.RowState == DataRowState.Detached) ? null : drv[column.AspectName]; + }; + } + if (column.IsEditable && column.AspectPutter == null && !String.IsNullOrEmpty(column.AspectName)) { + column.AspectPutter = delegate(object row, object newValue) { + // In most cases, rows will be DataRowView objects + DataRowView drv = row as DataRowView; + if (drv == null) + column.PutAspectByName(row, newValue); + else { + if (drv.Row.RowState != DataRowState.Detached) + drv[column.AspectName] = newValue; + } + }; + } + } + } + + #endregion + + #region Event Handlers + + /// + /// CurrencyManager ListChanged event handler. + /// Deals with fine-grained changes to list items. + /// + /// + /// It's actually difficult to deal with these changes in a fine-grained manner. + /// If our listview is grouped, then any change may make a new group appear or + /// an old group disappear. It is rarely enough to simply update the affected row. + /// + /// + /// + protected virtual void CurrencyManagerListChanged(object sender, ListChangedEventArgs e) { + Debug.Assert(sender == this.CurrencyManager); + + // Ignore changes make while frozen, since we will do a complete rebuild when we unfreeze + if (this.ListView.Frozen) + return; + + //System.Diagnostics.Debug.WriteLine(e.ListChangedType); + Stopwatch sw = Stopwatch.StartNew(); + switch (e.ListChangedType) { + + case ListChangedType.Reset: + this.HandleListChangedReset(e); + break; + + case ListChangedType.ItemChanged: + this.HandleListChangedItemChanged(e); + break; + + case ListChangedType.ItemAdded: + this.HandleListChangedItemAdded(e); + break; + + // An item has gone away. + case ListChangedType.ItemDeleted: + this.HandleListChangedItemDeleted(e); + break; + + // An item has changed its index. + case ListChangedType.ItemMoved: + this.HandleListChangedItemMoved(e); + break; + + // Something has changed in the metadata. + // CHECK: When are these events actually fired? + case ListChangedType.PropertyDescriptorAdded: + case ListChangedType.PropertyDescriptorChanged: + case ListChangedType.PropertyDescriptorDeleted: + this.HandleListChangedMetadataChanged(e); + break; + } + sw.Stop(); + System.Diagnostics.Debug.WriteLine(String.Format("PERF - Processing {0} event on {1} rows took {2}ms", e.ListChangedType, this.ListView.GetItemCount(), sw.ElapsedMilliseconds)); + + } + + /// + /// Handle PropertyDescriptor* events + /// + /// + protected virtual void HandleListChangedMetadataChanged(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle ItemMoved event + /// + /// + protected virtual void HandleListChangedItemMoved(ListChangedEventArgs e) { + // When is this actually triggered? + this.InitializeDataSource(); + } + + /// + /// Handle the ItemDeleted event + /// + /// + protected virtual void HandleListChangedItemDeleted(ListChangedEventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Handle an ItemAdded event. + /// + /// + protected virtual void HandleListChangedItemAdded(ListChangedEventArgs e) { + // We get this event twice if certain grid controls are used to add a new row to a + // datatable: once when the editing of a new row begins, and once again when that + // editing commits. (If the user cancels the creation of the new row, we never see + // the second creation.) We detect this by seeing if this is a view on a row in a + // DataTable, and if it is, testing to see if it's a new row under creation. + + Object newRow = this.CurrencyManager.List[e.NewIndex]; + DataRowView drv = newRow as DataRowView; + if (drv == null || !drv.IsNew) { + // Either we're not dealing with a view on a data table, or this is the commit + // notification. Either way, this is the final notification, so we want to + // handle the new row now! + this.InitializeDataSource(); + } + } + + /// + /// Handle the Reset event + /// + /// + protected virtual void HandleListChangedReset(ListChangedEventArgs e) { + // The whole list has changed utterly, so reload it. + this.InitializeDataSource(); + } + + /// + /// Handle ItemChanged event. This is triggered when a single item + /// has changed, so just refresh that one item. + /// + /// + /// Even in this simple case, we should probably rebuild the list. + /// For example, the change could put the item into its own new group. + protected virtual void HandleListChangedItemChanged(ListChangedEventArgs e) { + // A single item has changed, so just refresh that. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleListChangedItemChanged: {0}, {1}", e.NewIndex, e.PropertyDescriptor.Name)); + + Object changedRow = this.CurrencyManager.List[e.NewIndex]; + this.ListView.RefreshObject(changedRow); + } + + /// + /// The CurrencyManager calls this if the data source looks + /// different. We just reload everything. + /// + /// + /// + /// + /// CHECK: Do we need this if we are handle ListChanged metadata events? + /// + protected virtual void HandleCurrencyManagerMetaDataChanged(object sender, EventArgs e) { + this.InitializeDataSource(); + } + + /// + /// Called by the CurrencyManager when the currently selected item + /// changes. We update the ListView selection so that we stay in sync + /// with any other controls bound to the same source. + /// + /// + /// + protected virtual void HandleCurrencyManagerPositionChanged(object sender, EventArgs e) { + int index = this.CurrencyManager.Position; + + // Make sure the index is sane (-1 pops up from time to time) + if (index < 0 || index >= this.CurrencyManager.Count) + return; + + // Avoid recursion. If we are currently changing the index, don't + // start the process again. + if (this.isChangingIndex) + return; + + try { + this.isChangingIndex = true; + this.ChangePosition(index); + } + finally { + this.isChangingIndex = false; + } + } + private bool isChangingIndex = false; + + /// + /// Change the control's position (which is it's currently selected row) + /// to the nth row in the dataset + /// + /// The index of the row to be selected + protected virtual void ChangePosition(int index) { + // We can't use the index directly, since our listview may be sorted + this.ListView.SelectedObject = this.CurrencyManager.List[index]; + + // THINK: Do we always want to bring it into view? + if (this.ListView.SelectedIndices.Count > 0) + this.ListView.EnsureVisible(this.ListView.SelectedIndices[0]); + } + + #endregion + + #region ObjectListView event handlers + + /// + /// Handle the selection changing in our ListView. + /// We need to tell our currency manager about the new position. + /// + /// + /// + protected virtual void HandleListViewSelectionChanged(object sender, EventArgs e) { + // Prevent recursion + if (this.isChangingIndex) + return; + + // Sanity + if (this.CurrencyManager == null) + return; + + // If only one item is selected, tell the currency manager which item is selected. + // CurrencyManager can't handle multiple selection so there's nothing we can do + // if more than one row is selected. + if (this.ListView.SelectedIndices.Count != 1) + return; + + try { + this.isChangingIndex = true; + + // We can't use the selectedIndex directly, since our listview may be sorted and/or filtered + // So we have to find the index of the selected object within the original list. + this.CurrencyManager.Position = this.CurrencyManager.List.IndexOf(this.ListView.SelectedObject); + } finally { + this.isChangingIndex = false; + } + } + + /// + /// Handle the frozenness of our ListView changing. + /// + /// + /// + protected virtual void HandleListViewFreezing(object sender, FreezeEventArgs e) { + if (!alreadyFreezing && e.FreezeLevel == 0) { + try { + alreadyFreezing = true; + this.RebindDataSource(true); + } finally { + alreadyFreezing = false; + } + } + } + private bool alreadyFreezing = false; + + /// + /// Handle a change to the BindingContext of our ListView. + /// + /// + /// + protected virtual void HandleListViewBindingContextChanged(object sender, EventArgs e) { + this.RebindDataSource(false); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/Delegates.cs b/ObjectListView/Implementation/Delegates.cs new file mode 100644 index 0000000..52da366 --- /dev/null +++ b/ObjectListView/Implementation/Delegates.cs @@ -0,0 +1,168 @@ +/* + * Delegates - All delegate definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * v2.10 + * 2015-12-30 JPP - Added CellRendererGetterDelegate + * v2.? + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2015 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + #region Delegate declarations + + /// + /// These delegates are used to extract an aspect from a row object + /// + public delegate Object AspectGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed value back into a model object + /// + public delegate void AspectPutterDelegate(Object rowObject, Object newValue); + + /// + /// These delegates can be used to convert an aspect value to a display string, + /// instead of using the default ToString() + /// + public delegate string AspectToStringConverterDelegate(Object value); + + /// + /// These delegates are used to get the tooltip for a cell + /// + public delegate String CellToolTipGetterDelegate(OLVColumn column, Object modelObject); + + /// + /// These delegates are used to the state of the checkbox for a row object. + /// + /// + /// For reasons known only to someone in Microsoft, we can only set + /// a boolean on the ListViewItem to indicate it's "checked-ness", but when + /// we receive update events, we have to use a tristate CheckState. So we can + /// be told about an indeterminate state, but we can't set it ourselves. + /// + /// As of version 2.0, we can now return indeterminate state. + /// + public delegate CheckState CheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to get the state of the checkbox for a row object. + /// + /// + /// + public delegate bool BooleanCheckStateGetterDelegate(Object rowObject); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + public delegate CheckState CheckStatePutterDelegate(Object rowObject, CheckState newValue); + + /// + /// These delegates are used to put a changed check state back into a model object + /// + /// + /// + /// + public delegate bool BooleanCheckStatePutterDelegate(Object rowObject, bool newValue); + + /// + /// These delegates are used to get the renderer for a particular cell + /// + public delegate IRenderer CellRendererGetterDelegate(Object rowObject, OLVColumn column); + + /// + /// The callbacks for RightColumnClick events + /// + public delegate void ColumnRightClickEventHandler(object sender, ColumnClickEventArgs e); + + /// + /// This delegate will be used to own draw header column. + /// + public delegate bool HeaderDrawingDelegate(Graphics g, Rectangle r, int columnIndex, OLVColumn column, bool isPressed, HeaderStateStyle stateStyle); + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + public delegate void GroupFormatterDelegate(OLVGroup group, GroupingParameters parms); + + /// + /// These delegates are used to retrieve the object that is the key of the group to which the given row belongs. + /// + public delegate Object GroupKeyGetterDelegate(Object rowObject); + + /// + /// These delegates are used to convert a group key into a title for the group + /// + public delegate string GroupKeyToTitleConverterDelegate(Object groupKey); + + /// + /// These delegates are used to get the tooltip for a column header + /// + public delegate String HeaderToolTipGetterDelegate(OLVColumn column); + + /// + /// These delegates are used to fetch the image selector that should be used + /// to choose an image for this column. + /// + public delegate Object ImageGetterDelegate(Object rowObject); + + /// + /// These delegates are used to draw a cell + /// + public delegate bool RenderDelegate(EventArgs e, Graphics g, Rectangle r, Object rowObject); + + /// + /// These delegates are used to fetch a row object for virtual lists + /// + public delegate Object RowGetterDelegate(int rowIndex); + + /// + /// These delegates are used to format a listviewitem before it is added to the control. + /// + public delegate void RowFormatterDelegate(OLVListItem olvItem); + + /// + /// These delegates can be used to return the array of texts that should be searched for text filtering + /// + public delegate string[] SearchValueGetterDelegate(Object value); + + /// + /// These delegates are used to sort the listview in some custom fashion + /// + public delegate void SortDelegate(OLVColumn column, SortOrder sortOrder); + + /// + /// These delegates are used to order two strings. + /// x cannot be null. y can be null. + /// + public delegate int StringCompareDelegate(string x, string y); + + #endregion +} diff --git a/ObjectListView/Implementation/DragSource.cs b/ObjectListView/Implementation/DragSource.cs new file mode 100644 index 0000000..f0f4783 --- /dev/null +++ b/ObjectListView/Implementation/DragSource.cs @@ -0,0 +1,407 @@ +/* + * DragSource.cs - Add drag source functionality to an ObjectListView + * + * UNFINISHED + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * v2.3 + * 2009-07-06 JPP - Make sure Link is acceptable as an drop effect by default + * (since MS didn't make it part of the 'All' value) + * v2.2 + * 2009-04-15 JPP - Separated DragSource.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware +{ + /// + /// An IDragSource controls how drag out from the ObjectListView will behave + /// + public interface IDragSource + { + /// + /// A drag operation is beginning. Return the data object that will be used + /// for data transfer. Return null to prevent the drag from starting. + /// + /// + /// The returned object is later passed to the GetAllowedEffect() and EndDrag() + /// methods. + /// + /// What ObjectListView is being dragged from. + /// Which mouse button is down? + /// What item was directly dragged by the user? There may be more than just this + /// item selected. + /// The data object that will be used for data transfer. This will often be a subclass + /// of DataObject, but does not need to be. + Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item); + + /// + /// What operations are possible for this drag? This controls the icon shown during the drag + /// + /// The data object returned by StartDrag() + /// A combination of DragDropEffects flags + DragDropEffects GetAllowedEffects(Object dragObject); + + /// + /// The drag operation is complete. Do whatever is necessary to complete the action. + /// + /// The data object returned by StartDrag() + /// The value returned from GetAllowedEffects() + void EndDrag(Object dragObject, DragDropEffects effect); + } + + /// + /// A do-nothing implementation of IDragSource that can be safely subclassed. + /// + public class AbstractDragSource : IDragSource + { + #region IDragSource Members + + /// + /// See IDragSource documentation + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + return null; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.None; + } + + /// + /// See IDragSource documentation + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + } + + #endregion + } + + /// + /// A reasonable implementation of IDragSource that provides normal + /// drag source functionality. It creates a data object that supports + /// inter-application dragging of text and HTML representation of + /// the dragged rows. It can optionally force a refresh of all dragged + /// rows when the drag is complete. + /// + /// Subclasses can override GetDataObject() to add new + /// data formats to the data transfer object. + public class SimpleDragSource : IDragSource + { + #region Constructors + + /// + /// Construct a SimpleDragSource + /// + public SimpleDragSource() { + } + + /// + /// Construct a SimpleDragSource that refreshes the dragged rows when + /// the drag is complete + /// + /// + public SimpleDragSource(bool refreshAfterDrop) { + this.RefreshAfterDrop = refreshAfterDrop; + } + + #endregion + + #region Public properties + + /// + /// Gets or sets whether the dragged rows should be refreshed when the + /// drag operation is complete. + /// + public bool RefreshAfterDrop { + get { return refreshAfterDrop; } + set { refreshAfterDrop = value; } + } + private bool refreshAfterDrop; + + #endregion + + #region IDragSource Members + + /// + /// Create a DataObject when the user does a left mouse drag operation. + /// See IDragSource for further information. + /// + /// + /// + /// + /// + public virtual Object StartDrag(ObjectListView olv, MouseButtons button, OLVListItem item) { + // We only drag on left mouse + if (button != MouseButtons.Left) + return null; + + return this.CreateDataObject(olv); + } + + /// + /// Which operations are allowed in the operation? By default, all operations are supported. + /// + /// + /// All opertions are supported + public virtual DragDropEffects GetAllowedEffects(Object data) { + return DragDropEffects.All | DragDropEffects.Link; // why didn't MS include 'Link' in 'All'?? + } + + /// + /// The drag operation is finished. Refreshe the dragged rows if so configured. + /// + /// + /// + public virtual void EndDrag(Object dragObject, DragDropEffects effect) { + OLVDataObject data = dragObject as OLVDataObject; + if (data == null) + return; + + if (this.RefreshAfterDrop) + data.ListView.RefreshObjects(data.ModelObjects); + } + + /// + /// Create a data object that will be used to as the data object + /// for the drag operation. + /// + /// + /// Subclasses can override this method add new formats to the data object. + /// + /// The ObjectListView that is the source of the drag + /// A data object for the drag + protected virtual object CreateDataObject(ObjectListView olv) { + OLVDataObject data = new OLVDataObject(olv); + data.CreateTextFormats(); + return data; + } + + #endregion + } + + /// + /// A data transfer object that knows how to transform a list of model + /// objects into a text and HTML representation. + /// + public class OLVDataObject : DataObject + { + #region Life and death + + /// + /// Create a data object from the selected objects in the given ObjectListView + /// + /// The source of the data object + public OLVDataObject(ObjectListView olv) : this(olv, olv.SelectedObjects) { + } + + /// + /// Create a data object which operates on the given model objects + /// in the given ObjectListView + /// + /// The source of the data object + /// The model objects to be put into the data object + public OLVDataObject(ObjectListView olv, IList modelObjects) { + this.objectListView = olv; + this.modelObjects = modelObjects; + this.includeHiddenColumns = olv.IncludeHiddenColumnsInDataTransfer; + this.includeColumnHeaders = olv.IncludeColumnHeadersInCopy; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the text + /// and HTML representation. If this is false, only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. + /// + public bool IncludeColumnHeaders + { + get { return includeColumnHeaders; } + } + private bool includeColumnHeaders; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// + public ObjectListView ListView { + get { return objectListView; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + /// + /// Put a text and HTML representation of our model objects + /// into the data object. + /// + public void CreateTextFormats() { + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + // Build text and html versions of the selection + StringBuilder sbText = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (includeColumnHeaders) + { + sbHtml.Append(""); + } + + foreach (object modelObject in this.ModelObjects) + { + sbHtml.Append(""); + } + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) + { + if (col != columns[0]) + { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.Text; + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbText.Append("\t"); + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbText.Append(strValue); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbText.AppendLine(); + sbHtml.AppendLine("
      "); + + // Put both the text and html versions onto the clipboard. + // For some reason, SetText() with UnicodeText doesn't set the basic CF_TEXT format, + // but using SetData() does. + //this.SetText(sbText.ToString(), TextDataFormat.UnicodeText); + this.SetData(sbText.ToString()); + this.SetText(ConvertToHtmlFragment(sbHtml.ToString()), TextDataFormat.Html); + } + + /// + /// Make a HTML representation of our model objects + /// + public string CreateHtml() { + IList columns = this.ListView.ColumnsInDisplayOrder; + + // Build html version of the selection + StringBuilder sbHtml = new StringBuilder(""); + + foreach (object modelObject in this.ModelObjects) { + sbHtml.Append(""); + } + sbHtml.AppendLine("
      "); + foreach (OLVColumn col in columns) { + if (col != columns[0]) { + sbHtml.Append(""); + } + string strValue = col.GetStringValue(modelObject); + sbHtml.Append(strValue); //TODO: Should encode the string value + } + sbHtml.AppendLine("
      "); + + return sbHtml.ToString(); + } + + /// + /// Convert the fragment of HTML into the Clipboards HTML format. + /// + /// The HTML format is found here http://msdn2.microsoft.com/en-us/library/aa767917.aspx + /// + /// The HTML to put onto the clipboard. It must be valid HTML! + /// A string that can be put onto the clipboard and will be recognized as HTML + private string ConvertToHtmlFragment(string fragment) { + // Minimal implementation of HTML clipboard format + string source = "http://www.codeproject.com/KB/list/ObjectListView.aspx"; + + const String MARKER_BLOCK = + "Version:1.0\r\n" + + "StartHTML:{0,8}\r\n" + + "EndHTML:{1,8}\r\n" + + "StartFragment:{2,8}\r\n" + + "EndFragment:{3,8}\r\n" + + "StartSelection:{2,8}\r\n" + + "EndSelection:{3,8}\r\n" + + "SourceURL:{4}\r\n" + + "{5}"; + + int prefixLength = String.Format(MARKER_BLOCK, 0, 0, 0, 0, source, "").Length; + + const String DEFAULT_HTML_BODY = + "" + + "{0}"; + + string html = String.Format(DEFAULT_HTML_BODY, fragment); + int startFragment = prefixLength + html.IndexOf(fragment); + int endFragment = startFragment + fragment.Length; + + return String.Format(MARKER_BLOCK, prefixLength, prefixLength + html.Length, startFragment, endFragment, source, html); + } + } +} diff --git a/ObjectListView/Implementation/DropSink.cs b/ObjectListView/Implementation/DropSink.cs new file mode 100644 index 0000000..03818d8 --- /dev/null +++ b/ObjectListView/Implementation/DropSink.cs @@ -0,0 +1,1402 @@ +/* + * DropSink.cs - Add drop sink ability to an ObjectListView + * + * Author: Phillip Piper + * Date: 2009-03-17 5:15 PM + * + * Change log: + * 2010-08-24 JPP - Moved AcceptExternal property up to SimpleDragSource. + * v2.3 + * 2009-09-01 JPP - Correctly handle case where RefreshObjects() is called for + * objects that were children but are now roots. + * 2009-08-27 JPP - Added ModelDropEventArgs.RefreshObjects() to simplify updating after + * a drag-drop operation + * 2009-08-19 JPP - Changed to use OlvHitTest() + * v2.2.1 + * 2007-07-06 JPP - Added StandardDropActionFromKeys property to OlvDropEventArgs + * v2.2 + * 2009-05-17 JPP - Added a Handled flag to OlvDropEventArgs + * - Tweaked the appearance of the drop-on-background feedback + * 2009-04-15 JPP - Separated DragDrop.cs into DropSink.cs + * 2009-03-17 JPP - Initial version + * + * Copyright (C) 2009-2010 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. + */ + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Objects that implement this interface can acts as the receiver for drop + /// operation for an ObjectListView. + /// + public interface IDropSink + { + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + ObjectListView ListView { get; set; } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + void DrawFeedback(Graphics g, Rectangle bounds); + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + void Drop(DragEventArgs args); + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + void Enter(DragEventArgs args); + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// + void GiveFeedback(GiveFeedbackEventArgs args); + + /// + /// The drag has left the bounds of this control + /// + void Leave(); + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + void Over(DragEventArgs args); + + /// + /// Should the drag be allowed to continue? + /// + /// + void QueryContinue(QueryContinueDragEventArgs args); + } + + /// + /// This is a do-nothing implementation of IDropSink that is a useful + /// base class for more sophisticated implementations. + /// + public class AbstractDropSink : IDropSink + { + #region IDropSink Members + + /// + /// Gets or sets the ObjectListView that is the drop sink + /// + public virtual ObjectListView ListView { + get { return listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public virtual void DrawFeedback(Graphics g, Rectangle bounds) { + } + + /// + /// The user has released the drop over this control + /// + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. This value is returned + /// to the originator of the drag. + /// + /// + public virtual void Drop(DragEventArgs args) { + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public virtual void Enter(DragEventArgs args) { + } + + /// + /// The drag has left the bounds of this control + /// + public virtual void Leave() { + this.Cleanup(); + } + + /// + /// The drag is moving over this control. + /// + /// This is where any drop target should be calculated. + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + /// + public virtual void Over(DragEventArgs args) { + } + + /// + /// Change the cursor to reflect the current drag operation. + /// + /// You only need to override this if you want non-standard cursors. + /// The standard cursors are supplied automatically. + /// + public virtual void GiveFeedback(GiveFeedbackEventArgs args) { + args.UseDefaultCursors = true; + } + + /// + /// Should the drag be allowed to continue? + /// + /// + /// You only need to override this if you want the user to be able + /// to end the drop in some non-standard way, e.g. dragging to a + /// certain point even without releasing the mouse, or going outside + /// the bounds of the application. + /// + /// + public virtual void QueryContinue(QueryContinueDragEventArgs args) { + } + + + #endregion + + #region Commands + + /// + /// This is called when the mouse leaves the drop region and after the + /// drop has completed. + /// + protected virtual void Cleanup() { + } + + #endregion + } + + /// + /// The enum indicates which target has been found for a drop operation + /// + [Flags] + public enum DropTargetLocation + { + /// + /// No applicable target has been found + /// + None = 0, + + /// + /// The list itself is the target of the drop + /// + Background = 0x01, + + /// + /// An item is the target + /// + Item = 0x02, + + /// + /// Between two items (or above the top item or below the bottom item) + /// can be the target. This is not actually ever a target, only a value indicate + /// that it is valid to drop between items + /// + BetweenItems = 0x04, + + /// + /// Above an item is the target + /// + AboveItem = 0x08, + + /// + /// Below an item is the target + /// + BelowItem = 0x10, + + /// + /// A subitem is the target of the drop + /// + SubItem = 0x20, + + /// + /// On the right of an item is the target (not currently used) + /// + RightOfItem = 0x40, + + /// + /// On the left of an item is the target (not currently used) + /// + LeftOfItem = 0x80 + } + + /// + /// This class represents a simple implementation of a drop sink. + /// + /// + /// Actually, it's far from simple and can do quite a lot in its own right. + /// + public class SimpleDropSink : AbstractDropSink + { + #region Life and death + + /// + /// Make a new drop sink + /// + public SimpleDropSink() { + this.timer = new Timer(); + this.timer.Interval = 250; + this.timer.Tick += new EventHandler(this.timer_Tick); + + this.CanDropOnItem = true; + //this.CanDropOnSubItem = true; + //this.CanDropOnBackground = true; + //this.CanDropBetween = true; + + this.FeedbackColor = Color.FromArgb(180, Color.MediumBlue); + this.billboard = new BillboardOverlay(); + } + + #endregion + + #region Public properties + + /// + /// Get or set the locations where a drop is allowed to occur (OR-ed together) + /// + public DropTargetLocation AcceptableLocations { + get { return this.acceptableLocations; } + set { this.acceptableLocations = value; } + } + private DropTargetLocation acceptableLocations; + + /// + /// Gets or sets whether this sink allows model objects to be dragged from other lists + /// + public bool AcceptExternal { + get { return this.acceptExternal; } + set { this.acceptExternal = value; } + } + private bool acceptExternal = true; + + /// + /// Gets or sets whether the ObjectListView should scroll when the user drags + /// something near to the top or bottom rows. + /// + public bool AutoScroll { + get { return this.autoScroll; } + set { this.autoScroll = value; } + } + private bool autoScroll = true; + + /// + /// Gets the billboard overlay that will be used to display feedback + /// messages during a drag operation. + /// + /// Set this to null to stop the feedback. + public BillboardOverlay Billboard { + get { return this.billboard; } + set { this.billboard = value; } + } + private BillboardOverlay billboard; + + /// + /// Get or set whether a drop can occur between items of the list + /// + public bool CanDropBetween { + get { return (this.AcceptableLocations & DropTargetLocation.BetweenItems) == DropTargetLocation.BetweenItems; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.BetweenItems; + else + this.AcceptableLocations &= ~DropTargetLocation.BetweenItems; + } + } + + /// + /// Get or set whether a drop can occur on the listview itself + /// + public bool CanDropOnBackground { + get { return (this.AcceptableLocations & DropTargetLocation.Background) == DropTargetLocation.Background; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Background; + else + this.AcceptableLocations &= ~DropTargetLocation.Background; + } + } + + /// + /// Get or set whether a drop can occur on items in the list + /// + public bool CanDropOnItem { + get { return (this.AcceptableLocations & DropTargetLocation.Item) == DropTargetLocation.Item; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.Item; + else + this.AcceptableLocations &= ~DropTargetLocation.Item; + } + } + + /// + /// Get or set whether a drop can occur on a subitem in the list + /// + public bool CanDropOnSubItem { + get { return (this.AcceptableLocations & DropTargetLocation.SubItem) == DropTargetLocation.SubItem; } + set { + if (value) + this.AcceptableLocations |= DropTargetLocation.SubItem; + else + this.AcceptableLocations &= ~DropTargetLocation.SubItem; + } + } + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { + if (this.dropTargetIndex != value) { + this.dropTargetIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + } + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { + if (this.dropTargetLocation != value) { + this.dropTargetLocation = value; + this.ListView.Invalidate(); + } + } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { + if (this.dropTargetSubItemIndex != value) { + this.dropTargetSubItemIndex = value; + this.ListView.Invalidate(); + } + } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get or set the color that will be used to provide drop feedback + /// + public Color FeedbackColor { + get { return this.feedbackColor; } + set { this.feedbackColor = value; } + } + private Color feedbackColor; + + /// + /// Get whether the alt key was down during this drop event + /// + public bool IsAltDown { + get { return (this.KeyState & 32) == 32; } + } + + /// + /// Get whether any modifier key was down during this drop event + /// + public bool IsAnyModifierDown { + get { return (this.KeyState & (4 + 8 + 32)) != 0; } + } + + /// + /// Get whether the control key was down during this drop event + /// + public bool IsControlDown { + get { return (this.KeyState & 8) == 8; } + } + + /// + /// Get whether the left mouse button was down during this drop event + /// + public bool IsLeftMouseButtonDown { + get { return (this.KeyState & 1) == 1; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsMiddleMouseButtonDown { + get { return (this.KeyState & 16) == 16; } + } + + /// + /// Get whether the right mouse button was down during this drop event + /// + public bool IsRightMouseButtonDown { + get { return (this.KeyState & 2) == 2; } + } + + /// + /// Get whether the shift key was down during this drop event + /// + public bool IsShiftDown { + get { return (this.KeyState & 4) == 4; } + } + + /// + /// Get or set the state of the keys during this drop event + /// + public int KeyState { + get { return this.keyState; } + set { this.keyState = value; } + } + private int keyState; + + #endregion + + #region Events + + /// + /// Triggered when the sink needs to know if a drop can occur. + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler CanDrop; + + /// + /// Triggered when the drop is made. + /// + public event EventHandler Dropped; + + /// + /// Triggered when the sink needs to know if a drop can occur + /// AND the source is an ObjectListView + /// + /// + /// Handlers should set Effect to indicate what is possible. + /// Handlers can change any of the DropTarget* setttings to change + /// the target of the drop. + /// + public event EventHandler ModelCanDrop; + + /// + /// Triggered when the drop is made. + /// AND the source is an ObjectListView + /// + public event EventHandler ModelDropped; + + #endregion + + #region DropSink Interface + + /// + /// Cleanup the drop sink when the mouse has left the control or + /// the drag has finished. + /// + protected override void Cleanup() { + this.DropTargetLocation = DropTargetLocation.None; + this.ListView.FullRowSelect = this.originalFullRowSelect; + this.Billboard.Text = null; + } + + /// + /// Draw any feedback that is appropriate to the current drop state. + /// + /// + /// Any drawing is done over the top of the ListView. This operation should disturb + /// the Graphic as little as possible. Specifically, do not erase the area into which + /// you draw. + /// + /// A Graphic for drawing + /// The contents bounds of the ListView (not including any header) + public override void DrawFeedback(Graphics g, Rectangle bounds) { + g.SmoothingMode = ObjectListView.SmoothingMode; + + switch (this.DropTargetLocation) { + case DropTargetLocation.Background: + this.DrawFeedbackBackgroundTarget(g, bounds); + break; + case DropTargetLocation.Item: + this.DrawFeedbackItemTarget(g, bounds); + break; + case DropTargetLocation.AboveItem: + this.DrawFeedbackAboveItemTarget(g, bounds); + break; + case DropTargetLocation.BelowItem: + this.DrawFeedbackBelowItemTarget(g, bounds); + break; + } + + if (this.Billboard != null) { + this.Billboard.Draw(this.ListView, g, bounds); + } + } + + /// + /// The user has released the drop over this control + /// + /// + public override void Drop(DragEventArgs args) { + this.TriggerDroppedEvent(args); + this.timer.Stop(); + this.Cleanup(); + } + + /// + /// A drag has entered this control. + /// + /// Implementators should set args.Effect to the appropriate DragDropEffects. + /// + public override void Enter(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Enter"); + + /* + * When FullRowSelect is true, we have two problems: + * 1) GetItemRect(ItemOnly) returns the whole row rather than just the icon/text, which messes + * up our calculation of the drop rectangle. + * 2) during the drag, the Timer events will not fire! This is the major problem, since without + * those events we can't autoscroll. + * + * The first problem we can solve through coding, but the second is more difficult. + * We avoid both problems by turning off FullRowSelect during the drop operation. + */ + this.originalFullRowSelect = this.ListView.FullRowSelect; + this.ListView.FullRowSelect = false; + + // Setup our drop event args block + this.dropEventArgs = new ModelDropEventArgs(); + this.dropEventArgs.DropSink = this; + this.dropEventArgs.ListView = this.ListView; + this.dropEventArgs.DataObject = args.Data; + OLVDataObject olvData = args.Data as OLVDataObject; + if (olvData != null) { + this.dropEventArgs.SourceListView = olvData.ListView; + this.dropEventArgs.SourceModels = olvData.ModelObjects; + } + + this.Over(args); + } + + /// + /// The drag is moving over this control. + /// + /// + public override void Over(DragEventArgs args) { + //System.Diagnostics.Debug.WriteLine("Over"); + this.KeyState = args.KeyState; + Point pt = this.ListView.PointToClient(new Point(args.X, args.Y)); + args.Effect = this.CalculateDropAction(args, pt); + this.CheckScrolling(pt); + } + + #endregion + + #region Events + + /// + /// Trigger the Dropped events + /// + /// + protected virtual void TriggerDroppedEvent(DragEventArgs args) { + this.dropEventArgs.Handled = false; + + // If the source is an ObjectListView, trigger the ModelDropped event + if (this.dropEventArgs.SourceListView != null) + this.OnModelDropped(this.dropEventArgs); + + if (!this.dropEventArgs.Handled) + this.OnDropped(this.dropEventArgs); + } + + /// + /// Trigger CanDrop + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// Trigger Dropped + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// Trigger ModelCanDrop + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != null && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + return; + } + + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// Trigger ModelDropped + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + #endregion + + #region Implementation + + private void timer_Tick(object sender, EventArgs e) { + this.HandleTimerTick(); + } + + /// + /// Handle the timer tick event, which is sent when the listview should + /// scroll + /// + protected virtual void HandleTimerTick() { + + // If the mouse has been released, stop scrolling. + // This is only necessary if the mouse is released outside of the control. + // If the mouse is released inside the control, we would receive a Drop event. + if ((this.IsLeftMouseButtonDown && (Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left) || + (this.IsMiddleMouseButtonDown && (Control.MouseButtons & MouseButtons.Middle) != MouseButtons.Middle) || + (this.IsRightMouseButtonDown && (Control.MouseButtons & MouseButtons.Right) != MouseButtons.Right)) { + this.timer.Stop(); + this.Cleanup(); + return; + } + + // Auto scrolling will continune while the mouse is close to the ListView + const int GRACE_PERIMETER = 30; + + Point pt = this.ListView.PointToClient(Cursor.Position); + Rectangle r2 = this.ListView.ClientRectangle; + r2.Inflate(GRACE_PERIMETER, GRACE_PERIMETER); + if (r2.Contains(pt)) { + this.ListView.LowLevelScroll(0, this.scrollAmount); + } + } + + /// + /// When the mouse is at the given point, what should the target of the drop be? + /// + /// This method should update the DropTarget* members of the given arg block + /// + /// The mouse point, in client co-ordinates + protected virtual void CalculateDropTarget(OlvDropEventArgs args, Point pt) { + const int SMALL_VALUE = 3; + DropTargetLocation location = DropTargetLocation.None; + int targetIndex = -1; + int targetSubIndex = 0; + + if (this.CanDropOnBackground) + location = DropTargetLocation.Background; + + // Which item is the mouse over? + // If it is not over any item, it's over the background. + //ListViewHitTestInfo info = this.ListView.HitTest(pt.X, pt.Y); + OlvListViewHitTestInfo info = this.ListView.OlvHitTest(pt.X, pt.Y); + if (info.Item != null && this.CanDropOnItem) { + location = DropTargetLocation.Item; + targetIndex = info.Item.Index; + if (info.SubItem != null && this.CanDropOnSubItem) + targetSubIndex = info.Item.SubItems.IndexOf(info.SubItem); + } + + // Check to see if the mouse is "between" rows. + // ("between" is somewhat loosely defined) + if (this.CanDropBetween && this.ListView.GetItemCount() > 0) { + + // If the mouse is over an item, check to see if it is near the top or bottom + if (location == DropTargetLocation.Item) { + if (pt.Y - SMALL_VALUE <= info.Item.Bounds.Top) + location = DropTargetLocation.AboveItem; + if (pt.Y + SMALL_VALUE >= info.Item.Bounds.Bottom) + location = DropTargetLocation.BelowItem; + } else { + // Is there an item a little below the mouse? + // If so, we say the drop point is above that row + info = this.ListView.OlvHitTest(pt.X, pt.Y + SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.AboveItem; + } else { + // Is there an item a little above the mouse? + info = this.ListView.OlvHitTest(pt.X, pt.Y - SMALL_VALUE); + if (info.Item != null) { + targetIndex = info.Item.Index; + location = DropTargetLocation.BelowItem; + } + } + } + } + + args.DropTargetLocation = location; + args.DropTargetIndex = targetIndex; + args.DropTargetSubItemIndex = targetSubIndex; + } + + /// + /// What sort of action is possible when the mouse is at the given point? + /// + /// + /// + /// + /// + /// + public virtual DragDropEffects CalculateDropAction(DragEventArgs args, Point pt) { + this.CalculateDropTarget(this.dropEventArgs, pt); + + this.dropEventArgs.MouseLocation = pt; + this.dropEventArgs.InfoMessage = null; + this.dropEventArgs.Handled = false; + + if (this.dropEventArgs.SourceListView != null) { + this.dropEventArgs.TargetModel = this.ListView.GetModelObject(this.dropEventArgs.DropTargetIndex); + this.OnModelCanDrop(this.dropEventArgs); + } + + if (!this.dropEventArgs.Handled) + this.OnCanDrop(this.dropEventArgs); + + this.UpdateAfterCanDropEvent(this.dropEventArgs); + + return this.dropEventArgs.Effect; + } + + /// + /// Based solely on the state of the modifier keys, what drop operation should + /// be used? + /// + /// The drop operation that matches the state of the keys + public DragDropEffects CalculateStandardDropActionFromKeys() { + if (this.IsControlDown) { + if (this.IsShiftDown) + return DragDropEffects.Link; + else + return DragDropEffects.Copy; + } else { + return DragDropEffects.Move; + } + } + + /// + /// Should the listview be made to scroll when the mouse is at the given point? + /// + /// + protected virtual void CheckScrolling(Point pt) { + if (!this.AutoScroll) + return; + + Rectangle r = this.ListView.ContentRectangle; + int rowHeight = this.ListView.RowHeightEffective; + int close = rowHeight; + + // In Tile view, using the whole row height is too much + if (this.ListView.View == View.Tile) + close /= 2; + + if (pt.Y <= (r.Top + close)) { + // Scroll faster if the mouse is closer to the top + this.timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = -rowHeight; + } else { + if (pt.Y >= (r.Bottom - close)) { + this.timer.Interval = ((pt.Y >= (r.Bottom - close / 2)) ? 100 : 350); + this.timer.Start(); + this.scrollAmount = rowHeight; + } else { + this.timer.Stop(); + } + } + } + + /// + /// Update the state of our sink to reflect the information that + /// may have been written into the drop event args. + /// + /// + protected virtual void UpdateAfterCanDropEvent(OlvDropEventArgs args) { + this.DropTargetIndex = args.DropTargetIndex; + this.DropTargetLocation = args.DropTargetLocation; + this.DropTargetSubItemIndex = args.DropTargetSubItemIndex; + + if (this.Billboard != null) { + Point pt = args.MouseLocation; + pt.Offset(5, 5); + if (this.Billboard.Text != this.dropEventArgs.InfoMessage || this.Billboard.Location != pt) { + this.Billboard.Text = this.dropEventArgs.InfoMessage; + this.Billboard.Location = pt; + this.ListView.Invalidate(); + } + } + } + + #endregion + + #region Rendering + + /// + /// Draw the feedback that shows that the background is the target + /// + /// + /// + protected virtual void DrawFeedbackBackgroundTarget(Graphics g, Rectangle bounds) { + float penWidth = 12.0f; + Rectangle r = bounds; + r.Inflate((int)-penWidth / 2, (int)-penWidth / 2); + using (Pen p = new Pen(Color.FromArgb(128, this.FeedbackColor), penWidth)) { + using (GraphicsPath path = this.GetRoundedRect(r, 30.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows that an item (or a subitem) is the target + /// + /// + /// + /// + /// DropTargetItem and DropTargetSubItemIndex tells what is the target + /// + protected virtual void DrawFeedbackItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + r.Inflate(1, 1); + float diameter = r.Height / 3; + using (GraphicsPath path = this.GetRoundedRect(r, diameter)) { + using (SolidBrush b = new SolidBrush(Color.FromArgb(48, this.FeedbackColor))) { + g.FillPath(b, path); + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawPath(p, path); + } + } + } + + /// + /// Draw the feedback that shows the drop will occur before target + /// + /// + /// + protected virtual void DrawFeedbackAboveItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Top, r.Right, r.Top); + } + + /// + /// Draw the feedback that shows the drop will occur after target + /// + /// + /// + protected virtual void DrawFeedbackBelowItemTarget(Graphics g, Rectangle bounds) { + if (this.DropTargetItem == null) + return; + + Rectangle r = this.CalculateDropTargetRectangle(this.DropTargetItem, this.DropTargetSubItemIndex); + this.DrawBetweenLine(g, r.Left, r.Bottom, r.Right, r.Bottom); + } + + /// + /// Return a GraphicPath that is round corner rectangle. + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + + return path; + } + + /// + /// Calculate the target rectangle when the given item (and possible subitem) + /// is the target of the drop. + /// + /// + /// + /// + protected virtual Rectangle CalculateDropTargetRectangle(OLVListItem item, int subItem) { + if (subItem > 0) + return item.SubItems[subItem].Bounds; + + Rectangle r = this.ListView.CalculateCellTextBounds(item, subItem); + + // Allow for indent + if (item.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width; + r.X += (indentWidth * item.IndentCount); + r.Width -= (indentWidth * item.IndentCount); + } + + return r; + } + + /// + /// Draw a "between items" line at the given co-ordinates + /// + /// + /// + /// + /// + /// + protected virtual void DrawBetweenLine(Graphics g, int x1, int y1, int x2, int y2) { + using (Brush b = new SolidBrush(this.FeedbackColor)) { + int x = x1; + int y = y1; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 5, + x, y - 5); + gp.AddBezier( + x, y - 6, + x + 3, y - 2, + x + 6, y - 1, + x + 11, y); + gp.AddBezier( + x + 11, y, + x + 6, y + 1, + x + 3, y + 2, + x, y + 6); + gp.CloseFigure(); + g.FillPath(b, gp); + } + x = x2; + y = y2; + using (GraphicsPath gp = new GraphicsPath()) { + gp.AddLine( + x, y + 6, + x, y - 6); + gp.AddBezier( + x, y - 7, + x - 3, y - 2, + x - 6, y - 1, + x - 11, y); + gp.AddBezier( + x - 11, y, + x - 6, y + 1, + x - 3, y + 2, + x, y + 7); + gp.CloseFigure(); + g.FillPath(b, gp); + } + } + using (Pen p = new Pen(this.FeedbackColor, 3.0f)) { + g.DrawLine(p, x1, y1, x2, y2); + } + } + + #endregion + + private Timer timer; + private int scrollAmount; + private bool originalFullRowSelect; + private ModelDropEventArgs dropEventArgs; + } + + /// + /// This drop sink allows items within the same list to be rearranged, + /// as well as allowing items to be dropped from other lists. + /// + /// + /// + /// This class can only be used on plain ObjectListViews and FastObjectListViews. + /// The other flavours have no way to implement the insert operation that is required. + /// + /// + /// This class does not work with grouping. + /// + /// + /// This class works when the OLV is sorted, but it is up to the programmer + /// to decide what rearranging such lists "means". Example: if the control is sorting + /// students by academic grade, and the user drags a "Fail" grade student up amonst the "A+" + /// students, it is the responsibility of the programmer to makes the appropriate changes + /// to the model and redraw/rebuild the control so that the users action makes sense. + /// + /// + /// Users of this class should listen for the CanDrop event to decide + /// if models from another OLV can be moved to OLV under this sink. + /// + /// + public class RearrangingDropSink : SimpleDropSink + { + /// + /// Create a RearrangingDropSink + /// + public RearrangingDropSink() { + this.CanDropBetween = true; + this.CanDropOnBackground = true; + this.CanDropOnItem = false; + } + + /// + /// Create a RearrangingDropSink + /// + /// + public RearrangingDropSink(bool acceptDropsFromOtherLists) + : this() { + this.AcceptExternal = acceptDropsFromOtherLists; + } + + /// + /// Trigger OnModelCanDrop + /// + /// + protected override void OnModelCanDrop(ModelDropEventArgs args) { + base.OnModelCanDrop(args); + + if (args.Handled) + return; + + args.Effect = DragDropEffects.Move; + + // Don't allow drops from other list, if that's what's configured + if (!this.AcceptExternal && args.SourceListView != this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + args.InfoMessage = "This list doesn't accept drops from other lists"; + } + + // If we are rearranging a list, don't allow drops on the background + if (args.DropTargetLocation == DropTargetLocation.Background && args.SourceListView == this.ListView) { + args.Effect = DragDropEffects.None; + args.DropTargetLocation = DropTargetLocation.None; + } + } + + /// + /// Trigger OnModelDropped + /// + /// + protected override void OnModelDropped(ModelDropEventArgs args) { + base.OnModelDropped(args); + + if (!args.Handled) + this.RearrangeModels(args); + } + + /// + /// Do the work of processing the dropped items + /// + /// + public virtual void RearrangeModels(ModelDropEventArgs args) { + switch (args.DropTargetLocation) { + case DropTargetLocation.AboveItem: + this.ListView.MoveObjects(args.DropTargetIndex, args.SourceModels); + break; + case DropTargetLocation.BelowItem: + this.ListView.MoveObjects(args.DropTargetIndex + 1, args.SourceModels); + break; + case DropTargetLocation.Background: + this.ListView.AddObjects(args.SourceModels); + break; + default: + return; + } + + if (args.SourceListView != this.ListView) { + args.SourceListView.RemoveObjects(args.SourceModels); + } + } + } + + /// + /// When a drop sink needs to know if something can be dropped, or + /// to notify that a drop has occured, it uses an instance of this class. + /// + public class OlvDropEventArgs : EventArgs + { + /// + /// Create a OlvDropEventArgs + /// + public OlvDropEventArgs() { + } + + #region Data Properties + + /// + /// Get the data object that is being dragged + /// + public object DataObject { + get { return this.dataObject; } + internal set { this.dataObject = value; } + } + private object dataObject; + + /// + /// Get the drop sink that originated this event + /// + public SimpleDropSink DropSink { + get { return this.dropSink; } + internal set { this.dropSink = value; } + } + private SimpleDropSink dropSink; + + /// + /// Get or set the index of the item that is the target of the drop + /// + public int DropTargetIndex { + get { return dropTargetIndex; } + set { this.dropTargetIndex = value; } + } + private int dropTargetIndex = -1; + + /// + /// Get or set the location of the target of the drop + /// + public DropTargetLocation DropTargetLocation { + get { return dropTargetLocation; } + set { this.dropTargetLocation = value; } + } + private DropTargetLocation dropTargetLocation; + + /// + /// Get or set the index of the subitem that is the target of the drop + /// + public int DropTargetSubItemIndex { + get { return dropTargetSubItemIndex; } + set { this.dropTargetSubItemIndex = value; } + } + private int dropTargetSubItemIndex = -1; + + /// + /// Get the item that is the target of the drop + /// + public OLVListItem DropTargetItem { + get { + return this.ListView.GetItem(this.DropTargetIndex); + } + set { + if (value == null) + this.DropTargetIndex = -1; + else + this.DropTargetIndex = value.Index; + } + } + + /// + /// Get or set the drag effect that should be used for this operation + /// + public DragDropEffects Effect { + get { return this.effect; } + set { this.effect = value; } + } + private DragDropEffects effect; + + /// + /// Get or set if this event was handled. No further processing will be done for a handled event. + /// + public bool Handled { + get { return this.handled; } + set { this.handled = value; } + } + private bool handled; + + /// + /// Get or set the feedback message for this operation + /// + /// + /// If this is not null, it will be displayed as a feedback message + /// during the drag. + /// + public string InfoMessage { + get { return this.infoMessage; } + set { this.infoMessage = value; } + } + private string infoMessage; + + /// + /// Get the ObjectListView that is being dropped on + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Get the location of the mouse (in target ListView co-ords) + /// + public Point MouseLocation { + get { return this.mouseLocation; } + internal set { this.mouseLocation = value; } + } + private Point mouseLocation; + + /// + /// Get the drop action indicated solely by the state of the modifier keys + /// + public DragDropEffects StandardDropActionFromKeys { + get { + return this.DropSink.CalculateStandardDropActionFromKeys(); + } + } + + #endregion + } + + /// + /// These events are triggered when the drag source is an ObjectListView. + /// + public class ModelDropEventArgs : OlvDropEventArgs + { + /// + /// Create a ModelDropEventArgs + /// + public ModelDropEventArgs() + { + } + + /// + /// Gets the model objects that are being dragged. + /// + public IList SourceModels { + get { return this.dragModels; } + internal set { + this.dragModels = value; + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + } + } + private IList dragModels; + private ArrayList toBeRefreshed = new ArrayList(); + + /// + /// Gets the ObjectListView that is the source of the dragged objects. + /// + public ObjectListView SourceListView { + get { return this.sourceListView; } + internal set { this.sourceListView = value; } + } + private ObjectListView sourceListView; + + /// + /// Get the model object that is being dropped upon. + /// + /// This is only value for TargetLocation == Item + public object TargetModel { + get { return this.targetModel; } + internal set { this.targetModel = value; } + } + private object targetModel; + + /// + /// Refresh all the objects involved in the operation + /// + public void RefreshObjects() { + TreeListView tlv = this.SourceListView as TreeListView; + if (tlv != null) { + foreach (object model in this.SourceModels) { + object parent = tlv.GetParent(model); + if (!toBeRefreshed.Contains(parent)) + toBeRefreshed.Add(parent); + } + } + toBeRefreshed.AddRange(this.SourceModels); + if (this.ListView == this.SourceListView) { + toBeRefreshed.Add(this.TargetModel); + this.ListView.RefreshObjects(toBeRefreshed); + } else { + this.SourceListView.RefreshObjects(toBeRefreshed); + this.ListView.RefreshObject(this.TargetModel); + } + } + } +} diff --git a/ObjectListView/Implementation/Enums.cs b/ObjectListView/Implementation/Enums.cs new file mode 100644 index 0000000..572b4b4 --- /dev/null +++ b/ObjectListView/Implementation/Enums.cs @@ -0,0 +1,104 @@ +/* + * Enums - All enum definitions used in ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BrightIdeasSoftware { + + public partial class ObjectListView { + /// + /// How does a user indicate that they want to edit cells? + /// + public enum CellEditActivateMode { + /// + /// This list cannot be edited. F2 does nothing. + /// + None = 0, + + /// + /// A single click on a subitem will edit the value. Single clicking the primary column, + /// selects the row just like normal. The user must press F2 to edit the primary column. + /// + SingleClick = 1, + + /// + /// Double clicking a subitem or the primary column will edit that cell. + /// F2 will edit the primary column. + /// + DoubleClick = 2, + + /// + /// Pressing F2 is the only way to edit the cells. Once the primary column is being edited, + /// the other cells in the row can be edited by pressing Tab. + /// + F2Only = 3, + + /// + /// A single click on a any cell will edit the value, even the primary column. + /// + SingleClickAlways = 4, + } + + /// + /// These values specify how column selection will be presented to the user + /// + public enum ColumnSelectBehaviour { + /// + /// No column selection will be presented + /// + None, + + /// + /// The columns will be show in the main menu + /// + InlineMenu, + + /// + /// The columns will be shown in a submenu + /// + Submenu, + + /// + /// A model dialog will be presented to allow the user to choose columns + /// + ModelDialog, + + /* + * NonModelDialog is just a little bit tricky since the OLV can change views while the dialog is showing + * So, just comment this out for the time being. + + /// + /// A non-model dialog will be presented to allow the user to choose columns + /// + NonModelDialog + * + */ + } + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/Events.cs b/ObjectListView/Implementation/Events.cs new file mode 100644 index 0000000..7a1c466 --- /dev/null +++ b/ObjectListView/Implementation/Events.cs @@ -0,0 +1,2514 @@ +/* + * Events - All the events that can be triggered within an ObjectListView. + * + * Author: Phillip Piper + * Date: 17/10/2008 9:15 PM + * + * Change log: + * v2.8.0 + * 2014-05-20 JPP - Added IsHyperlinkEventArgs.IsHyperlink + * v2.6 + * 2012-04-17 JPP - Added group state change and group expansion events + * v2.5 + * 2010-08-08 JPP - CellEdit validation and finish events now have NewValue property. + * v2.4 + * 2010-03-04 JPP - Added filtering events + * v2.3 + * 2009-08-16 JPP - Added group events + * 2009-08-08 JPP - Added HotItem event + * 2009-07-24 JPP - Added Hyperlink events + * - Added Formatting events + * v2.2.1 + * 2009-06-13 JPP - Added Cell events + * - Moved all event parameter blocks to this file. + * - Added Handled property to AfterSearchEventArgs + * v2.2 + * 2009-06-01 JPP - Added ColumnToGroupBy and GroupByOrder to sorting events + - Gave all event descriptions + * 2009-04-23 JPP - Added drag drop events + * v2.1 + * 2009-01-18 JPP - Moved SelectionChanged event to this file + * v2.0 + * 2008-12-06 JPP - Added searching events + * 2008-12-01 JPP - Added secondary sort information to Before/AfterSorting events + * 2008-10-17 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + /// + /// The callbacks for CellEditing events + /// + /// this + /// We could replace this with EventHandler<CellEditEventArgs> but that would break all + /// cell editing event code from v1.x. + /// + public delegate void CellEditEventHandler(object sender, CellEditEventArgs e); + + public partial class ObjectListView { + //----------------------------------------------------------------------------------- + + #region Events + + /// + /// Triggered after a ObjectListView has been searched by the user typing into the list + /// + [Category("ObjectListView"), + Description("This event is triggered after the control has done a search-by-typing action.")] + public event EventHandler AfterSearching; + + /// + /// Triggered after a ObjectListView has been sorted + /// + [Category("ObjectListView"), + Description("This event is triggered after the items in the list have been sorted.")] + public event EventHandler AfterSorting; + + /// + /// Triggered before a ObjectListView is searched by the user typing into the list + /// + /// + /// Set Cancelled to true to prevent the searching from taking place. + /// Changing StringToFind or StartSearchFrom will change the subsequent search. + /// + [Category("ObjectListView"), + Description("This event is triggered before the control does a search-by-typing action.")] + public event EventHandler BeforeSearching; + + /// + /// Triggered before a ObjectListView is sorted + /// + /// + /// Set Cancelled to true to prevent the sort from taking place. + /// Changing ColumnToSort or SortOrder will change the subsequent sort. + /// + [Category("ObjectListView"), + Description("This event is triggered before the items in the list are sorted.")] + public event EventHandler BeforeSorting; + + /// + /// Triggered after a ObjectListView has created groups + /// + [Category("ObjectListView"), + Description("This event is triggered after the groups are created.")] + public event EventHandler AfterCreatingGroups; + + /// + /// Triggered before a ObjectListView begins to create groups + /// + /// + /// Set Groups to prevent the default group creation process + /// + [Category("ObjectListView"), + Description("This event is triggered before the groups are created.")] + public event EventHandler BeforeCreatingGroups; + + /// + /// Triggered just before a ObjectListView creates groups + /// + /// + /// You can make changes to the groups, which have been created, before those + /// groups are created within the listview. + /// + [Category("ObjectListView"), + Description("This event is triggered when the groups are just about to be created.")] + public event EventHandler AboutToCreateGroups; + + /// + /// Triggered when a button in a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a button.")] + public event EventHandler ButtonClick; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the user drop the currently dragged items at the current mouse location?")] + public event EventHandler CanDrop; + + /// + /// Triggered when a cell has finished being edited. + /// + [Category("ObjectListView"), + Description("This event is triggered cell edit operation has completely finished")] + public event CellEditEventHandler CellEditFinished; + + /// + /// Triggered when a cell is about to finish being edited. + /// + /// If Cancel is already true, the user is cancelling the edit operation. + /// Set Cancel to true to prevent the value from the cell being written into the model. + /// You cannot prevent the editing from finishing within this event -- you need + /// the CellEditValidating event for that. + [Category("ObjectListView"), + Description("This event is triggered cell edit operation is finishing.")] + public event CellEditEventHandler CellEditFinishing; + + /// + /// Triggered when a cell is about to be edited. + /// + /// Set Cancel to true to prevent the cell being edited. + /// You can change the Control to be something completely different. + [Category("ObjectListView"), + Description("This event is triggered when cell edit is about to begin.")] + public event CellEditEventHandler CellEditStarting; + + /// + /// Triggered when a cell editor needs to be validated + /// + /// + /// If this event is cancelled, focus will remain on the cell editor. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell editor is about to lose focus and its new contents need to be validated.")] + public event CellEditEventHandler CellEditValidating; + + /// + /// Triggered when a cell is left clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user left clicks a cell.")] + public event EventHandler CellClick; + + /// + /// Triggered when the mouse is above a cell. + /// + [Category("ObjectListView"), + Description("This event is triggered when the mouse is over a cell.")] + public event EventHandler CellOver; + + /// + /// Triggered when a cell is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a cell.")] + public event EventHandler CellRightClick; + + /// + /// This event is triggered when a cell needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs a tool tip.")] + public event EventHandler CellToolTipShowing; + + /// + /// This event is triggered when a checkbox is checked/unchecked on a subitem + /// + [Category("ObjectListView"), + Description("This event is triggered when a checkbox is checked/unchecked on a subitem.")] + public event EventHandler SubItemChecking; + + /// + /// Triggered when a column header is right clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user right clicks a column header.")] + public event ColumnRightClickEventHandler ColumnRightClick; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler. + /// + [Category("ObjectListView"), + Description("This event is triggered when the user dropped items onto the control.")] + public event EventHandler Dropped; + + /// + /// This event is triggered when the control needs to filter its collection of objects. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to filter its collection of objects.")] + public event EventHandler Filter; + + /// + /// This event is triggered when a cell needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a cell needs to be formatted.")] + public event EventHandler FormatCell; + + /// + /// This event is triggered when the frozenness of the control changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when frozenness of the control changes.")] + public event EventHandler Freezing; + + /// + /// This event is triggered when a row needs to be formatted. + /// + [Category("ObjectListView"), + Description("This event is triggered when a row needs to be formatted.")] + public event EventHandler FormatRow; + + /// + /// This event is triggered when a group is about to collapse or expand. + /// This can be cancelled to prevent the expansion. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group is about to collapse or expand.")] + public event EventHandler GroupExpandingCollapsing; + + /// + /// This event is triggered when a group changes state. + /// + [Category("ObjectListView"), + Description("This event is triggered when a group changes state.")] + public event EventHandler GroupStateChanged; + + /// + /// This event is triggered when a header checkbox is changing value + /// + [Category("ObjectListView"), + Description("This event is triggered when a header checkbox changes value.")] + public event EventHandler HeaderCheckBoxChanging; + + /// + /// This event is triggered when a header needs a tool tip. + /// + [Category("ObjectListView"), + Description("This event is triggered when a header needs a tool tip.")] + public event EventHandler HeaderToolTipShowing; + + /// + /// Triggered when the "hot" item changes + /// + [Category("ObjectListView"), + Description("This event is triggered when the hot item changed.")] + public event EventHandler HotItemChanged; + + /// + /// Triggered when a hyperlink cell is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when a hyperlink cell is clicked.")] + public event EventHandler HyperlinkClicked; + + /// + /// Triggered when the task text of a group is clicked. + /// + [Category("ObjectListView"), + Description("This event is triggered when the task text of a group is clicked.")] + public event EventHandler GroupTaskClicked; + + /// + /// Is the value in the given cell a hyperlink. + /// + [Category("ObjectListView"), + Description("This event is triggered when the control needs to know if a given cell contains a hyperlink.")] + public event EventHandler IsHyperlink; + + /// + /// Some new objects are about to be added to an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are about to be added to the control")] + public event EventHandler ItemsAdding; + + /// + /// The contents of the ObjectListView has changed. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control have changed.")] + public event EventHandler ItemsChanged; + + /// + /// The contents of the ObjectListView is about to change via a SetObjects call + /// + /// + /// Set Cancelled to true to prevent the contents of the list changing. This does not work with virtual lists. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the control changes.")] + public event EventHandler ItemsChanging; + + /// + /// Some objects are about to be removed from an ObjectListView. + /// + [Category("ObjectListView"), + Description("This event is triggered when objects are removed from the control.")] + public event EventHandler ItemsRemoving; + + /// + /// This event is triggered when the user moves a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler, and when the source control + /// for the drag was an ObjectListView. + /// + /// + /// Handlers for this event should set the Effect argument and optionally the + /// InfoMsg property. They can also change any of the DropTarget* settings to change + /// the target of the drop. + /// + [Category("ObjectListView"), + Description("Can the dragged collection of model objects be dropped at the current mouse location")] + public event EventHandler ModelCanDrop; + + /// + /// This event is triggered when the user releases a drag over an ObjectListView that + /// has a SimpleDropSink installed as the drop handler and when the source control + /// for the drag was an ObjectListView. + /// + [Category("ObjectListView"), + Description("A collection of model objects from a ObjectListView has been dropped on this control")] + public event EventHandler ModelDropped; + + /// + /// This event is triggered once per user action that changes the selection state + /// of one or more rows. + /// + [Category("ObjectListView"), + Description("This event is triggered once per user action that changes the selection state of one or more rows.")] + public event EventHandler SelectionChanged; + + /// + /// This event is triggered when the contents of the ObjectListView has scrolled. + /// + [Category("ObjectListView"), + Description("This event is triggered when the contents of the ObjectListView has scrolled.")] + public event EventHandler Scroll; + + #endregion + + //----------------------------------------------------------------------------------- + + #region OnEvents + + /// + /// + /// + /// + protected virtual void OnAboutToCreateGroups(CreateGroupsEventArgs e) { + if (this.AboutToCreateGroups != null) + this.AboutToCreateGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeCreatingGroups(CreateGroupsEventArgs e) { + if (this.BeforeCreatingGroups != null) + this.BeforeCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterCreatingGroups(CreateGroupsEventArgs e) { + if (this.AfterCreatingGroups != null) + this.AfterCreatingGroups(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSearching(AfterSearchingEventArgs e) { + if (this.AfterSearching != null) + this.AfterSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnAfterSorting(AfterSortingEventArgs e) { + if (this.AfterSorting != null) + this.AfterSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSearching(BeforeSearchingEventArgs e) { + if (this.BeforeSearching != null) + this.BeforeSearching(this, e); + } + + /// + /// + /// + /// + protected virtual void OnBeforeSorting(BeforeSortingEventArgs e) { + if (this.BeforeSorting != null) + this.BeforeSorting(this, e); + } + + /// + /// + /// + /// + protected virtual void OnButtonClick(CellClickEventArgs args) { + if (this.ButtonClick != null) + this.ButtonClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCanDrop(OlvDropEventArgs args) { + if (this.CanDrop != null) + this.CanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellClick(CellClickEventArgs args) { + if (this.CellClick != null) + this.CellClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellOver(CellOverEventArgs args) { + if (this.CellOver != null) + this.CellOver(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellRightClick(CellRightClickEventArgs args) { + if (this.CellRightClick != null) + this.CellRightClick(this, args); + } + + /// + /// + /// + /// + protected virtual void OnCellToolTip(ToolTipShowingEventArgs args) { + if (this.CellToolTipShowing != null) + this.CellToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSubItemChecking(SubItemCheckingEventArgs args) { + if (this.SubItemChecking != null) + this.SubItemChecking(this, args); + } + + /// + /// + /// + /// + protected virtual void OnColumnRightClick(ColumnRightClickEventArgs e) { + if (this.ColumnRightClick != null) + this.ColumnRightClick(this, e); + } + + /// + /// + /// + /// + protected virtual void OnDropped(OlvDropEventArgs args) { + if (this.Dropped != null) + this.Dropped(this, args); + } + + /// + /// + /// + /// + internal protected virtual void OnFilter(FilterEventArgs e) { + if (this.Filter != null) + this.Filter(this, e); + } + + /// + /// + /// + /// + protected virtual void OnFormatCell(FormatCellEventArgs args) { + if (this.FormatCell != null) + this.FormatCell(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFormatRow(FormatRowEventArgs args) { + if (this.FormatRow != null) + this.FormatRow(this, args); + } + + /// + /// + /// + /// + protected virtual void OnFreezing(FreezeEventArgs args) { + if (this.Freezing != null) + this.Freezing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupExpandingCollapsing(GroupExpandingCollapsingEventArgs args) { + if (this.GroupExpandingCollapsing != null) + this.GroupExpandingCollapsing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnGroupStateChanged(GroupStateChangedEventArgs args) { + if (this.GroupStateChanged != null) + this.GroupStateChanged(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderCheckBoxChanging(HeaderCheckBoxChangingEventArgs args) { + if (this.HeaderCheckBoxChanging != null) + this.HeaderCheckBoxChanging(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHeaderToolTip(ToolTipShowingEventArgs args) { + if (this.HeaderToolTipShowing != null) + this.HeaderToolTipShowing(this, args); + } + + /// + /// + /// + /// + protected virtual void OnHotItemChanged(HotItemChangedEventArgs e) { + if (this.HotItemChanged != null) + this.HotItemChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnHyperlinkClicked(HyperlinkClickedEventArgs e) { + if (this.HyperlinkClicked != null) + this.HyperlinkClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnGroupTaskClicked(GroupTaskClickedEventArgs e) { + if (this.GroupTaskClicked != null) + this.GroupTaskClicked(this, e); + } + + /// + /// + /// + /// + protected virtual void OnIsHyperlink(IsHyperlinkEventArgs e) { + if (this.IsHyperlink != null) + this.IsHyperlink(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsAdding(ItemsAddingEventArgs e) { + if (this.ItemsAdding != null) + this.ItemsAdding(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanged(ItemsChangedEventArgs e) { + if (this.ItemsChanged != null) + this.ItemsChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsChanging(ItemsChangingEventArgs e) { + if (this.ItemsChanging != null) + this.ItemsChanging(this, e); + } + + /// + /// + /// + /// + protected virtual void OnItemsRemoving(ItemsRemovingEventArgs e) { + if (this.ItemsRemoving != null) + this.ItemsRemoving(this, e); + } + + /// + /// + /// + /// + protected virtual void OnModelCanDrop(ModelDropEventArgs args) { + if (this.ModelCanDrop != null) + this.ModelCanDrop(this, args); + } + + /// + /// + /// + /// + protected virtual void OnModelDropped(ModelDropEventArgs args) { + if (this.ModelDropped != null) + this.ModelDropped(this, args); + } + + /// + /// + /// + /// + protected virtual void OnSelectionChanged(EventArgs e) { + if (this.SelectionChanged != null) + this.SelectionChanged(this, e); + } + + /// + /// + /// + /// + protected virtual void OnScroll(ScrollEventArgs e) { + if (this.Scroll != null) + this.Scroll(this, e); + } + + + /// + /// Tell the world when a cell is about to be edited. + /// + protected virtual void OnCellEditStarting(CellEditEventArgs e) { + if (this.CellEditStarting != null) + this.CellEditStarting(this, e); + } + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditorValidating(CellEditEventArgs e) { + // Hack. ListView is an imperfect control container. It does not manage validation + // perfectly. If the ListView is part of a TabControl, and the cell editor loses + // focus by the user clicking on another tab, the TabControl processes the click + // and switches tabs, even if this Validating event cancels. This results in the + // strange situation where the cell editor is active, but isn't visible. When the + // user switches back to the tab with the ListView, composite controls like spin + // controls, DateTimePicker and ComboBoxes do not work properly. Specifically, + // keyboard input still works fine, but the controls do not respond to mouse + // input. SO, if the validation fails, we have to specifically give focus back to + // the cell editor. (this is the Select() call in the code below). + // But (there is always a 'but'), doing that changes the focus so the cell editor + // triggers another Validating event -- which fails again. From the user's point + // of view, they click away from the cell editor, and the validating code + // complains twice. So we only trigger a Validating event if more than 0.1 seconds + // has elapsed since the last validate event. + // I know it's a hack. I'm very open to hear a neater solution. + + // Also, this timed response stops us from sending a series of validation events + // if the user clicks and holds on the OLV scroll bar. + //System.Diagnostics.Debug.WriteLine(Environment.TickCount - lastValidatingEvent); + if ((Environment.TickCount - lastValidatingEvent) < 100) { + e.Cancel = true; + } else { + lastValidatingEvent = Environment.TickCount; + if (this.CellEditValidating != null) + this.CellEditValidating(this, e); + } + + lastValidatingEvent = Environment.TickCount; + } + + private int lastValidatingEvent = 0; + + /// + /// Tell the world when a cell is about to finish being edited. + /// + protected virtual void OnCellEditFinishing(CellEditEventArgs e) { + if (this.CellEditFinishing != null) + this.CellEditFinishing(this, e); + } + + /// + /// Tell the world when a cell has finished being edited. + /// + protected virtual void OnCellEditFinished(CellEditEventArgs e) { + if (this.CellEditFinished != null) + this.CellEditFinished(this, e); + } + + #endregion + } + + public partial class TreeListView { + + #region Events + + /// + /// This event is triggered when user input requests the expansion of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to expand.")] + public event EventHandler Expanding; + + /// + /// This event is triggered when user input requests the collapse of a list item. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch is about to collapsed.")] + public event EventHandler Collapsing; + + /// + /// This event is triggered after the expansion of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been expanded.")] + public event EventHandler Expanded; + + /// + /// This event is triggered after the collapse of a list item due to user input. + /// + [Category("ObjectListView"), + Description("This event is triggered when a branch has been collapsed.")] + public event EventHandler Collapsed; + + #endregion + + #region OnEvents + + /// + /// Trigger the expanding event + /// + /// + protected virtual void OnExpanding(TreeBranchExpandingEventArgs e) { + if (this.Expanding != null) + this.Expanding(this, e); + } + + /// + /// Trigger the collapsing event + /// + /// + protected virtual void OnCollapsing(TreeBranchCollapsingEventArgs e) { + if (this.Collapsing != null) + this.Collapsing(this, e); + } + + /// + /// Trigger the expanded event + /// + /// + protected virtual void OnExpanded(TreeBranchExpandedEventArgs e) { + if (this.Expanded != null) + this.Expanded(this, e); + } + + /// + /// Trigger the collapsed event + /// + /// + protected virtual void OnCollapsed(TreeBranchCollapsedEventArgs e) { + if (this.Collapsed != null) + this.Collapsed(this, e); + } + + #endregion + } + + //----------------------------------------------------------------------------------- + + #region Event Parameter Blocks + + /// + /// Let the world know that a cell edit operation is beginning or ending + /// + public class CellEditEventArgs : EventArgs { + /// + /// Create an event args + /// + /// + /// + /// + /// + /// + public CellEditEventArgs(OLVColumn column, Control control, Rectangle cellBounds, OLVListItem item, int subItemIndex) { + this.Control = control; + this.column = column; + this.cellBounds = cellBounds; + this.listViewItem = item; + this.rowObject = item.RowObject; + this.subItemIndex = subItemIndex; + this.value = column.GetValue(item.RowObject); + } + + /// + /// Change this to true to cancel the cell editing operation. + /// + /// + /// During the CellEditStarting event, setting this to true will prevent the cell from being edited. + /// During the CellEditFinishing event, if this value is already true, this indicates that the user has + /// cancelled the edit operation and that the handler should perform cleanup only. Setting this to true, + /// will prevent the ObjectListView from trying to write the new value into the model object. + /// + public bool Cancel; + + /// + /// During the CellEditStarting event, this can be modified to be the control that you want + /// to edit the value. You must fully configure the control before returning from the event, + /// including its bounds and the value it is showing. + /// During the CellEditFinishing event, you can use this to get the value that the user + /// entered and commit that value to the model. Changing the control during the finishing + /// event has no effect. + /// + public Control Control; + + /// + /// The column of the cell that is going to be or has been edited. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is going to be or has been edited. + /// + public Object RowObject { + get { return this.rowObject; } + } + + private Object rowObject; + + /// + /// The listview item of the cell that is going to be or has been edited. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The data value of the cell as it stands in the control. + /// + /// Only validate during Validating and Finishing events. + public Object NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private Object newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + + /// + /// The data value of the cell before the edit operation began. + /// + public Object Value { + get { return this.value; } + } + + private Object value; + + /// + /// The bounds of the cell that is going to be or has been edited. + /// + public Rectangle CellBounds { + get { return this.cellBounds; } + } + + private Rectangle cellBounds; + + /// + /// Gets or sets whether the control used for editing should be auto matically disposed + /// when the cell edit operation finishes. Defaults to true + /// + /// If the control is expensive to create, you might want to cache it and reuse for + /// for various cells. If so, you don't want ObjectListView to dispose of the control automatically + public bool AutoDispose { + get { return autoDispose; } + set { autoDispose = value; } + } + + private bool autoDispose = true; + } + + /// + /// Event blocks for events that can be cancelled + /// + public class CancellableEventArgs : EventArgs { + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled; + } + + /// + /// BeforeSorting + /// + public class BeforeSortingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = column; + this.GroupByOrder = order; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Create BeforeSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public BeforeSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.ColumnToGroupBy = groupColumn; + this.GroupByOrder = groupOrder; + this.ColumnToSort = column; + this.SortOrder = order; + this.SecondaryColumnToSort = column2; + this.SecondarySortOrder = order2; + } + + /// + /// Did the event handler already do the sorting for us? + /// + public bool Handled; + + /// + /// What column will be used for grouping + /// + public OLVColumn ColumnToGroupBy; + + /// + /// How will groups be ordered + /// + public SortOrder GroupByOrder; + + /// + /// What column will be used for sorting + /// + public OLVColumn ColumnToSort; + + /// + /// What order will be used for sorting. None means no sorting. + /// + public SortOrder SortOrder; + + /// + /// What column will be used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort; + + /// + /// What order will be used for secondary sorting? + /// + public SortOrder SecondarySortOrder; + } + + /// + /// Sorting has just occurred. + /// + public class AfterSortingEventArgs : EventArgs { + /// + /// Create a AfterSortingEventArgs + /// + /// + /// + /// + /// + /// + /// + public AfterSortingEventArgs(OLVColumn groupColumn, SortOrder groupOrder, OLVColumn column, SortOrder order, OLVColumn column2, SortOrder order2) { + this.columnToGroupBy = groupColumn; + this.groupByOrder = groupOrder; + this.columnToSort = column; + this.sortOrder = order; + this.secondaryColumnToSort = column2; + this.secondarySortOrder = order2; + } + + /// + /// Create a AfterSortingEventArgs + /// + /// + public AfterSortingEventArgs(BeforeSortingEventArgs args) { + this.columnToGroupBy = args.ColumnToGroupBy; + this.groupByOrder = args.GroupByOrder; + this.columnToSort = args.ColumnToSort; + this.sortOrder = args.SortOrder; + this.secondaryColumnToSort = args.SecondaryColumnToSort; + this.secondarySortOrder = args.SecondarySortOrder; + } + + /// + /// What column was used for grouping? + /// + public OLVColumn ColumnToGroupBy { + get { return columnToGroupBy; } + } + + private OLVColumn columnToGroupBy; + + /// + /// What ordering was used for grouping? + /// + public SortOrder GroupByOrder { + get { return groupByOrder; } + } + + private SortOrder groupByOrder; + + /// + /// What column was used for sorting? + /// + public OLVColumn ColumnToSort { + get { return columnToSort; } + } + + private OLVColumn columnToSort; + + /// + /// What ordering was used for sorting? + /// + public SortOrder SortOrder { + get { return sortOrder; } + } + + private SortOrder sortOrder; + + /// + /// What column was used for secondary sorting? + /// + public OLVColumn SecondaryColumnToSort { + get { return secondaryColumnToSort; } + } + + private OLVColumn secondaryColumnToSort; + + /// + /// What order was used for secondary sorting? + /// + public SortOrder SecondarySortOrder { + get { return secondarySortOrder; } + } + + private SortOrder secondarySortOrder; + } + + /// + /// This event is triggered when the contents of a list have changed + /// and we want the world to have a chance to filter the list. + /// + public class FilterEventArgs : EventArgs { + /// + /// Create a FilterEventArgs + /// + /// + public FilterEventArgs(IEnumerable objects) { + this.Objects = objects; + } + + /// + /// Gets or sets what objects are being filtered + /// + public IEnumerable Objects; + + /// + /// Gets or sets what objects survived the filtering + /// + public IEnumerable FilteredObjects; + } + + /// + /// This event is triggered after the items in the list have been changed, + /// either through SetObjects, AddObjects or RemoveObjects. + /// + public class ItemsChangedEventArgs : EventArgs { + /// + /// Create a ItemsChangedEventArgs + /// + public ItemsChangedEventArgs() { } + + /// + /// Constructor for this event when used by a virtual list + /// + /// + /// + public ItemsChangedEventArgs(int oldObjectCount, int newObjectCount) { + this.oldObjectCount = oldObjectCount; + this.newObjectCount = newObjectCount; + } + + /// + /// Gets how many items were in the list before it changed + /// + public int OldObjectCount { + get { return oldObjectCount; } + } + + private int oldObjectCount; + + /// + /// Gets how many objects are in the list after the change. + /// + public int NewObjectCount { + get { return newObjectCount; } + } + + private int newObjectCount; + } + + /// + /// This event is triggered by AddObjects before any change has been made to the list. + /// + public class ItemsAddingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsAddingEventArgs + /// + /// + public ItemsAddingEventArgs(ICollection objectsToAdd) { + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Create an ItemsAddingEventArgs + /// + /// + /// + public ItemsAddingEventArgs(int index, ICollection objectsToAdd) { + this.Index = index; + this.ObjectsToAdd = objectsToAdd; + } + + /// + /// Gets or sets where the collection is going to be inserted. + /// + public int Index; + + /// + /// Gets or sets the objects to be added to the list + /// + public ICollection ObjectsToAdd; + } + + /// + /// This event is triggered by SetObjects before any change has been made to the list. + /// + /// + /// When used with a virtual list, OldObjects will always be null. + /// + public class ItemsChangingEventArgs : CancellableEventArgs { + /// + /// Create ItemsChangingEventArgs + /// + /// + /// + public ItemsChangingEventArgs(IEnumerable oldObjects, IEnumerable newObjects) { + this.oldObjects = oldObjects; + this.NewObjects = newObjects; + } + + /// + /// Gets the objects that were in the list before it change. + /// For virtual lists, this will always be null. + /// + public IEnumerable OldObjects { + get { return oldObjects; } + } + + private IEnumerable oldObjects; + + /// + /// Gets or sets the objects that will be in the list after it changes. + /// + public IEnumerable NewObjects; + } + + /// + /// This event is triggered by RemoveObjects before any change has been made to the list. + /// + public class ItemsRemovingEventArgs : CancellableEventArgs { + /// + /// Create an ItemsRemovingEventArgs + /// + /// + public ItemsRemovingEventArgs(ICollection objectsToRemove) { + this.ObjectsToRemove = objectsToRemove; + } + + /// + /// Gets or sets the objects that will be removed + /// + public ICollection ObjectsToRemove; + } + + /// + /// Triggered after the user types into a list + /// + public class AfterSearchingEventArgs : EventArgs { + /// + /// Create an AfterSearchingEventArgs + /// + /// + /// + public AfterSearchingEventArgs(string stringToFind, int indexSelected) { + this.stringToFind = stringToFind; + this.indexSelected = indexSelected; + } + + /// + /// Gets the string that was actually searched for + /// + public string StringToFind { + get { return this.stringToFind; } + } + + private string stringToFind; + + /// + /// Gets or sets whether an the event handler already handled this event + /// + public bool Handled; + + /// + /// Gets the index of the row that was selected by the search. + /// -1 means that no row was matched + /// + public int IndexSelected { + get { return this.indexSelected; } + } + + private int indexSelected; + } + + /// + /// Triggered when the user types into a list + /// + public class BeforeSearchingEventArgs : CancellableEventArgs { + /// + /// Create BeforeSearchingEventArgs + /// + /// + /// + public BeforeSearchingEventArgs(string stringToFind, int startSearchFrom) { + this.StringToFind = stringToFind; + this.StartSearchFrom = startSearchFrom; + } + + /// + /// Gets or sets the string that will be found by the search routine + /// + /// Modifying this value does not modify the memory of what the user has typed. + /// When the user next presses a character, the search string will revert to what + /// the user has actually typed. + public string StringToFind; + + /// + /// Gets or sets the index of the first row that will be considered to matching. + /// + public int StartSearchFrom; + } + + /// + /// The parameter block when telling the world about a cell based event + /// + public class CellEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + /// This is null for events triggered by the header. + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + /// This is -1 for events triggered by the header. + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location { + get { return this.location; } + internal set { this.location = value; } + } + + private Point location; + + /// + /// Gets the state of the modifier keys at the time of the event + /// + public Keys ModifierKeys { + get { return this.modifierKeys; } + internal set { this.modifierKeys = value; } + } + + private Keys modifierKeys; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view and + /// for event triggered by the header + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the HitTest object that determined which cell was hit + /// + public OlvListViewHitTestInfo HitTest { + get { return hitTest; } + internal set { hitTest = value; } + } + + private OlvListViewHitTestInfo hitTest; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled; + } + + /// + /// Tells the world that a cell was clicked + /// + public class CellClickEventArgs : CellEventArgs { + /// + /// Gets or sets the number of clicks associated with this event + /// + public int ClickCount { + get { return this.clickCount; } + set { this.clickCount = value; } + } + + private int clickCount; + } + + /// + /// Tells the world that a cell was right clicked + /// + public class CellRightClickEventArgs : CellEventArgs { + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ContextMenuStrip MenuStrip; + } + + /// + /// Tell the world that the mouse is over a given cell + /// + public class CellOverEventArgs : CellEventArgs { } + + /// + /// Tells the world that the frozen-ness of the ObjectListView has changed. + /// + public class FreezeEventArgs : EventArgs { + /// + /// Make a FreezeEventArgs + /// + /// + public FreezeEventArgs(int freeze) { + this.FreezeLevel = freeze; + } + + /// + /// How frozen is the control? 0 means that the control is unfrozen, + /// more than 0 indicates froze. + /// + public int FreezeLevel { + get { return this.freezeLevel; } + set { this.freezeLevel = value; } + } + + private int freezeLevel; + } + + /// + /// The parameter block when telling the world that a tool tip is about to be shown. + /// + public class ToolTipShowingEventArgs : CellEventArgs { + /// + /// Gets the tooltip control that is triggering the tooltip event + /// + public ToolTipControl ToolTipControl { + get { return this.toolTipControl; } + internal set { this.toolTipControl = value; } + } + + private ToolTipControl toolTipControl; + + /// + /// Gets or sets the text should be shown on the tooltip for this event + /// + /// Setting this to empty or null prevents any tooltip from showing + public string Text; + + /// + /// In what direction should the text for this tooltip be drawn? + /// + public RightToLeft RightToLeft; + + /// + /// Should the tooltip for this event been shown in bubble style? + /// + /// This doesn't work reliable under Vista + public bool? IsBalloon; + + /// + /// What color should be used for the background of the tooltip + /// + /// Setting this does nothing under Vista + public Color? BackColor; + + /// + /// What color should be used for the foreground of the tooltip + /// + /// Setting this does nothing under Vista + public Color? ForeColor; + + /// + /// What string should be used as the title for the tooltip for this event? + /// + public string Title; + + /// + /// Which standard icon should be used for the tooltip for this event + /// + public ToolTipControl.StandardIcons? StandardIcon; + + /// + /// How many milliseconds should the tooltip remain before it automatically + /// disappears. + /// + public int? AutoPopDelay; + + /// + /// What font should be used to draw the text of the tooltip? + /// + public Font Font; + } + + /// + /// Common information to all hyperlink events + /// + public class HyperlinkEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the ObjectListView that is the source of the event + /// + public string Url { + get { return this.url; } + internal set { this.url = value; } + } + + private string url; + + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + } + + /// + /// + /// + public class IsHyperlinkEventArgs : EventArgs { + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.model; } + internal set { this.model = value; } + } + + private object model; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the text of the cell + /// + public string Text { + get { return this.text; } + internal set { this.text = value; } + } + + private string text; + + /// + /// Gets or sets whether or not this cell is a hyperlink. + /// Defaults to true for enabled rows and false for disabled rows. + /// + public bool IsHyperlink { + get { return this.isHyperlink; } + set { this.isHyperlink = value; } + } + + private bool isHyperlink; + + /// + /// Gets or sets the url that should be invoked when this cell is clicked. + /// + /// Setting this to None or String.Empty means that this cell is not a hyperlink + public string Url; + } + + /// + /// + public class FormatRowEventArgs : EventArgs { + //TODO: Unified with CellEventArgs + + /// + /// Gets the ObjectListView that is the source of the event + /// + public ObjectListView ListView { + get { return this.listView; } + internal set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the item of the cell + /// + public OLVListItem Item { + get { return item; } + internal set { this.item = value; } + } + + private OLVListItem item; + + /// + /// Gets the model object under the cell + /// + public object Model { + get { return this.Item.RowObject; } + } + + /// + /// Gets the row index of the cell + /// + public int RowIndex { + get { return this.rowIndex; } + internal set { this.rowIndex = value; } + } + + private int rowIndex = -1; + + /// + /// Gets the display index of the row + /// + public int DisplayIndex { + get { return this.displayIndex; } + internal set { this.displayIndex = value; } + } + + private int displayIndex = -1; + + /// + /// Should events be triggered for each cell in this row? + /// + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + + private bool useCellFormatEvents; + } + + /// + /// Parameter block for FormatCellEvent + /// + public class FormatCellEventArgs : FormatRowEventArgs { + /// + /// Gets the column index of the cell + /// + /// This is -1 when the view is not in details view. + public int ColumnIndex { + get { return this.columnIndex; } + internal set { this.columnIndex = value; } + } + + private int columnIndex = -1; + + /// + /// Gets the column of the cell + /// + /// This is null when the view is not in details view. + public OLVColumn Column { + get { return this.column; } + internal set { this.column = value; } + } + + private OLVColumn column; + + /// + /// Gets the subitem of the cell + /// + /// This is null when the view is not in details view + public OLVListSubItem SubItem { + get { return subItem; } + internal set { this.subItem = value; } + } + + private OLVListSubItem subItem; + + /// + /// Gets the model value that is being displayed by the cell. + /// + /// This is null when the view is not in details view + public object CellValue { + get { return this.SubItem == null ? null : this.SubItem.ModelValue; } + } + } + + /// + /// The event args when a hyperlink is clicked + /// + public class HyperlinkClickedEventArgs : CellEventArgs { + /// + /// Gets the url that was associated with this cell. + /// + public string Url { + get { return url; } + set { url = value; } + } + + private string url; + + } + + /// + /// The event args when the check box in a column header is changing + /// + public class HeaderCheckBoxChangingEventArgs : CancelEventArgs { + + /// + /// Get the column whose checkbox is changing + /// + public OLVColumn Column { + get { return column; } + internal set { column = value; } + } + + private OLVColumn column; + + /// + /// Get or set the new state that should be used by the column + /// + public CheckState NewCheckState { + get { return newCheckState; } + set { newCheckState = value; } + } + + private CheckState newCheckState; + } + + /// + /// The event args when the hot item changed + /// + public class HotItemChangedEventArgs : EventArgs { + /// + /// Gets or set if this event completely handled. If it was, no further processing + /// will be done for it. + /// + public bool Handled { + get { return handled; } + set { handled = value; } + } + + private bool handled; + + /// + /// Gets the part of the cell that the mouse is over + /// + public HitTestLocation HotCellHitLocation { + get { return newHotCellHitLocation; } + internal set { newHotCellHitLocation = value; } + } + + private HitTestLocation newHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + public virtual HitTestLocationEx HotCellHitLocationEx { + get { return this.hotCellHitLocationEx; } + internal set { this.hotCellHitLocationEx = value; } + } + + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse is over + /// + /// In non-details view, this will always be 0. + public int HotColumnIndex { + get { return newHotColumnIndex; } + internal set { newHotColumnIndex = value; } + } + + private int newHotColumnIndex; + + /// + /// Gets the index of the row that the mouse is over + /// + public int HotRowIndex { + get { return newHotRowIndex; } + internal set { newHotRowIndex = value; } + } + + private int newHotRowIndex; + + /// + /// Gets the group that the mouse is over + /// + public OLVGroup HotGroup { + get { return hotGroup; } + internal set { hotGroup = value; } + } + + private OLVGroup hotGroup; + + /// + /// Gets the part of the cell that the mouse used to be over + /// + public HitTestLocation OldHotCellHitLocation { + get { return oldHotCellHitLocation; } + internal set { oldHotCellHitLocation = value; } + } + + private HitTestLocation oldHotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse used to be over + /// + public virtual HitTestLocationEx OldHotCellHitLocationEx { + get { return this.oldHotCellHitLocationEx; } + internal set { this.oldHotCellHitLocationEx = value; } + } + + private HitTestLocationEx oldHotCellHitLocationEx; + + /// + /// Gets the index of the column that the mouse used to be over + /// + public int OldHotColumnIndex { + get { return oldHotColumnIndex; } + internal set { oldHotColumnIndex = value; } + } + + private int oldHotColumnIndex; + + /// + /// Gets the index of the row that the mouse used to be over + /// + public int OldHotRowIndex { + get { return oldHotRowIndex; } + internal set { oldHotRowIndex = value; } + } + + private int oldHotRowIndex; + + /// + /// Gets the group that the mouse used to be over + /// + public OLVGroup OldHotGroup { + get { return oldHotGroup; } + internal set { oldHotGroup = value; } + } + + private OLVGroup oldHotGroup; + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() { + return string.Format("NewHotCellHitLocation: {0}, HotCellHitLocationEx: {1}, NewHotColumnIndex: {2}, NewHotRowIndex: {3}, HotGroup: {4}", this.newHotCellHitLocation, this.hotCellHitLocationEx, this.newHotColumnIndex, this.newHotRowIndex, this.hotGroup); + } + } + + /// + /// Let the world know that a checkbox on a subitem is changing + /// + public class SubItemCheckingEventArgs : CancellableEventArgs { + /// + /// Create a new event block + /// + /// + /// + /// + /// + /// + public SubItemCheckingEventArgs(OLVColumn column, OLVListItem item, int subItemIndex, CheckState currentValue, CheckState newValue) { + this.column = column; + this.listViewItem = item; + this.subItemIndex = subItemIndex; + this.currentValue = currentValue; + this.newValue = newValue; + } + + /// + /// The column of the cell that is having its checkbox changed. + /// + public OLVColumn Column { + get { return this.column; } + } + + private OLVColumn column; + + /// + /// The model object of the row of the cell that is having its checkbox changed. + /// + public Object RowObject { + get { return this.listViewItem.RowObject; } + } + + /// + /// The listview item of the cell that is having its checkbox changed. + /// + public OLVListItem ListViewItem { + get { return this.listViewItem; } + } + + private OLVListItem listViewItem; + + /// + /// The current check state of the cell. + /// + public CheckState CurrentValue { + get { return this.currentValue; } + } + + private CheckState currentValue; + + /// + /// The proposed new check state of the cell. + /// + public CheckState NewValue { + get { return this.newValue; } + set { this.newValue = value; } + } + + private CheckState newValue; + + /// + /// The index of the cell that is going to be or has been edited. + /// + public int SubItemIndex { + get { return this.subItemIndex; } + } + + private int subItemIndex; + } + + /// + /// This event argument block is used when groups are created for a list. + /// + public class CreateGroupsEventArgs : EventArgs { + /// + /// Create a CreateGroupsEventArgs + /// + /// + public CreateGroupsEventArgs(GroupingParameters parms) { + this.parameters = parms; + } + + /// + /// Gets the settings that control the creation of groups + /// + public GroupingParameters Parameters { + get { return this.parameters; } + } + + private GroupingParameters parameters; + + /// + /// Gets or sets the groups that should be used + /// + public IList Groups { + get { return this.groups; } + set { this.groups = value; } + } + + private IList groups; + + /// + /// Has this event been cancelled by the event handler? + /// + public bool Canceled { + get { return canceled; } + set { canceled = value; } + } + + private bool canceled; + + } + + /// + /// This event argument block is used when the text of a group task is clicked + /// + public class GroupTaskClickedEventArgs : EventArgs { + /// + /// Create a GroupTaskClickedEventArgs + /// + /// + public GroupTaskClickedEventArgs(OLVGroup group) { + this.group = group; + } + + /// + /// Gets which group was clicked + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + } + + /// + /// This event argument block is used when a group is about to expand or collapse + /// + public class GroupExpandingCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a GroupExpandingCollapsingEventArgs + /// + /// + public GroupExpandingCollapsingEventArgs(OLVGroup group) { + if (group == null) throw new ArgumentNullException("group"); + this.olvGroup = group; + } + + /// + /// Gets which group is expanding/collapsing + /// + public OLVGroup Group { + get { return this.olvGroup; } + } + + private readonly OLVGroup olvGroup; + + /// + /// Gets whether this event is going to expand the group. + /// If this is false, the group must be collapsing. + /// + public bool IsExpanding { + get { return this.Group.Collapsed; } + } + } + + /// + /// This event argument block is used when the state of group has changed (collapsed, selected) + /// + public class GroupStateChangedEventArgs : EventArgs { + /// + /// Create a GroupStateChangedEventArgs + /// + /// + /// + /// + public GroupStateChangedEventArgs(OLVGroup group, GroupState oldState, GroupState newState) { + this.group = group; + this.oldState = oldState; + this.newState = newState; + } + + /// + /// Gets whether the group was collapsed by this event + /// + public bool Collapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was focused by this event + /// + public bool Focused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was selected by this event + /// + public bool Selected { + get { + return ((oldState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets whether the group was uncollapsed by this event + /// + public bool Uncollapsed { + get { + return ((oldState & GroupState.LVGS_COLLAPSED) == GroupState.LVGS_COLLAPSED) && + ((newState & GroupState.LVGS_COLLAPSED) != GroupState.LVGS_COLLAPSED); + } + } + + /// + /// Gets whether the group was unfocused by this event + /// + public bool Unfocused { + get { + return ((oldState & GroupState.LVGS_FOCUSED) == GroupState.LVGS_FOCUSED) && + ((newState & GroupState.LVGS_FOCUSED) != GroupState.LVGS_FOCUSED); + } + } + + /// + /// Gets whether the group was unselected by this event + /// + public bool Unselected { + get { + return ((oldState & GroupState.LVGS_SELECTED) == GroupState.LVGS_SELECTED) && + ((newState & GroupState.LVGS_SELECTED) != GroupState.LVGS_SELECTED); + } + } + + /// + /// Gets which group had its state changed + /// + public OLVGroup Group { + get { return this.group; } + } + + private readonly OLVGroup group; + + /// + /// Gets the previous state of the group + /// + public GroupState OldState { + get { return this.oldState; } + } + + private readonly GroupState oldState; + + + /// + /// Gets the new state of the group + /// + public GroupState NewState { + get { return this.newState; } + } + + private readonly GroupState newState; + } + + /// + /// This event argument block is used when a branch of a tree is about to be expanded + /// + public class TreeBranchExpandingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to expand. If null, all branches are going to be expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree has just been expanded + /// + public class TreeBranchExpandedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchExpandedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was expanded. If null, all branches were expanded. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was expanded + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// This event argument block is used when a branch of a tree is about to be collapsed + /// + public class TreeBranchCollapsingEventArgs : CancellableEventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsingEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is about to collapse. If this is null, all models are going to collapse. + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that is about to be collapsed. Can be null + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + } + + + /// + /// This event argument block is used when a branch of a tree has just been collapsed + /// + public class TreeBranchCollapsedEventArgs : EventArgs { + /// + /// Create a new event args + /// + /// + /// + public TreeBranchCollapsedEventArgs(object model, OLVListItem item) { + this.Model = model; + this.Item = item; + } + + /// + /// Gets the model that is was collapsed. If null, all branches were collapsed + /// + public object Model { + get { return model; } + private set { model = value; } + } + + private object model; + + /// + /// Gets the OLVListItem that was collapsed + /// + public OLVListItem Item { + get { return item; } + private set { item = value; } + } + + private OLVListItem item; + + } + + /// + /// Tells the world that a column header was right clicked + /// + public class ColumnRightClickEventArgs : ColumnClickEventArgs { + public ColumnRightClickEventArgs(int columnIndex, ToolStripDropDown menu, Point location) : base(columnIndex) { + MenuStrip = menu; + Location = location; + } + + /// + /// Set this to true to cancel the right click operation. + /// + public bool Cancel; + + /// + /// Gets or sets the menu that should be displayed as a result of this event. + /// + /// The menu will be positioned at Location, so changing that property changes + /// where the menu will be displayed. + public ToolStripDropDown MenuStrip; + + /// + /// Gets the location of the mouse at the time of the event + /// + public Point Location; + } + + #endregion +} diff --git a/ObjectListView/Implementation/GroupingParameters.cs b/ObjectListView/Implementation/GroupingParameters.cs new file mode 100644 index 0000000..a87f217 --- /dev/null +++ b/ObjectListView/Implementation/GroupingParameters.cs @@ -0,0 +1,204 @@ +/* + * GroupingParameters - All the data that is used to create groups in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// This class contains all the settings used when groups are created + /// + public class GroupingParameters { + /// + /// Create a GroupingParameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public GroupingParameters(ObjectListView olv, OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder, + string titleFormat, string titleSingularFormat, bool sortItemsByPrimaryColumn) { + this.ListView = olv; + this.GroupByColumn = groupByColumn; + this.GroupByOrder = groupByOrder; + this.PrimarySort = column; + this.PrimarySortOrder = order; + this.SecondarySort = secondaryColumn; + this.SecondarySortOrder = secondaryOrder; + this.SortItemsByPrimaryColumn = sortItemsByPrimaryColumn; + this.TitleFormat = titleFormat; + this.TitleSingularFormat = titleSingularFormat; + } + + /// + /// Gets or sets the ObjectListView being grouped + /// + public ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the column used to create groups + /// + public OLVColumn GroupByColumn { + get { return this.groupByColumn; } + set { this.groupByColumn = value; } + } + private OLVColumn groupByColumn; + + /// + /// In what order will the groups themselves be sorted? + /// + public SortOrder GroupByOrder { + get { return this.groupByOrder; } + set { this.groupByOrder = value; } + } + private SortOrder groupByOrder; + + /// + /// If this is set, this comparer will be used to order the groups + /// + public IComparer GroupComparer { + get { return this.groupComparer; } + set { this.groupComparer = value; } + } + private IComparer groupComparer; + + /// + /// If this is set, this comparer will be used to order items within each group + /// + public IComparer ItemComparer { + get { return this.itemComparer; } + set { this.itemComparer = value; } + } + private IComparer itemComparer; + + /// + /// Gets or sets the column that will be the primary sort + /// + public OLVColumn PrimarySort { + get { return this.primarySort; } + set { this.primarySort = value; } + } + private OLVColumn primarySort; + + /// + /// Gets or sets the ordering for the primary sort + /// + public SortOrder PrimarySortOrder { + get { return this.primarySortOrder; } + set { this.primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets the column used for secondary sorting + /// + public OLVColumn SecondarySort { + get { return this.secondarySort; } + set { this.secondarySort = value; } + } + private OLVColumn secondarySort; + + /// + /// Gets or sets the ordering for the secondary sort + /// + public SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder; + + /// + /// Gets or sets the title format used for groups with zero or more than one element + /// + public string TitleFormat { + get { return this.titleFormat; } + set { this.titleFormat = value; } + } + private string titleFormat; + + /// + /// Gets or sets the title format used for groups with only one element + /// + public string TitleSingularFormat { + get { return this.titleSingularFormat; } + set { this.titleSingularFormat = value; } + } + private string titleSingularFormat; + + /// + /// Gets or sets whether the items should be sorted by the primary column + /// + public bool SortItemsByPrimaryColumn { + get { return this.sortItemsByPrimaryColumn; } + set { this.sortItemsByPrimaryColumn = value; } + } + private bool sortItemsByPrimaryColumn; + + /// + /// Create an OLVGroup for the given information + /// + /// + /// + /// + /// + public OLVGroup CreateGroup(object key, int count, bool hasCollapsibleGroups) { + string title = GroupByColumn.ConvertGroupKeyToTitle(key); + if (!String.IsNullOrEmpty(TitleFormat)) + { + string format = (count == 1 ? TitleSingularFormat : TitleFormat); + try + { + title = String.Format(format, title, count); + } + catch (FormatException) + { + title = "Invalid group format: " + format; + } + } + OLVGroup lvg = new OLVGroup(title); + lvg.Column = GroupByColumn; + lvg.Collapsible = hasCollapsibleGroups; + lvg.Key = key; + lvg.SortValue = key as IComparable; + return lvg; + } + } +} diff --git a/ObjectListView/Implementation/Groups.cs b/ObjectListView/Implementation/Groups.cs new file mode 100644 index 0000000..33a7cb2 --- /dev/null +++ b/ObjectListView/Implementation/Groups.cs @@ -0,0 +1,761 @@ +/* + * Groups - Enhancements to the normal ListViewGroup + * + * Author: Phillip Piper + * Date: 22/08/2009 6:03PM + * + * Change log: + * v2.3 + * 2009-09-09 JPP - Added Collapsed and Collapsible properties + * 2009-09-01 JPP - Cleaned up code, added more docs + * - Works under VS2005 again + * 2009-08-22 JPP - Initial version + * + * To do: + * - Implement subseting + * - Implement footer items + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// These values indicate what is the state of the group. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupState + { + /// + /// Normal + /// + LVGS_NORMAL = 0x0, + + /// + /// Collapsed + /// + LVGS_COLLAPSED = 0x1, + + /// + /// Hidden + /// + LVGS_HIDDEN = 0x2, + + /// + /// NoHeader + /// + LVGS_NOHEADER = 0x4, + + /// + /// Can be collapsed + /// + LVGS_COLLAPSIBLE = 0x8, + + /// + /// Has focus + /// + LVGS_FOCUSED = 0x10, + + /// + /// Is Selected + /// + LVGS_SELECTED = 0x20, + + /// + /// Is subsetted + /// + LVGS_SUBSETED = 0x40, + + /// + /// Subset link has focus + /// + LVGS_SUBSETLINKFOCUSED = 0x80, + + /// + /// All styles + /// + LVGS_ALL = 0xFFFF + } + + /// + /// This mask indicates which members of a LVGROUP have valid data. These values + /// are taken directly from the SDK and many are not used by ObjectListView. + /// + [Flags] + public enum GroupMask + { + /// + /// No mask + /// + LVGF_NONE = 0, + + /// + /// Group has header + /// + LVGF_HEADER = 1, + + /// + /// Group has footer + /// + LVGF_FOOTER = 2, + + /// + /// Group has state + /// + LVGF_STATE = 4, + + /// + /// + /// + LVGF_ALIGN = 8, + + /// + /// + /// + LVGF_GROUPID = 0x10, + + /// + /// pszSubtitle is valid + /// + LVGF_SUBTITLE = 0x00100, + + /// + /// pszTask is valid + /// + LVGF_TASK = 0x00200, + + /// + /// pszDescriptionTop is valid + /// + LVGF_DESCRIPTIONTOP = 0x00400, + + /// + /// pszDescriptionBottom is valid + /// + LVGF_DESCRIPTIONBOTTOM = 0x00800, + + /// + /// iTitleImage is valid + /// + LVGF_TITLEIMAGE = 0x01000, + + /// + /// iExtendedImage is valid + /// + LVGF_EXTENDEDIMAGE = 0x02000, + + /// + /// iFirstItem and cItems are valid + /// + LVGF_ITEMS = 0x04000, + + /// + /// pszSubsetTitle is valid + /// + LVGF_SUBSET = 0x08000, + + /// + /// readonly, cItems holds count of items in visible subset, iFirstItem is valid + /// + LVGF_SUBSETITEMS = 0x10000 + } + + /// + /// This mask indicates which members of a GROUPMETRICS structure are valid + /// + [Flags] + public enum GroupMetricsMask + { + /// + /// + /// + LVGMF_NONE = 0, + + /// + /// + /// + LVGMF_BORDERSIZE = 1, + + /// + /// + /// + LVGMF_BORDERCOLOR = 2, + + /// + /// + /// + LVGMF_TEXTCOLOR = 4 + } + + /// + /// Instances of this class enhance the capabilities of a normal ListViewGroup, + /// enabling the functionality that was released in v6 of the common controls. + /// + /// + /// + /// In this implementation (2009-09), these objects are essentially passive. + /// Setting properties does not automatically change the associated group in + /// the listview. Collapsed and Collapsible are two exceptions to this and + /// give immediate results. + /// + /// + /// This really should be a subclass of ListViewGroup, but that class is + /// sealed (why is that?). So this class provides the same interface as a + /// ListViewGroup, plus many other new properties. + /// + /// + public class OLVGroup + { + #region Creation + + /// + /// Create an OLVGroup + /// + public OLVGroup() : this("Default group header") { + } + + /// + /// Create a group with the given title + /// + /// Title of the group + public OLVGroup(string header) { + this.Header = header; + this.Id = OLVGroup.nextId++; + this.TitleImage = -1; + this.ExtendedImage = -1; + } + private static int nextId; + + #endregion + + #region Public properties + + /// + /// Gets or sets the bottom description of the group + /// + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + /// + /// THIS PROPERTY IS CURRENTLY NOT USED. + /// + /// + public string BottomDescription { + get { return this.bottomDescription; } + set { this.bottomDescription = value; } + } + private string bottomDescription; + + /// + /// Gets or sets whether or not this group is collapsed + /// + public bool Collapsed { + get { return this.GetOneState(GroupState.LVGS_COLLAPSED); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSED); } + } + + /// + /// Gets or sets whether or not this group can be collapsed + /// + public bool Collapsible { + get { return this.GetOneState(GroupState.LVGS_COLLAPSIBLE); } + set { this.SetOneState(value, GroupState.LVGS_COLLAPSIBLE); } + } + + /// + /// Gets or sets the column that was used to construct this group. + /// + public OLVColumn Column { + get { return this.column; } + set { this.column = value; } + } + private OLVColumn column; + + /// + /// Gets or sets some representation of the contents of this group + /// + /// This is user defined (like Tag) + public IList Contents { + get { return this.contents; } + set { this.contents = value; } + } + private IList contents; + + /// + /// Gets whether this group has been created. + /// + public bool Created { + get { return this.ListView != null; } + } + + /// + /// Gets or sets the int or string that will select the extended image to be shown against the title + /// + public object ExtendedImage { + get { return this.extendedImage; } + set { this.extendedImage = value; } + } + private object extendedImage; + + /// + /// Gets or sets the footer of the group + /// + public string Footer { + get { return this.footer; } + set { this.footer = value; } + } + private string footer; + + /// + /// Gets the internal id of our associated ListViewGroup. + /// + public int GroupId { + get { + if (this.ListViewGroup == null) + return this.Id; + + // Use reflection to get around the access control on the ID property + if (OLVGroup.groupIdPropInfo == null) { + OLVGroup.groupIdPropInfo = typeof(ListViewGroup).GetProperty("ID", + BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(OLVGroup.groupIdPropInfo != null); + } + + int? groupId = OLVGroup.groupIdPropInfo.GetValue(this.ListViewGroup, null) as int?; + return groupId.HasValue ? groupId.Value : -1; + } + } + private static PropertyInfo groupIdPropInfo; + + /// + /// Gets or sets the header of the group + /// + public string Header { + get { return this.header; } + set { this.header = value; } + } + private string header; + + /// + /// Gets or sets the horizontal alignment of the group header + /// + public HorizontalAlignment HeaderAlignment { + get { return this.headerAlignment; } + set { this.headerAlignment = value; } + } + private HorizontalAlignment headerAlignment; + + /// + /// Gets or sets the internally created id of the group + /// + public int Id { + get { return this.id; } + set { this.id = value; } + } + private int id; + + /// + /// Gets or sets ListViewItems that are members of this group + /// + /// Listener of the BeforeCreatingGroups event can populate this collection. + /// It is only used on non-virtual lists. + public IList Items { + get { return this.items; } + set { this.items = value; } + } + private IList items = new List(); + + /// + /// Gets or sets the key that was used to partition objects into this group + /// + /// This is user defined (like Tag) + public object Key { + get { return this.key; } + set { this.key = value; } + } + private object key; + + /// + /// Gets the ObjectListView that this group belongs to + /// + /// If this is null, the group has not yet been created. + public ObjectListView ListView { + get { return this.listView; } + protected set { this.listView = value; } + } + private ObjectListView listView; + + /// + /// Gets or sets the name of the group + /// + /// As of 2009-09-01, this property is not used. + public string Name { + get { return this.name; } + set { this.name = value; } + } + private string name; + + /// + /// Gets or sets whether this group is focused + /// + public bool Focused + { + get { return this.GetOneState(GroupState.LVGS_FOCUSED); } + set { this.SetOneState(value, GroupState.LVGS_FOCUSED); } + } + + /// + /// Gets or sets whether this group is selected + /// + public bool Selected + { + get { return this.GetOneState(GroupState.LVGS_SELECTED); } + set { this.SetOneState(value, GroupState.LVGS_SELECTED); } + } + + /// + /// Gets or sets the text that will show that this group is subsetted + /// + /// + /// As of WinSDK v7.0, subsetting of group is officially unimplemented. + /// We can get around this using undocumented interfaces and may do so. + /// + public string SubsetTitle { + get { return this.subsetTitle; } + set { this.subsetTitle = value; } + } + private string subsetTitle; + + /// + /// Gets or set the subtitleof the task + /// + public string Subtitle { + get { return this.subtitle; } + set { this.subtitle = value; } + } + private string subtitle; + + /// + /// Gets or sets the value by which this group will be sorted. + /// + public IComparable SortValue { + get { return this.sortValue; } + set { this.sortValue = value; } + } + private IComparable sortValue; + + /// + /// Gets or sets the state of the group + /// + public GroupState State { + get { return this.state; } + set { this.state = value; } + } + private GroupState state; + + /// + /// Gets or sets which bits of State are valid + /// + public GroupState StateMask { + get { return this.stateMask; } + set { this.stateMask = value; } + } + private GroupState stateMask; + + /// + /// Gets or sets whether this group is showing only a subset of its elements + /// + /// + /// As of WinSDK v7.0, this property officially does nothing. + /// + public bool Subseted { + get { return this.GetOneState(GroupState.LVGS_SUBSETED); } + set { this.SetOneState(value, GroupState.LVGS_SUBSETED); } + } + + /// + /// Gets or sets the user-defined data attached to this group + /// + public object Tag { + get { return this.tag; } + set { this.tag = value; } + } + private object tag; + + /// + /// Gets or sets the task of this group + /// + /// This task is the clickable text that appears on the right margin + /// of the group header. + public string Task { + get { return this.task; } + set { this.task = value; } + } + private string task; + + /// + /// Gets or sets the int or string that will select the image to be shown against the title + /// + public object TitleImage { + get { return this.titleImage; } + set { this.titleImage = value; } + } + private object titleImage; + + /// + /// Gets or sets the top description of the group + /// + /// + /// Descriptions only appear when group is centered and there is a title image + /// + public string TopDescription { + get { return this.topDescription; } + set { this.topDescription = value; } + } + private string topDescription; + + /// + /// Gets or sets the number of items that are within this group. + /// + /// This should only be used for virtual groups. + public int VirtualItemCount { + get { return this.virtualItemCount; } + set { this.virtualItemCount = value; } + } + private int virtualItemCount; + + #endregion + + #region Protected properties + + /// + /// Gets or sets the ListViewGroup that is shadowed by this group. + /// + /// For virtual groups, this will always be null. + protected ListViewGroup ListViewGroup { + get { return this.listViewGroup; } + set { this.listViewGroup = value; } + } + private ListViewGroup listViewGroup; + #endregion + + #region Calculations/Conversions + + /// + /// Calculate the index into the group image list of the given image selector + /// + /// + /// + public int GetImageIndex(object imageSelector) { + if (imageSelector == null || this.ListView == null || this.ListView.GroupImageList == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null) + return this.ListView.GroupImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Convert this object to a string representation + /// + /// + public override string ToString() { + return this.Header; + } + + #endregion + + #region Commands + + /// + /// Insert a native group into the underlying Windows control, + /// *without* using a ListViewGroup + /// + /// + /// This is used when creating virtual groups + public void InsertGroupNewStyle(ObjectListView olv) { + this.ListView = olv; + NativeMethods.InsertGroup(olv, this.AsNativeGroup(true)); + } + + /// + /// Insert a native group into the underlying control via a ListViewGroup + /// + /// + public void InsertGroupOldStyle(ObjectListView olv) { + this.ListView = olv; + + // Create/update the associated ListViewGroup + if (this.ListViewGroup == null) + this.ListViewGroup = new ListViewGroup(); + this.ListViewGroup.Header = this.Header; + this.ListViewGroup.HeaderAlignment = this.HeaderAlignment; + this.ListViewGroup.Name = this.Name; + + // Remember which OLVGroup created the ListViewGroup + this.ListViewGroup.Tag = this; + + // Add the group to the control + olv.Groups.Add(this.ListViewGroup); + + // Add any extra information + NativeMethods.SetGroupInfo(olv, this.GroupId, this.AsNativeGroup(false)); + } + + /// + /// Change the members of the group to match the current contents of Items, + /// using a ListViewGroup + /// + public void SetItemsOldStyle() { + List list = this.Items as List; + if (list == null) { + foreach (OLVListItem item in this.Items) { + this.ListViewGroup.Items.Add(item); + } + } else { + this.ListViewGroup.Items.AddRange(list.ToArray()); + } + } + + #endregion + + #region Implementation + + /// + /// Create a native LVGROUP structure that matches this group + /// + internal NativeMethods.LVGROUP2 AsNativeGroup(bool withId) { + + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2)); + group.mask = (uint)(GroupMask.LVGF_HEADER ^ GroupMask.LVGF_ALIGN ^ GroupMask.LVGF_STATE); + group.pszHeader = this.Header; + group.uAlign = (uint)this.HeaderAlignment; + group.stateMask = (uint)this.StateMask; + group.state = (uint)this.State; + + if (withId) { + group.iGroupId = this.GroupId; + group.mask ^= (uint)GroupMask.LVGF_GROUPID; + } + + if (!String.IsNullOrEmpty(this.Footer)) { + group.pszFooter = this.Footer; + group.mask ^= (uint)GroupMask.LVGF_FOOTER; + } + + if (!String.IsNullOrEmpty(this.Subtitle)) { + group.pszSubtitle = this.Subtitle; + group.mask ^= (uint)GroupMask.LVGF_SUBTITLE; + } + + if (!String.IsNullOrEmpty(this.Task)) { + group.pszTask = this.Task; + group.mask ^= (uint)GroupMask.LVGF_TASK; + } + + if (!String.IsNullOrEmpty(this.TopDescription)) { + group.pszDescriptionTop = this.TopDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONTOP; + } + + if (!String.IsNullOrEmpty(this.BottomDescription)) { + group.pszDescriptionBottom = this.BottomDescription; + group.mask ^= (uint)GroupMask.LVGF_DESCRIPTIONBOTTOM; + } + + int imageIndex = this.GetImageIndex(this.TitleImage); + if (imageIndex >= 0) { + group.iTitleImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_TITLEIMAGE; + } + + imageIndex = this.GetImageIndex(this.ExtendedImage); + if (imageIndex >= 0) { + group.iExtendedImage = imageIndex; + group.mask ^= (uint)GroupMask.LVGF_EXTENDEDIMAGE; + } + + if (!String.IsNullOrEmpty(this.SubsetTitle)) { + group.pszSubsetTitle = this.SubsetTitle; + group.mask ^= (uint)GroupMask.LVGF_SUBSET; + } + + if (this.VirtualItemCount > 0) { + group.cItems = this.VirtualItemCount; + group.mask ^= (uint)GroupMask.LVGF_ITEMS; + } + + return group; + } + + private bool GetOneState(GroupState mask) { + if (this.Created) + this.State = this.GetState(); + return (this.State & mask) == mask; + } + + /// + /// Get the current state of this group from the underlying control + /// + protected GroupState GetState() { + return NativeMethods.GetGroupState(this.ListView, this.GroupId, GroupState.LVGS_ALL); + } + + /// + /// Get the current state of this group from the underlying control + /// + protected int SetState(GroupState newState, GroupState mask) { + NativeMethods.LVGROUP2 group = new NativeMethods.LVGROUP2(); + group.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUP2))); + group.mask = (uint)GroupMask.LVGF_STATE; + group.state = (uint)newState; + group.stateMask = (uint)mask; + return NativeMethods.SetGroupInfo(this.ListView, this.GroupId, group); + } + + private void SetOneState(bool value, GroupState mask) + { + this.StateMask ^= mask; + if (value) + this.State ^= mask; + else + this.State &= ~mask; + + if (this.Created) + this.SetState(this.State, mask); + } + + #endregion + + } +} diff --git a/ObjectListView/Implementation/Munger.cs b/ObjectListView/Implementation/Munger.cs new file mode 100644 index 0000000..8b81aec --- /dev/null +++ b/ObjectListView/Implementation/Munger.cs @@ -0,0 +1,568 @@ +/* + * Munger - An Interface pattern on getting and setting values from object through Reflection + * + * Author: Phillip Piper + * Date: 28/11/2008 17:15 + * + * Change log: + * v2.5.1 + * 2012-05-01 JPP - Added IgnoreMissingAspects property + * v2.5 + * 2011-05-20 JPP - Accessing through an indexer when the target had both a integer and + * a string indexer didn't work reliably. + * v2.4.1 + * 2010-08-10 JPP - Refactored into Munger/SimpleMunger. 3x faster! + * v2.3 + * 2009-02-15 JPP - Made Munger a public class + * 2009-01-20 JPP - Made the Munger capable of handling indexed access. + * Incidentally, this removed the ugliness that the last change introduced. + * 2009-01-18 JPP - Handle target objects from a DataListView (normally DataRowViews) + * v2.0 + * 2008-11-28 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace BrightIdeasSoftware +{ + /// + /// An instance of Munger gets a value from or puts a value into a target object. The property + /// to be peeked (or poked) is determined from a string. The peeking or poking is done using reflection. + /// + /// + /// Name of the aspect to be peeked can be a field, property or parameterless method. The name of an + /// aspect to poke can be a field, writable property or single parameter method. + /// + /// Aspect names can be dotted to chain a series of references. + /// + /// Order.Customer.HomeAddress.State + /// + public class Munger + { + #region Life and death + + /// + /// Create a do nothing Munger + /// + public Munger() + { + } + + /// + /// Create a Munger that works on the given aspect name + /// + /// The name of the + public Munger(String aspectName) + { + this.AspectName = aspectName; + } + + #endregion + + #region Static utility methods + + /// + /// A helper method to put the given value into the given aspect of the given object. + /// + /// This method catches and silently ignores any errors that occur + /// while modifying the target object + /// The object to be modified + /// The name of the property/field to be modified + /// The value to be assigned + /// Did the modification work? + public static bool PutProperty(object target, string propertyName, object value) { + try { + Munger munger = new Munger(propertyName); + return munger.PutValue(target, value); + } + catch (MungerException) { + // Not a lot we can do about this. Something went wrong in the bowels + // of the property. Let's take the ostrich approach and just ignore it :-) + + // Normally, we would never just silently ignore an exception. + // However, in this case, this is a utility method that explicitly + // contracts to catch and ignore errors. If this is not acceptable, + // the programmer should not use this method. + } + + return false; + } + + /// + /// Gets or sets whether Mungers will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if a Munger is asked to fetch a field/property/method + /// that does not exist from a model, it returns an error message, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error, and the munger should simply keep quiet. + /// + /// By default this is true during release builds. + /// + public static bool IgnoreMissingAspects { + get { return ignoreMissingAspects; } + set { ignoreMissingAspects = value; } + } + private static bool ignoreMissingAspects +#if !DEBUG + = true +#endif + ; + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or parameter-less method. + /// + /// + /// The name can be dotted, which chains references. If any link in the chain returns + /// null, the entire chain is considered to return null. + /// + /// + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + public string AspectName + { + get { return aspectName; } + set { + aspectName = value; + + // Clear any cache + aspectParts = null; + } + } + private string aspectName; + + #endregion + + + #region Public interface + + /// + /// Extract the value indicated by our AspectName from the given target. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValue(Object target) { + if (this.Parts.Count == 0) + return null; + + try { + return this.EvaluateParts(target, this.Parts); + } catch (MungerException ex) { + if (Munger.IgnoreMissingAspects) + return null; + + return String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", + ex.Munger.AspectName, ex.Target.GetType()); + } + } + + /// + /// Extract the value indicated by our AspectName from the given target, raising exceptions + /// if the munger fails. + /// + /// If the aspect name is null or empty, this will return null. + /// The object that will be peeked + /// The value read from the target + public Object GetValueEx(Object target) { + if (this.Parts.Count == 0) + return null; + + return this.EvaluateParts(target, this.Parts); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// + /// + /// If the AspectName is a dotted path, all the selectors bar the last + /// are used to find the object that should be updated, and the last + /// selector is used as the property to update on that object. + /// + /// + /// So, if 'target' is a Person and the AspectName is "HomeAddress.Postcode", + /// this method will first fetch "HomeAddress" property, and then try to set the + /// "Postcode" property on the home address object. + /// + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating whether the put worked + public bool PutValue(Object target, Object value) + { + if (this.Parts.Count == 0) + return false; + + SimpleMunger lastPart = this.Parts[this.Parts.Count - 1]; + + if (this.Parts.Count > 1) { + List parts = new List(this.Parts); + parts.RemoveAt(parts.Count - 1); + try { + target = this.EvaluateParts(target, parts); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + return false; + } + } + + if (target != null) { + try { + return lastPart.PutValue(target, value); + } catch (MungerException ex) { + this.ReportPutValueException(ex); + } + } + + return false; + } + + #endregion + + #region Implementation + + /// + /// Gets the list of SimpleMungers that match our AspectName + /// + private IList Parts { + get { + if (aspectParts == null) + aspectParts = BuildParts(this.AspectName); + return aspectParts; + } + } + private IList aspectParts; + + /// + /// Convert a possibly dotted AspectName into a list of SimpleMungers + /// + /// + /// + private IList BuildParts(string aspect) { + List parts = new List(); + if (!String.IsNullOrEmpty(aspect)) { + foreach (string part in aspect.Split('.')) { + parts.Add(new SimpleMunger(part.Trim())); + } + } + return parts; + } + + /// + /// Evaluate the given chain of SimpleMungers against an initial target. + /// + /// + /// + /// + private object EvaluateParts(object target, IList parts) { + foreach (SimpleMunger part in parts) { + if (target == null) + break; + target = part.GetValue(target); + } + return target; + } + + private void ReportPutValueException(MungerException ex) { + //TODO: How should we report this error? + System.Diagnostics.Debug.WriteLine("PutValue failed"); + System.Diagnostics.Debug.WriteLine(String.Format("- Culprit aspect: {0}", ex.Munger.AspectName)); + System.Diagnostics.Debug.WriteLine(String.Format("- Target: {0} of type {1}", ex.Target, ex.Target.GetType())); + System.Diagnostics.Debug.WriteLine(String.Format("- Inner exception: {0}", ex.InnerException)); + } + + #endregion + } + + /// + /// A SimpleMunger deals with a single property/field/method on its target. + /// + /// + /// Munger uses a chain of these resolve a dotted aspect name. + /// + public class SimpleMunger + { + #region Life and death + + /// + /// Create a SimpleMunger + /// + /// + public SimpleMunger(String aspectName) + { + this.aspectName = aspectName; + } + + #endregion + + #region Public properties + + /// + /// The name of the aspect that is to be peeked or poked. + /// + /// + /// + /// This name can be a field, property or method. + /// When using a method to get a value, the method must be parameter-less. + /// When using a method to set a value, the method must accept 1 parameter. + /// + /// + /// It cannot be a dotted name. + /// + /// + public string AspectName { + get { return aspectName; } + } + private readonly string aspectName; + + #endregion + + #region Public interface + + /// + /// Get a value from the given target + /// + /// + /// + public Object GetValue(Object target) { + if (target == null) + return null; + + this.ResolveName(target, this.AspectName, 0); + + try { + if (this.resolvedPropertyInfo != null) + return this.resolvedPropertyInfo.GetValue(target, null); + + if (this.resolvedMethodInfo != null) + return this.resolvedMethodInfo.Invoke(target, null); + + if (this.resolvedFieldInfo != null) + return this.resolvedFieldInfo.GetValue(target); + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) + return this.indexerPropertyInfo.GetValue(target, new object[] { this.AspectName }); + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + // If we get to here, we couldn't find a match for the aspect + throw new MungerException(this, target, new MissingMethodException()); + } + + /// + /// Poke the given value into the given target indicated by our AspectName. + /// + /// The object that will be poked + /// The value that will be poked into the target + /// bool indicating if the put worked + public bool PutValue(object target, object value) { + if (target == null) + return false; + + this.ResolveName(target, this.AspectName, 1); + + try { + if (this.resolvedPropertyInfo != null) { + this.resolvedPropertyInfo.SetValue(target, value, null); + return true; + } + + if (this.resolvedMethodInfo != null) { + this.resolvedMethodInfo.Invoke(target, new object[] { value }); + return true; + } + + if (this.resolvedFieldInfo != null) { + this.resolvedFieldInfo.SetValue(target, value); + return true; + } + + // If that didn't work, try to use the indexer property. + // This covers things like dictionaries and DataRows. + if (this.indexerPropertyInfo != null) { + this.indexerPropertyInfo.SetValue(target, value, new object[] { this.AspectName }); + return true; + } + } catch (Exception ex) { + // Lots of things can do wrong in these invocations + throw new MungerException(this, target, ex); + } + + return false; + } + + #endregion + + #region Implementation + + private void ResolveName(object target, string name, int numberMethodParameters) { + + if (cachedTargetType == target.GetType() && cachedName == name && cachedNumberParameters == numberMethodParameters) + return; + + cachedTargetType = target.GetType(); + cachedName = name; + cachedNumberParameters = numberMethodParameters; + + resolvedFieldInfo = null; + resolvedPropertyInfo = null; + resolvedMethodInfo = null; + indexerPropertyInfo = null; + + const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.NonPublic*/; + + foreach (PropertyInfo pinfo in target.GetType().GetProperties(flags)) { + if (pinfo.Name == name) { + resolvedPropertyInfo = pinfo; + return; + } + + // See if we can find an string indexer property while we are here. + // We also need to allow for old style keyed collections. + if (indexerPropertyInfo == null && pinfo.Name == "Item") { + ParameterInfo[] par = pinfo.GetGetMethod().GetParameters(); + if (par.Length > 0) { + Type parameterType = par[0].ParameterType; + if (parameterType == typeof(string) || parameterType == typeof(object)) + indexerPropertyInfo = pinfo; + } + } + } + + foreach (FieldInfo info in target.GetType().GetFields(flags)) { + if (info.Name == name) { + resolvedFieldInfo = info; + return; + } + } + + foreach (MethodInfo info in target.GetType().GetMethods(flags)) { + if (info.Name == name && info.GetParameters().Length == numberMethodParameters) { + resolvedMethodInfo = info; + return; + } + } + } + + private Type cachedTargetType; + private string cachedName; + private int cachedNumberParameters; + + private FieldInfo resolvedFieldInfo; + private PropertyInfo resolvedPropertyInfo; + private MethodInfo resolvedMethodInfo; + private PropertyInfo indexerPropertyInfo; + + #endregion + } + + /// + /// These exceptions are raised when a munger finds something it cannot process + /// + public class MungerException : ApplicationException + { + /// + /// Create a MungerException + /// + /// + /// + /// + public MungerException(SimpleMunger munger, object target, Exception ex) + : base("Munger failed", ex) { + this.munger = munger; + this.target = target; + } + + /// + /// Get the munger that raised the exception + /// + public SimpleMunger Munger { + get { return munger; } + } + private readonly SimpleMunger munger; + + /// + /// Gets the target that threw the exception + /// + public object Target { + get { return target; } + } + private readonly object target; + } + + /* + * We don't currently need this + * 2010-08-06 + * + + internal class SimpleBinder : Binder + { + public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, System.Globalization.CultureInfo culture) { + //return Type.DefaultBinder.BindToField( + throw new NotImplementedException(); + } + + public override object ChangeType(object value, Type type, System.Globalization.CultureInfo culture) { + throw new NotImplementedException(); + } + + public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] names, out object state) { + throw new NotImplementedException(); + } + + public override void ReorderArgumentArray(ref object[] args, object state) { + throw new NotImplementedException(); + } + + public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { + throw new NotImplementedException(); + } + + public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { + if (match == null) + throw new ArgumentNullException("match"); + + if (match.Length == 0) + return null; + + return match[0]; + } + } + */ + +} diff --git a/ObjectListView/Implementation/NativeMethods.cs b/ObjectListView/Implementation/NativeMethods.cs new file mode 100644 index 0000000..d48588f --- /dev/null +++ b/ObjectListView/Implementation/NativeMethods.cs @@ -0,0 +1,1223 @@ +/* + * NativeMethods - All the Windows SDK structures and imports + * + * Author: Phillip Piper + * Date: 10/10/2006 + * + * Change log: + * v2.8.0 + * 2014-05-21 JPP - Added DeselectOneItem + * - Added new imagelist drawing + * v2.3 + * 2006-10-10 JPP - Initial version + * + * To do: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// Wrapper for all native method calls on ListView controls + /// + internal static class NativeMethods + { + #region Constants + + private const int LVM_FIRST = 0x1000; + private const int LVM_GETCOLUMN = LVM_FIRST + 95; + private const int LVM_GETCOUNTPERPAGE = LVM_FIRST + 40; + private const int LVM_GETGROUPINFO = LVM_FIRST + 149; + private const int LVM_GETGROUPSTATE = LVM_FIRST + 92; + private const int LVM_GETHEADER = LVM_FIRST + 31; + private const int LVM_GETTOOLTIPS = LVM_FIRST + 78; + private const int LVM_GETTOPINDEX = LVM_FIRST + 39; + private const int LVM_HITTEST = LVM_FIRST + 18; + private const int LVM_INSERTGROUP = LVM_FIRST + 145; + private const int LVM_REMOVEALLGROUPS = LVM_FIRST + 160; + private const int LVM_SCROLL = LVM_FIRST + 20; + private const int LVM_SETBKIMAGE = LVM_FIRST + 0x8A; + private const int LVM_SETCOLUMN = LVM_FIRST + 96; + private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54; + private const int LVM_SETGROUPINFO = LVM_FIRST + 147; + private const int LVM_SETGROUPMETRICS = LVM_FIRST + 155; + private const int LVM_SETIMAGELIST = LVM_FIRST + 3; + private const int LVM_SETITEM = LVM_FIRST + 76; + private const int LVM_SETITEMCOUNT = LVM_FIRST + 47; + private const int LVM_SETITEMSTATE = LVM_FIRST + 43; + private const int LVM_SETSELECTEDCOLUMN = LVM_FIRST + 140; + private const int LVM_SETTOOLTIPS = LVM_FIRST + 74; + private const int LVM_SUBITEMHITTEST = LVM_FIRST + 57; + private const int LVS_EX_SUBITEMIMAGES = 0x0002; + + private const int LVIF_TEXT = 0x0001; + private const int LVIF_IMAGE = 0x0002; + private const int LVIF_PARAM = 0x0004; + private const int LVIF_STATE = 0x0008; + private const int LVIF_INDENT = 0x0010; + private const int LVIF_NORECOMPUTE = 0x0800; + + private const int LVIS_SELECTED = 2; + + private const int LVCF_FMT = 0x0001; + private const int LVCF_WIDTH = 0x0002; + private const int LVCF_TEXT = 0x0004; + private const int LVCF_SUBITEM = 0x0008; + private const int LVCF_IMAGE = 0x0010; + private const int LVCF_ORDER = 0x0020; + private const int LVCFMT_LEFT = 0x0000; + private const int LVCFMT_RIGHT = 0x0001; + private const int LVCFMT_CENTER = 0x0002; + private const int LVCFMT_JUSTIFYMASK = 0x0003; + + private const int LVCFMT_IMAGE = 0x0800; + private const int LVCFMT_BITMAP_ON_RIGHT = 0x1000; + private const int LVCFMT_COL_HAS_IMAGES = 0x8000; + + private const int LVBKIF_SOURCE_NONE = 0x0; + private const int LVBKIF_SOURCE_HBITMAP = 0x1; + private const int LVBKIF_SOURCE_URL = 0x2; + private const int LVBKIF_SOURCE_MASK = 0x3; + private const int LVBKIF_STYLE_NORMAL = 0x0; + private const int LVBKIF_STYLE_TILE = 0x10; + private const int LVBKIF_STYLE_MASK = 0x10; + private const int LVBKIF_FLAG_TILEOFFSET = 0x100; + private const int LVBKIF_TYPE_WATERMARK = 0x10000000; + private const int LVBKIF_FLAG_ALPHABLEND = 0x20000000; + + private const int LVSICF_NOINVALIDATEALL = 1; + private const int LVSICF_NOSCROLL = 2; + + private const int HDM_FIRST = 0x1200; + private const int HDM_HITTEST = HDM_FIRST + 6; + private const int HDM_GETITEMRECT = HDM_FIRST + 7; + private const int HDM_GETITEM = HDM_FIRST + 11; + private const int HDM_SETITEM = HDM_FIRST + 12; + + private const int HDI_WIDTH = 0x0001; + private const int HDI_TEXT = 0x0002; + private const int HDI_FORMAT = 0x0004; + private const int HDI_BITMAP = 0x0010; + private const int HDI_IMAGE = 0x0020; + + private const int HDF_LEFT = 0x0000; + private const int HDF_RIGHT = 0x0001; + private const int HDF_CENTER = 0x0002; + private const int HDF_JUSTIFYMASK = 0x0003; + private const int HDF_RTLREADING = 0x0004; + private const int HDF_STRING = 0x4000; + private const int HDF_BITMAP = 0x2000; + private const int HDF_BITMAP_ON_RIGHT = 0x1000; + private const int HDF_IMAGE = 0x0800; + private const int HDF_SORTUP = 0x0400; + private const int HDF_SORTDOWN = 0x0200; + + private const int SB_HORZ = 0; + private const int SB_VERT = 1; + private const int SB_CTL = 2; + private const int SB_BOTH = 3; + + private const int SIF_RANGE = 0x0001; + private const int SIF_PAGE = 0x0002; + private const int SIF_POS = 0x0004; + private const int SIF_DISABLENOSCROLL = 0x0008; + private const int SIF_TRACKPOS = 0x0010; + private const int SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS); + + private const int ILD_NORMAL = 0x0; + private const int ILD_TRANSPARENT = 0x1; + private const int ILD_MASK = 0x10; + private const int ILD_IMAGE = 0x20; + private const int ILD_BLEND25 = 0x2; + private const int ILD_BLEND50 = 0x4; + + const int SWP_NOSIZE = 1; + const int SWP_NOMOVE = 2; + const int SWP_NOZORDER = 4; + const int SWP_NOREDRAW = 8; + const int SWP_NOACTIVATE = 16; + public const int SWP_FRAMECHANGED = 32; + + const int SWP_ZORDERONLY = SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOACTIVATE; + const int SWP_SIZEONLY = SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER | SWP_NOACTIVATE; + const int SWP_UPDATE_FRAME = SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED; + + #endregion + + #region Structures + + [StructLayout(LayoutKind.Sequential)] + public struct HDITEM + { + public int mask; + public int cxy; + public IntPtr pszText; + public IntPtr hbm; + public int cchTextMax; + public int fmt; + public IntPtr lParam; + public int iImage; + public int iOrder; + //if (_WIN32_IE >= 0x0500) + public int type; + public IntPtr pvFilter; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + } + + [StructLayout(LayoutKind.Sequential)] + public class HDLAYOUT + { + public IntPtr prc; + public IntPtr pwpos; + } + + [StructLayout(LayoutKind.Sequential)] + public struct IMAGELISTDRAWPARAMS + { + public int cbSize; + public IntPtr himl; + public int i; + public IntPtr hdcDst; + public int x; + public int y; + public int cx; + public int cy; + public int xBitmap; + public int yBitmap; + public uint rgbBk; + public uint rgbFg; + public uint fStyle; + public uint dwRop; + public uint fState; + public uint Frame; + public uint crEffect; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVBKIMAGE + { + public int ulFlags; + public IntPtr hBmp; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszImage; + public int cchImageMax; + public int xOffset; + public int yOffset; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVCOLUMN + { + public int mask; + public int fmt; + public int cx; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iSubItem; + // These are available in Common Controls >= 0x0300 + public int iImage; + public int iOrder; + }; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVFINDINFO + { + public int flags; + public string psz; + public IntPtr lParam; + public int ptX; + public int ptY; + public int vkDirection; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public int cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUP2 + { + public uint cbSize; + public uint mask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszHeader; + public uint cchHeader; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszFooter; + public int cchFooter; + public int iGroupId; + public uint stateMask; + public uint state; + public uint uAlign; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubtitle; + public uint cchSubtitle; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszTask; + public uint cchTask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionTop; + public uint cchDescriptionTop; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszDescriptionBottom; + public uint cchDescriptionBottom; + public int iTitleImage; + public int iExtendedImage; + public int iFirstItem; // Read only + public int cItems; // Read only + [MarshalAs(UnmanagedType.LPTStr)] + public string pszSubsetTitle; // NULL if group is not subset + public uint cchSubsetTitle; + } + + [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + public struct LVGROUPMETRICS + { + public uint cbSize; + public uint mask; + public uint Left; + public uint Top; + public uint Right; + public uint Bottom; + public int crLeft; + public int crTop; + public int crRight; + public int crBottom; + public int crHeader; + public int crFooter; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags; + public int iItem; + public int iSubItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVITEM + { + public int mask; + public int iItem; + public int iSubItem; + public int state; + public int stateMask; + [MarshalAs(UnmanagedType.LPTStr)] + public string pszText; + public int cchTextMax; + public int iImage; + public IntPtr lParam; + // These are available in Common Controls >= 0x0300 + public int iIndent; + // These are available in Common Controls >= 0x056 + public int iGroupId; + public int cColumns; + public IntPtr puColumns; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct NMHDR + { + public IntPtr hwndFrom; + public IntPtr idFrom; + public int code; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMCUSTOMDRAW + { + public NativeMethods.NMHDR nmcd; + public int dwDrawStage; + public IntPtr hdc; + public NativeMethods.RECT rc; + public IntPtr dwItemSpec; + public int uItemState; + public IntPtr lItemlParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMHEADER + { + public NMHDR nhdr; + public int iItem; + public int iButton; + public IntPtr pHDITEM; + } + + const int MAX_LINKID_TEXT = 48; + const int L_MAX_URL_LENGTH = 2048 + 32 + 4; + //#define L_MAX_URL_LENGTH (2048 + 32 + sizeof("://")) + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct LITEM + { + public uint mask; + public int iLink; + public uint state; + public uint stateMask; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_LINKID_TEXT)] + public string szID; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = L_MAX_URL_LENGTH)] + public string szUrl; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLISTVIEW + { + public NativeMethods.NMHDR hdr; + public int iItem; + public int iSubItem; + public int uNewState; + public int uOldState; + public int uChanged; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVCUSTOMDRAW + { + public NativeMethods.NMCUSTOMDRAW nmcd; + public int clrText; + public int clrTextBk; + public int iSubItem; + public int dwItemType; + public int clrFace; + public int iIconEffect; + public int iIconPhase; + public int iPartId; + public int iStateId; + public NativeMethods.RECT rcText; + public uint uAlign; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVFINDITEM + { + public NativeMethods.NMHDR hdr; + public int iStart; + public NativeMethods.LVFINDINFO lvfi; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGETINFOTIP + { + public NativeMethods.NMHDR hdr; + public int dwFlags; + public string pszText; + public int cchTextMax; + public int iItem; + public int iSubItem; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVGROUP + { + public NMHDR hdr; + public int iGroupId; // which group is changing + public uint uNewState; // LVGS_xxx flags + public uint uOldState; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVLINK + { + public NMHDR hdr; + public LITEM link; + public int iItem; + public int iSubItem; + } + + [StructLayout(LayoutKind.Sequential)] + public struct NMLVSCROLL + { + public NativeMethods.NMHDR hdr; + public int dx; + public int dy; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct NMTTDISPINFO + { + public NativeMethods.NMHDR hdr; + [MarshalAs(UnmanagedType.LPTStr)] + public string lpszText; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] + public string szText; + public IntPtr hinst; + public int uFlags; + public IntPtr lParam; + //public int hbmp; This is documented but doesn't work + } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + } + + [StructLayout(LayoutKind.Sequential)] + public class SCROLLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO)); + public int fMask; + public int nMin; + public int nMax; + public int nPage; + public int nPos; + public int nTrackPos; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class TOOLINFO + { + public int cbSize = Marshal.SizeOf(typeof(NativeMethods.TOOLINFO)); + public int uFlags; + public IntPtr hwnd; + public IntPtr uId; + public NativeMethods.RECT rect; + public IntPtr hinst = IntPtr.Zero; + public IntPtr lpszText; + public IntPtr lParam = IntPtr.Zero; + } + + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPOS + { + public IntPtr hwnd; + public IntPtr hwndInsertAfter; + public int x; + public int y; + public int cx; + public int cy; + public int flags; + } + + #endregion + + #region Entry points + + // Various flavours of SendMessage: plain vanilla, and passing references to various structures + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVHITTESTINFO ht); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageRECT(IntPtr hWnd, int msg, int wParam, ref RECT r); + //[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + //private static extern IntPtr SendMessageLVColumn(IntPtr hWnd, int m, int wParam, ref LVCOLUMN lvc); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + private static extern IntPtr SendMessageHDItem(IntPtr hWnd, int msg, int wParam, ref HDITEM hdi); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageHDHITTESTINFO(IntPtr hWnd, int Msg, IntPtr wParam, [In, Out] HDHITTESTINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageTOOLINFO(IntPtr hWnd, int Msg, int wParam, NativeMethods.TOOLINFO lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageLVBKIMAGE(IntPtr hWnd, int Msg, int wParam, ref NativeMethods.LVBKIMAGE lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageString(IntPtr hWnd, int Msg, int wParam, string lParam); + [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessageIUnknown(IntPtr hWnd, int msg, [MarshalAs(UnmanagedType.IUnknown)] object wParam, int lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP2 lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUPMETRICS lParam); + + [DllImport("gdi32.dll")] + public static extern bool DeleteObject(IntPtr objectHandle); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetClientRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo); + + [DllImport("user32.dll", EntryPoint = "GetUpdateRect", CharSet = CharSet.Auto)] + private static extern bool GetUpdateRectInternal(IntPtr hWnd, ref Rectangle r, bool eraseBackground); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_Draw(IntPtr himl, int i, IntPtr hdcDst, int x, int y, int fStyle); + + [DllImport("comctl32.dll", CharSet = CharSet.Auto)] + private static extern bool ImageList_DrawIndirect(ref IMAGELISTDRAWPARAMS parms); + + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle r); + + [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll", EntryPoint = "ValidateRect", CharSet = CharSet.Auto)] + private static extern IntPtr ValidatedRectInternal(IntPtr hWnd, ref Rectangle r); + + #endregion + + //[DllImport("user32.dll", EntryPoint = "LockWindowUpdate", CharSet = CharSet.Auto)] + //private static extern int LockWindowUpdateInternal(IntPtr hWnd); + + //public static void LockWindowUpdate(IWin32Window window) { + // if (window == null) + // NativeMethods.LockWindowUpdateInternal(IntPtr.Zero); + // else + // NativeMethods.LockWindowUpdateInternal(window.Handle); + //} + + /// + /// Put an image under the ListView. + /// + /// + /// + /// The ListView must have its handle created before calling this. + /// + /// + /// This doesn't work very well. Specifically, it doesn't play well with owner drawn, + /// and grid lines are drawn over it. + /// + /// + /// + /// The image to be used as the background. If this is null, any existing background image will be cleared. + /// If this is true, the image is pinned to the bottom right and does not scroll. The other parameters are ignored + /// If this is true, the image will be tiled to fill the whole control background. The offset parameters will be ignored. + /// If both watermark and tiled are false, this indicates the horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// If both watermark and tiled are false, this indicates the vertical percentage where the image will be placed. + /// + public static bool SetBackgroundImage(ListView lv, Image image, bool isWatermark, bool isTiled, int xOffset, int yOffset) { + + LVBKIMAGE lvbkimage = new LVBKIMAGE(); + + // We have to clear any pre-existing background image, otherwise the attempt to set the image will fail. + // We don't know which type may already have been set, so we just clear both the watermark and the image. + lvbkimage.ulFlags = LVBKIF_TYPE_WATERMARK; + IntPtr result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + lvbkimage.ulFlags = LVBKIF_SOURCE_HBITMAP; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + + Bitmap bm = image as Bitmap; + if (bm != null) { + lvbkimage.hBmp = bm.GetHbitmap(); + lvbkimage.ulFlags = isWatermark ? LVBKIF_TYPE_WATERMARK : (isTiled ? LVBKIF_SOURCE_HBITMAP | LVBKIF_STYLE_TILE : LVBKIF_SOURCE_HBITMAP); + lvbkimage.xOffset = xOffset; + lvbkimage.yOffset = yOffset; + result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage); + } + + return (result != IntPtr.Zero); + } + + public static bool DrawImageList(Graphics g, ImageList il, int index, int x, int y, bool isSelected, bool isDisabled) { + ImageListDrawItemConstants flags = (isSelected ? ImageListDrawItemConstants.ILD_SELECTED : ImageListDrawItemConstants.ILD_NORMAL) | ImageListDrawItemConstants.ILD_TRANSPARENT; + ImageListDrawStateConstants state = isDisabled ? ImageListDrawStateConstants.ILS_SATURATE : ImageListDrawStateConstants.ILS_NORMAL; + try { + IntPtr hdc = g.GetHdc(); + return DrawImage(il, hdc, index, x, y, flags, 0, 0, state); + } + finally { + g.ReleaseHdc(); + } + } + + /// + /// Flags controlling how the Image List item is + /// drawn + /// + [Flags] + public enum ImageListDrawItemConstants + { + /// + /// Draw item normally. + /// + ILD_NORMAL = 0x0, + /// + /// Draw item transparently. + /// + ILD_TRANSPARENT = 0x1, + /// + /// Draw item blended with 25% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_BLEND25 = 0x2, + /// + /// Draw item blended with 50% of the specified foreground colour + /// or the Highlight colour if no foreground colour specified. + /// + ILD_SELECTED = 0x4, + /// + /// Draw the icon's mask + /// + ILD_MASK = 0x10, + /// + /// Draw the icon image without using the mask + /// + ILD_IMAGE = 0x20, + /// + /// Draw the icon using the ROP specified. + /// + ILD_ROP = 0x40, + /// + /// Preserves the alpha channel in dest. XP only. + /// + ILD_PRESERVEALPHA = 0x1000, + /// + /// Scale the image to cx, cy instead of clipping it. XP only. + /// + ILD_SCALE = 0x2000, + /// + /// Scale the image to the current DPI of the display. XP only. + /// + ILD_DPISCALE = 0x4000 + } + + /// + /// Enumeration containing XP ImageList Draw State options + /// + [Flags] + public enum ImageListDrawStateConstants + { + /// + /// The image state is not modified. + /// + ILS_NORMAL = (0x00000000), + /// + /// Adds a glow effect to the icon, which causes the icon to appear to glow + /// with a given color around the edges. (Note: does not appear to be implemented) + /// + ILS_GLOW = (0x00000001), //The color for the glow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Adds a drop shadow effect to the icon. (Note: does not appear to be implemented) + /// + ILS_SHADOW = (0x00000002), //The color for the drop shadow effect is passed to the IImageList::Draw method in the crEffect member of IMAGELISTDRAWPARAMS. + /// + /// Saturates the icon by increasing each color component + /// of the RGB triplet for each pixel in the icon. (Note: only ever appears to result in a completely unsaturated icon) + /// + ILS_SATURATE = (0x00000004), // The amount to increase is indicated by the frame member in the IMAGELISTDRAWPARAMS method. + /// + /// Alpha blends the icon. Alpha blending controls the transparency + /// level of an icon, according to the value of its alpha channel. + /// (Note: does not appear to be implemented). + /// + ILS_ALPHA = (0x00000008) //The value of the alpha channel is indicated by the frame member in the IMAGELISTDRAWPARAMS method. The alpha channel can be from 0 to 255, with 0 being completely transparent, and 255 being completely opaque. + } + + private const uint CLR_DEFAULT = 0xFF000000; + + /// + /// Draws an image using the specified flags and state on XP systems. + /// + /// The image list from which an item will be drawn + /// Device context to draw to + /// Index of image to draw + /// X Position to draw at + /// Y Position to draw at + /// Drawing flags + /// Width to draw + /// Height to draw + /// State flags + public static bool DrawImage(ImageList il, IntPtr hdc, int index, int x, int y, ImageListDrawItemConstants flags, int cx, int cy, ImageListDrawStateConstants stateFlags) { + IMAGELISTDRAWPARAMS pimldp = new IMAGELISTDRAWPARAMS(); + pimldp.hdcDst = hdc; + pimldp.cbSize = Marshal.SizeOf(pimldp.GetType()); + pimldp.i = index; + pimldp.x = x; + pimldp.y = y; + pimldp.cx = cx; + pimldp.cy = cy; + pimldp.rgbFg = CLR_DEFAULT; + pimldp.fStyle = (uint) flags; + pimldp.fState = (uint) stateFlags; + pimldp.himl = il.Handle; + return ImageList_DrawIndirect(ref pimldp); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + public static void ForceSubItemImagesExStyle(ListView list) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES); + } + + /// + /// Change the virtual list size of the given ListView (which must be in virtual mode) + /// + /// This will not change the scroll position + /// The listview to send a message to + /// How many rows should the list have? + public static void SetItemCount(ListView list, int count) { + SendMessage(list.Handle, LVM_SETITEMCOUNT, count, LVSICF_NOSCROLL); + } + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + /// The listview to send a m to + /// + /// + public static void SetExtendedStyle(ListView list, int style, int styleMask) { + SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, styleMask, style); + } + + /// + /// Calculates the number of items that can fit vertically in the visible area of a list-view (which + /// must be in details or list view. + /// + /// The listView + /// Number of visible items per page + public static int GetCountPerPage(ListView list) { + return (int)SendMessage(list.Handle, LVM_GETCOUNTPERPAGE, 0, 0); + } + /// + /// For the given item and subitem, make it display the given image + /// + /// The listview to send a m to + /// row number (0 based) + /// subitem (0 is the item itself) + /// index into the image list + public static void SetSubItemImage(ListView list, int itemIndex, int subItemIndex, int imageIndex) { + LVITEM lvItem = new LVITEM(); + lvItem.mask = LVIF_IMAGE; + lvItem.iItem = itemIndex; + lvItem.iSubItem = subItemIndex; + lvItem.iImage = imageIndex; + SendMessageLVItem(list.Handle, LVM_SETITEM, 0, ref lvItem); + } + + /// + /// Setup the given column of the listview to show the given image to the right of the text. + /// If the image index is -1, any previous image is cleared + /// + /// The listview to send a m to + /// Index of the column to modify + /// + /// Index into the small image list + public static void SetColumnImage(ListView list, int columnIndex, SortOrder order, int imageIndex) { + IntPtr hdrCntl = NativeMethods.GetHeaderControl(list); + if (hdrCntl.ToInt32() == 0) + return; + + HDITEM item = new HDITEM(); + item.mask = HDI_FORMAT; + IntPtr result = SendMessageHDItem(hdrCntl, HDM_GETITEM, columnIndex, ref item); + + item.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN | HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + + if (NativeMethods.HasBuiltinSortIndicators()) { + if (order == SortOrder.Ascending) + item.fmt |= HDF_SORTUP; + if (order == SortOrder.Descending) + item.fmt |= HDF_SORTDOWN; + } else { + item.mask |= HDI_IMAGE; + item.fmt |= (HDF_IMAGE | HDF_BITMAP_ON_RIGHT); + item.iImage = imageIndex; + } + + result = SendMessageHDItem(hdrCntl, HDM_SETITEM, columnIndex, ref item); + } + + /// + /// Does this version of the operating system have builtin sort indicators? + /// + /// Are there builtin sort indicators + /// XP and later have these + public static bool HasBuiltinSortIndicators() { + return OSFeature.Feature.GetVersionPresent(OSFeature.Themes) != null; + } + + /// + /// Return the bounds of the update region on the given control. + /// + /// The BeginPaint() system call validates the update region, effectively wiping out this information. + /// So this call has to be made before the BeginPaint() call. + /// The control whose update region is be calculated + /// A rectangle + public static Rectangle GetUpdateRect(Control cntl) { + Rectangle r = new Rectangle(); + GetUpdateRectInternal(cntl.Handle, ref r, false); + return r; + } + + /// + /// Validate an area of the given control. A validated area will not be repainted at the next redraw. + /// + /// The control to be validated + /// The area of the control to be validated + public static void ValidateRect(Control cntl, Rectangle r) { + ValidatedRectInternal(cntl.Handle, ref r); + } + + /// + /// Select all rows on the given listview + /// + /// The listview whose items are to be selected + public static void SelectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, LVIS_SELECTED); + } + + /// + /// Deselect all rows on the given listview + /// + /// The listview whose items are to be deselected + public static void DeselectAllItems(ListView list) { + NativeMethods.SetItemState(list, -1, LVIS_SELECTED, 0); + } + + /// + /// Deselect a single row + /// + /// + /// + public static void DeselectOneItem(ListView list, int index) { + NativeMethods.SetItemState(list, index, LVIS_SELECTED, 0); + } + + /// + /// Set the item state on the given item + /// + /// The listview whose item's state is to be changed + /// The index of the item to be changed + /// Which bits of the value are to be set? + /// The value to be set + public static void SetItemState(ListView list, int itemIndex, int mask, int value) { + LVITEM lvItem = new LVITEM(); + lvItem.stateMask = mask; + lvItem.state = value; + SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem); + } + + /// + /// Scroll the given listview by the given deltas + /// + /// + /// + /// + /// true if the scroll succeeded + public static bool Scroll(ListView list, int dx, int dy) { + return SendMessage(list.Handle, LVM_SCROLL, dx, dy) != IntPtr.Zero; + } + + /// + /// Return the handle to the header control on the given list + /// + /// The listview whose header control is to be returned + /// The handle to the header control + public static IntPtr GetHeaderControl(ListView list) { + return SendMessage(list.Handle, LVM_GETHEADER, 0, 0); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetColumnSides(ObjectListView lv, int columnIndex) { + Point sides = new Point(-1, -1); + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + return new Point(r.left, r.right); + } + + /// + /// Return the edges of the given column. + /// + /// + /// + /// A Point holding the left and right co-ords of the column. + /// -1 means that the sides could not be retrieved. + public static Point GetScrolledColumnSides(ListView lv, int columnIndex) { + IntPtr hdr = NativeMethods.GetHeaderControl(lv); + if (hdr == IntPtr.Zero) + return new Point(-1, -1); + + RECT r = new RECT(); + IntPtr result = NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r); + int scrollH = NativeMethods.GetScrollPosition(lv, true); + return new Point(r.left - scrollH, r.right - scrollH); + } + + /// + /// Return the index of the column of the header that is under the given point. + /// Return -1 if no column is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the column under the point, or -1 if no column header is under that point + public static int GetColumnUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONHEADER = 2; + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONHEADER | HHT_ONDIVIDER); + } + + private static int HeaderControlHitTest(IntPtr handle, Point pt, int flag) { + HDHITTESTINFO testInfo = new HDHITTESTINFO(); + testInfo.pt_x = pt.X; + testInfo.pt_y = pt.Y; + IntPtr result = NativeMethods.SendMessageHDHITTESTINFO(handle, HDM_HITTEST, IntPtr.Zero, testInfo); + if ((testInfo.flags & flag) != 0) + return testInfo.iItem; + else + return -1; + } + + /// + /// Return the index of the divider under the given point. Return -1 if no divider is under the pt + /// + /// The list we are interested in + /// The client co-ords + /// The index of the divider under the point, or -1 if no divider is under that point + public static int GetDividerUnderPoint(IntPtr handle, Point pt) { + const int HHT_ONDIVIDER = 4; + return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONDIVIDER); + } + + /// + /// Get the scroll position of the given scroll bar + /// + /// + /// + /// + public static int GetScrollPosition(ListView lv, bool horizontalBar) { + int fnBar = (horizontalBar ? SB_HORZ : SB_VERT); + + SCROLLINFO scrollInfo = new SCROLLINFO(); + scrollInfo.fMask = SIF_POS; + if (GetScrollInfo(lv.Handle, fnBar, scrollInfo)) + return scrollInfo.nPos; + else + return -1; + } + + /// + /// Change the z-order to the window 'toBeMoved' so it appear directly on top of 'reference' + /// + /// + /// + /// + public static bool ChangeZOrder(IWin32Window toBeMoved, IWin32Window reference) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, reference.Handle, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Make the given control/window a topmost window + /// + /// + /// + public static bool MakeTopMost(IWin32Window toBeMoved) { + IntPtr HWND_TOPMOST = (IntPtr)(-1); + return NativeMethods.SetWindowPos(toBeMoved.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_ZORDERONLY); + } + + /// + /// Change the size of the window without affecting any other attributes + /// + /// + /// + /// + /// + public static bool ChangeSize(IWin32Window toBeMoved, int width, int height) { + return NativeMethods.SetWindowPos(toBeMoved.Handle, IntPtr.Zero, 0, 0, width, height, SWP_SIZEONLY); + } + + /// + /// Show the given window without activating it + /// + /// The window to show + static public void ShowWithoutActivate(IWin32Window win) { + const int SW_SHOWNA = 8; + NativeMethods.ShowWindow(win.Handle, SW_SHOWNA); + } + + /// + /// Mark the given column as being selected. + /// + /// + /// The OLVColumn or null to clear + /// + /// This method works, but it prevents subitems in the given column from having + /// back colors. + /// + static public void SetSelectedColumn(ListView objectListView, ColumnHeader value) { + NativeMethods.SendMessage(objectListView.Handle, + LVM_SETSELECTEDCOLUMN, (value == null) ? -1 : value.Index, 0); + } + + static public int GetTopIndex(ListView lv) { + return (int)SendMessage(lv.Handle, LVM_GETTOPINDEX, 0, 0); + } + + static public IntPtr GetTooltipControl(ListView lv) { + return SendMessage(lv.Handle, LVM_GETTOOLTIPS, 0, 0); + } + + static public IntPtr SetTooltipControl(ListView lv, ToolTipControl tooltip) { + return SendMessage(lv.Handle, LVM_SETTOOLTIPS, 0, tooltip.Handle); + } + + static public bool HasHorizontalScrollBar(ListView lv) { + const int GWL_STYLE = -16; + const int WS_HSCROLL = 0x00100000; + + return (NativeMethods.GetWindowLong(lv.Handle, GWL_STYLE) & WS_HSCROLL) != 0; + } + + public static int GetWindowLong(IntPtr hWnd, int nIndex) { + if (IntPtr.Size == 4) + return (int)GetWindowLong32(hWnd, nIndex); + else + return (int)(long)GetWindowLongPtr64(hWnd, nIndex); + } + + public static int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong) { + if (IntPtr.Size == 4) + return (int)SetWindowLongPtr32(hWnd, nIndex, dwNewLong); + else + return (int)(long)SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + } + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetBkColor(IntPtr hDC, int clr); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetTextColor(IntPtr hDC, int crColor); + + [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj); + + [DllImport("uxtheme.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr SetWindowTheme(IntPtr hWnd, string subApp, string subIdList); + + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + public static extern bool InvalidateRect(IntPtr hWnd, int ignored, bool erase); + + [StructLayout(LayoutKind.Sequential)] + public struct LVITEMINDEX + { + public int iItem; + public int iGroup; + } + + [StructLayout(LayoutKind.Sequential)] + public struct POINT + { + public int x; + public int y; + } + + public static int GetGroupInfo(ObjectListView olv, int groupId, ref LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPINFO, groupId, ref group); + } + + public static GroupState GetGroupState(ObjectListView olv, int groupId, GroupState mask) { + return (GroupState)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPSTATE, groupId, (int)mask); + } + + public static int InsertGroup(ObjectListView olv, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_INSERTGROUP, -1, ref group); + } + + public static int SetGroupInfo(ObjectListView olv, int groupId, LVGROUP2 group) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPINFO, groupId, ref group); + } + + public static int SetGroupMetrics(ObjectListView olv, LVGROUPMETRICS metrics) { + return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPMETRICS, 0, ref metrics); + } + + public static void ClearGroups(VirtualObjectListView virtualObjectListView) { + NativeMethods.SendMessage(virtualObjectListView.Handle, LVM_REMOVEALLGROUPS, 0, 0); + } + + public static void SetGroupImageList(ObjectListView olv, ImageList il) { + const int LVSIL_GROUPHEADER = 3; + NativeMethods.SendMessage(olv.Handle, LVM_SETIMAGELIST, LVSIL_GROUPHEADER, il == null ? IntPtr.Zero : il.Handle); + } + + public static int HitTest(ObjectListView olv, ref LVHITTESTINFO hittest) + { + return (int)NativeMethods.SendMessage(olv.Handle, olv.View == View.Details ? LVM_SUBITEMHITTEST : LVM_HITTEST, -1, ref hittest); + } + } +} diff --git a/ObjectListView/Implementation/NullableDictionary.cs b/ObjectListView/Implementation/NullableDictionary.cs new file mode 100644 index 0000000..79b3c1e --- /dev/null +++ b/ObjectListView/Implementation/NullableDictionary.cs @@ -0,0 +1,87 @@ +/* + * NullableDictionary - A simple Dictionary that can handle null as a key + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2017 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace BrightIdeasSoftware { + + /// + /// A simple-minded implementation of a Dictionary that can handle null as a key. + /// + /// The type of the dictionary key + /// The type of the values to be stored + /// This is not a full implementation and is only meant to handle + /// collecting groups by their keys, since groups can have null as a key value. + internal class NullableDictionary : Dictionary { + private bool hasNullKey; + private TValue nullValue; + + new public TValue this[TKey key] { + get { + if (key != null) + return base[key]; + + if (this.hasNullKey) + return this.nullValue; + + throw new KeyNotFoundException(); + } + set { + if (key == null) { + this.hasNullKey = true; + this.nullValue = value; + } else + base[key] = value; + } + } + + new public bool ContainsKey(TKey key) { + return key == null ? this.hasNullKey : base.ContainsKey(key); + } + + new public IList Keys { + get { + ArrayList list = new ArrayList(base.Keys); + if (this.hasNullKey) + list.Add(null); + return list; + } + } + + new public IList Values { + get { + List list = new List(base.Values); + if (this.hasNullKey) + list.Add(this.nullValue); + return list; + } + } + } +} diff --git a/ObjectListView/Implementation/OLVListItem.cs b/ObjectListView/Implementation/OLVListItem.cs new file mode 100644 index 0000000..d488123 --- /dev/null +++ b/ObjectListView/Implementation/OLVListItem.cs @@ -0,0 +1,325 @@ +/* + * OLVListItem - A row in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-09-01 JPP - Handle rare case of getting subitems when there are no columns + * v2.9 + * 2015-08-22 JPP - Added OLVListItem.SelectedBackColor and SelectedForeColor + * 2015-06-09 JPP - Added HasAnyHyperlinks property + * v2.8 + * 2014-09-27 JPP - Remove faulty caching of CheckState + * 2014-05-06 JPP - Added OLVListItem.Enabled flag + * vOld + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// OLVListItems are specialized ListViewItems that know which row object they came from, + /// and the row index at which they are displayed, even when in group view mode. They + /// also know the image they should draw against themselves + /// + public class OLVListItem : ListViewItem { + #region Constructors + + /// + /// Create a OLVListItem for the given row object + /// + public OLVListItem(object rowObject) { + this.rowObject = rowObject; + } + + /// + /// Create a OLVListItem for the given row object, represented by the given string and image + /// + public OLVListItem(object rowObject, string text, Object image) + : base(text, -1) { + this.rowObject = rowObject; + this.imageSelector = image; + } + + #endregion. + + #region Properties + + /// + /// Gets the bounding rectangle of the item, including all subitems + /// + new public Rectangle Bounds { + get { + try { + return base.Bounds; + } + catch (System.ArgumentException) { + // If the item is part of a collapsed group, Bounds will throw an exception + return Rectangle.Empty; + } + } + } + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how the cells of this item will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the checkedness of this item. + /// + /// + /// Virtual lists don't handle checkboxes well, so we have to intercept attempts to change them + /// through the items, and change them into something that will work. + /// Unfortunately, this won't work if this property is set through the base class, since + /// the property is not declared as virtual. + /// + new public bool Checked { + get { + return base.Checked; + } + set { + if (this.Checked != value) { + if (value) + ((ObjectListView)this.ListView).CheckObject(this.RowObject); + else + ((ObjectListView)this.ListView).UncheckObject(this.RowObject); + } + } + } + + /// + /// Enable tri-state checkbox. + /// + /// .NET's Checked property was not built to handle tri-state checkboxes, + /// and will return True for both Checked and Indeterminate states. + public CheckState CheckState { + get { + switch (this.StateImageIndex) { + case 0: + return System.Windows.Forms.CheckState.Unchecked; + case 1: + return System.Windows.Forms.CheckState.Checked; + case 2: + return System.Windows.Forms.CheckState.Indeterminate; + default: + return System.Windows.Forms.CheckState.Unchecked; + } + } + set { + switch (value) { + case System.Windows.Forms.CheckState.Unchecked: + this.StateImageIndex = 0; + break; + case System.Windows.Forms.CheckState.Checked: + this.StateImageIndex = 1; + break; + case System.Windows.Forms.CheckState.Indeterminate: + this.StateImageIndex = 2; + break; + } + } + } + + /// + /// Gets if this item has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + if (this.HasDecoration) + return this.Decorations[0]; + else + return null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Gets whether or not this row can be selected and activated + /// + public bool Enabled + { + get { return this.enabled; } + internal set { this.enabled = value; } + } + private bool enabled; + + /// + /// Gets whether any cell on this item is showing a hyperlink + /// + public bool HasAnyHyperlinks { + get { + foreach (OLVListSubItem subItem in this.SubItems) { + if (!String.IsNullOrEmpty(subItem.Url)) + return true; + } + return false; + } + } + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { + imageSelector = value; + if (value is Int32) + this.ImageIndex = (Int32)value; + else if (value is String) + this.ImageKey = (String)value; + else + this.ImageIndex = -1; + } + } + private Object imageSelector; + + /// + /// Gets or sets the model object that is source of the data for this list item. + /// + public object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + private object rowObject; + + /// + /// Gets or sets the color that will be used for this row's background when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection BackColor will be used. + /// + /// + public Color? SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color? selectedBackColor; + + /// + /// Gets or sets the color that will be used for this row's foreground when it is selected and + /// the control is focused. + /// + /// + /// To work reliably, this property must be set during a FormatRow event. + /// + /// If this is not set, the normal selection ForeColor will be used. + /// + /// + public Color? SelectedForeColor + { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color? selectedForeColor; + + #endregion + + #region Accessing + + /// + /// Return the sub item at the given index + /// + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index) { + if (index >= 0 && index < this.SubItems.Count) + // If the control has 0 columns, ListViewItem.SubItems will auto create a + // SubItem of the wrong type. Casting using 'as' handles this rare case. + return this.SubItems[index] as OLVListSubItem; + + return null; + } + + + /// + /// Return bounds of the given subitem + /// + /// This correctly calculates the bounds even for column 0. + public virtual Rectangle GetSubItemBounds(int subItemIndex) { + if (subItemIndex == 0) { + Rectangle r = this.Bounds; + Point sides = NativeMethods.GetScrolledColumnSides(this.ListView, subItemIndex); + r.X = sides.X + 1; + r.Width = sides.Y - sides.X; + return r; + } + + OLVListSubItem subItem = this.GetSubItem(subItemIndex); + return subItem == null ? new Rectangle() : subItem.Bounds; + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/OLVListSubItem.cs b/ObjectListView/Implementation/OLVListSubItem.cs new file mode 100644 index 0000000..e4f5bfe --- /dev/null +++ b/ObjectListView/Implementation/OLVListSubItem.cs @@ -0,0 +1,173 @@ +/* + * OLVListSubItem - A single cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.ComponentModel; + +namespace BrightIdeasSoftware { + + /// + /// A ListViewSubItem that knows which image should be drawn against it. + /// + [Browsable(false)] + public class OLVListSubItem : ListViewItem.ListViewSubItem { + #region Constructors + + /// + /// Create a OLVListSubItem + /// + public OLVListSubItem() { + } + + /// + /// Create a OLVListSubItem that shows the given string and image + /// + public OLVListSubItem(object modelValue, string text, Object image) { + this.ModelValue = modelValue; + this.Text = text; + this.ImageSelector = image; + } + + #endregion + + #region Properties + + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// This setting only takes effect when the control is owner drawn. + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how this cell will be vertically aligned + /// + /// This setting only takes effect when the control is owner drawn. + public StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets the model value is being displayed by this subitem. + /// + public object ModelValue + { + get { return modelValue; } + private set { modelValue = value; } + } + private object modelValue; + + /// + /// Gets if this subitem has any decorations set for it. + /// + public bool HasDecoration { + get { + return this.decorations != null && this.decorations.Count > 0; + } + } + + /// + /// Gets or sets the decoration that will be drawn over this item + /// + /// Setting this replaces all other decorations + public IDecoration Decoration { + get { + return this.HasDecoration ? this.Decorations[0] : null; + } + set { + this.Decorations.Clear(); + if (value != null) + this.Decorations.Add(value); + } + } + + /// + /// Gets the collection of decorations that will be drawn over this item + /// + public IList Decorations { + get { + if (this.decorations == null) + this.decorations = new List(); + return this.decorations; + } + } + private IList decorations; + + /// + /// Get or set the image that should be shown against this item + /// + /// This can be an Image, a string or an int. A string or an int will + /// be used as an index into the small image list. + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + private Object imageSelector; + + /// + /// Gets or sets the url that should be invoked when this subitem is clicked + /// + public string Url + { + get { return this.url; } + set { this.url = value; } + } + private string url; + + /// + /// Gets or sets whether this cell is selected + /// + public bool Selected + { + get { return this.selected; } + set { this.selected = value; } + } + private bool selected; + + #endregion + + #region Implementation Properties + + /// + /// Return the state of the animation of the image on this subitem. + /// Null means there is either no image, or it is not an animation + /// + internal ImageRenderer.AnimationState AnimationState; + + #endregion + } + +} diff --git a/ObjectListView/Implementation/OlvListViewHitTestInfo.cs b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs new file mode 100644 index 0000000..7cc28eb --- /dev/null +++ b/ObjectListView/Implementation/OlvListViewHitTestInfo.cs @@ -0,0 +1,388 @@ +/* + * OlvListViewHitTestInfo - All information gathered during a OlvHitTest() operation + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware { + + /// + /// An indication of where a hit was within ObjectListView cell + /// + public enum HitTestLocation { + /// + /// Nowhere + /// + Nothing, + + /// + /// On the text + /// + Text, + + /// + /// On the image + /// + Image, + + /// + /// On the checkbox + /// + CheckBox, + + /// + /// On the expand button (TreeListView) + /// + ExpandButton, + + /// + /// in a button (cell must have ButtonRenderer) + /// + Button, + + /// + /// in the cell but not in any more specific location + /// + InCell, + + /// + /// UserDefined location1 (used for custom renderers) + /// + UserDefined, + + /// + /// On the expand/collapse widget of the group + /// + GroupExpander, + + /// + /// Somewhere on a group + /// + Group, + + /// + /// Somewhere in a column header + /// + Header, + + /// + /// Somewhere in a column header checkbox + /// + HeaderCheckBox, + + /// + /// Somewhere in a header divider + /// + HeaderDivider, + } + + /// + /// A collection of ListViewHitTest constants + /// + [Flags] + public enum HitTestLocationEx { + /// + /// + /// + LVHT_NOWHERE = 0x00000001, + /// + /// + /// + LVHT_ONITEMICON = 0x00000002, + /// + /// + /// + LVHT_ONITEMLABEL = 0x00000004, + /// + /// + /// + LVHT_ONITEMSTATEICON = 0x00000008, + /// + /// + /// + LVHT_ONITEM = (LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON), + + /// + /// + /// + LVHT_ABOVE = 0x00000008, + /// + /// + /// + LVHT_BELOW = 0x00000010, + /// + /// + /// + LVHT_TORIGHT = 0x00000020, + /// + /// + /// + LVHT_TOLEFT = 0x00000040, + + /// + /// + /// + LVHT_EX_GROUP_HEADER = 0x10000000, + /// + /// + /// + LVHT_EX_GROUP_FOOTER = 0x20000000, + /// + /// + /// + LVHT_EX_GROUP_COLLAPSE = 0x40000000, + /// + /// + /// + LVHT_EX_GROUP_BACKGROUND = -2147483648, // 0x80000000 + /// + /// + /// + LVHT_EX_GROUP_STATEICON = 0x01000000, + /// + /// + /// + LVHT_EX_GROUP_SUBSETLINK = 0x02000000, + /// + /// + /// + LVHT_EX_GROUP = (LVHT_EX_GROUP_BACKGROUND | LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_FOOTER | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD = (LVHT_EX_GROUP_COLLAPSE | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON | LVHT_EX_GROUP_SUBSETLINK), + /// + /// + /// + LVHT_EX_ONCONTENTS = 0x04000000, // On item AND not on the background + /// + /// + /// + LVHT_EX_FOOTER = 0x08000000, + } + + /// + /// Instances of this class encapsulate the information gathered during a OlvHitTest() + /// operation. + /// + /// Custom renderers can use HitTestLocation.UserDefined and the UserData + /// object to store more specific locations for use during event handlers. + public class OlvListViewHitTestInfo { + + /// + /// Create a OlvListViewHitTestInfo + /// + public OlvListViewHitTestInfo(OLVListItem olvListItem, OLVListSubItem subItem, int flags, OLVGroup group, int iColumn) + { + this.item = olvListItem; + this.subItem = subItem; + this.location = ConvertNativeFlagsToDotNetLocation(olvListItem, flags); + this.HitTestLocationEx = (HitTestLocationEx)flags; + this.Group = group; + this.ColumnIndex = iColumn; + this.ListView = olvListItem == null ? null : (ObjectListView)olvListItem.ListView; + + switch (location) { + case ListViewHitTestLocations.StateImage: + this.HitTestLocation = HitTestLocation.CheckBox; + break; + case ListViewHitTestLocations.Image: + this.HitTestLocation = HitTestLocation.Image; + break; + case ListViewHitTestLocations.Label: + this.HitTestLocation = HitTestLocation.Text; + break; + default: + if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) == HitTestLocationEx.LVHT_EX_GROUP_COLLAPSE) + this.HitTestLocation = HitTestLocation.GroupExpander; + else if ((this.HitTestLocationEx & HitTestLocationEx.LVHT_EX_GROUP_MINUS_FOOTER_AND_BKGRD) != 0) + this.HitTestLocation = HitTestLocation.Group; + else + this.HitTestLocation = HitTestLocation.Nothing; + break; + } + } + + /// + /// Create a OlvListViewHitTestInfo when the header was hit + /// + public OlvListViewHitTestInfo(ObjectListView olv, int iColumn, bool isOverCheckBox, int iDivider) { + this.ListView = olv; + this.ColumnIndex = iColumn; + this.HeaderDividerIndex = iDivider; + this.HitTestLocation = isOverCheckBox ? HitTestLocation.HeaderCheckBox : (iDivider < 0 ? HitTestLocation.Header : HitTestLocation.HeaderDivider); + } + + private static ListViewHitTestLocations ConvertNativeFlagsToDotNetLocation(OLVListItem hitItem, int flags) + { + // Untangle base .NET behaviour. + + // In Windows SDK, the value 8 can have two meanings here: LVHT_ONITEMSTATEICON or LVHT_ABOVE. + // .NET changes these to be: + // - LVHT_ABOVE becomes ListViewHitTestLocations.AboveClientArea (which is 0x100). + // - LVHT_ONITEMSTATEICON becomes ListViewHitTestLocations.StateImage (which is 0x200). + // So, if we see the 8 bit set in flags, we change that to either a state image hit + // (if we hit an item) or to AboveClientAream if nothing was hit. + + if ((8 & flags) == 8) + return (ListViewHitTestLocations)(0xf7 & flags | (hitItem == null ? 0x100 : 0x200)); + + // Mask off the LVHT_EX_XXXX values since ListViewHitTestLocations doesn't have them + return (ListViewHitTestLocations)(flags & 0xffff); + } + + #region Public fields + + /// + /// Where is the hit location? + /// + public HitTestLocation HitTestLocation; + + /// + /// Where is the hit location? + /// + public HitTestLocationEx HitTestLocationEx; + + /// + /// Which group was hit? + /// + public OLVGroup Group; + + /// + /// Custom renderers can use this information to supply more details about the hit location + /// + public Object UserData; + + #endregion + + #region Public read-only properties + + /// + /// Gets the item that was hit + /// + public OLVListItem Item { + get { return item; } + internal set { item = value; } + } + private OLVListItem item; + + /// + /// Gets the subitem that was hit + /// + public OLVListSubItem SubItem { + get { return subItem; } + internal set { subItem = value; } + } + private OLVListSubItem subItem; + + /// + /// Gets the part of the subitem that was hit + /// + public ListViewHitTestLocations Location { + get { return location; } + internal set { location = value; } + } + private ListViewHitTestLocations location; + + /// + /// Gets the ObjectListView that was tested + /// + public ObjectListView ListView { + get { return listView; } + internal set { listView = value; } + } + private ObjectListView listView; + + /// + /// Gets the model object that was hit + /// + public Object RowObject { + get { + return this.Item == null ? null : this.Item.RowObject; + } + } + + /// + /// Gets the index of the row under the hit point or -1 + /// + public int RowIndex { + get { return this.Item == null ? -1 : this.Item.Index; } + } + + /// + /// Gets the index of the column under the hit point + /// + public int ColumnIndex { + get { return columnIndex; } + internal set { columnIndex = value; } + } + private int columnIndex; + + /// + /// Gets the index of the header divider + /// + public int HeaderDividerIndex { + get { return headerDividerIndex; } + internal set { headerDividerIndex = value; } + } + private int headerDividerIndex = -1; + + /// + /// Gets the column that was hit + /// + public OLVColumn Column { + get { + int index = this.ColumnIndex; + return index < 0 || this.ListView == null ? null : this.ListView.GetColumn(index); + } + } + + #endregion + + /// + /// Returns a string that represents the current object. + /// + /// + /// A string that represents the current object. + /// + /// 2 + public override string ToString() + { + return string.Format("HitTestLocation: {0}, HitTestLocationEx: {1}, Item: {2}, SubItem: {3}, Location: {4}, Group: {5}, ColumnIndex: {6}", + this.HitTestLocation, this.HitTestLocationEx, this.item, this.subItem, this.location, this.Group, this.ColumnIndex); + } + + internal class HeaderHitTestInfo + { + public int ColumnIndex; + public bool IsOverCheckBox; + public int OverDividerIndex; + } + } +} diff --git a/ObjectListView/Implementation/TreeDataSourceAdapter.cs b/ObjectListView/Implementation/TreeDataSourceAdapter.cs new file mode 100644 index 0000000..e54cf10 --- /dev/null +++ b/ObjectListView/Implementation/TreeDataSourceAdapter.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeDataSourceAdapter knows how to build a tree structure from a binding list. + /// + /// To build a tree + public class TreeDataSourceAdapter : DataSourceAdapter + { + #region Life and death + + /// + /// Create a data source adaptor that knows how to build a tree structure + /// + /// + public TreeDataSourceAdapter(DataTreeListView tlv) + : base(tlv) { + this.treeListView = tlv; + this.treeListView.CanExpandGetter = delegate(object model) { return this.CalculateHasChildren(model); }; + this.treeListView.ChildrenGetter = delegate(object model) { return this.CalculateChildren(model); }; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the name of the property/column that uniquely identifies each row. + /// + /// + /// + /// The value contained by this column must be unique across all rows + /// in the data source. Odd and unpredictable things will happen if two + /// rows have the same id. + /// + /// Null cannot be a valid key value. + /// + public virtual string KeyAspectName { + get { return keyAspectName; } + set { + if (keyAspectName == value) + return; + keyAspectName = value; + this.keyMunger = new Munger(this.KeyAspectName); + this.InitializeDataSource(); + } + } + private string keyAspectName; + + /// + /// Gets or sets the name of the property/column that contains the key of + /// the parent of a row. + /// + /// + /// + /// The test condition for deciding if one row is the parent of another is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateParentRow[this.KeyAspectName], row[this.ParentKeyAspectName]) + /// + /// + /// Unlike key value, parent keys can be null but a null parent key can only be used + /// to identify root objects. + /// + public virtual string ParentKeyAspectName { + get { return parentKeyAspectName; } + set { + if (parentKeyAspectName == value) + return; + parentKeyAspectName = value; + this.parentKeyMunger = new Munger(this.ParentKeyAspectName); + this.InitializeDataSource(); + } + } + private string parentKeyAspectName; + + /// + /// Gets or sets the value that identifies a row as a root object. + /// When the ParentKey of a row equals the RootKeyValue, that row will + /// be treated as root of the TreeListView. + /// + /// + /// + /// The test condition for deciding a root object is functionally + /// equivalent to this: + /// + /// Object.Equals(candidateRow[this.ParentKeyAspectName], this.RootKeyValue) + /// + /// + /// The RootKeyValue can be null. + /// + public virtual object RootKeyValue { + get { return rootKeyValue; } + set { + if (Equals(rootKeyValue, value)) + return; + rootKeyValue = value; + this.InitializeDataSource(); + } + } + private object rootKeyValue; + + /// + /// Gets or sets whether or not the key columns (id and parent id) should + /// be shown to the user. + /// + /// This must be set before the DataSource is set. It has no effect + /// afterwards. + public virtual bool ShowKeyColumns { + get { return showKeyColumns; } + set { showKeyColumns = value; } + } + private bool showKeyColumns = true; + + + #endregion + + #region Implementation properties + + /// + /// Gets the DataTreeListView that is being managed + /// + protected DataTreeListView TreeListView { + get { return treeListView; } + } + private readonly DataTreeListView treeListView; + + #endregion + + #region Implementation + + /// + /// + /// + protected override void InitializeDataSource() { + base.InitializeDataSource(); + this.TreeListView.RebuildAll(true); + } + + /// + /// + /// + protected override void SetListContents() { + this.TreeListView.Roots = this.CalculateRoots(); + } + + /// + /// + /// + /// + /// + protected override bool ShouldCreateColumn(PropertyDescriptor property) { + // If the property is a key column, and we aren't supposed to show keys, don't show it + if (!this.ShowKeyColumns && (property.Name == this.KeyAspectName || property.Name == this.ParentKeyAspectName)) + return false; + + return base.ShouldCreateColumn(property); + } + + /// + /// + /// + /// + protected override void HandleListChangedItemChanged(System.ComponentModel.ListChangedEventArgs e) { + // If the id or the parent id of a row changes, we just rebuild everything. + // We can't do anything more specific. We don't know what the previous values, so we can't + // tell the previous parent to refresh itself. If the id itself has changed, things that used + // to be children will no longer be children. Just rebuild everything. + // It seems PropertyDescriptor is only filled in .NET 4 :( + if (e.PropertyDescriptor != null && + (e.PropertyDescriptor.Name == this.KeyAspectName || + e.PropertyDescriptor.Name == this.ParentKeyAspectName)) + this.InitializeDataSource(); + else + base.HandleListChangedItemChanged(e); + } + + /// + /// + /// + /// + protected override void ChangePosition(int index) { + // We can't use our base method directly, since the normal position management + // doesn't know about our tree structure. They treat our dataset as a flat list + // but we have a collapsible structure. This means that the 5'th row to them + // may not even be visible to us + + // To display the n'th row, we have to make sure that all its ancestors + // are expanded. Then we will be able to select it. + object model = this.CurrencyManager.List[index]; + object parent = this.CalculateParent(model); + while (parent != null && !this.TreeListView.IsExpanded(parent)) { + this.TreeListView.Expand(parent); + parent = this.CalculateParent(parent); + } + + base.ChangePosition(index); + } + + private IEnumerable CalculateRoots() { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(this.RootKeyValue, parentKey)) + yield return x; + } + } + + private bool CalculateHasChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue == null) + return false; + + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + return true; + } + return false; + } + + private IEnumerable CalculateChildren(object model) { + object keyValue = this.GetKeyValue(model); + if (keyValue != null) { + foreach (object x in this.CurrencyManager.List) { + object parentKey = this.GetParentValue(x); + if (Object.Equals(keyValue, parentKey)) + yield return x; + } + } + } + + private object CalculateParent(object model) { + object parentValue = this.GetParentValue(model); + if (parentValue == null) + return null; + + foreach (object x in this.CurrencyManager.List) { + object key = this.GetKeyValue(x); + if (Object.Equals(parentValue, key)) + return x; + } + return null; + } + + private object GetKeyValue(object model) { + return this.keyMunger == null ? null : this.keyMunger.GetValue(model); + } + + private object GetParentValue(object model) { + return this.parentKeyMunger == null ? null : this.parentKeyMunger.GetValue(model); + } + + #endregion + + private Munger keyMunger; + private Munger parentKeyMunger; + } +} \ No newline at end of file diff --git a/ObjectListView/Implementation/VirtualGroups.cs b/ObjectListView/Implementation/VirtualGroups.cs new file mode 100644 index 0000000..1466ebb --- /dev/null +++ b/ObjectListView/Implementation/VirtualGroups.cs @@ -0,0 +1,341 @@ +/* + * Virtual groups - Classes and interfaces needed to implement virtual groups + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * 2011-02-21 JPP - Correctly honor group comparer and collapsible groups settings + * v2.3 + * 2009-08-28 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A IVirtualGroups is the interface that a virtual list must implement to support virtual groups + /// + public interface IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + IList GetGroups(GroupingParameters parameters); + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + int GetGroupMember(OLVGroup group, int indexWithinGroup); + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + int GetGroup(int itemIndex); + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + int GetIndexWithinGroup(OLVGroup group, int itemIndex); + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex); + } + + /// + /// This is a safe, do nothing implementation of a grouping strategy + /// + public class AbstractVirtualGroups : IVirtualGroups + { + /// + /// Return the list of groups that should be shown according to the given parameters + /// + /// + /// + public virtual IList GetGroups(GroupingParameters parameters) { + return new List(); + } + + /// + /// Return the index of the item that appears at the given position within the given group. + /// + /// + /// + /// + public virtual int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return -1; + } + + /// + /// Return the index of the group to which the given item belongs + /// + /// + /// + public virtual int GetGroup(int itemIndex) { + return -1; + } + + /// + /// Return the index at which the given item is shown in the given group + /// + /// + /// + /// + public virtual int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return -1; + } + + /// + /// A hint that the given range of items are going to be required + /// + /// + /// + /// + /// + public virtual void CacheHint(int fromGroupIndex, int fromIndex, int toGroupIndex, int toIndex) { + } + } + + + /// + /// Provides grouping functionality to a FastObjectListView + /// + public class FastListGroupingStrategy : AbstractVirtualGroups + { + /// + /// Create groups for FastListView + /// + /// + /// + public override IList GetGroups(GroupingParameters parameters) { + + // There is a lot of overlap between this method and ObjectListView.MakeGroups() + // Any changes made here may need to be reflected there + + // This strategy can only be used on FastObjectListViews + FastObjectListView folv = (FastObjectListView)parameters.ListView; + + // Separate the list view items into groups, using the group key as the descrimanent + int objectCount = 0; + NullableDictionary> map = new NullableDictionary>(); + foreach (object model in folv.FilteredObjects) { + object key = parameters.GroupByColumn.GetGroupKey(model); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(model); + objectCount++; + } + + // Sort the items within each group + OLVColumn primarySortColumn = parameters.SortItemsByPrimaryColumn ? parameters.ListView.GetColumn(0) : parameters.PrimarySort; + ModelObjectComparer sorter = new ModelObjectComparer(primarySortColumn, parameters.PrimarySortOrder, + parameters.SecondarySort, parameters.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(sorter); + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parameters.CreateGroup(key, map[key].Count, folv.HasCollapsibleGroups); + lvg.Contents = map[key].ConvertAll(delegate(object x) { return folv.IndexOf(x); }); + lvg.VirtualItemCount = map[key].Count; + if (parameters.GroupByColumn.GroupFormatter != null) + parameters.GroupByColumn.GroupFormatter(lvg, parameters); + groups.Add(lvg); + } + + // Sort the groups + if (parameters.GroupByOrder != SortOrder.None) + groups.Sort(parameters.GroupComparer ?? new OLVGroupComparer(parameters.GroupByOrder)); + + // Build an array that remembers which group each item belongs to. + this.indexToGroupMap = new List(objectCount); + this.indexToGroupMap.AddRange(new int[objectCount]); + + for (int i = 0; i < groups.Count; i++) { + OLVGroup group = groups[i]; + List members = (List)group.Contents; + foreach (int j in members) + this.indexToGroupMap[j] = i; + } + + return groups; + } + private List indexToGroupMap; + + /// + /// + /// + /// + /// + /// + public override int GetGroupMember(OLVGroup group, int indexWithinGroup) { + return (int)group.Contents[indexWithinGroup]; + } + + /// + /// + /// + /// + /// + public override int GetGroup(int itemIndex) { + return this.indexToGroupMap[itemIndex]; + } + + /// + /// + /// + /// + /// + /// + public override int GetIndexWithinGroup(OLVGroup group, int itemIndex) { + return group.Contents.IndexOf(itemIndex); + } + } + + + /// + /// This is the COM interface that a ListView must be given in order for groups in virtual lists to work. + /// + /// + /// This interface is NOT documented by MS. It was found on Greg Chapell's site. This means that there is + /// no guarantee that it will work on future versions of Windows, nor continue to work on current ones. + /// + [ComImport(), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown), + Guid("44C09D56-8D3B-419D-A462-7B956B105B47")] + internal interface IOwnerDataCallback + { + /// + /// Not sure what this does + /// + /// + /// + void GetItemPosition(int i, out NativeMethods.POINT pt); + + /// + /// Not sure what this does + /// + /// + /// + void SetItemPosition(int t, NativeMethods.POINT pt); + + /// + /// Get the index of the item that occurs at the n'th position of the indicated group. + /// + /// Index of the group + /// Index within the group + /// Index of the item within the whole list + void GetItemInGroup(int groupIndex, int n, out int itemIndex); + + /// + /// Get the index of the group to which the given item belongs + /// + /// Index of the item within the whole list + /// Which occurrences of the item is wanted + /// Index of the group + void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex); + + /// + /// Get the number of groups that contain the given item + /// + /// Index of the item within the whole list + /// How many groups does it occur within + void GetItemGroupCount(int itemIndex, out int occurrenceCount); + + /// + /// A hint to prepare any cache for the given range of requests + /// + /// + /// + void OnCacheHint(NativeMethods.LVITEMINDEX i, NativeMethods.LVITEMINDEX j); + } + + /// + /// A default implementation of the IOwnerDataCallback interface + /// + [Guid("6FC61F50-80E8-49b4-B200-3F38D3865ABD")] + internal class OwnerDataCallbackImpl : IOwnerDataCallback + { + public OwnerDataCallbackImpl(VirtualObjectListView olv) { + this.olv = olv; + } + VirtualObjectListView olv; + + #region IOwnerDataCallback Members + + public void GetItemPosition(int i, out NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("GetItemPosition"); + throw new NotSupportedException(); + } + + public void SetItemPosition(int t, NativeMethods.POINT pt) { + //System.Diagnostics.Debug.WriteLine("SetItemPosition"); + throw new NotSupportedException(); + } + + public void GetItemInGroup(int groupIndex, int n, out int itemIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("-> GetItemInGroup({0}, {1})", groupIndex, n)); + itemIndex = this.olv.GroupingStrategy.GetGroupMember(this.olv.OLVGroups[groupIndex], n); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", itemIndex)); + } + + public void GetItemGroup(int itemIndex, int occurrenceCount, out int groupIndex) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroup({0}, {1})", itemIndex, occurrenceCount)); + groupIndex = this.olv.GroupingStrategy.GetGroup(itemIndex); + //System.Diagnostics.Debug.WriteLine(String.Format("<- {0}", groupIndex)); + } + + public void GetItemGroupCount(int itemIndex, out int occurrenceCount) { + //System.Diagnostics.Debug.WriteLine(String.Format("GetItemGroupCount({0})", itemIndex)); + occurrenceCount = 1; + } + + public void OnCacheHint(NativeMethods.LVITEMINDEX from, NativeMethods.LVITEMINDEX to) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnCacheHint({0}, {1}, {2}, {3})", from.iGroup, from.iItem, to.iGroup, to.iItem)); + this.olv.GroupingStrategy.CacheHint(from.iGroup, from.iItem, to.iGroup, to.iItem); + } + + #endregion + } +} diff --git a/ObjectListView/Implementation/VirtualListDataSource.cs b/ObjectListView/Implementation/VirtualListDataSource.cs new file mode 100644 index 0000000..7bc378d --- /dev/null +++ b/ObjectListView/Implementation/VirtualListDataSource.cs @@ -0,0 +1,349 @@ +/* + * VirtualListDataSource - Encapsulate how data is provided to a virtual list + * + * Author: Phillip Piper + * Date: 28/08/2009 11:10am + * + * Change log: + * v2.4 + * 2010-04-01 JPP - Added IFilterableDataSource + * v2.3 + * 2009-08-28 JPP - Initial version (Separated from VirtualObjectListView.cs) + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A VirtualListDataSource is a complete manner to provide functionality to a virtual list. + /// An object that implements this interface provides a VirtualObjectListView with all the + /// information it needs to be fully functional. + /// + /// Implementors must provide functioning implementations of at least GetObjectCount() + /// and GetNthObject(), otherwise nothing will appear in the list. + public interface IVirtualListDataSource + { + /// + /// Return the object that should be displayed at the n'th row. + /// + /// The index of the row whose object is to be returned. + /// The model object at the n'th row, or null if the fetching was unsuccessful. + Object GetNthObject(int n); + + /// + /// Return the number of rows that should be visible in the virtual list + /// + /// The number of rows the list view should have. + int GetObjectCount(); + + /// + /// Get the index of the row that is showing the given model object + /// + /// The model object sought + /// The index of the row showing the model, or -1 if the object could not be found. + int GetObjectIndex(Object model); + + /// + /// The ListView is about to request the given range of items. Do + /// whatever caching seems appropriate. + /// + /// + /// + void PrepareCache(int first, int last); + + /// + /// Find the first row that "matches" the given text in the given range. + /// + /// The text typed by the user + /// Start searching from this index. This may be greater than the 'to' parameter, + /// in which case the search should descend + /// Do not search beyond this index. This may be less than the 'from' parameter. + /// The column that should be considered when looking for a match. + /// Return the index of row that was matched, or -1 if no match was found + int SearchText(string value, int first, int last, OLVColumn column); + + /// + /// Sort the model objects in the data source. + /// + /// + /// + void Sort(OLVColumn column, SortOrder order); + + //----------------------------------------------------------------------------------- + // Modification commands + // THINK: Should we split these four into a separate interface? + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + void AddObjects(ICollection modelObjects); + + /// + /// Insert the given collection of model objects to this control at the position + /// + /// Index where the collection will be added + /// A collection of model objects + void InsertObjects(int index, ICollection modelObjects); + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + void RemoveObjects(ICollection modelObjects); + + /// + /// Set the collection of objects that this control will show. + /// + /// + void SetObjects(IEnumerable collection); + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + void UpdateObject(int index, object modelObject); + } + + /// + /// This extension allow virtual lists to filter their contents + /// + public interface IFilterableDataSource + { + /// + /// All subsequent retrievals on this data source should be filtered + /// through the given filters. null means no filtering of that kind. + /// + /// + /// + void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter); + } + + /// + /// A do-nothing implementation of the VirtualListDataSource interface. + /// + public class AbstractVirtualListDataSource : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Creates an AbstractVirtualListDataSource + /// + /// + public AbstractVirtualListDataSource(VirtualObjectListView listView) { + this.listView = listView; + } + + /// + /// The list view that this data source is giving information to. + /// + protected VirtualObjectListView listView; + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return -1; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int from, int to) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return -1; + } + + /// + /// + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + } + + /// + /// + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + } + + /// + /// + /// + /// + public virtual void SetObjects(IEnumerable collection) { + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public virtual void UpdateObject(int index, object modelObject) { + } + + /// + /// This is a useful default implementation of SearchText method, intended to be called + /// by implementors of IVirtualListDataSource. + /// + /// + /// + /// + /// + /// + /// + static public int DefaultSearchText(string value, int first, int last, OLVColumn column, IVirtualListDataSource source) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(source.GetNthObject(i)); + if (data.StartsWith(value, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + virtual public void ApplyFilters(IModelFilter modelFilter, IListFilter listFilter) { + } + + #endregion + } + + /// + /// This class mimics the behavior of VirtualObjectListView v1.x. + /// + public class VirtualListVersion1DataSource : AbstractVirtualListDataSource + { + /// + /// Creates a VirtualListVersion1DataSource + /// + /// + public VirtualListVersion1DataSource(VirtualObjectListView listView) + : base(listView) { + } + + #region Public properties + + /// + /// How will the n'th object of the data source be fetched? + /// + public RowGetterDelegate RowGetter { + get { return rowGetter; } + set { rowGetter = value; } + } + private RowGetterDelegate rowGetter; + + #endregion + + #region IVirtualListDataSource implementation + + /// + /// + /// + /// + /// + public override object GetNthObject(int n) { + if (this.RowGetter == null) + return null; + else + return this.RowGetter(n); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public override int SearchText(string value, int first, int last, OLVColumn column) { + return DefaultSearchText(value, first, last, column, this); + } + + #endregion + } +} diff --git a/ObjectListView/OLVColumn.cs b/ObjectListView/OLVColumn.cs new file mode 100644 index 0000000..21ce4f9 --- /dev/null +++ b/ObjectListView/OLVColumn.cs @@ -0,0 +1,1909 @@ +/* + * OLVColumn - A column in an ObjectListView + * + * Author: Phillip Piper + * Date: 31-March-2011 5:53 pm + * + * Change log: + * 2018-05-05 JPP - Added EditorCreator to OLVColumn + * 2015-06-12 JPP - HeaderTextAlign became nullable so that it can be "not set" (this was always the intent) + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-27 JPP - Added Sortable, Hideable, Groupable, Searchable, ShowTextInHeader properties + * 2011-04-12 JPP - Added HasFilterIndicator + * 2011-03-31 JPP - Split into its own file + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Diagnostics; +using System.Drawing.Design; + +namespace BrightIdeasSoftware { + + // TODO + //[TypeConverter(typeof(ExpandableObjectConverter))] + //public class CheckBoxSettings + //{ + // private bool useSettings; + // private Image checkedImage; + + // public bool UseSettings { + // get { return useSettings; } + // set { useSettings = value; } + // } + + // public Image CheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image UncheckedImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + + // public Image IndeterminateImage { + // get { return checkedImage; } + // set { checkedImage = value; } + // } + //} + + /// + /// An OLVColumn knows which aspect of an object it should present. + /// + /// + /// The column knows how to: + /// + /// extract its aspect from the row object + /// convert an aspect to a string + /// calculate the image for the row object + /// extract a group "key" from the row object + /// convert a group "key" into a title for the group + /// + /// For sorting to work correctly, aspects from the same column + /// must be of the same type, that is, the same aspect cannot sometimes + /// return strings and other times integers. + /// + [Browsable(false)] + public partial class OLVColumn : ColumnHeader { + + /// + /// How should the button be sized? + /// + public enum ButtonSizingMode + { + /// + /// Every cell will have the same sized button, as indicated by ButtonSize property + /// + FixedBounds, + + /// + /// Every cell will draw a button that fills the cell, inset by ButtonPadding + /// + CellBounds, + + /// + /// Each button will be resized to contain the text of the Aspect + /// + TextBounds + } + + #region Life and death + + /// + /// Create an OLVColumn + /// + public OLVColumn() { + } + + /// + /// Initialize a column to have the given title, and show the given aspect + /// + /// The title of the column + /// The aspect to be shown in the column + public OLVColumn(string title, string aspect) + : this() { + this.Text = title; + this.AspectName = aspect; + } + + #endregion + + #region Public Properties + + /// + /// This delegate will be used to extract a value to be displayed in this column. + /// + /// + /// If this is set, AspectName is ignored. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectGetterDelegate AspectGetter { + get { return aspectGetter; } + set { aspectGetter = value; } + } + private AspectGetterDelegate aspectGetter; + + /// + /// Remember if this aspect getter for this column was generated internally, and can therefore + /// be regenerated at will + /// + [Obsolete("This property is no longer maintained", true), + Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AspectGetterAutoGenerated { + get { return aspectGetterAutoGenerated; } + set { aspectGetterAutoGenerated = value; } + } + private bool aspectGetterAutoGenerated; + + /// + /// The name of the property or method that should be called to get the value to display in this column. + /// This is only used if a ValueGetterDelegate has not been given. + /// + /// This name can be dotted to chain references to properties or parameter-less methods. + /// "DateOfBirth" + /// "Owner.HomeAddress.Postcode" + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(null)] + public string AspectName { + get { return aspectName; } + set { + aspectName = value; + this.aspectMunger = null; + } + } + private string aspectName; + + /// + /// This delegate will be used to put an edited value back into the model object. + /// + /// + /// This does nothing if IsEditable == false. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { aspectPutter = value; } + } + private AspectPutterDelegate aspectPutter; + + /// + /// The delegate that will be used to translate the aspect to display in this column into a string. + /// + /// If this value is set, AspectToStringFormat will be ignored. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public AspectToStringConverterDelegate AspectToStringConverter { + get { return aspectToStringConverter; } + set { aspectToStringConverter = value; } + } + private AspectToStringConverterDelegate aspectToStringConverter; + + /// + /// This format string will be used to convert an aspect to its string representation. + /// + /// + /// This string is passed as the first parameter to the String.Format() method. + /// This is only used if AspectToStringConverter has not been set. + /// "{0:C}" to convert a number to currency + [Category("ObjectListView"), + Description("The format string that will be used to convert an aspect to its string representation"), + DefaultValue(null)] + public string AspectToStringFormat { + get { return aspectToStringFormat; } + set { aspectToStringFormat = value; } + } + private string aspectToStringFormat; + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(true)] + public bool AutoCompleteEditor { + get { return this.AutoCompleteEditorMode != AutoCompleteMode.None; } + set { + if (value) { + if (this.AutoCompleteEditorMode == AutoCompleteMode.None) + this.AutoCompleteEditorMode = AutoCompleteMode.Append; + } else + this.AutoCompleteEditorMode = AutoCompleteMode.None; + } + } + + /// + /// Gets or sets whether the cell editor should use AutoComplete + /// + [Category("ObjectListView"), + Description("Should the editor for cells of this column use AutoComplete"), + DefaultValue(AutoCompleteMode.Append)] + public AutoCompleteMode AutoCompleteEditorMode { + get { return autoCompleteEditorMode; } + set { autoCompleteEditorMode = value; } + } + private AutoCompleteMode autoCompleteEditorMode = AutoCompleteMode.Append; + + /// + /// Gets whether this column can be hidden by user actions + /// + /// This take into account both the Hideable property and whether this column + /// is the primary column of the listview (column 0). + [Browsable(false)] + public bool CanBeHidden { + get { + return this.Hideable && (this.Index != 0); + } + } + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false (the default) and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// If this property is not set on the column, the value from the control will be used + /// + /// This value is only used when the control is in Details view. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(null)] + public virtual bool? CellEditUseWholeCell + { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool? cellEditUseWholeCell; + + /// + /// Get whether the whole cell should be used when editing a cell in this column + /// + /// This calculates the current effective value, which may be different to CellEditUseWholeCell + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CellEditUseWholeCellEffective { + get { + bool? columnSpecificValue = this.ListView.View == View.Details ? this.CellEditUseWholeCell : (bool?) null; + return (columnSpecificValue ?? ((ObjectListView) this.ListView).CellEditUseWholeCell); + } + } + + /// + /// Gets or sets how many pixels will be left blank around this cells in this column + /// + /// This setting only takes effect when the control is owner drawn. + [Category("ObjectListView"), + Description("How many pixels will be left blank around the cells in this column?"), + DefaultValue(null)] + public Rectangle? CellPadding + { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells in this column will be vertically aligned. + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// + /// If this is not set, the value from the control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets or sets whether this column will show a checkbox. + /// + /// + /// Setting this on column 0 has no effect. Column 0 check box is controlled + /// by the CheckBoxes property on the ObjectListView itself. + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a checkbox, rather than a string?"), + DefaultValue(false)] + public virtual bool CheckBoxes { + get { return checkBoxes; } + set { + if (this.checkBoxes == value) + return; + + this.checkBoxes = value; + if (this.checkBoxes) { + if (this.Renderer == null) + this.Renderer = new CheckStateRenderer(); + } else { + if (this.Renderer is CheckStateRenderer) + this.Renderer = null; + } + } + } + private bool checkBoxes; + + /// + /// Gets or sets the clustering strategy used for this column. + /// + /// + /// + /// The clustering strategy is used to build a Filtering menu for this item. + /// If this is null, a useful default will be chosen. + /// + /// + /// To disable filtering on this column, set UseFiltering to false. + /// + /// + /// Cluster strategies belong to a particular column. The same instance + /// cannot be shared between multiple columns. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IClusteringStrategy ClusteringStrategy { + get { + if (this.clusteringStrategy == null) + this.ClusteringStrategy = this.DecideDefaultClusteringStrategy(); + return clusteringStrategy; + } + set { + this.clusteringStrategy = value; + if (this.clusteringStrategy != null) + this.clusteringStrategy.Column = this; + } + } + private IClusteringStrategy clusteringStrategy; + + /// + /// Gets or sets a delegate that will create an editor for a cell in this column. + /// + /// + /// If you need different editors for different cells in the same column, this + /// delegate is your solution. Return null to use the default editor for the cell. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public EditorCreatorDelegate EditorCreator { + get { return editorCreator; } + set { editorCreator = value; } + } + private EditorCreatorDelegate editorCreator; + + /// + /// Gets or sets whether the button in this column (if this column is drawing buttons) will be enabled + /// even if the row itself is disabled + /// + [Category("ObjectListView"), + Description("If this column contains a button, should the button be enabled even if the row is disabled?"), + DefaultValue(false)] + public bool EnableButtonWhenItemIsDisabled + { + get { return this.enableButtonWhenItemIsDisabled; } + set { this.enableButtonWhenItemIsDisabled = value; } + } + private bool enableButtonWhenItemIsDisabled; + + /// + /// Should this column resize to fill the free space in the listview? + /// + /// + /// + /// If you want two (or more) columns to equally share the available free space, set this property to True. + /// If you want this column to have a larger or smaller share of the free space, you must + /// set the FreeSpaceProportion property explicitly. + /// + /// + /// Space filling columns are still governed by the MinimumWidth and MaximumWidth properties. + /// + /// /// + [Category("ObjectListView"), + Description("Will this column resize to fill unoccupied horizontal space in the listview?"), + DefaultValue(false)] + public bool FillsFreeSpace { + get { return this.FreeSpaceProportion > 0; } + set { this.FreeSpaceProportion = value ? 1 : 0; } + } + + /// + /// What proportion of the unoccupied horizontal space in the control should be given to this column? + /// + /// + /// + /// There are situations where it would be nice if a column (normally the rightmost one) would expand as + /// the list view expands, so that as much of the column was visible as possible without having to scroll + /// horizontally (you should never, ever make your users have to scroll anything horizontally!). + /// + /// + /// A space filling column is resized to occupy a proportion of the unoccupied width of the listview (the + /// unoccupied width is the width left over once all the non-filling columns have been given their space). + /// This property indicates the relative proportion of that unoccupied space that will be given to this column. + /// The actual value of this property is not important -- only its value relative to the value in other columns. + /// For example: + /// + /// + /// If there is only one space filling column, it will be given all the free space, regardless of the value in FreeSpaceProportion. + /// + /// + /// If there are two or more space filling columns and they all have the same value for FreeSpaceProportion, + /// they will share the free space equally. + /// + /// + /// If there are three space filling columns with values of 3, 2, and 1 + /// for FreeSpaceProportion, then the first column with occupy half the free space, the second will + /// occupy one-third of the free space, and the third column one-sixth of the free space. + /// + /// + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int FreeSpaceProportion { + get { return freeSpaceProportion; } + set { freeSpaceProportion = Math.Max(0, value); } + } + private int freeSpaceProportion; + + /// + /// Gets or sets whether groups will be rebuild on this columns values when this column's header is clicked. + /// + /// + /// This setting is only used when ShowGroups is true. + /// + /// If this is false, clicking the header will not rebuild groups. It will not provide + /// any feedback as to why the list is not being regrouped. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeCreatingGroups events are still fired, which can be used to allow grouping + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will the list create groups when this header is clicked?"), + DefaultValue(true)] + public bool Groupable { + get { return groupable; } + set { groupable = value; } + } + private bool groupable = true; + + /// + /// This delegate is called when a group has been created but not yet made + /// into a real ListViewGroup. The user can take this opportunity to fill + /// in lots of other details about the group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupFormatterDelegate GroupFormatter { + get { return groupFormatter; } + set { groupFormatter = value; } + } + private GroupFormatterDelegate groupFormatter; + + /// + /// This delegate is called to get the object that is the key for the group + /// to which the given row belongs. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { groupKeyGetter = value; } + } + private GroupKeyGetterDelegate groupKeyGetter; + + /// + /// This delegate is called to convert a group key into a title for that group. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public GroupKeyToTitleConverterDelegate GroupKeyToTitleConverter { + get { return groupKeyToTitleConverter; } + set { groupKeyToTitleConverter = value; } + } + private GroupKeyToTitleConverterDelegate groupKeyToTitleConverter; + + /// + /// When the listview is grouped by this column and group title has an item count, + /// how should the label be formatted? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Gets this.GroupWithItemCountFormat or a reasonable default + /// + /// + /// If GroupWithItemCountFormat is not set, its value will be taken from the ObjectListView if possible. + /// + [Browsable(false)] + public string GroupWithItemCountFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountFormat)) + return this.GroupWithItemCountFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountFormat = ((ObjectListView)this.ListView).GroupWithItemCountFormatOrDefault; + return cachedGroupWithItemCountFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountFormat ?? "{0} [{1} items]"; + } + } + private string cachedGroupWithItemCountFormat; + + /// + /// When the listview is grouped by this column and a group title has an item count, + /// how should the label be formatted if there is only one item in the group? + /// + /// + /// The given format string can/should have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Get this.GroupWithItemCountSingularFormat or a reasonable default + /// + /// + /// If this value is not set, the values from the list view will be used + /// + [Browsable(false)] + public string GroupWithItemCountSingularFormatOrDefault { + get { + if (!String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat)) + return this.GroupWithItemCountSingularFormat; + + if (this.ListView != null) { + cachedGroupWithItemCountSingularFormat = ((ObjectListView)this.ListView).GroupWithItemCountSingularFormatOrDefault; + return cachedGroupWithItemCountSingularFormat; + } + + // There is one rare but pathologically possible case where the ListView can + // be null (if the column is grouping a ListView, but is not one of the columns + // for that ListView) so we have to provide a workable default for that rare case. + return cachedGroupWithItemCountSingularFormat ?? "{0} [{1} item]"; + } + } + private string cachedGroupWithItemCountSingularFormat; + + /// + /// Gets whether this column should be drawn with a filter indicator in the column header. + /// + [Browsable(false)] + public bool HasFilterIndicator { + get { + return this.UseFiltering && this.ValuesChosenForFiltering != null && this.ValuesChosenForFiltering.Count > 0; + } + } + + /// + /// Gets or sets a delegate that will be used to own draw header column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public HeaderDrawingDelegate HeaderDrawing { + get { return headerDrawing; } + set { headerDrawing = value; } + } + private HeaderDrawingDelegate headerDrawing; + + /// + /// Gets or sets the style that will be used to draw the header for this column + /// + /// This is only uses when the owning ObjectListView has HeaderUsesThemes set to false. + [Category("ObjectListView"), + Description("What style will be used to draw the header of this column"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the font in which the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Which font will be used to draw the header?"), + DefaultValue(null)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the color in which the text of the header for this column will be drawn + /// + /// You should probably use a HeaderFormatStyle instead of this property + /// This is only uses when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("In what color will the header text be drawn?"), + DefaultValue(typeof(Color), "")] + public Color HeaderForeColor { + get { return this.HeaderFormatStyle == null ? Color.Empty : this.HeaderFormatStyle.Normal.ForeColor; } + set { + if (value.IsEmpty && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetForeColor(value); + } + } + + /// + /// Gets or sets the ImageList key of the image that will be drawn in the header of this column. + /// + /// This is only taken into account when HeaderUsesThemes is false. + [Category("ObjectListView"), + Description("Name of the image that will be shown in the column header."), + DefaultValue(null), + TypeConverter(typeof(ImageKeyConverter)), + Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), + RefreshProperties(RefreshProperties.Repaint)] + public string HeaderImageKey { + get { return headerImageKey; } + set { headerImageKey = value; } + } + private string headerImageKey; + + + /// + /// Gets or sets how the text of the header will be drawn? + /// + [Category("ObjectListView"), + Description("How will the header text be aligned? If this is not set, the alignment of the header will follow the alignment of the column"), + DefaultValue(null)] + public HorizontalAlignment? HeaderTextAlign { + get { return headerTextAlign; } + set { headerTextAlign = value; } + } + private HorizontalAlignment? headerTextAlign; + + /// + /// Return the text alignment of the header. This will either have been set explicitly, + /// or will follow the alignment of the text in the column + /// + [Browsable(false)] + public HorizontalAlignment HeaderTextAlignOrDefault + { + get { return headerTextAlign.HasValue ? headerTextAlign.Value : this.TextAlign; } + } + + /// + /// Gets the header alignment converted to a StringAlignment + /// + [Browsable(false)] + public StringAlignment HeaderTextAlignAsStringAlignment { + get { + switch (this.HeaderTextAlignOrDefault) { + case HorizontalAlignment.Left: return StringAlignment.Near; + case HorizontalAlignment.Center: return StringAlignment.Center; + case HorizontalAlignment.Right: return StringAlignment.Far; + default: return StringAlignment.Near; + } + } + } + + /// + /// Gets whether or not this column has an image in the header + /// + [Browsable(false)] + public bool HasHeaderImage { + get { + return (this.ListView != null && + this.ListView.SmallImageList != null && + this.ListView.SmallImageList.Images.ContainsKey(this.HeaderImageKey)); + } + } + + /// + /// Gets or sets whether this header will place a checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderCheckBox + { + get { return headerCheckBox; } + set { headerCheckBox = value; } + } + private bool headerCheckBox; + + /// + /// Gets or sets whether this header will place a tri-state checkbox in the header + /// + [Category("ObjectListView"), + Description("Draw a tri-state checkbox in the header of this column"), + DefaultValue(false)] + public bool HeaderTriStateCheckBox + { + get { return headerTriStateCheckBox; } + set { headerTriStateCheckBox = value; } + } + private bool headerTriStateCheckBox; + + /// + /// Gets or sets the checkedness of the checkbox in the header of this column + /// + [Category("ObjectListView"), + Description("Checkedness of the header checkbox"), + DefaultValue(CheckState.Unchecked)] + public CheckState HeaderCheckState + { + get { return headerCheckState; } + set { headerCheckState = value; } + } + private CheckState headerCheckState = CheckState.Unchecked; + + /// + /// Gets or sets whether the + /// checking/unchecking the value of the header's checkbox will result in the + /// checkboxes for all cells in this column being set to the same checked/unchecked. + /// Defaults to true. + /// + /// + /// + /// There is no reverse of this function that automatically updates the header when the + /// checkedness of a cell changes. + /// + /// + /// This property's behaviour on a TreeListView is probably best describes as undefined + /// and should be avoided. + /// + /// + /// The performance of this action (checking/unchecking all rows) is O(n) where n is the + /// number of rows. It will work on large virtual lists, but it may take some time. + /// + /// + [Category("ObjectListView"), + Description("Update row checkboxes when the header checkbox is clicked by the user"), + DefaultValue(true)] + public bool HeaderCheckBoxUpdatesRowCheckBoxes { + get { return headerCheckBoxUpdatesRowCheckBoxes; } + set { headerCheckBoxUpdatesRowCheckBoxes = value; } + } + private bool headerCheckBoxUpdatesRowCheckBoxes = true; + + /// + /// Gets or sets whether the checkbox in the header is disabled + /// + /// + /// Clicking on a disabled checkbox does not change its value, though it does raise + /// a HeaderCheckBoxChanging event, which allows the programmer the opportunity to do + /// something appropriate. + [Category("ObjectListView"), + Description("Is the checkbox in the header of this column disabled"), + DefaultValue(false)] + public bool HeaderCheckBoxDisabled + { + get { return headerCheckBoxDisabled; } + set { headerCheckBoxDisabled = value; } + } + private bool headerCheckBoxDisabled; + + /// + /// Gets or sets whether this column can be hidden by the user. + /// + /// + /// Column 0 can never be hidden, regardless of this setting. + /// + [Category("ObjectListView"), + Description("Will the user be able to choose to hide this column?"), + DefaultValue(true)] + public bool Hideable { + get { return hideable; } + set { hideable = value; } + } + private bool hideable = true; + + /// + /// Gets or sets whether the text values in this column will act like hyperlinks + /// + [Category("ObjectListView"), + Description("Will the text values in the cells of this column act like hyperlinks?"), + DefaultValue(false)] + public bool Hyperlink { + get { return hyperlink; } + set { hyperlink = value; } + } + private bool hyperlink; + + /// + /// This is the name of property that will be invoked to get the image selector of the + /// image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// + /// This is ignored if ImageGetter is not null. + /// The property can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Category("ObjectListView"), + Description("The name of the property that holds the image selector"), + DefaultValue(null)] + public string ImageAspectName { + get { return imageAspectName; } + set { imageAspectName = value; } + } + private string imageAspectName; + + /// + /// This delegate is called to get the image selector of the image that should be shown in this column. + /// It can return an int, string, Image or null. + /// + /// This delegate can use these return value to identify the image: + /// + /// null or -1 -- indicates no image + /// an int -- the int value will be used as an index into the image list + /// a String -- the string value will be used as a key into the image list + /// an Image -- the Image will be drawn directly (only in OwnerDrawn mode) + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { imageGetter = value; } + } + private ImageGetterDelegate imageGetter; + + /// + /// Gets or sets whether this column will draw buttons in its cells + /// + /// + /// + /// When this is set to true, the renderer for the column is become a ColumnButtonRenderer + /// if it isn't already. If this is set to false, any previous button renderer will be discarded + /// + /// If the cell's aspect is null or empty, nothing will be drawn in the cell. + [Category("ObjectListView"), + Description("Does this column draw its cells as buttons?"), + DefaultValue(false)] + public bool IsButton { + get { return isButton; } + set { + isButton = value; + if (value) { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) { + this.Renderer = this.CreateColumnButtonRenderer(); + this.FillInColumnButtonRenderer(); + } + } else { + if (this.Renderer is ColumnButtonRenderer) + this.Renderer = null; + } + } + } + private bool isButton; + + /// + /// Create a ColumnButtonRenderer to draw buttons in this column + /// + /// + protected virtual ColumnButtonRenderer CreateColumnButtonRenderer() { + return new ColumnButtonRenderer(); + } + + /// + /// Fill in details to our ColumnButtonRenderer based on the properties set on the column + /// + protected virtual void FillInColumnButtonRenderer() { + ColumnButtonRenderer buttonRenderer = this.Renderer as ColumnButtonRenderer; + if (buttonRenderer == null) + return; + + buttonRenderer.SizingMode = this.ButtonSizing; + buttonRenderer.ButtonSize = this.ButtonSize; + buttonRenderer.ButtonPadding = this.ButtonPadding; + buttonRenderer.MaxButtonWidth = this.ButtonMaxWidth; + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int ButtonMaxWidth { + get { return this.buttonMaxWidth; } + set { + this.buttonMaxWidth = value; + FillInColumnButtonRenderer(); + } + } + private int buttonMaxWidth = -1; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds"), + DefaultValue(null)] + public Size? ButtonPadding { + get { return this.buttonPadding; } + set { + this.buttonPadding = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonPadding; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize { + get { return this.buttonSize; } + set { + this.buttonSize = value; + this.FillInColumnButtonRenderer(); + } + } + private Size? buttonSize; + + /// + /// Gets or sets how each button will be sized if this column is displaying buttons + /// + [Category("ObjectListView"), + Description("If this column is showing buttons, how each button will be sized"), + DefaultValue(ButtonSizingMode.TextBounds)] + public ButtonSizingMode ButtonSizing { + get { return this.buttonSizing; } + set { + this.buttonSizing = value; + this.FillInColumnButtonRenderer(); + } + } + private ButtonSizingMode buttonSizing = ButtonSizingMode.TextBounds; + + /// + /// Can the values shown in this column be edited? + /// + /// This defaults to true, since the primary means to control the editability of a listview + /// is on the listview itself. Once a listview is editable, all the columns are too, unless the + /// programmer explicitly marks them as not editable + [Category("ObjectListView"), + Description("Can the value in this column be edited?"), + DefaultValue(true)] + public bool IsEditable + { + get { return isEditable; } + set { isEditable = value; } + } + private bool isEditable = true; + + /// + /// Is this column a fixed width column? + /// + [Browsable(false)] + public bool IsFixedWidth { + get { + return (this.MinimumWidth != -1 && this.MaximumWidth != -1 && this.MinimumWidth >= this.MaximumWidth); + } + } + + /// + /// Get/set whether this column should be used when the view is switched to tile view. + /// + /// Column 0 is always included in tileview regardless of this setting. + /// Tile views do not work well with many "columns" of information. + /// Two or three works best. + [Category("ObjectListView"), + Description("Will this column be used when the view is switched to tile view"), + DefaultValue(false)] + public bool IsTileViewColumn { + get { return isTileViewColumn; } + set { isTileViewColumn = value; } + } + private bool isTileViewColumn; + + /// + /// Gets or sets whether the text of this header should be rendered vertically. + /// + /// + /// If this is true, it is a good idea to set ToolTipText to the name of the column so it's easy to read. + /// Vertical headers are text only. They do not draw their image. + /// + [Category("ObjectListView"), + Description("Will the header for this column be drawn vertically?"), + DefaultValue(false)] + public bool IsHeaderVertical { + get { return isHeaderVertical; } + set { isHeaderVertical = value; } + } + private bool isHeaderVertical; + + /// + /// Can this column be seen by the user? + /// + /// After changing this value, you must call RebuildColumns() before the changes will take effect. + [Category("ObjectListView"), + Description("Can this column be seen by the user?"), + DefaultValue(true)] + public bool IsVisible { + get { return isVisible; } + set + { + if (isVisible == value) + return; + + isVisible = value; + OnVisibilityChanged(EventArgs.Empty); + } + } + private bool isVisible = true; + + /// + /// Where was this column last positioned within the Detail view columns + /// + /// DisplayIndex is volatile. Once a column is removed from the control, + /// there is no way to discover where it was in the display order. This property + /// guards that information even when the column is not in the listview's active columns. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int LastDisplayIndex { + get { return this.lastDisplayIndex; } + set { this.lastDisplayIndex = value; } + } + private int lastDisplayIndex = -1; + + /// + /// What is the maximum width that the user can give to this column? + /// + /// -1 means there is no maximum width. Give this the same value as MinimumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the maximum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MaximumWidth { + get { return maxWidth; } + set { + maxWidth = value; + if (maxWidth != -1 && this.Width > maxWidth) + this.Width = maxWidth; + } + } + private int maxWidth = -1; + + /// + /// What is the minimum width that the user can give to this column? + /// + /// -1 means there is no minimum width. Give this the same value as MaximumWidth to make a fixed width column. + [Category("ObjectListView"), + Description("What is the minimum width to which the user can resize this column? -1 means no limit"), + DefaultValue(-1)] + public int MinimumWidth { + get { return minWidth; } + set { + minWidth = value; + if (this.Width < minWidth) + this.Width = minWidth; + } + } + private int minWidth = -1; + + /// + /// Get/set the renderer that will be invoked when a cell needs to be redrawn + /// + [Category("ObjectListView"), + Description("The renderer will draw this column when the ListView is owner drawn"), + DefaultValue(null)] + public IRenderer Renderer { + get { return renderer; } + set { renderer = value; } + } + private IRenderer renderer; + + /// + /// This delegate is called when a cell needs to be drawn in OwnerDrawn mode. + /// + /// This method is kept primarily for backwards compatibility. + /// New code should implement an IRenderer, though this property will be maintained. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public RenderDelegate RendererDelegate { + get { + Version1Renderer version1Renderer = this.Renderer as Version1Renderer; + return version1Renderer != null ? version1Renderer.RenderDelegate : null; + } + set { + this.Renderer = value == null ? null : new Version1Renderer(value); + } + } + + /// + /// Gets or sets whether the text in this column's cell will be used when doing text searching. + /// + /// + /// + /// If this is false, text filters will not trying searching this columns cells when looking for matches. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the cells in this column be considered when searching?"), + DefaultValue(true)] + public bool Searchable { + get { return searchable; } + set { searchable = value; } + } + private bool searchable = true; + + /// + /// Gets or sets a delegate which will return the array of text values that should be + /// considered for text matching when using a text based filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public SearchValueGetterDelegate SearchValueGetter { + get { return searchValueGetter; } + set { searchValueGetter = value; } + } + private SearchValueGetterDelegate searchValueGetter; + + /// + /// Gets or sets whether the header for this column will include the column's Text. + /// + /// + /// + /// If this is false, the only thing rendered in the column header will be the image from . + /// + /// This setting is only considered when is false on the owning ObjectListView. + /// + [Category("ObjectListView"), + Description("Will the header for this column include text?"), + DefaultValue(true)] + public bool ShowTextInHeader { + get { return showTextInHeader; } + set { showTextInHeader = value; } + } + private bool showTextInHeader = true; + + /// + /// Gets or sets whether the contents of the list will be resorted when the user clicks the + /// header of this column. + /// + /// + /// + /// If this is false, clicking the header will not sort the list, but will not provide + /// any feedback as to why the list is not being sorted. It is the programmers responsibility to + /// provide appropriate feedback. + /// + /// When this is false, BeforeSorting events are still fired, which can be used to allow sorting + /// or give feedback, on a case by case basis. + /// + [Category("ObjectListView"), + Description("Will clicking this columns header resort the list?"), + DefaultValue(true)] + public bool Sortable { + get { return sortable; } + set { sortable = value; } + } + private bool sortable = true; + + /// + /// Gets or sets the horizontal alignment of the contents of the column. + /// + /// .NET will not allow column 0 to have any alignment except + /// to the left. We can't change the basic behaviour of the listview, + /// but when owner drawn, column 0 can now have other alignments. + new public HorizontalAlignment TextAlign { + get { + return this.textAlign.HasValue ? this.textAlign.Value : base.TextAlign; + } + set { + this.textAlign = value; + base.TextAlign = value; + } + } + private HorizontalAlignment? textAlign; + + /// + /// Gets the StringAlignment equivalent of the column text alignment + /// + [Browsable(false)] + public StringAlignment TextStringAlign { + get { + switch (this.TextAlign) { + case HorizontalAlignment.Center: + return StringAlignment.Center; + case HorizontalAlignment.Left: + return StringAlignment.Near; + case HorizontalAlignment.Right: + return StringAlignment.Far; + default: + return StringAlignment.Near; + } + } + } + + /// + /// What string should be displayed when the mouse is hovered over the header of this column? + /// + /// If a HeaderToolTipGetter is installed on the owning ObjectListView, this + /// value will be ignored. + [Category("ObjectListView"), + Description("The tooltip to show when the mouse is hovered over the header of this column"), + DefaultValue((String)null), + Localizable(true)] + public String ToolTipText { + get { return toolTipText; } + set { toolTipText = value; } + } + private String toolTipText; + + /// + /// Should this column have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). + /// + [Category("ObjectListView"), + Description("Should values in this column be treated as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + } + } + private bool triStateCheckBoxes; + + /// + /// Group objects by the initial letter of the aspect of the column + /// + /// + /// One common pattern is to group column by the initial letter of the value for that group. + /// The aspect must be a string (obviously). + /// + [Category("ObjectListView"), + Description("The name of the property or method that should be called to get the aspect to display in this column"), + DefaultValue(false)] + public bool UseInitialLetterForGroup { + get { return useInitialLetterForGroup; } + set { useInitialLetterForGroup = value; } + } + private bool useInitialLetterForGroup; + + /// + /// Gets or sets whether or not this column should be user filterable + /// + [Category("ObjectListView"), + Description("Does this column want to show a Filter menu item when its header is right clicked"), + DefaultValue(true)] + public bool UseFiltering { + get { return useFiltering; } + set { useFiltering = value; } + } + private bool useFiltering = true; + + /// + /// Gets or sets a filter that will only include models where the model's value + /// for this column is one of the values in ValuesChosenForFiltering + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IModelFilter ValueBasedFilter { + get { + if (!this.UseFiltering) + return null; + + if (valueBasedFilter != null) + return valueBasedFilter; + + if (this.ClusteringStrategy == null) + return null; + + if (this.ValuesChosenForFiltering == null || this.ValuesChosenForFiltering.Count == 0) + return null; + + return this.ClusteringStrategy.CreateFilter(this.ValuesChosenForFiltering); + } + set { valueBasedFilter = value; } + } + private IModelFilter valueBasedFilter; + + /// + /// Gets or sets the values that will be used to generate a filter for this + /// column. For a model to be included by the generated filter, its value for this column + /// must be in this list. If the list is null or empty, this column will + /// not be used for filtering. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList ValuesChosenForFiltering { + get { return this.valuesChosenForFiltering; } + set { this.valuesChosenForFiltering = value; } + } + private IList valuesChosenForFiltering = new ArrayList(); + + /// + /// What is the width of this column? + /// + [Category("ObjectListView"), + Description("The width in pixels of this column"), + DefaultValue(60)] + public new int Width { + get { return base.Width; } + set { + if (this.MaximumWidth != -1 && value > this.MaximumWidth) + base.Width = this.MaximumWidth; + else + base.Width = Math.Max(this.MinimumWidth, value); + } + } + + /// + /// Gets or set whether the contents of this column's cells should be word wrapped + /// + /// If this column uses a custom IRenderer (that is, one that is not descended + /// from BaseRenderer), then that renderer is responsible for implementing word wrapping. + [Category("ObjectListView"), + Description("Draw this column cell's word wrapped"), + DefaultValue(false)] + public bool WordWrap { + get { return wordWrap; } + set { wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Object commands + + /// + /// For a given group value, return the string that should be used as the groups title. + /// + /// The group key that is being converted to a title + /// string + public string ConvertGroupKeyToTitle(object value) { + if (this.groupKeyToTitleConverter != null) + return this.groupKeyToTitleConverter(value); + + return value == null ? ObjectListView.GroupTitleDefault : this.ValueToString(value); + } + + /// + /// Get the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// The checkedness of the object + public CheckState GetCheckState(object rowObject) { + if (!this.CheckBoxes) + return CheckState.Unchecked; + + bool? aspectAsBool = this.GetValue(rowObject) as bool?; + if (aspectAsBool.HasValue) { + if (aspectAsBool.Value) + return CheckState.Checked; + else + return CheckState.Unchecked; + } else + return CheckState.Indeterminate; + } + + /// + /// Put the checkedness of the given object for this column + /// + /// The row object that is being displayed + /// + /// The checkedness of the object + public void PutCheckState(object rowObject, CheckState newState) { + if (newState == CheckState.Checked) + this.PutValue(rowObject, true); + else + if (newState == CheckState.Unchecked) + this.PutValue(rowObject, false); + else + this.PutValue(rowObject, null); + } + + /// + /// For a given row object, extract the value indicated by the AspectName property of this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect named by AspectName + public object GetAspectByName(object rowObject) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + return this.aspectMunger.GetValue(rowObject); + } + private Munger aspectMunger; + + /// + /// For a given row object, return the object that is the key of the group that this row belongs to. + /// + /// The row object that is being displayed + /// Group key object + public object GetGroupKey(object rowObject) { + if (this.groupKeyGetter != null) + return this.groupKeyGetter(rowObject); + + object key = this.GetValue(rowObject); + + if (this.UseInitialLetterForGroup) { + String keyAsString = key as String; + if (!String.IsNullOrEmpty(keyAsString)) + return keyAsString.Substring(0, 1).ToUpper(); + } + + return key; + } + + /// + /// For a given row object, return the image selector of the image that should displayed in this column. + /// + /// The row object that is being displayed + /// int or string or Image. int or string will be used as index into image list. null or -1 means no image + public Object GetImage(object rowObject) { + if (this.CheckBoxes) + return this.GetCheckStateImage(rowObject); + + if (this.ImageGetter != null) + return this.ImageGetter(rowObject); + + if (!String.IsNullOrEmpty(this.ImageAspectName)) { + if (this.imageAspectMunger == null) + this.imageAspectMunger = new Munger(this.ImageAspectName); + + return this.imageAspectMunger.GetValue(rowObject); + } + + // I think this is wrong. ImageKey is meant for the image in the header, not in the rows + if (!String.IsNullOrEmpty(this.ImageKey)) + return this.ImageKey; + + return this.ImageIndex; + } + private Munger imageAspectMunger; + + /// + /// Return the image that represents the check box for the given model + /// + /// + /// + public string GetCheckStateImage(Object rowObject) { + CheckState checkState = this.GetCheckState(rowObject); + + if (checkState == CheckState.Checked) + return ObjectListView.CHECKED_KEY; + + if (checkState == CheckState.Unchecked) + return ObjectListView.UNCHECKED_KEY; + + return ObjectListView.INDETERMINATE_KEY; + } + + /// + /// For a given row object, return the strings that will be searched when trying to filter by string. + /// + /// + /// This will normally be the simple GetStringValue result, but if this column is non-textual (e.g. image) + /// you might want to install a SearchValueGetter delegate which can return something that could be used + /// for text filtering. + /// + /// + /// The array of texts to be searched. If this returns null, search will not match that object. + public string[] GetSearchValues(object rowObject) { + if (this.SearchValueGetter != null) + return this.SearchValueGetter(rowObject); + + var stringValue = this.GetStringValue(rowObject); + + DescribedTaskRenderer dtr = this.Renderer as DescribedTaskRenderer; + if (dtr != null) { + return new string[] { stringValue, dtr.GetDescription(rowObject) }; + } + + return new string[] { stringValue }; + } + + /// + /// For a given row object, return the string representation of the value shown in this column. + /// + /// + /// For aspects that are string (e.g. aPerson.Name), the aspect and its string representation are the same. + /// For non-strings (e.g. aPerson.DateOfBirth), the string representation is very different. + /// + /// + /// + public string GetStringValue(object rowObject) + { + return this.ValueToString(this.GetValue(rowObject)); + } + + /// + /// For a given row object, return the object that is to be displayed in this column. + /// + /// The row object that is being displayed + /// An object, which is the aspect to be displayed + public object GetValue(object rowObject) { + if (this.AspectGetter == null) + return this.GetAspectByName(rowObject); + else + return this.AspectGetter(rowObject); + } + + /// + /// Update the given model object with the given value using the column's + /// AspectName. + /// + /// The model object to be updated + /// The value to be put into the model + public void PutAspectByName(Object rowObject, Object newValue) { + if (this.aspectMunger == null) + this.aspectMunger = new Munger(this.AspectName); + + this.aspectMunger.PutValue(rowObject, newValue); + } + + /// + /// Update the given model object with the given value + /// + /// The model object to be updated + /// The value to be put into the model + public void PutValue(Object rowObject, Object newValue) { + if (this.aspectPutter == null) + this.PutAspectByName(rowObject, newValue); + else + this.aspectPutter(rowObject, newValue); + } + + /// + /// Convert the aspect object to its string representation. + /// + /// + /// If the column has been given a AspectToStringConverter, that will be used to do + /// the conversion, otherwise just use ToString(). + /// The returned value will not be null. Nulls are always converted + /// to empty strings. + /// + /// The value of the aspect that should be displayed + /// A string representation of the aspect + public string ValueToString(object value) { + // Give the installed converter a chance to work (even if the value is null) + if (this.AspectToStringConverter != null) + return this.AspectToStringConverter(value) ?? String.Empty; + + // Without a converter, nulls become simple empty strings + if (value == null) + return String.Empty; + + string fmt = this.AspectToStringFormat; + if (String.IsNullOrEmpty(fmt)) + return value.ToString(); + else + return String.Format(fmt, value); + } + + #endregion + + #region Utilities + + /// + /// Decide the clustering strategy that will be used for this column + /// + /// + private IClusteringStrategy DecideDefaultClusteringStrategy() { + if (!this.UseFiltering) + return null; + + if (this.DataType == typeof(DateTime)) + return new DateTimeClusteringStrategy(); + + return new ClustersFromGroupsStrategy(); + } + + /// + /// Gets or sets the type of data shown in this column. + /// + /// If this is not set, it will try to get the type + /// by looking through the rows of the listview. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Type DataType { + get { + if (this.dataType == null) { + ObjectListView olv = this.ListView as ObjectListView; + if (olv != null) { + object value = olv.GetFirstNonNullValue(this); + if (value != null) + return value.GetType(); // THINK: Should we cache this? + } + } + return this.dataType; + } + set { + this.dataType = value; + } + } + private Type dataType; + + #region Events + + /// + /// This event is triggered when the visibility of this column changes. + /// + [Category("ObjectListView"), + Description("This event is triggered when the visibility of the column changes.")] + public event EventHandler VisibilityChanged; + + /// + /// Tell the world when visibility of a column changes. + /// + public virtual void OnVisibilityChanged(EventArgs e) + { + if (this.VisibilityChanged != null) + this.VisibilityChanged(this, e); + } + + #endregion + + /// + /// Create groupies + /// This is an untyped version to help with Generator and OLVColumn attributes + /// + /// + /// + public void MakeGroupies(object[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions) { + this.MakeGroupies(values, descriptions, null, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images) { + this.MakeGroupies(values, descriptions, images, null, null); + } + + /// + /// Create groupies + /// + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles) { + this.MakeGroupies(values, descriptions, images, subtitles, null); + } + + /// + /// Create groupies. + /// Install delegates that will group the columns aspects into progressive partitions. + /// If an aspect is less than value[n], it will be grouped with description[n]. + /// If an aspect has a value greater than the last element in "values", it will be grouped + /// with the last element in "descriptions". + /// + /// Array of values. Values must be able to be + /// compared to the aspect (using IComparable) + /// The description for the matching value. The last element is the default description. + /// If there are n values, there must be n+1 descriptions. + /// + /// this.salaryColumn.MakeGroupies( + /// new UInt32[] { 20000, 100000 }, + /// new string[] { "Lowly worker", "Middle management", "Rarified elevation"}); + /// + /// + /// + /// + /// + public void MakeGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length + 1 != descriptions.Length) + throw new ArgumentException("descriptions must have one more element than values."); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + Object aspect = this.GetValue(row); + if (aspect == null || aspect == DBNull.Value) + return -1; + IComparable comparable = (IComparable)aspect; + for (int i = 0; i < values.Length; i++) { + if (comparable.CompareTo(values[i]) < 0) + return i; + } + + // Display the last element in the array + return descriptions.Length - 1; + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + if ((int)key < 0) + return ""; + + return descriptions[(int)key]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + /// + /// Create groupies based on exact value matches. + /// + /// + /// Install delegates that will group rows into partitions based on equality of this columns aspects. + /// If an aspect is equal to value[n], it will be grouped with description[n]. + /// If an aspect is not equal to any value, it will be grouped with "[other]". + /// + /// Array of values. Values must be able to be + /// equated to the aspect + /// The description for the matching value. + /// + /// this.marriedColumn.MakeEqualGroupies( + /// new MaritalStatus[] { MaritalStatus.Single, MaritalStatus.Married, MaritalStatus.Divorced, MaritalStatus.Partnered }, + /// new string[] { "Looking", "Content", "Looking again", "Mostly content" }); + /// + /// + /// + /// + /// + public void MakeEqualGroupies(T[] values, string[] descriptions, object[] images, string[] subtitles, string[] tasks) { + // Sanity checks + if (values == null) + throw new ArgumentNullException("values"); + if (descriptions == null) + throw new ArgumentNullException("descriptions"); + if (values.Length != descriptions.Length) + throw new ArgumentException("descriptions must have the same number of elements as values."); + + ArrayList valuesArray = new ArrayList(values); + + // Install a delegate that returns the index of the description to be shown + this.GroupKeyGetter = delegate(object row) { + return valuesArray.IndexOf(this.GetValue(row)); + }; + + // Install a delegate that simply looks up the given index in the descriptions. + this.GroupKeyToTitleConverter = delegate(object key) { + int intKey = (int)key; // we know this is an int since we created it in GroupKeyGetter + return (intKey < 0) ? "[other]" : descriptions[intKey]; + }; + + // Install one delegate that does all the other formatting + this.GroupFormatter = delegate(OLVGroup group, GroupingParameters parms) { + int key = (int)group.Key; // we know this is an int since we created it in GroupKeyGetter + + if (key >= 0) { + if (images != null && key < images.Length) + group.TitleImage = images[key]; + + if (subtitles != null && key < subtitles.Length) + group.Subtitle = subtitles[key]; + + if (tasks != null && key < tasks.Length) + group.Task = tasks[key]; + } + }; + } + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.DesignTime.cs b/ObjectListView/ObjectListView.DesignTime.cs new file mode 100644 index 0000000..2fac113 --- /dev/null +++ b/ObjectListView/ObjectListView.DesignTime.cs @@ -0,0 +1,550 @@ +/* + * DesignSupport - Design time support for the various classes within ObjectListView + * + * Author: Phillip Piper + * Date: 12/08/2009 8:36 PM + * + * Change log: + * 2012-08-27 JPP - Fall back to more specific type name for the ListViewDesigner if + * the first GetType() fails. + * v2.5.1 + * 2012-04-26 JPP - Filter group events from TreeListView since it can't have groups + * 2011-06-06 JPP - Vastly improved ObjectListViewDesigner, based off information in + * "'Inheriting' from an Internal WinForms Designer" on CodeProject. + * v2.3 + * 2009-08-12 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Windows.Forms.Design; + +namespace BrightIdeasSoftware.Design +{ + + /// + /// Designer for and its subclasses. + /// + /// + /// + /// This designer removes properties and events that are available on ListView but that are not + /// useful on ObjectListView. + /// + /// + /// We can't inherit from System.Windows.Forms.Design.ListViewDesigner, since it is marked internal. + /// So, this class uses reflection to create a ListViewDesigner and then forwards messages to that designer. + /// + /// + public class ObjectListViewDesigner : ControlDesigner + { + + #region Initialize & Dispose + + /// + /// Initialises the designer with the specified component. + /// + /// The to associate the designer with. This component must always be an instance of, or derive from, . + public override void Initialize(IComponent component) { + // Debug.WriteLine("ObjectListViewDesigner.Initialize"); + + // Use reflection to bypass the "internal" marker on ListViewDesigner + // If we can't get the unversioned designer, look specifically for .NET 4.0 version of it. + Type tListViewDesigner = Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design") ?? + Type.GetType("System.Windows.Forms.Design.ListViewDesigner, System.Design, " + + "Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + if (tListViewDesigner == null) throw new ArgumentException("Could not load ListViewDesigner"); + + this.listViewDesigner = (ControlDesigner)Activator.CreateInstance(tListViewDesigner, BindingFlags.Instance | BindingFlags.Public, null, null, null); + this.designerFilter = this.listViewDesigner; + + // Fetch the methods from the ListViewDesigner that we know we want to use + this.listViewDesignGetHitTest = tListViewDesigner.GetMethod("GetHitTest", BindingFlags.Instance | BindingFlags.NonPublic); + this.listViewDesignWndProc = tListViewDesigner.GetMethod("WndProc", BindingFlags.Instance | BindingFlags.NonPublic); + + Debug.Assert(this.listViewDesignGetHitTest != null, "Required method (GetHitTest) not found on ListViewDesigner"); + Debug.Assert(this.listViewDesignWndProc != null, "Required method (WndProc) not found on ListViewDesigner"); + + // Tell the Designer to use properties of default designer as well as the properties of this class (do before base.Initialize) + TypeDescriptor.CreateAssociation(component, this.listViewDesigner); + + IServiceContainer site = (IServiceContainer)component.Site; + if (site != null && GetService(typeof(DesignerCommandSet)) == null) { + site.AddService(typeof(DesignerCommandSet), new CDDesignerCommandSet(this)); + } else { + Debug.Fail("site != null && GetService(typeof (DesignerCommandSet)) == null"); + } + + this.listViewDesigner.Initialize(component); + base.Initialize(component); + + RemoveDuplicateDockingActionList(); + } + + /// + /// Initialises a newly created component. + /// + /// A name/value dictionary of default values to apply to properties. May be null if no default values are specified. + public override void InitializeNewComponent(IDictionary defaultValues) { + // Debug.WriteLine("ObjectListViewDesigner.InitializeNewComponent"); + base.InitializeNewComponent(defaultValues); + this.listViewDesigner.InitializeNewComponent(defaultValues); + } + + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) { + // Debug.WriteLine("ObjectListViewDesigner.Dispose"); + if (disposing) { + if (this.listViewDesigner != null) { + this.listViewDesigner.Dispose(); + // Normally we would now null out the designer, but this designer + // still has methods called AFTER it is disposed. + } + } + + base.Dispose(disposing); + } + + /// + /// Removes the duplicate DockingActionList added by this designer to the . + /// + /// + /// adds an internal DockingActionList : 'Dock/Undock in Parent Container'. + /// But the default designer has already added that action list. So we need to remove one. + /// + private void RemoveDuplicateDockingActionList() { + // This is a true hack -- in a class that is basically a huge hack itself. + // Reach into the bowel of our base class, get a private field, and use that fields value to + // remove an action from the designer. + // In ControlDesigner, there is "private DockingActionList dockingAction;" + // Don't you just love Reflector?! + FieldInfo fi = typeof(ControlDesigner).GetField("dockingAction", BindingFlags.Instance | BindingFlags.NonPublic); + if (fi != null) { + DesignerActionList dockingAction = (DesignerActionList)fi.GetValue(this); + if (dockingAction != null) { + DesignerActionService service = (DesignerActionService)GetService(typeof(DesignerActionService)); + if (service != null) { + service.Remove(this.Control, dockingAction); + } + } + } + } + + #endregion + + #region IDesignerFilter overrides + + /// + /// Adjusts the set of properties the component exposes through a . + /// + /// An containing the properties for the class of the component. + protected override void PreFilterProperties(IDictionary properties) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterProperties"); + + // Always call the base PreFilterProperties implementation + // before you modify the properties collection. + base.PreFilterProperties(properties); + + // Give the listviewdesigner a chance to filter the properties + // (though we already know it's not going to do anything) + this.designerFilter.PreFilterProperties(properties); + + // I'd like to just remove the redundant properties, but that would + // break backward compatibility. The deserialiser that handles the XXX.Designer.cs file + // works off the designer, so even if the property exists in the class, the deserialiser will + // throw an error if the associated designer actually removes that property. + // So we shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + + List unwantedProperties = new List(new string[] { + "BackgroundImage", "BackgroundImageTiled", "HotTracking", "HoverSelection", + "LabelEdit", "VirtualListSize", "VirtualMode" }); + + // Also hid Tooltip properties, since giving a tooltip to the control through the IDE + // messes up the tooltip handling + foreach (string propertyName in properties.Keys) { + if (propertyName.StartsWith("ToolTip")) { + unwantedProperties.Add(propertyName); + } + } + + // If we are looking at a TreeListView, remove group related properties + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwantedProperties.AddRange(new string[] { + "GroupImageList", "GroupWithItemCountFormat", "GroupWithItemCountSingularFormat", "HasCollapsibleGroups", + "SpaceBetweenGroups", "ShowGroups", "SortGroupItemsByPrimaryColumn", "ShowItemCountOnGroups" + }); + } + + // Shadow the unwanted properties, and give the replacement properties + // non-browsable attributes so that they are hidden from the user + foreach (string unwantedProperty in unwantedProperties) { + PropertyDescriptor propertyDesc = TypeDescriptor.CreateProperty( + typeof(ObjectListView), + (PropertyDescriptor)properties[unwantedProperty], + new BrowsableAttribute(false)); + properties[unwantedProperty] = propertyDesc; + } + } + + /// + /// Allows a designer to add to the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PreFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PreFilterEvents"); + base.PreFilterEvents(events); + this.designerFilter.PreFilterEvents(events); + + // Remove the events that don't make sense for an ObjectListView. + // See PreFilterProperties() for why we do this dance rather than just remove the event. + List unwanted = new List(new string[] { + "AfterLabelEdit", + "BeforeLabelEdit", + "DrawColumnHeader", + "DrawItem", + "DrawSubItem", + "RetrieveVirtualItem", + "SearchForVirtualItem", + "VirtualItemsSelectionRangeChanged" + }); + + // If we are looking at a TreeListView, remove group related events + // since TreeListViews can't show groups + if (this.Control is TreeListView) { + unwanted.AddRange(new string[] { + "AboutToCreateGroups", + "AfterCreatingGroups", + "BeforeCreatingGroups", + "GroupTaskClicked", + "GroupExpandingCollapsing", + "GroupStateChanged" + }); + } + + foreach (string unwantedEvent in unwanted) { + EventDescriptor eventDesc = TypeDescriptor.CreateEvent( + typeof(ObjectListView), + (EventDescriptor)events[unwantedEvent], + new BrowsableAttribute(false)); + events[unwantedEvent] = eventDesc; + } + } + + /// + /// Allows a designer to change or remove items from the set of attributes that it exposes through a . + /// + /// The attributes for the class of the component. + protected override void PostFilterAttributes(IDictionary attributes) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterAttributes"); + this.designerFilter.PostFilterAttributes(attributes); + base.PostFilterAttributes(attributes); + } + + /// + /// Allows a designer to change or remove items from the set of events that it exposes through a . + /// + /// The events for the class of the component. + protected override void PostFilterEvents(IDictionary events) { + // Debug.WriteLine("ObjectListViewDesigner.PostFilterEvents"); + this.designerFilter.PostFilterEvents(events); + base.PostFilterEvents(events); + } + + #endregion + + #region Overrides + + /// + /// Gets the design-time action lists supported by the component associated with the designer. + /// + /// + /// The design-time action lists supported by the component associated with the designer. + /// + public override DesignerActionListCollection ActionLists { + get { + // We want to change the first action list so it only has the commands we want + DesignerActionListCollection actionLists = this.listViewDesigner.ActionLists; + if (actionLists.Count > 0 && !(actionLists[0] is ListViewActionListAdapter)) { + actionLists[0] = new ListViewActionListAdapter(this, actionLists[0]); + } + return actionLists; + } + } + + /// + /// Gets the collection of components associated with the component managed by the designer. + /// + /// + /// The components that are associated with the component managed by the designer. + /// + public override ICollection AssociatedComponents { + get { + ArrayList components = new ArrayList(base.AssociatedComponents); + components.AddRange(this.listViewDesigner.AssociatedComponents); + return components; + } + } + + /// + /// Indicates whether a mouse click at the specified point should be handled by the control. + /// + /// + /// true if a click at the specified point is to be handled by the control; otherwise, false. + /// + /// A indicating the position at which the mouse was clicked, in screen coordinates. + protected override bool GetHitTest(Point point) { + // The ListViewDesigner wants to allow column dividers to be resized + return (bool)this.listViewDesignGetHitTest.Invoke(listViewDesigner, new object[] { point }); + } + + /// + /// Processes Windows messages and optionally routes them to the control. + /// + /// The to process. + protected override void WndProc(ref Message m) { + switch (m.Msg) { + case 0x4e: + case 0x204e: + // The listview designer is interested in HDN_ENDTRACK notifications + this.listViewDesignWndProc.Invoke(listViewDesigner, new object[] { m }); + break; + default: + base.WndProc(ref m); + break; + } + } + + #endregion + + #region Implementation variables + + private ControlDesigner listViewDesigner; + private IDesignerFilter designerFilter; + private MethodInfo listViewDesignGetHitTest; + private MethodInfo listViewDesignWndProc; + + #endregion + + #region Custom action list + + /// + /// This class modifies a ListViewActionList, by removing the "Edit Items" and "Edit Groups" actions. + /// + /// + /// + /// That class is internal, so we cannot simply subclass it, which would be simpler. + /// + /// + /// Action lists use reflection to determine if that action can be executed, so we not + /// only have to modify the returned collection of actions, but we have to implement + /// the properties and commands that the returned actions use. + /// + private class ListViewActionListAdapter : DesignerActionList + { + public ListViewActionListAdapter(ObjectListViewDesigner designer, DesignerActionList wrappedList) + : base(wrappedList.Component) { + this.designer = designer; + this.wrappedList = wrappedList; + } + + public override DesignerActionItemCollection GetSortedActionItems() { + DesignerActionItemCollection items = wrappedList.GetSortedActionItems(); + items.RemoveAt(2); // remove Edit Groups + items.RemoveAt(0); // remove Edit Items + return items; + } + + private void EditValue(ComponentDesigner componentDesigner, IComponent iComponent, string propertyName) { + // One more complication. The ListViewActionList classes uses an internal class, EditorServiceContext, to + // edit the items/columns/groups collections. So, we use reflection to bypass the data hiding. + Type tEditorServiceContext = Type.GetType("System.Windows.Forms.Design.EditorServiceContext, System.Design"); + tEditorServiceContext.InvokeMember("EditValue", BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object[] { componentDesigner, iComponent, propertyName }); + } + + private void SetValue(object target, string propertyName, object value) { + TypeDescriptor.GetProperties(target)[propertyName].SetValue(target, value); + } + + public void InvokeColumnsDialog() { + EditValue(this.designer, base.Component, "Columns"); + } + + // Don't need these since we removed their corresponding actions from the list. + // Keep the methods just in case. + + //public void InvokeGroupsDialog() { + // EditValue(this.designer, base.Component, "Groups"); + //} + + //public void InvokeItemsDialog() { + // EditValue(this.designer, base.Component, "Items"); + //} + + public ImageList LargeImageList { + get { return ((ListView)base.Component).LargeImageList; } + set { SetValue(base.Component, "LargeImageList", value); } + } + + public ImageList SmallImageList { + get { return ((ListView)base.Component).SmallImageList; } + set { SetValue(base.Component, "SmallImageList", value); } + } + + public View View { + get { return ((ListView)base.Component).View; } + set { SetValue(base.Component, "View", value); } + } + + ObjectListViewDesigner designer; + DesignerActionList wrappedList; + } + + #endregion + + #region DesignerCommandSet + + private class CDDesignerCommandSet : DesignerCommandSet + { + + public CDDesignerCommandSet(ComponentDesigner componentDesigner) { + this.componentDesigner = componentDesigner; + } + + public override ICollection GetCommands(string name) { + // Debug.WriteLine("CDDesignerCommandSet.GetCommands:" + name); + if (componentDesigner != null) { + if (name.Equals("Verbs")) { + return componentDesigner.Verbs; + } + if (name.Equals("ActionLists")) { + return componentDesigner.ActionLists; + } + } + return base.GetCommands(name); + } + + private readonly ComponentDesigner componentDesigner; + } + + #endregion + } + + /// + /// This class works in conjunction with the OLVColumns property to allow OLVColumns + /// to be added to the ObjectListView. + /// + public class OLVColumnCollectionEditor : System.ComponentModel.Design.CollectionEditor + { + /// + /// Create a OLVColumnCollectionEditor + /// + /// + public OLVColumnCollectionEditor(Type t) + : base(t) { + } + + /// + /// What type of object does this editor create? + /// + /// + protected override Type CreateCollectionItemType() { + return typeof(OLVColumn); + } + + /// + /// Edit a given value + /// + /// + /// + /// + /// + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + if (context == null) + throw new ArgumentNullException("context"); + if (provider == null) + throw new ArgumentNullException("provider"); + + // Figure out which ObjectListView we are working on. This should be the Instance of the context. + ObjectListView olv = context.Instance as ObjectListView; + Debug.Assert(olv != null, "Instance must be an ObjectListView"); + + // Edit all the columns, not just the ones that are visible + base.EditValue(context, provider, olv.AllColumns); + + // Set the columns on the ListView to just the visible columns + List newColumns = olv.GetFilteredColumns(View.Details); + olv.Columns.Clear(); + olv.Columns.AddRange(newColumns.ToArray()); + + return olv.Columns; + } + + /// + /// What text should be shown in the list for the given object? + /// + /// + /// + protected override string GetDisplayText(object value) { + OLVColumn col = value as OLVColumn; + if (col == null || String.IsNullOrEmpty(col.AspectName)) + return base.GetDisplayText(value); + + return String.Format("{0} ({1})", base.GetDisplayText(value), col.AspectName); + } + } + + /// + /// Control how the overlay is presented in the IDE + /// + internal class OverlayConverter : ExpandableObjectConverter + { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { + return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); + } + + public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { + if (destinationType == typeof(string)) { + ImageOverlay imageOverlay = value as ImageOverlay; + if (imageOverlay != null) { + return imageOverlay.Image == null ? "(none)" : "(set)"; + } + TextOverlay textOverlay = value as TextOverlay; + if (textOverlay != null) { + return String.IsNullOrEmpty(textOverlay.Text) ? "(none)" : "(set)"; + } + } + + return base.ConvertTo(context, culture, value, destinationType); + } + } +} diff --git a/ObjectListView/ObjectListView.FxCop b/ObjectListView/ObjectListView.FxCop new file mode 100644 index 0000000..b5653dd --- /dev/null +++ b/ObjectListView/ObjectListView.FxCop @@ -0,0 +1,3521 @@ + + + + True + c:\program files\microsoft fxcop 1.36\Xml\FxCopReport.xsl + + + + + + True + True + True + 10 + 1 + + False + + False + 120 + True + 2.0 + + + + $(ProjectDir)/trunk/ObjectListView/bin/Debug/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 'ObjectListView.dll' + + + + + + + + + + + 'BarRenderer' + 'Pen' + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BarRenderer(int, int, Pen, Brush)' + 'BarRenderer.UseStandardBar' + 'bool' + false + + + + + + + + + + + + + + 'BarRenderer.BackgroundColor' + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + + + + + 'BaseRenderer.GetBackgroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetForegroundColor()' + + + + + + + + + + + + + + 'BaseRenderer.GetImageSelector()' + + + + + + + + + 'BaseRenderer.GetText()' + + + + + + + + + + + + + + 'BaseRenderer.GetTextBackgroundColor()' + + + + + + + + + + + + + + + + 'BorderDecoration' + 'SolidBrush' + + + + + + + + + 'CellEditEventHandler' + + + + + + + + + + + + + + + + 'g' + 'CheckStateRenderer.CalculateCheckBoxBounds(Graphics, Rectangle)' + + + + + + + + + + + 'ColumnRightClickEventHandler' + + + + + + + + + + + + + + + + + + 'ComboBoxItem.Key.get()' + + + + + + + + + + + + + + + 'DataListView.currencyManager_ListChanged(object, ListChangedEventArgs)' + + + + + + + + + 'DataListView.currencyManager_MetaDataChanged(object, EventArgs)' + + + + + + + + + 'DataListView.currencyManager_PositionChanged(object, EventArgs)' + + + + + + + + + + + + + 'DescribedTaskRenderer.GetDescription()' + + + + + + + + + + + 'DropTargetLocation' + + + + + + + + + + + 'collection' + 'ICollection' + 'FastObjectListDataSource.EnumerableToArray(IEnumerable)' + castclass + + + + + + + + + + + 'FastObjectListDataSource.FilteredObjectList.get()' + + + + + + + + + + + + + Flag + 'FlagRenderer' + + + + + + + + + + + + + 'FloatCellEditor.Value.get()' + + + + + + + + + + + + + + 'FloatCellEditor.Value.set(double)' + + + + + + + + + + + + + + + + + + + + + + 'GlassPanelForm.CreateParams.get()' + 'Form.CreateParams.get()' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GlassPanelForm.WndProc(ref Message)' + 'Form.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + + + + + + + 'GroupMetricsMask' + 'GroupMetricsMask.LVGMF_NONE' + + + + + + + + + + 'GroupMetricsMask' + + + + + + + + + + + + + + 'GroupState' + 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 + + + + + 'GroupState' + 'GroupState.LVGS_NORMAL' + + + + + 'GroupState' + + + + + + + + + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.AssignHandle(IntPtr)' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + 'HeaderControl.HeaderControl(ObjectListView)' + 'NativeWindow.NativeWindow()' + ->'HeaderControl.HeaderControl(ObjectListView)' ->'HeaderControl.HeaderControl(ObjectListView)' + + + + + + + + + + + + + + 'g' + 'HeaderControl.CalculateHeight(Graphics)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawHeaderText(Graphics, Rectangle, OLVColumn, HeaderStateStyle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedBackground(Graphics, Rectangle, int, bool)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + 'g' + 'HeaderControl.DrawThemedSortIndicator(Graphics, Rectangle)' + 'Graphics' + 'IDeviceContext' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedBackground(Graphics, Rectangle, int, bool, HeaderStateStyle)' + + + + + + + + + Unthemed + 'HeaderControl.DrawUnthemedSortIndicator(Graphics, Rectangle)' + + + + + + + + + 'm' + 'HeaderControl.HandleDestroy(ref Message)' + + + + + + + + + 'm' + 'HeaderControl.HandleMouseMove(ref Message)' + + + + + 'm' + + + + + + + + + + + + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + 'HeaderControl.HandleNotify(ref Message)' + 'Message.LParam.get()' + ->'HeaderControl.HandleNotify(ref Message)' ->'HeaderControl.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + + + 'value' + 'HeaderControl.HotFontStyle.set(FontStyle)' + + + + + + + + + + + Flags + 'HeaderControl.TextFormatFlags' + + + + + + + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'HeaderControl.WndProc(ref Message)' + 'Message.Msg.get()' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + 'HeaderControl.WndProc(ref Message)' + 'NativeWindow.WndProc(ref Message)' + ->'HeaderControl.WndProc(ref Message)' ->'HeaderControl.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'text' + 'HighlightTextRenderer.HighlightTextRenderer(string)' + + + + + + + + + + + 'value' + 'HighlightTextRenderer.StringComparison.set(StringComparison)' + + + + + + + + + + + + + 'value' + 'HighlightTextRenderer.TextToHighlight.set(string)' + + + + + + + + + + + + + + + + + 'HyperlinkEventArgs.Column.set(OLVColumn)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ColumnIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Item.set(OLVListItem)' + + + + + + + + + + + + + 'HyperlinkEventArgs.ListView.set(ObjectListView)' + + + + + + + + + + + + + 'HyperlinkEventArgs.Model.set(object)' + + + + + + + + + + + + + 'HyperlinkEventArgs.RowIndex.set(int)' + + + + + + + + + + + + + 'HyperlinkEventArgs.SubItem.set(OLVListSubItem)' + + + + + + + + + + + 'HyperlinkEventArgs.Url' + + + + + + + + + 'HyperlinkEventArgs.Url.set(string)' + + + + + + + + + + + + + + + 'ImageRenderer.GetImageFromAspect()' + + + + + + + + + + + + + + + + + + + + 'IntUpDown.Value.get()' + + + + + + + + + + + + + + 'IntUpDown.Value.set(int)' + + + + + + + + + + + + + + + + + + + + 'IVirtualListDataSource.GetObjectCount()' + + + + + + + + + + + + + + + + Multi + 'MultiImageRenderer' + + + + + + + + + + + + + + 'MultiImageRenderer.ImageSelector' + 'BaseRenderer.GetImageSelector()' + + + + + + + + + + + + + 'Munger.GetValue(object)' + 'object' + + + + + + + + + + + + + + 'Munger.PutValue(object, object)' + 'object' + + + 'Munger.PutValue(object, object)' + 'object' + + + + + + + + + + + + + + + + + + 'NativeMethods.ChangeSize(IWin32Window, int, int)' + + + + + + + + + 'NativeMethods.ChangeZOrder(IWin32Window, IWin32Window)' + + + + + + + + + 'NativeMethods.DeleteObject(IntPtr)' + + + + + + + + + 'NativeMethods.DrawImageList(Graphics, ImageList, int, int, int, bool)' + + + + + + + + + 'NativeMethods.GetClientRect(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + + + + + 'NativeMethods.GetColumnSides(ObjectListView, int)' + 'Point' + + + + + + + + + 'NativeMethods.GetGroupInfo(ObjectListView, int, ref NativeMethods.LVGROUP2)' + + + + + + + + + 'NativeMethods.GetScrollInfo(IntPtr, int, NativeMethods.SCROLLINFO)' + + + + + + + + + 'NativeMethods.GetUpdateRect(Control)' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'eraseBackground' + 'NativeMethods.GetUpdateRectInternal(IntPtr, ref Rectangle, bool)' + + + + + + + + + 'NativeMethods.GetWindowLong32(IntPtr, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'NativeMethods.GetWindowLongPtr64(IntPtr, int)' + 'user32.dll' + GetWindowLongPtr + + + + + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + 'NativeMethods.ImageList_Draw(IntPtr, int, IntPtr, int, int, int)' + + + + + + + + + 'erase' + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + 'NativeMethods.InvalidateRect(IntPtr, int, bool)' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUP2)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVGROUPMETRICS)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, ref NativeMethods.LVHITTESTINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessage(IntPtr, int, int, IntPtr)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'lParam' + 'NativeMethods.SendMessage(IntPtr, int, IntPtr, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageHDItem(IntPtr, int, int, ref NativeMethods.HDITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + + + + + 'lParam' + 'NativeMethods.SendMessageIUnknown(IntPtr, int, object, int)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + + + + + 'wParam' + 'NativeMethods.SendMessageLVBKIMAGE(IntPtr, int, int, ref NativeMethods.LVBKIMAGE)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageLVItem(IntPtr, int, int, ref NativeMethods.LVITEM)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageRECT(IntPtr, int, int, ref NativeMethods.RECT)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageString(IntPtr, int, int, string)' + 4 + 64-bit + 8 + 'int' + + + + + 'lParam' + + + + + + + + + 'wParam' + 'NativeMethods.SendMessageTOOLINFO(IntPtr, int, int, NativeMethods.TOOLINFO)' + 4 + 64-bit + 8 + 'int' + + + + + + + + + 'NativeMethods.SetBackgroundImage(ListView, Image)' + + + + + + + + + 'NativeMethods.SetBkColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetSelectedColumn(ListView, ColumnHeader)' + + + + + + + + + 'NativeMethods.SetTextColor(IntPtr, int)' + + + + + + + + + 'NativeMethods.SetTooltipControl(ListView, ToolTipControl)' + + + + + + + + + 'NativeMethods.SetWindowLongPtr32(IntPtr, int, int)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + + + + + 'dwNewLong' + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 4 + 64-bit + 8 + 'int' + + + + + 'NativeMethods.SetWindowLongPtr64(IntPtr, int, int)' + 'user32.dll' + SetWindowLongPtr + + + + + + + + + 'NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, uint)' + + + + + + + + + 'NativeMethods.SetWindowTheme(IntPtr, string, string)' + 8 + 64-bit + 4 + 'IntPtr' + + + + + 'subApp' + + + + + 'subIdList' + + + + + + + + + 'NativeMethods.ShowWindow(IntPtr, int)' + + + + + + + + + 'NativeMethods.ValidatedRectInternal(IntPtr, ref Rectangle)' + + + + + + + + + 'NativeMethods.ValidateRect(Control, Rectangle)' + + + + + + + + + + + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.ColumnIndexUnderCursor.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'HeaderControl.IsCursorOverLockedDivider.get()' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'OLVListItem.GetSubItemBounds(int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.CalculateCellBounds(OLVListItem, int, ItemBoundsPortion)' ->'ObjectListView.CalculateCellTextBounds(OLVListItem, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'ObjectListView.OlvHitTest(int, int)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'NativeMethods.GetScrolledColumnSides(ListView, int)' ->'TintedColumnDecoration.Draw(ObjectListView, Graphics, Rectangle)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.EnsureGroupVisible(ListViewGroup)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleBeginScroll(ref Message)' + + + 'NativeMethods.SCROLLINFO.SCROLLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.SCROLLINFO.SCROLLINFO()' ->'NativeMethods.GetScrollPosition(ListView, bool)' ->'ObjectListView.HandleKeyDown(ref Message)' + + + + + + + + + + + + + + + + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.AddTool(IWin32Window)' + + + 'NativeMethods.TOOLINFO.TOOLINFO()' + 'Marshal.SizeOf(Type)' + ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'NativeMethods.TOOLINFO.TOOLINFO()' ->'ToolTipControl.MakeToolInfoStruct(IWin32Window)' ->'ToolTipControl.RemoveToolTip(IWin32Window)' + + + + + + + + + + + + + + + + + + 'ObjectListView.AllColumns' + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.AllColumns' + + + + + + + + + + + + + + 'rowIndex' + 'ObjectListView.ApplyHyperlinkStyle(int, OLVListItem)' + + + + + + + + + 'ObjectListView.BooleanCheckStateGetter' + + + + + + + + + 'ObjectListView.BooleanCheckStatePutter' + + + + + + + + + 'item' + 'ObjectListView.CalculateCellBounds(OLVListItem, int)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'ObjectListView.CellEditor' + 'ObjectListView.GetCellEditor(OLVListItem, int)' + + + + + + + + + 'ObjectListView.CellEditor_Validating(object, CancelEventArgs)' + + + + + + + + + 'ObjectListView.CellToolTip' + 'ObjectListView.GetCellToolTip(int, int)' + + + + + + + + + 'ObjectListView.CheckedObject' + 'ObjectListView.GetCheckedObject()' + + + + + + + + + 'ObjectListView.CheckedObjects' + 'ObjectListView.GetCheckedObjects()' + + + + + 'ObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.ColumnsInDisplayOrder' + + + + + + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn)' + tb + 'tb' + + + + + + + + + 'ObjectListView.ConfigureAutoComplete(TextBox, OLVColumn, int)' + tb + 'tb' + + + + + + + + + 'List<OLVListItem>' + 'ObjectListView.DrawAllDecorations(Graphics, List<OLVListItem>)' + + + + + + + + + 'ObjectListView.EditorRegistry' + + + + + + + + + 'ObjectListView.EnsureGroupVisible(ListViewGroup)' + lvg + 'lvg' + + + + + + + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aListFilter' + + + 'ObjectListView.FilterObjects(IEnumerable, IModelFilter, IListFilter)' + a + 'aModelFilter' + + + + + + + + + 'control' + 'CheckBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'ComboBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + 'control' + 'TextBox' + 'ObjectListView.GetControlValue(Control)' + castclass + + + + + + + + + 'List<OLVColumn>' + 'ObjectListView.GetFilteredColumns(View)' + + + + + + + + + + + + + + 'selectedColumn' + + + + + + + + + + + + + + 'ObjectListView.GetItemCount()' + + + + + + + + + + + + + + 'ObjectListView.GetLastItemInDisplayOrder()' + + + + + + + + + 'ObjectListView.GetSelectedObject()' + + + + + + + + + + + + + + 'ObjectListView.GetSelectedObjects()' + + + + + + + + + + + + + + 'ObjectListView.HandleApplicationIdle(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleApplicationIdle_ResizeColumns(object, EventArgs)' + + + + + + + + + 'ObjectListView.HandleCellToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleChar(ref Message)' + 'Control.ProcessKeyEventArgs(ref Message)' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + 'ObjectListView.HandleChar(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleChar(ref Message)' ->'ObjectListView.HandleChar(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleColumnClick(object, ColumnClickEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanged(object, ColumnWidthChangedEventArgs)' + + + + + + + + + 'ObjectListView.HandleColumnWidthChanging(object, ColumnWidthChangingEventArgs)' + + + + + + + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + 'ObjectListView.HandleContextMenu(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleContextMenu(ref Message)' ->'ObjectListView.HandleContextMenu(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + 'ObjectListView.HandleFindItem(ref Message)' + 'Message.WParam.get()' + ->'ObjectListView.HandleFindItem(ref Message)' ->'ObjectListView.HandleFindItem(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleHeaderToolTipShowing(object, ToolTipShowingEventArgs)' + + + + + + + + + 'ObjectListView.HandleLayout(object, LayoutEventArgs)' + + + + + + + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.PtrToStructure(IntPtr, Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'Message.Result.set(IntPtr)' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + 'ObjectListView.HandleNotify(ref Message)' + 'NativeWindow.Handle.get()' + ->'ObjectListView.HandleNotify(ref Message)' ->'ObjectListView.HandleNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Marshal.StructureToPtr(object, IntPtr, bool)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.GetLParam(Type)' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + 'ObjectListView.HandleReflectNotify(ref Message)' + 'Message.LParam.get()' + ->'ObjectListView.HandleReflectNotify(ref Message)' ->'ObjectListView.HandleReflectNotify(ref Message)' + + + + + + + + + + 'm' + + + + + + + + + + + + + + 'ObjectListView.HeaderToolTip' + 'ObjectListView.GetHeaderToolTip(int)' + + + + + + + + + 'url' + 'ObjectListView.IsUrlVisited(string)' + + + + + + + + + 'url' + 'ObjectListView.MarkUrlVisited(string)' + + + + + + + + + Unsort + 'ObjectListView.MenuLabelUnsort' + + + + + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)] + + + + + 'ObjectListView.ProcessDialogKey(Keys)' + 'Control.ProcessDialogKey(Keys)' + ->'ObjectListView.ProcessDialogKey(Keys)' ->'ObjectListView.ProcessDialogKey(Keys)' + + + + + + + + + + + + + + 'ObjectListView.SelectedObject' + 'ObjectListView.GetSelectedObject()' + + + + + + + + + 'ObjectListView.SelectedObjects' + 'ObjectListView.GetSelectedObjects()' + + + + + 'ObjectListView.SelectedObjects' + + + + + + + + + + + + + + 'control' + 'ComboBox' + 'ObjectListView.SetControlValue(Control, object, string)' + castclass + + + + + + + + + Checkedness + 'ObjectListView.SetObjectCheckedness(object, CheckState)' + + + + + + + + + + + + + + 'item' + 'ObjectListView.SetSubItemImages(int, OLVListItem, bool)' + 'OLVListItem' + 'ListViewItem' + + + + + + + + + + + + + + 'columnToSort' + 'ObjectListView.ShowSortIndicator(OLVColumn, SortOrder)' + 'OLVColumn' + 'ColumnHeader' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_DOWN_KEY' + + + + + + + + + + + + + + 'ObjectListView.SORT_INDICATOR_UP_KEY' + + + + + + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.BeginInit()' + + + + + + + + + 'ObjectListView' + 'ISupportInitialize.EndInit()' + + + + + + + + + Renderering + 'ObjectListView.TextRendereringHint' + + + + + + + + + Unsort + 'ObjectListView.Unsort()' + + + + + + + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + + + + + 'ObjectListView.WndProc(ref Message)' + 'Control.DefWndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'ListView.WndProc(ref Message)' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + 'ObjectListView.WndProc(ref Message)' + 'Message.Msg.get()' + ->'ObjectListView.WndProc(ref Message)' ->'ObjectListView.WndProc(ref Message)' + + + + + + + + + + + + + + + + + + 'ObjectListView.ObjectListViewState.VersionNumber' + + + + + + + + + + + + + + + + 'OLVColumnAttribute' + + + + + 'OLVColumnAttribute.Title' + 'title' + + + + + 'OLVColumnAttribute' + + + + + + + + + Cutoffs + 'OLVColumnAttribute.GroupCutoffs' + + + + + 'OLVColumnAttribute.GroupCutoffs' + + + + + + + + + 'OLVColumnAttribute.GroupDescriptions' + + + + + + + + + + + + + 'OLVDataObject.ConvertToHtmlFragment(string)' + 'string.IndexOf(string)' + 'string.IndexOf(string, StringComparison)' + + + + + + + + + + + + + 'OLVGroup.GetState()' + + + + + + + + + 'OLVGroup.State' + 'OLVGroup.GetState()' + + + + + + + + + Subseted + 'OLVGroup.Subseted' + + + + + + + + + + + 'OLVListItem' + + + + + + + + + 'OLVListItem.Bounds' + 'ListViewItem.GetBounds(ItemBoundsPortion)' + + + + + + + + + + + 'value' + 'string' + 'OLVListItem.ImageSelector.set(object)' + castclass + + + + + + + + + + + + + + + 'OLVListSubItem.Url' + + + + + + + + + + + 'SimpleDropSink' + 'Timer' + + + + + + + + + 'Timer.Interval.set(int)' + 'SimpleDropSink.SimpleDropSink()' + + + + + + + + + + + 'TextAdornment' + 'StringFormat' + + + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[])' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, TextMatchFilter.MatchKind)' + StringComparison.InvariantCultureIgnoreCase + 'TextMatchFilter.TextMatchFilter(ObjectListView, string, OLVColumn[], TextMatchFilter.MatchKind, StringComparison)' + + + + + + + + + 'TextMatchFilter.Columns' + + + + + + + + + 'TextMatchFilter.IsIncluded(OLVColumn)' + + + + + + + + + + + 'TextMatchFilter.MatchKind' + + + + + + + + + + + + + + 'TintedColumnDecoration' + 'SolidBrush' + + + + + + + + + + + Disp + 'ToolTipControl.HandleGetDispInfo(ref Message)' + + + + + + + + + + + + + + 'window' + 'ToolTipControl.PopToolTip(IWin32Window)' + + + + + + + + + + + 'ToolTipControl.StandardIcons' + + + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.ChildBranches' + + + + + + + + + 'List<TreeListView.Branch>' + 'TreeListView.Branch.FilteredChildBranches' + + + + + + + + + Flag + 'TreeListView.Branch.ManageLastChildFlag(MethodInvoker)' + + + + + + + + + + + Flags + 'TreeListView.Branch.BranchFlags' + + + + + + + + + + + 'TreeListView.Tree.GetBranchComparer()' + + + + + + + + + + + + + + + + + + 'TreeListView.TreeRenderer.PIXELS_PER_LEVEL' + + + + + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStateGetter' + + + + + + + + + 'TypedObjectListView<T>.BooleanCheckStatePutter' + + + + + + + + + 'TypedObjectListView<T>.CellToolTipGetter' + + + + + + + + + 'TypedObjectListView<T>.CheckedObjects' + + + + + + + + + + + + + + 'TypedObjectListView<T>.SelectedObjects' + + + + + + + + + + + + + + + + + + + + 'UintUpDown.Value.get()' + + + + + + + + + + + + + + 'UintUpDown.Value.set(uint)' + + + + + + + + + + + + + + + + + + + + 'VirtualObjectListView.CheckedObjects' + + + + + + + + + + + + + + 'VirtualObjectListView.HandleCacheVirtualItems(object, CacheVirtualItemsEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleRetrieveVirtualItem(object, RetrieveVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.HandleSearchForVirtualItem(object, SearchForVirtualItemEventArgs)' + + + + + + + + + 'VirtualObjectListView.SetVirtualListSize(int)' + 'Exception' + + + + + + + + + + + + + + + + + + + + + These should be methods rather than properties + The out parameter is necessary since this method returns two pieces of information: the item under the point and the subitem item too + This is used to ensure we understand the newly load state. + All these properties should be assignable. + Our project is build with unsafe code enabled, so it automatically has the SecurityProperty set + These initializations are not unnecessary + We have to pass the windows message by reference + Instances of this class do not need to be disposable + These are utility methods that could well be used at runtime + Old style constants. Can't change now + These are OK like this. We need List<>, not IList<> since only List has a ToArray() method + Legacy cases that have to be kept like this + These are acceptable as methods rather than properties + windows messages should be passed by reference + This is not a security risk + There are several problems that can occur here and we want to ignore them all + These spellings are acceptable + These will only be used by OL types + + + Not appropriate here + Can't change now + we want to catch everthing + MS! + not flags + MS! + MS + + + + + Sign {0} with a strong name key. + + + Consider a design that does not require that {0} be an out parameter. + + + {0} appears to have no upstream public or protected callers. + + + Seal {0}, if possible. + + + It appears that field {0} is never used or is only ever assigned to. Use this field or remove it. + + + Change {0} to be read-only by removing the property setter. + + + Consider changing the type of parameter {0} in {1} from {2} to its base type {3}. This method appears to only require base class members in its implementation. Suppress this violation if there is a compelling reason to require the more derived type in the method signature. + + + Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. + + + {0}, a parameter, is cast to type {1} multiple times in method {2}. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant {3} instruction. + + + Modify {0} to catch a more specific exception than {1} or rethrow the exception. + + + Change {0} in {1} to use Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V> + + + {0} calls {1} but does not use the HRESULT or error code that the method returns. This could lead to unexpected behavior in error conditions or low-resource situations. Use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method. + {0} creates a new instance of {1} which is never used. Pass the instance as an argument to another method, assign the instance to a variable, or remove the object creation if it is unnecessary. + + + + {0} initializes field {1} of type {2} to {3}. Remove this initialization because it will be done automatically by the runtime. + + + {0} is marked with FlagsAttribute but a discrete member cannot be found for every settable bit that is used across the range of enum values. Remove FlagsAttribute from the type or define new members for the following (currently missing) values: {1} + + + + Modify the call to {0} in method {1} to set the timer interval to a value that's greater than or equal to one second. + + + In enum {0}, change the name of {1} to 'None'. + + + If enumeration name {0} is singular, change it to a plural form. + + + Correct the spelling of '{0}' in member name {1} or remove it entirely if it represents any sort of Hungarian notation. + In method {0}, correct the spelling of '{1}' in parameter name {2} or remove it entirely if it represents any sort of Hungarian notation. + Correct the spelling of '{0}' in type name {1}. + + + + Make {0} sealed (a breaking change if this class has previously shipped), implement the method non-explicitly, or implement a new method that exposes the functionality of {1} and is visible to derived classes. + + + Specify AttributeUsage on {0}. + + + Add the MarshalAsAttribute to parameter {0} of P/Invoke {1}. If the corresponding unmanaged parameter is a 4-byte Win32 'BOOL', use [MarshalAs(UnmanagedType.Bool)]. For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + Add the MarshalAsAttribute to the return type of P/Invoke {0}. If the corresponding unmanaged return type is a 4-byte Win32 'BOOL', use MarshalAs(UnmanagedType.Bool). For a 1-byte C++ 'bool', use MarshalAs(UnmanagedType.U1). + + + The constituent members of {0} appear to represent flags that can be combined rather than discrete values. If this is correct, mark the enumeration with FlagsAttribute. + + + Add [Serializable] to {0} as this type implements ISerializable. + + + Consider making {0} non-public or a constant. + + + If the name {0} is plural, change it to its singular form. + + + Add the following security attribute to {0} in order to match a LinkDemand on base method {1}: {2}. + + + As it is declared in your code, parameter {0} of P/Invoke {1} will be {2} bytes wide on {3} platforms. This is not correct, as the actual native declaration of this API indicates it should be {4} bytes wide on {3} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {5}. + As it is declared in your code, the return type of P/Invoke {0} will be {1} bytes wide on {2} platforms. This is not correct, as the actual native declaration of this API indicates it should be {3} bytes wide on {2} platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of {4}. + + + Correct the declaration of {0} so that it correctly points to an existing entry point in {1}. The unmanaged entry point name currently linked to is {2}. + + + Because property {0} is write-only, either add a property getter with an accessibility that is greater than or equal to its setter or convert this property into a method. + + + Change {0} to return a collection or make it a method. + + + The property name {0} is confusing given the existence of inherited method {1}. Rename or remove this property. + The property name {0} is confusing given the existence of method {1}. Rename or remove one of these members. + + + Parameter {0} of {1} is never used. Remove the parameter or use it in the method body. + + + Consider making {0} not externally visible. + + + To reduce security risk, marshal parameter {0} as Unicode, by setting DllImport.CharSet to CharSet.Unicode, or by explicitly marshaling the parameter as UnmanagedType.LPWStr. If you need to marshal this string as ANSI or system-dependent, set BestFitMapping=false; for added security, also set ThrowOnUnmappableChar=true. + + + {0} makes a call to {1} that does not explicitly provide a StringComparison. This should be replaced with a call to {2}. + + + Implement IDisposable on {0} because it creates members of the following IDisposable types: {1}. If {0} has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers. + + + Change the type of parameter {0} of method {1} from string to System.Uri, or provide an overload of {1}, that allows {0} to be passed as a System.Uri object. + + + Change the type of property {0} from string to System.Uri. + + + Remove {0} and replace its usage with EventHandler<T> + + + {0} passes {1} as an argument to {2}. Replace this usage with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase if appropriate. + + + Replace the term '{0}' in member name {1} with an appropriate alternate or remove it entirely. + Replace the term '{0}' in type name {1} with an appropriate alternate or remove it entirely. + + + Change {0} to a property if appropriate. + + + + diff --git a/ObjectListView/ObjectListView.cs b/ObjectListView/ObjectListView.cs new file mode 100644 index 0000000..7b4bbe5 --- /dev/null +++ b/ObjectListView/ObjectListView.cs @@ -0,0 +1,10924 @@ +/* + * ObjectListView - A listview to show various aspects of a collection of objects + * + * Author: Phillip Piper + * Date: 9/10/2006 11:15 AM + * + * Change log + * 2018-10-06 JPP - InsertObjects() when in a non-Detail View now correctly positions the items (SF bug #154) + * 2018-09-01 JPP - Hardened code against the rare case of the control having no columns (SF bug #174) + * The underlying ListView does not like having rows when there are no columns and throws exceptions.j + * 2018-05-05 JPP - Added OLVColumn.EditorCreator to allow fine control over what control is used to edit + * a particular cell. + * - Added IOlvEditor to allow custom editor to easily integrate with our editing scheme + * - ComboBoxes resize drop downs to show the widest entry via ControlUtilities.AutoResizeDropDown() + * 2018-05-03 JPP - Extend OnColumnRightClick so the event handler can tweak the menu to be shown + * 2018-04-27 JPP - Sorting now works when grouping is locked on a column AND SortGroupItemsByPrimaryColumn is true + * - Correctly report right clicks on group headers via CellRightClick events. + * v2.9.2 + * 2016-06-02 JPP - Cell editors now respond to mouse wheel events. Set AllowCellEditorsToProcessMouseWheel + * to false revert to previous behaviour. + * - Fixed issue in PauseAnimations() that prevented it from working until + * after the control had been rendered at least once. + * - CellEditUseWholeCell now has correct default value (true). + * - Dropping on a subitem when CellEditActivation is set to SingleClick no longer + * initiates a cell edit + * v2.9.1 + * 2015-12-30 JPP - Added CellRendererGetter to allow each cell to have a different renderer. + * - Obsolete properties are no longer code-gen'ed. + * + * v2.9.0 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * - Renamed properties related to selection colours: + * - HighlightBackgroundColor -> SelectedBackColor + * - HighlightForegroundColor -> SelectedForeColor + * - UnfocusedHighlightBackgroundColor -> UnfocusedSelectedBackColor + * - UnfocusedHighlightForegroundColor -> UnfocusedSelectedForeColor + * - UseCustomSelectionColors is no longer used + * 2015-08-03 JPP - Added ObjectListView.CellEditFinished event + * - Added EditorRegistry.Unregister() + * 2015-07-08 JPP - All ObjectListViews are now OwnerDrawn by default. This allows all the great features + * of ObjectListView to work correctly at the slight cost of more processing at render time. + * It also avoids the annoying "hot item background ignored in column 0" behaviour that native + * ListView has. Programmers can still turn it back off if they wish. + * 2015-06-27 JPP - Yet another attempt to disable ListView's "shift click toggles checkboxes" behaviour. + * The last strategy (fake right click) worked, but had nasty side effects. This one works + * by intercepting a HITTEST message so that it fails. It no longer creates fake right mouse events. + * - Trigger SelectionChanged when filter is changed + * 2015-06-23 JPP - [BIG] Added support for Buttons + * 2015-06-22 JPP - Added OLVColumn.SearchValueGetter to allow the text used when text filtering to be customised + * - The default DefaultRenderer is now a HighlightTextRenderer, since that seems more generally useful + * 2015-06-17 JPP - Added FocusedObject property + * - Hot item is now always applied to the row even if FullRowSelect is false + * 2015-06-11 JPP - Added DefaultHotItemStyle property + * 2015-06-07 JPP - Added HeaderMinimumHeight property + * - Added ObjectListView.CellEditUsesWholeCell and OLVColumn.CellEditUsesWholeCell properties. + * 2015-05-15 JPP - Allow ImageGetter to return an Image (which I can't believe didn't work from the beginning!) + * 2015-04-27 JPP - Fix bug where setting View to LargeIcon in the designer was not persisted + * 2015-04-07 JPP - Ensure changes to row.Font in FormatRow are not wiped out by FormatCell (SF #141) + * + * v2.8.1 + * 2014-10-15 JPP - Added CellEditActivateMode.SingleClickAlways mode + * - Fire Filter event even if ModelFilter and ListFilter are null (SF #126) + * - Fixed issue where single-click editing didn't work (SF #128) + * v2.8.0 + * 2014-10-11 JPP - Fixed some XP-only flicker issues + * 2014-09-26 JPP - Fixed intricate bug involving checkboxes on non-owner-drawn virtual lists. + * - Fixed long standing (but previously unreported) error on non-details virtual lists where + * users could not click on checkboxes. + * 2014-09-07 JPP - (Major) Added ability to have checkboxes in headers + * - CellOver events are raised when the mouse moves over the header. Set TriggerCellOverEventsWhenOverHeader + * to false to disable this behaviour. + * - Freeze/Unfreeze now use BeginUpdate/EndUpdate to disable Window level drawing + * - Changed default value of ObjectListView.HeaderUsesThemes from true to false. Too many people were + * being confused, trying to make something interesting appear in the header and nothing showing up + * 2014-08-04 JPP - Final attempt to fix the multiple hyperlink events being raised. This involves turning + * a NM_CLICK notification into a NM_RCLICK. + * 2014-05-21 JPP - (Major) Added ability to disable rows. DisabledObjects, DisableObjects(), DisabledItemStyle. + * 2014-04-25 JPP - Fixed issue where virtual lists containing a single row didn't update hyperlinks on MouseOver + * - Added sanity check before BuildGroups() + * 2014-03-22 JPP - Fixed some subtle bugs resulting from misuse of TryGetValue() + * 2014-03-09 JPP - Added CollapsedGroups property + * - Several minor Resharper complaints quiesced. + * v2.7 + * 2014-02-14 JPP - Fixed issue with ShowHeaderInAllViews (another one!) where setting it to false caused the list to lose + * its other extended styles, leading to nasty flickering and worse. + * 2014-02-06 JPP - Fix issue on virtual lists where the filter was not correctly reapplied after columns were added or removed. + * - Made disposing of cell editors optional (defaults to true). This allows controls to be cached and reused. + * - Bracketed column resizing with BeginUpdate/EndUpdate to smooth redraws (thanks to Davide) + * 2014-02-01 JPP - Added static property ObjectListView.GroupTitleDefault to allow the default group title to be localised. + * 2013-09-24 JPP - Fixed issue in RefreshObjects() when model objects overrode the Equals()/GetHashCode() methods. + * - Made sure get state checker were used when they should have been + * 2013-04-21 JPP - Clicking on a non-groupable column header when showing groups will now sort + * the group contents by that column. + * v2.6 + * 2012-08-16 JPP - Added ObjectListView.EditModel() -- a convenience method to start an edit operation on a model + * 2012-08-10 JPP - Don't trigger selection changed events during sorting/grouping or add/removing columns + * 2012-08-06 JPP - Don't start a cell edit operation when the user clicks on the background of a checkbox cell. + * - Honor values from the BeforeSorting event when calling a CustomSorter + * 2012-08-02 JPP - Added CellVerticalAlignment and CellPadding properties. + * 2012-07-04 JPP - Fixed issue with cell editing where the cell editing didn't finish until the first idle event. + * This meant that if you clicked and held on the scroll thumb to finish a cell edit, the editor + * wouldn't be removed until the mouse was released. + * 2012-07-03 JPP - Fixed issue with SingleClick cell edit mode where the cell editing would not begin until the + * mouse moved after the click. + * 2012-06-25 JPP - Fixed bug where removing a column from a LargeIcon or SmallIcon view would crash the control. + * 2012-06-15 JPP - Added Reset() method, which definitively removes all rows *and* columns from an ObjectListView. + * 2012-06-11 JPP - Added FilteredObjects property which returns the collection of objects that survives any installed filters. + * 2012-06-04 JPP - [Big] Added UseNotifyPropertyChanged to allow OLV to listen for INotifyPropertyChanged events on models. + * 2012-05-30 JPP - Added static property ObjectListView.IgnoreMissingAspects. If this is set to true, all + * ObjectListViews will silently ignore missing aspect errors. Read the remarks to see why this would be useful. + * 2012-05-23 JPP - Setting UseFilterIndicator to true now sets HeaderUsesTheme to false. + * Also, changed default value of UseFilterIndicator to false. Previously, HeaderUsesTheme and UseFilterIndicator + * defaulted to true, which was pointless since when the HeaderUsesTheme is true, UseFilterIndicator does nothing. + * v2.5.1 + * 2012-05-06 JPP - Fix bug where collapsing the first group would cause decorations to stop being drawn (SR #3502608) + * 2012-04-23 JPP - Trigger GroupExpandingCollapsing event to allow the expand/collapse to be cancelled + * - Fixed SetGroupSpacing() so it corrects updates the space between all groups. + * - ResizeLastGroup() now does nothing since it was broken and I can't remember what it was + * even supposed to do :) + * 2012-04-18 JPP - Upgraded hit testing to include hits on groups. + * - HotItemChanged is now correctly recalculated on each mouse move. Includes "hot" group information. + * 2012-04-14 JPP - Added GroupStateChanged event. Useful for knowing when a group is collapsed/expanded. + * - Added AdditionalFilter property. This filter is combined with the Excel-like filtering that + * the end user might enact at runtime. + * 2012-04-10 JPP - Added PersistentCheckBoxes property to allow primary checkboxes to remember their values + * across list rebuilds. + * 2012-04-05 JPP - Reverted some code to .NET 2.0 standard. + * - Tweaked some code + * 2012-02-05 JPP - Fixed bug when selecting a separator on a drop down menu + * 2011-06-24 JPP - Added CanUseApplicationIdle property to cover cases where Application.Idle events + * are not triggered. For example, when used within VS (and probably Office) extensions + * Application.Idle is never triggered. Set CanUseApplicationIdle to false to handle + * these cases. + * - Handle cases where a second tool tip is installed onto the ObjectListView. + * - Correctly recolour rows after an Insert or Move + * - Removed m.LParam cast which could cause overflow issues on Win7/64 bit. + * v2.5.0 + * 2011-05-31 JPP - SelectObject() and SelectObjects() no longer deselect all other rows. + Set the SelectedObject or SelectedObjects property to do that. + * - Added CheckedObjectsEnumerable + * - Made setting CheckedObjects more efficient on large collections + * - Deprecated GetSelectedObject() and GetSelectedObjects() + * 2011-04-25 JPP - Added SubItemChecking event + * - Fixed bug in handling of NewValue on CellEditFinishing event + * 2011-04-12 JPP - Added UseFilterIndicator + * - Added some more localizable messages + * 2011-04-10 JPP - FormatCellEventArgs now has a CellValue property, which is the model value displayed + * by the cell. For example, for the Birthday column, the CellValue might be + * DateTime(1980, 12, 31), whereas the cell's text might be 'Dec 31, 1980'. + * 2011-04-04 JPP - Tweaked UseTranslucentSelection and UseTranslucentHotItem to look (a little) more + * like Vista/Win7. + * - Alternate colours are now only applied in Details view (as they always should have been) + * - Alternate colours are now correctly recalculated after removing objects + * 2011-03-29 JPP - Added SelectColumnsOnRightClickBehaviour to allow the selecting of columns mechanism + * to be changed. Can now be InlineMenu (the default), SubMenu, or ModelDialog. + * - ColumnSelectionForm was moved from the demo into the ObjectListView project itself. + * - Ctrl-C copying is now able to use the DragSource to create the data transfer object. + * 2011-03-19 JPP - All model object comparisons now use Equals rather than == (thanks to vulkanino) + * - [Small Break] GetNextItem() and GetPreviousItem() now accept and return OLVListView + * rather than ListViewItems. + * 2011-03-07 JPP - [Big] Added Excel-style filtering. Right click on a header to show a Filtering menu. + * - Added CellEditKeyEngine to allow key handling when cell editing to be completely customised. + * Add CellEditTabChangesRows and CellEditEnterChangesRows to show some of these abilities. + * 2011-03-06 JPP - Added OLVColumn.AutoCompleteEditorMode in preference to AutoCompleteEditor + * (which is now just a wrapper). Thanks to Clive Haskins + * - Added lots of docs to new classes + * 2011-02-25 JPP - Preserve word wrap settings on TreeListView + * - Resize last group to keep it on screen (thanks to ?) + * 2010-11-16 JPP - Fixed (once and for all) DisplayIndex problem with Generator + * - Changed the serializer used in SaveState()/RestoreState() so that it resolves on + * class name alone. + * - Fixed bug in GroupWithItemCountSingularFormatOrDefault + * - Fixed strange flickering in grouped, owner drawn OLV's using RefreshObject() + * v2.4.1 + * 2010-08-25 JPP - Fixed bug where setting OLVColumn.CheckBoxes to false gave it a renderer + * specialized for checkboxes. Oddly, this made Generator created owner drawn + * lists appear to be completely empty. + * - In IDE, all ObjectListView properties are now in a single "ObjectListView" category, + * rather than splitting them between "Appearance" and "Behavior" categories. + * - Added GroupingParameters.GroupComparer to allow groups to be sorted in a customizable fashion. + * - Sorting of items within a group can be disabled by setting + * GroupingParameters.PrimarySortOrder to None. + * 2010-08-24 JPP - Added OLVColumn.IsHeaderVertical to make a column draw its header vertical. + * - Added OLVColumn.HeaderTextAlign to control the alignment of a column's header text. + * - Added HeaderMaximumHeight to limit how tall the header section can become + * 2010-08-18 JPP - Fixed long standing bug where having 0 columns caused a InvalidCast exception. + * - Added IncludeAllColumnsInDataObject property + * - Improved BuildList(bool) so that it preserves scroll position even when + * the listview is grouped. + * 2010-08-08 JPP - Added OLVColumn.HeaderImageKey to allow column headers to have an image. + * - CellEdit validation and finish events now have NewValue property. + * 2010-08-03 JPP - Subitem checkboxes improvements: obey IsEditable, can be hot, can be disabled. + * - No more flickering of selection when tabbing between cells + * - Added EditingCellBorderDecoration to make it clearer which cell is being edited. + * 2010-08-01 JPP - Added ObjectListView.SmoothingMode to control the smoothing of all graphics + * operations + * - Columns now cache their group item format strings so that they still work as + * grouping columns after they have been removed from the listview. This cached + * value is only used when the column is not part of the listview. + * 2010-07-25 JPP - Correctly trigger a Click event when the mouse is clicked. + * 2010-07-16 JPP - Invalidate the control before and after cell editing to make sure it looks right + * 2010-06-23 JPP - Right mouse clicks on checkboxes no longer confuse them + * 2010-06-21 JPP - Avoid bug in underlying ListView control where virtual lists in SmallIcon view + * generate GETTOOLINFO msgs with invalid item indices. + * - Fixed bug where FastObjectListView would throw an exception when showing hyperlinks + * in any view except Details. + * 2010-06-15 JPP - Fixed bug in ChangeToFilteredColumns() that resulted in column display order + * being lost when a column was hidden. + * - Renamed IsVista property to IsVistaOrLater which more accurately describes its function. + * v2.4 + * 2010-04-14 JPP - Prevent object disposed errors when mouse event handlers cause the + * ObjectListView to be destroyed (e.g. closing a form during a + * double click event). + * - Avoid checkbox munging bug in standard ListView when shift clicking on non-primary + * columns when FullRowSelect is true. + * 2010-04-12 JPP - Fixed bug in group sorting (thanks Mike). + * 2010-04-07 JPP - Prevent hyperlink processing from triggering spurious MouseUp events. + * This showed itself by launching the same url multiple times. + * 2010-04-06 JPP - Space filling columns correctly resize upon initial display + * - ShowHeaderInAllViews is better but still not working reliably. + * See comments on property for more details. + * 2010-03-23 JPP - Added ObjectListView.HeaderFormatStyle and OLVColumn.HeaderFormatStyle. + * This makes HeaderFont and HeaderForeColor properties unnecessary -- + * they will be marked obsolete in the next version and removed after that. + * 2010-03-16 JPP - Changed object checking so that objects can be pre-checked before they + * are added to the list. Normal ObjectListViews managed "checkedness" in + * the ListViewItem, so this won't work for them, unless check state getters + * and putters have been installed. It will work not on virtual lists (thus fast lists and + * tree views) since they manage their own check state. + * 2010-03-06 JPP - Hide "Items" and "Groups" from the IDE properties grid since they shouldn't be set like that. + * They can still be accessed through "Custom Commands" and there's nothing we can do + * about that. + * 2010-03-05 JPP - Added filtering + * 2010-01-18 JPP - Overlays can be turned off. They also only work on 32-bit displays + * v2.3 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * 2009-10-28 JPP - Fix bug when right clicking in the empty area of the header + * 2009-10-20 JPP - Redraw the control after setting EmptyListMsg property + * v2.3 + * 2009-09-30 JPP - Added Dispose() method to properly release resources + * 2009-09-16 JPP - Added OwnerDrawnHeader, which you can set to true if you want to owner draw + * the header yourself. + * 2009-09-15 JPP - Added UseExplorerTheme, which allow complete visual compliance with Vista explorer. + * But see property documentation for its many limitations. + * - Added ShowHeaderInAllViews. To make this work, Columns are no longer + * changed when switching to/from Tile view. + * 2009-09-11 JPP - Added OLVColumn.AutoCompleteEditor to allow the autocomplete of cell editors + * to be disabled. + * 2009-09-01 JPP - Added ObjectListView.TextRenderingHint property which controls the + * text rendering hint of all drawn text. + * 2009-08-28 JPP - [BIG] Added group formatting to supercharge what is possible with groups + * - [BIG] Virtual groups now work + * - Extended MakeGroupies() to handle more aspects of group creation + * 2009-08-19 JPP - Added ability to show basic column commands when header is right clicked + * - Added SelectedRowDecoration, UseTranslucentSelection and UseTranslucentHotItem. + * - Added PrimarySortColumn and PrimarySortOrder + * 2009-08-15 JPP - Correct problems with standard hit test and subitems + * 2009-08-14 JPP - [BIG] Support Decorations + * - [BIG] Added header formatting capabilities: font, color, word wrap + * - Gave ObjectListView its own designer to hide unwanted properties + * - Separated design time stuff into separate file + * - Added FormatRow and FormatCell events + * 2009-08-09 JPP - Get around bug in HitTest when not FullRowSelect + * - Added OLVListItem.GetSubItemBounds() method which works correctly + * for all columns including column 0 + * 2009-08-07 JPP - Added Hot* properties that track where the mouse is + * - Added HotItemChanged event + * - Overrode TextAlign on columns so that column 0 can have something other + * than just left alignment. This is only honored when owner drawn. + * v2.2.1 + * 2009-08-03 JPP - Subitem edit rectangles always allowed for an image in the cell, even if there was none. + * Now they only allow for an image when there actually is one. + * - Added Bounds property to OLVListItem which handles items being part of collapsed groups. + * 2009-07-29 JPP - Added GetSubItem() methods to ObjectListView and OLVListItem + * 2009-07-26 JPP - Avoided bug in .NET framework involving column 0 of owner drawn listviews not being + * redrawn when the listview was scrolled horizontally (this was a LOT of work to track + * down and fix!) + * - The cell edit rectangle is now correctly calculated when the listview is scrolled + * horizontally. + * 2009-07-14 JPP - If the user clicks/double clicks on a tree list cell, an edit operation will no longer begin + * if the click was to the left of the expander. This is implemented in such a way that + * other renderers can have similar "dead" zones. + * 2009-07-11 JPP - CalculateCellBounds() messed with the FullRowSelect property, which confused the + * tooltip handling on the underlying control. It no longer does this. + * - The cell edit rectangle is now correctly calculated for owner-drawn, non-Details views. + * 2009-07-08 JPP - Added Cell events (CellClicked, CellOver, CellRightClicked) + * - Made BuildList(), AddObject() and RemoveObject() thread-safe + * 2009-07-04 JPP - Space bar now properly toggles checkedness of selected rows + * 2009-07-02 JPP - Fixed bug with tooltips when the underlying Windows control was destroyed. + * - CellToolTipShowing events are now triggered in all views. + * v2.2 + * 2009-06-02 JPP - BeforeSortingEventArgs now has a Handled property to let event handlers do + * the item sorting themselves. + * - AlwaysGroupByColumn works again, as does SortGroupItemsByPrimaryColumn and all their + * various permutations. + * - SecondarySortOrder and SecondarySortColumn are now "null" by default + * 2009-05-15 JPP - Fixed bug so that KeyPress events are again triggered + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-07 JPP - Don't use glass panel for overlays when in design mode. It's too confusing. + * 2009-05-05 JPP - Added Scroll event (thanks to Christophe Hosten for the complete patch to implement this) + * - Added Unfocused foreground and background colors (also thanks to Christophe Hosten) + * 2009-04-29 JPP - Added SelectedColumn property, which puts a slight tint on that column. Combine + * this with TintSortColumn property and the sort column is automatically tinted. + * - Use an overlay to implement "empty list" msg. Default empty list msg is now prettier. + * 2009-04-28 JPP - Fixed bug where DoubleClick events were not triggered when CheckBoxes was true + * 2009-04-23 JPP - Fixed various bugs under Vista. + * - Made groups collapsible - Vista only. Thanks to Crustyapplesniffer. + * - Forward events from DropSink to the control itself. This allows handlers to be defined + * within the IDE for drop events + * 2009-04-16 JPP - Made several properties localizable. + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-11 JPP - Implemented overlay architecture, based on CustomDraw scheme. + * This unified drag drop feedback, empty list msgs and overlay images. + * - Added OverlayImage and friends, which allows an image to be drawn + * transparently over the listview + * 2009-04-10 JPP - Fixed long-standing annoying flicker on owner drawn virtual lists! + * This means, amongst other things, that grid lines no longer get confused, + * and drag-select no longer flickers. + * 2009-04-07 JPP - Calculate edit rectangles more accurately + * 2009-04-06 JPP - Double-clicking no longer toggles the checkbox + * - Double-clicking on a checkbox no longer confuses the checkbox + * 2009-03-16 JPP - Optimized the build of autocomplete lists + * v2.1 + * 2009-02-24 JPP - Fix bug where double-clicking VERY quickly on two different cells + * could give two editors + * - Maintain focused item when rebuilding list (SF #2547060) + * 2009-02-22 JPP - Reworked checkboxes so that events are triggered for virtual lists + * 2009-02-15 JPP - Added ObjectListView.ConfigureAutoComplete utility method + * 2009-02-02 JPP - Fixed bug with AlwaysGroupByColumn where column header clicks would not resort groups. + * 2009-02-01 JPP - OLVColumn.CheckBoxes and TriStateCheckBoxes now work. + * 2009-01-28 JPP - Complete overhaul of renderers! + * - Use IRenderer + * - Added ObjectListView.ItemRenderer to draw whole items + * 2009-01-23 JPP - Simple Checkboxes now work properly + * - Added TriStateCheckBoxes property to control whether the user can + * set the row checkbox to have the Indeterminate value + * - CheckState property is now just a wrapper around the StateImageIndex property + * 2009-01-20 JPP - Changed to always draw columns when owner drawn, rather than falling back on DrawDefault. + * This simplified several owner drawn problems + * - Added DefaultRenderer property to help with the above + * - HotItem background color is applied to all cells even when FullRowSelect is false + * - Allow grouping by CheckedAspectName columns + * - Commented out experimental animations. Still needs work. + * 2009-01-17 JPP - Added HotItemStyle and UseHotItem to highlight the row under the cursor + * - Added UseCustomSelectionColors property + * - Owner draw mode now honors ForeColor and BackColor settings on the list + * 2009-01-16 JPP - Changed to use EditorRegistry rather than hard coding cell editors + * 2009-01-10 JPP - Changed to use Equals() method rather than == to compare model objects. + * v2.0.1 + * 2009-01-08 JPP - Fixed long-standing "multiple columns generated" problem. + * Thanks to pinkjones for his help with solving this one! + * - Added EnsureGroupVisible() + * 2009-01-07 JPP - Made all public and protected methods virtual + * - FinishCellEditing, PossibleFinishCellEditing and CancelCellEditing are now public + * 2008-12-20 JPP - Fixed bug with group comparisons when a group key was null (SF#2445761) + * 2008-12-19 JPP - Fixed bug with space filling columns and layout events + * - Fixed RowHeight so that it only changes the row height, not the width of the images. + * v2.0 + * 2008-12-10 JPP - Handle Backspace key. Resets the search-by-typing state without delay + * - Made some changes to the column collection editor to try and avoid + * the multiple column generation problem. + * - Updated some documentation + * 2008-12-07 JPP - Search-by-typing now works when showing groups + * - Added BeforeSearching and AfterSearching events which are triggered when the user types + * into the list. + * - Added secondary sort information to Before/AfterSorting events + * - Reorganized group sorting code. Now triggers Sorting events. + * - Added GetItemIndexInDisplayOrder() + * - Tweaked in the interaction of the column editor with the IDE so that we (normally) + * don't rely on a hack to find the owning ObjectListView + * - Changed all 'DefaultValue(typeof(Color), "Empty")' to 'DefaultValue(typeof(Color), "")' + * since the first does not given Color.Empty as I thought, but the second does. + * 2008-11-28 JPP - Fixed long standing bug with horizontal scrollbar when shrinking the window. + * (thanks to Bartosz Borowik) + * 2008-11-25 JPP - Added support for dynamic tooltips + * - Split out comparers and header controls stuff into their own files + * 2008-11-21 JPP - Fixed bug where enabling grouping when there was not a sort column would not + * produce a grouped list. Grouping column now defaults to column 0. + * - Preserve selection on virtual lists when sorting + * 2008-11-20 JPP - Added ability to search by sort column to ObjectListView. Unified this with + * ability that was already in VirtualObjectListView + * 2008-11-19 JPP - Fixed bug in ChangeToFilteredColumns() where DisplayOrder was not always restored correctly. + * 2008-10-29 JPP - Event argument blocks moved to directly within the namespace, rather than being + * nested inside ObjectListView class. + * - Removed OLVColumn.CellEditor since it was never used. + * - Marked OLVColumn.AspectGetterAutoGenerated as obsolete (it has not been used for + * several versions now). + * 2008-10-28 JPP - SelectedObjects is now an IList, rather than an ArrayList. This allows + * it to accept generic list (e.g. List). + * 2008-10-09 JPP - Support indeterminate checkbox values. + * [BREAKING CHANGE] CheckStateGetter/CheckStatePutter now use CheckState types only. + * BooleanCheckStateGetter and BooleanCheckStatePutter added to ease transition. + * 2008-10-08 JPP - Added setFocus parameter to SelectObject(), which allows focus to be set + * at the same time as selecting. + * 2008-09-27 JPP - BIG CHANGE: Fissioned this file into separate files for each component + * 2008-09-24 JPP - Corrected bug with owner drawn lists where a column 0 with a renderer + * would draw at column 0 even if column 0 was dragged to another position. + * - Correctly handle space filling columns when columns are added/removed + * 2008-09-16 JPP - Consistently use try..finally for BeginUpdate()/EndUpdate() pairs + * 2008-08-24 JPP - If LastSortOrder is None when adding objects, don't force a resort. + * 2008-08-22 JPP - Catch and ignore some problems with setting TopIndex on FastObjectListViews. + * 2008-08-05 JPP - In the right-click column select menu, columns are now sorted by display order, rather than alphabetically + * v1.13 + * 2008-07-23 JPP - Consistently use copy-on-write semantics with Add/RemoveObject methods + * 2008-07-10 JPP - Enable validation on cell editors through a CellEditValidating event. + * (thanks to Artiom Chilaru for the initial suggestion and implementation). + * 2008-07-09 JPP - Added HeaderControl.Handle to allow OLV to be used within UserControls. + * (thanks to Michael Coffey for tracking this down). + * 2008-06-23 JPP - Split the more generally useful CopyObjectsToClipboard() method + * out of CopySelectionToClipboard() + * 2008-06-22 JPP - Added AlwaysGroupByColumn and AlwaysGroupBySortOrder, which + * force the list view to always be grouped by a particular column. + * 2008-05-31 JPP - Allow check boxes on FastObjectListViews + * - Added CheckedObject and CheckedObjects properties + * 2008-05-11 JPP - Allow selection foreground and background colors to be changed. + * Windows doesn't allow this, so we can only make it happen when owner + * drawing. Set the HighlightForegroundColor and HighlightBackgroundColor + * properties and then call EnableCustomSelectionColors(). + * v1.12 + * 2008-05-08 JPP - Fixed bug where the column select menu would not appear if the + * ObjectListView has a context menu installed. + * 2008-05-05 JPP - Non detail views can now be owner drawn. The renderer installed for + * primary column is given the chance to render the whole item. + * See BusinessCardRenderer in the demo for an example. + * - BREAKING CHANGE: RenderDelegate now returns a bool to indicate if default + * rendering should be done. Previously returned void. Only important if your + * code used RendererDelegate directly. Renderers derived from BaseRenderer + * are unchanged. + * 2008-05-03 JPP - Changed cell editing to use values directly when the values are Strings. + * Previously, values were always handed to the AspectToStringConverter. + * - When editing a cell, tabbing no longer tries to edit the next subitem + * when not in details view! + * 2008-05-02 JPP - MappedImageRenderer can now handle a Aspects that return a collection + * of values. Each value will be drawn as its own image. + * - Made AddObjects() and RemoveObjects() work for all flavours (or at least not crash) + * - Fixed bug with clearing virtual lists that has been scrolled vertically + * - Made TopItemIndex work with virtual lists. + * 2008-05-01 JPP - Added AddObjects() and RemoveObjects() to allow faster mods to the list + * - Reorganised public properties. Now alphabetical. + * - Made the class ObjectListViewState internal, as it always should have been. + * v1.11 + * 2008-04-29 JPP - Preserve scroll position when building the list or changing columns. + * - Added TopItemIndex property. Due to problems with the underlying control, this + * property is not always reliable. See property docs for info. + * 2008-04-27 JPP - Added SelectedIndex property. + * - Use a different, more general strategy to handle Invoke(). Removed all delegates + * that were only declared to support Invoke(). + * - Check all native structures for 64-bit correctness. + * 2008-04-25 JPP - Released on SourceForge. + * 2008-04-13 JPP - Added ColumnRightClick event. + * - Made the assembly CLS-compliant. To do this, our cell editors were made internal, and + * the constraint on FlagRenderer template parameter was removed (the type must still + * be an IConvertible, but if it isn't, the error will be caught at runtime, not compile time). + * 2008-04-12 JPP - Changed HandleHeaderRightClick() to have a columnIndex parameter, which tells + * exactly which column was right-clicked. + * 2008-03-31 JPP - Added SaveState() and RestoreState() + * - When cell editing, scrolling with a mouse wheel now ends the edit operation. + * v1.10 + * 2008-03-25 JPP - Added space filling columns. See OLVColumn.FreeSpaceProportion property for details. + * A space filling columns fills all (or a portion) of the width unoccupied by other columns. + * 2008-03-23 JPP - Finished tinkering with support for Mono. Compile with conditional compilation symbol 'MONO' + * to enable. On Windows, current problems with Mono: + * - grid lines on virtual lists crashes + * - when grouped, items sometimes are not drawn when any item is scrolled out of view + * - i can't seem to get owner drawing to work + * - when editing cell values, the editing controls always appear behind the listview, + * where they function fine -- the user just can't see them :-) + * 2008-03-16 JPP - Added some methods suggested by Chris Marlowe (thanks for the suggestions Chris) + * - ClearObjects() + * - GetCheckedObject(), GetCheckedObjects() + * - GetItemAt() variation that gets both the item and the column under a point + * 2008-02-28 JPP - Fixed bug with subitem colors when using OwnerDrawn lists and a RowFormatter. + * v1.9.1 + * 2008-01-29 JPP - Fixed bug that caused owner-drawn virtual lists to use 100% CPU + * - Added FlagRenderer to help draw bitwise-OR'ed flag values + * 2008-01-23 JPP - Fixed bug (introduced in v1.9) that made alternate row colour with groups not quite right + * - Ensure that DesignerSerializationVisibility.Hidden is set on all non-browsable properties + * - Make sure that sort indicators are shown after changing which columns are visible + * 2008-01-21 JPP - Added FastObjectListView + * v1.9 + * 2008-01-18 JPP - Added IncrementalUpdate() + * 2008-01-16 JPP - Right clicking on column header will allow the user to choose which columns are visible. + * Set SelectColumnsOnRightClick to false to prevent this behaviour. + * - Added ImagesRenderer to draw more than one images in a column + * - Changed the positioning of the empty list m to use all the client area. Thanks to Matze. + * 2007-12-13 JPP - Added CopySelectionToClipboard(). Ctrl-C invokes this method. Supports text + * and HTML formats. + * 2007-12-12 JPP - Added support for checkboxes via CheckStateGetter and CheckStatePutter properties. + * - Made ObjectListView and OLVColumn into partial classes so that others can extend them. + * 2007-12-09 JPP - Added ability to have hidden columns, i.e. columns that the ObjectListView knows + * about but that are not visible to the user. Controlled by OLVColumn.IsVisible. + * Added ColumnSelectionForm to the project to show how it could be used in an application. + * + * v1.8 + * 2007-11-26 JPP - Cell editing fully functional + * 2007-11-21 JPP - Added SelectionChanged event. This event is triggered once when the + * selection changes, no matter how many items are selected or deselected (in + * contrast to SelectedIndexChanged which is called once for every row that + * is selected or deselected). Thanks to lupokehl42 (Daniel) for his suggestions and + * improvements on this idea. + * 2007-11-19 JPP - First take at cell editing + * 2007-11-17 JPP - Changed so that items within a group are not sorted if lastSortOrder == None + * - Only call MakeSortIndicatorImages() if we haven't already made the sort indicators + * (Corrected misspelling in the name of the method too) + * 2007-11-06 JPP - Added ability to have secondary sort criteria when sorting + * (SecondarySortColumn and SecondarySortOrder properties) + * - Added SortGroupItemsByPrimaryColumn to allow group items to be sorted by the + * primary column. Previous default was to sort by the grouping column. + * v1.7 + * No big changes to this version but made to work with ListViewPrinter and released with it. + * + * 2007-11-05 JPP - Changed BaseRenderer to use DrawString() rather than TextRenderer, since TextRenderer + * does not work when printing. + * v1.6 + * 2007-11-03 JPP - Fixed some bugs in the rebuilding of DataListView. + * 2007-10-31 JPP - Changed to use builtin sort indicators on XP and later. This also avoids alignment + * problems on Vista. (thanks to gravybod for the suggestion and example implementation) + * 2007-10-21 JPP - Added MinimumWidth and MaximumWidth properties to OLVColumn. + * - Added ability for BuildList() to preserve selection. Calling BuildList() directly + * tries to preserve selection; calling SetObjects() does not. + * - Added SelectAll() and DeselectAll() methods. Useful for working with large lists. + * 2007-10-08 JPP - Added GetNextItem() and GetPreviousItem(), which walk sequentially through the + * listview items, even when the view is grouped. + * - Added SelectedItem property + * 2007-09-28 JPP - Optimized aspect-to-string conversion. BuildList() 15% faster. + * - Added empty implementation of RefreshObjects() to VirtualObjectListView since + * RefreshObjects() cannot work on virtual lists. + * 2007-09-13 JPP - Corrected bug with custom sorter in VirtualObjectListView (thanks for mpgjunky) + * 2007-09-07 JPP - Corrected image scaling bug in DrawAlignedImage() (thanks to krita970) + * 2007-08-29 JPP - Allow item count labels on groups to be set per column (thanks to cmarlow for idea) + * 2007-08-14 JPP - Major rework of DataListView based on Ian Griffiths's great work + * 2007-08-11 JPP - When empty, the control can now draw a "List Empty" m + * - Added GetColumn() and GetItem() methods + * v1.5 + * 2007-08-03 JPP - Support animated GIFs in ImageRenderer + * - Allow height of rows to be specified - EXPERIMENTAL! + * 2007-07-26 JPP - Optimised redrawing of owner-drawn lists by remembering the update rect + * - Allow sort indicators to be turned off + * 2007-06-30 JPP - Added RowFormatter delegate + * - Allow a different label when there is only one item in a group (thanks to cmarlow) + * v1.4 + * 2007-04-12 JPP - Allow owner drawn on steriods! + * - Column headers now display sort indicators + * - ImageGetter delegates can now return ints, strings or Images + * (Images are only visible if the list is owner drawn) + * - Added OLVColumn.MakeGroupies to help with group partitioning + * - All normal listview views are now supported + * - Allow dotted aspect names, e.g. Owner.Workgroup.Name (thanks to OlafD) + * - Added SelectedObject and SelectedObjects properties + * v1.3 + * 2007-03-01 JPP - Added DataListView + * - Added VirtualObjectListView + * - Added Freeze/Unfreeze capabilities + * - Allowed sort handler to be installed + * - Simplified sort comparisons: handles 95% of cases with only 6 lines of code! + * - Fixed bug with alternative line colors on unsorted lists (thanks to cmarlow) + * 2007-01-13 JPP - Fixed bug with lastSortOrder (thanks to Kwan Fu Sit) + * - Non-OLVColumns are no longer allowed + * 2007-01-04 JPP - Clear sorter before rebuilding list. 10x faster! (thanks to aaberg) + * - Include GetField in GetAspectByName() so field values can be Invoked too. + * - Fixed subtle bug in RefreshItem() that erased background colors. + * 2006-11-01 JPP - Added alternate line colouring + * 2006-10-20 JPP - Refactored all sorting comparisons and made it extendable. See ComparerManager. + * - Improved IDE integration + * - Made control DoubleBuffered + * - Added object selection methods + * 2006-10-13 JPP Implemented grouping and column sorting + * 2006-10-09 JPP Initial version + * + * TO DO: + * - Support undocumented group features: subseted groups, group footer items + * + * Copyright (C) 2006-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Serialization.Formatters.Binary; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Runtime.Serialization.Formatters; +using System.Threading; + +namespace BrightIdeasSoftware +{ + /// + /// An ObjectListView is a much easier to use, and much more powerful, version of the ListView. + /// + /// + /// + /// An ObjectListView automatically populates a ListView control with information taken + /// from a given collection of objects. It can do this because each column is configured + /// to know which bit of the model object (the "aspect") it should be displaying. Columns similarly + /// understand how to sort the list based on their aspect, and how to construct groups + /// using their aspect. + /// + /// + /// Aspects are extracted by giving the name of a method to be called or a + /// property to be fetched. These names can be simple names or they can be dotted + /// to chain property access e.g. "Owner.Address.Postcode". + /// Aspects can also be extracted by installing a delegate. + /// + /// + /// An ObjectListView can show a "this list is empty" message when there is nothing to show in the list, + /// so that the user knows the control is supposed to be empty. + /// + /// + /// Right clicking on a column header should present a menu which can contain: + /// commands (sort, group, ungroup); filtering; and column selection. Whether these + /// parts of the menu appear is controlled by ShowCommandMenuOnRightClick, + /// ShowFilterMenuOnRightClick and SelectColumnsOnRightClick respectively. + /// + /// + /// The groups created by an ObjectListView can be configured to include other formatting + /// information, including a group icon, subtitle and task button. Using some undocumented + /// interfaces, these groups can even on virtual lists. + /// + /// + /// ObjectListView supports dragging rows to other places, including other application. + /// Special support is provide for drops from other ObjectListViews in the same application. + /// In many cases, an ObjectListView becomes a full drag source by setting to + /// true. Similarly, to accept drops, it is usually enough to set to true, + /// and then handle the and events (or the and + /// events, if you only want to handle drops from other ObjectListViews in your application). + /// + /// + /// For these classes to build correctly, the project must have references to these assemblies: + /// + /// + /// System + /// System.Data + /// System.Design + /// System.Drawing + /// System.Windows.Forms (obviously) + /// + /// + [Designer(typeof(BrightIdeasSoftware.Design.ObjectListViewDesigner))] + public partial class ObjectListView : ListView, ISupportInitialize { + + #region Life and death + + /// + /// Create an ObjectListView + /// + public ObjectListView() { + this.ColumnClick += new ColumnClickEventHandler(this.HandleColumnClick); + this.Layout += new LayoutEventHandler(this.HandleLayout); + this.ColumnWidthChanging += new ColumnWidthChangingEventHandler(this.HandleColumnWidthChanging); + this.ColumnWidthChanged += new ColumnWidthChangedEventHandler(this.HandleColumnWidthChanged); + + base.View = View.Details; + + // Turn on owner draw so that we are responsible for our own fates (and isolated from bugs in the underlying ListView) + this.OwnerDraw = true; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.DoubleBuffered = true; // kill nasty flickers. hiss... me hates 'em + this.ShowSortIndicators = true; + + // Setup the overlays that will be controlled by the IDE settings + this.InitializeStandardOverlays(); + this.InitializeEmptyListMsgOverlay(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + } + + /// + /// Dispose of any resources this instance has been using + /// + /// + protected override void Dispose(bool disposing) { + base.Dispose(disposing); + + if (!disposing) + return; + + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Unbind(); + glassPanel.Dispose(); + } + this.glassPanels.Clear(); + + this.UnsubscribeNotifications(null); + } + + #endregion + + // TODO + //public CheckBoxSettings CheckBoxSettings { + // get { return checkBoxSettings; } + // private set { checkBoxSettings = value; } + //} + + #region Static properties + + /// + /// Gets whether or not the left mouse button is down at this very instant + /// + public static bool IsLeftMouseDown { + get { return (Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left; } + } + + /// + /// Gets whether the program running on Vista or later? + /// + public static bool IsVistaOrLater { + get { + if (!ObjectListView.sIsVistaOrLater.HasValue) + ObjectListView.sIsVistaOrLater = Environment.OSVersion.Version.Major >= 6; + return ObjectListView.sIsVistaOrLater.Value; + } + } + private static bool? sIsVistaOrLater; + + /// + /// Gets whether the program running on Win7 or later? + /// + public static bool IsWin7OrLater { + get { + if (!ObjectListView.sIsWin7OrLater.HasValue) { + // For some reason, Win7 is v6.1, not v7.0 + Version version = Environment.OSVersion.Version; + ObjectListView.sIsWin7OrLater = version.Major > 6 || (version.Major == 6 && version.Minor > 0); + } + return ObjectListView.sIsWin7OrLater.Value; + } + } + private static bool? sIsWin7OrLater; + + /// + /// Gets or sets how what smoothing mode will be applied to graphic operations. + /// + public static System.Drawing.Drawing2D.SmoothingMode SmoothingMode { + get { return ObjectListView.sSmoothingMode; } + set { ObjectListView.sSmoothingMode = value; } + } + private static System.Drawing.Drawing2D.SmoothingMode sSmoothingMode = + System.Drawing.Drawing2D.SmoothingMode.HighQuality; + + /// + /// Gets or sets how should text be rendered. + /// + public static System.Drawing.Text.TextRenderingHint TextRenderingHint { + get { return ObjectListView.sTextRendereringHint; } + set { ObjectListView.sTextRendereringHint = value; } + } + private static System.Drawing.Text.TextRenderingHint sTextRendereringHint = + System.Drawing.Text.TextRenderingHint.SystemDefault; + + /// + /// Gets or sets the string that will be used to title groups when the group key is null. + /// Exposed so it can be localized. + /// + public static string GroupTitleDefault { + get { return ObjectListView.sGroupTitleDefault; } + set { ObjectListView.sGroupTitleDefault = value ?? "{null}"; } + } + private static string sGroupTitleDefault = "{null}"; + + /// + /// Convert the given enumerable into an ArrayList as efficiently as possible + /// + /// The source collection + /// If true, this method will always create a new + /// collection. + /// An ArrayList with the same contents as the given collection. + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static ArrayList EnumerableToArray(IEnumerable collection, bool alwaysCreate) { + if (collection == null) + return new ArrayList(); + + if (!alwaysCreate) { + ArrayList array = collection as ArrayList; + if (array != null) + return array; + + IList iList = collection as IList; + if (iList != null) + return ArrayList.Adapter(iList); + } + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return new ArrayList(iCollection); + + ArrayList newObjects = new ArrayList(); + foreach (object x in collection) + newObjects.Add(x); + return newObjects; + } + + + /// + /// Return the count of items in the given enumerable + /// + /// + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + public static int EnumerableCount(IEnumerable collection) { + if (collection == null) + return 0; + + ICollection iCollection = collection as ICollection; + if (iCollection != null) + return iCollection.Count; + + int i = 0; +// ReSharper disable once UnusedVariable + foreach (object x in collection) + i++; + return i; + } + + /// + /// Return whether or not the given enumerable is empty. A string is regarded as + /// an empty collection. + /// + /// + /// True if the given collection is null or empty + /// + /// When we move to .NET 3.5, we can use LINQ and not need this method. + /// + public static bool IsEnumerableEmpty(IEnumerable collection) { + return collection == null || (collection is string) || !collection.GetEnumerator().MoveNext(); + } + + /// + /// Gets or sets whether all ObjectListViews will silently ignore missing aspect errors. + /// + /// + /// + /// By default, if an ObjectListView is asked to display an aspect + /// (i.e. a field/property/method) + /// that does not exist from a model, it displays an error message in that cell, since that + /// condition is normally a programming error. There are some use cases where + /// this is not an error -- in those cases, set this to true and ObjectListView will + /// simply display an empty cell. + /// + /// Be warned: if you set this to true, it can be very difficult to track down + /// typing mistakes or name changes in AspectNames. + /// + public static bool IgnoreMissingAspects { + get { return Munger.IgnoreMissingAspects; } + set { Munger.IgnoreMissingAspects = value; } + } + + /// + /// Gets or sets whether the control will draw a rectangle in each cell showing the cell padding. + /// + /// + /// + /// This can help with debugging display problems from cell padding. + /// + /// As with all cell padding, this setting only takes effect when the control is owner drawn. + /// + public static bool ShowCellPaddingBounds { + get { return sShowCellPaddingBounds; } + set { sShowCellPaddingBounds = value; } + } + private static bool sShowCellPaddingBounds; + + /// + /// Gets the style that will be used by default to format disabled rows + /// + public static SimpleItemStyle DefaultDisabledItemStyle { + get { + if (sDefaultDisabledItemStyle == null) { + sDefaultDisabledItemStyle = new SimpleItemStyle(); + sDefaultDisabledItemStyle.ForeColor = Color.DarkGray; + } + return sDefaultDisabledItemStyle; + } + } + private static SimpleItemStyle sDefaultDisabledItemStyle; + + /// + /// Gets the style that will be used by default to format hot rows + /// + public static HotItemStyle DefaultHotItemStyle { + get { + if (sDefaultHotItemStyle == null) { + sDefaultHotItemStyle = new HotItemStyle(); + sDefaultHotItemStyle.BackColor = Color.FromArgb(224, 235, 253); + } + return sDefaultHotItemStyle; + } + } + private static HotItemStyle sDefaultHotItemStyle; + + #endregion + + #region Public properties + + /// + /// Gets or sets an model filter that is combined with any column filtering that the end-user specifies. + /// + /// This is different from the ModelFilter property, since setting that will replace + /// any column filtering, whereas setting this will combine this filter with the column filtering + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter AdditionalFilter + { + get { return this.additionalFilter; } + set + { + if (this.additionalFilter == value) + return; + this.additionalFilter = value; + this.UpdateColumnFiltering(); + } + } + private IModelFilter additionalFilter; + + /// + /// Get or set all the columns that this control knows about. + /// Only those columns where IsVisible is true will be seen by the user. + /// + /// + /// + /// If you want to add new columns programmatically, add them to + /// AllColumns and then call RebuildColumns(). Normally, you do not have to + /// deal with this property directly. Just use the IDE. + /// + /// If you do add or remove columns from the AllColumns collection, + /// you have to call RebuildColumns() to make those changes take effect. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public virtual List AllColumns { + get { return this.allColumns; } + set { this.allColumns = value ?? new List(); } + } + private List allColumns = new List(); + + /// + /// Gets or sets whether or not ObjectListView will allow cell editors to response to mouse wheel events. Default is true. + /// If this is true, cell editors that respond to mouse wheel events (e.g. numeric edit, DateTimeEditor, combo boxes) will operate + /// as expected. + /// If this is false, a mouse wheel event is interpreted as a request to scroll the control vertically. This will automatically + /// finish any cell edit operation that was in flight. This was the default behaviour prior to v2.9. + /// + [Category("ObjectListView"), + Description("Should ObjectListView allow cell editors to response to mouse wheel events (default: true)"), + DefaultValue(true)] + public virtual bool AllowCellEditorsToProcessMouseWheel + { + get { return allowCellEditorsToProcessMouseWheel; } + set { allowCellEditorsToProcessMouseWheel = value; } + } + private bool allowCellEditorsToProcessMouseWheel = true; + + /// + /// Gets or sets the background color of every second row + /// + [Category("ObjectListView"), + Description("If using alternate colors, what color should the background of alternate rows be?"), + DefaultValue(typeof(Color), "")] + public Color AlternateRowBackColor { + get { return alternateRowBackColor; } + set { alternateRowBackColor = value; } + } + private Color alternateRowBackColor = Color.Empty; + + /// + /// Gets the alternate row background color that has been set, or the default color + /// + [Browsable(false)] + public virtual Color AlternateRowBackColorOrDefault { + get { + return this.alternateRowBackColor == Color.Empty ? Color.LemonChiffon : this.alternateRowBackColor; + } + } + + /// + /// This property forces the ObjectListView to always group items by the given column. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn AlwaysGroupByColumn { + get { return alwaysGroupByColumn; } + set { alwaysGroupByColumn = value; } + } + private OLVColumn alwaysGroupByColumn; + + /// + /// If AlwaysGroupByColumn is not null, this property will be used to decide how + /// those groups are sorted. If this property has the value SortOrder.None, then + /// the sort order will toggle according to the users last header click. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder AlwaysGroupBySortOrder { + get { return alwaysGroupBySortOrder; } + set { alwaysGroupBySortOrder = value; } + } + private SortOrder alwaysGroupBySortOrder = SortOrder.None; + + /// + /// Give access to the image list that is actually being used by the control + /// + /// + /// Normally, it is preferable to use SmallImageList. Only use this property + /// if you know exactly what you are doing. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ImageList BaseSmallImageList { + get { return base.SmallImageList; } + set { base.SmallImageList = value; } + } + + /// + /// How does the user indicate that they want to edit a cell? + /// None means that the listview cannot be edited. + /// + /// Columns can also be marked as editable. + [Category("ObjectListView"), + Description("How does the user indicate that they want to edit a cell?"), + DefaultValue(CellEditActivateMode.None)] + public virtual CellEditActivateMode CellEditActivation { + get { return cellEditActivation; } + set { + cellEditActivation = value; + if (this.Created) + this.Invalidate(); + } + } + private CellEditActivateMode cellEditActivation = CellEditActivateMode.None; + + /// + /// When a cell is edited, should the whole cell be used (minus any space used by checkbox or image)? + /// Defaults to true. + /// + /// + /// This is always treated as true when the control is NOT owner drawn. + /// + /// When this is false and the control is owner drawn, + /// ObjectListView will try to calculate the width of the cell's + /// actual contents, and then size the editing control to be just the right width. If this is true, + /// the whole width of the cell will be used, regardless of the cell's contents. + /// + /// Each column can have a different value for property. This value from the control is only + /// used when a column is not specified one way or another. + /// Regardless of this setting, developers can specify the exact size of the editing control + /// by listening for the CellEditStarting event. + /// + [Category("ObjectListView"), + Description("When a cell is edited, should the whole cell be used?"), + DefaultValue(true)] + public virtual bool CellEditUseWholeCell { + get { return cellEditUseWholeCell; } + set { cellEditUseWholeCell = value; } + } + private bool cellEditUseWholeCell = true; + + /// + /// Gets or sets the engine that will handle key presses during a cell edit operation. + /// Settings this to null will reset it to default value. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public CellEditKeyEngine CellEditKeyEngine { + get { return this.cellEditKeyEngine ?? (this.cellEditKeyEngine = new CellEditKeyEngine()); } + set { this.cellEditKeyEngine = value; } + } + private CellEditKeyEngine cellEditKeyEngine; + + /// + /// Gets the control that is currently being used for editing a cell. + /// + /// This will obviously be null if no cell is being edited. + [Browsable(false)] + public Control CellEditor { + get { + return this.cellEditor; + } + } + + /// + /// Gets or sets the behaviour of the Tab key when editing a cell on the left or right + /// edge of the control. If this is false (the default), pressing Tab will wrap to the other side + /// of the same row. If this is true, pressing Tab when editing the right most cell will advance + /// to the next row + /// and Shift-Tab when editing the left-most cell will change to the previous row. + /// + [Category("ObjectListView"), + Description("Should Tab/Shift-Tab change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditTabChangesRows { + get { return cellEditTabChangesRows; } + set { + cellEditTabChangesRows = value; + if (cellEditTabChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.ChangeRow); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab|Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.ChangeRow); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab, CellEditCharacterBehaviour.ChangeColumnRight, CellEditAtEdgeBehaviour.Wrap); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Tab | Keys.Shift, CellEditCharacterBehaviour.ChangeColumnLeft, CellEditAtEdgeBehaviour.Wrap); + } + } + } + private bool cellEditTabChangesRows; + + /// + /// Gets or sets the behaviour of the Enter keys while editing a cell. + /// If this is false (the default), pressing Enter will simply finish the editing operation. + /// If this is true, Enter will finish the edit operation and start a new edit operation + /// on the cell below the current cell, wrapping to the top of the next row when at the bottom cell. + /// + [Category("ObjectListView"), + Description("Should Enter change rows while cell editing?"), + DefaultValue(false)] + public virtual bool CellEditEnterChangesRows { + get { return cellEditEnterChangesRows; } + set { + cellEditEnterChangesRows = value; + if (cellEditEnterChangesRows) { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.ChangeRowDown, CellEditAtEdgeBehaviour.ChangeColumn); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.ChangeRowUp, CellEditAtEdgeBehaviour.ChangeColumn); + } else { + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + this.CellEditKeyEngine.SetKeyBehaviour(Keys.Enter | Keys.Shift, CellEditCharacterBehaviour.EndEdit, CellEditAtEdgeBehaviour.EndEdit); + } + } + } + private bool cellEditEnterChangesRows; + + /// + /// Gets the tool tip control that shows tips for the cells + /// + [Browsable(false)] + public ToolTipControl CellToolTip { + get { + if (this.cellToolTip == null) { + this.CreateCellToolTip(); + } + return this.cellToolTip; + } + } + private ToolTipControl cellToolTip; + + /// + /// Gets or sets how many pixels will be left blank around each cell of this item. + /// Cell contents are aligned after padding has been taken into account. + /// + /// + /// Each value of the given rectangle will be treated as an inset from + /// the corresponding side. The width of the rectangle is the padding for the + /// right cell edge. The height of the rectangle is the padding for the bottom + /// cell edge. + /// + /// + /// So, this.olv1.CellPadding = new Rectangle(1, 2, 3, 4); will leave one pixel + /// of space to the left of the cell, 2 pixels at the top, 3 pixels of space + /// on the right edge, and 4 pixels of space at the bottom of each cell. + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// This setting only affects the contents of the cell. The background is + /// not affected. + /// If you set this to a foolish value, your control will appear to be empty. + /// + [Category("ObjectListView"), + Description("How much padding will be applied to each cell in this control?"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets or sets how cells will be vertically aligned by default. + /// + /// This setting only takes effect when the control is owner drawn. It will only be noticeable + /// when RowHeight has been set such that there is some vertical space in each row. + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(StringAlignment.Center)] + public virtual StringAlignment CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment cellVerticalAlignment = StringAlignment.Center; + + /// + /// Should this list show checkboxes? + /// + public new bool CheckBoxes { + get { return base.CheckBoxes; } + set { + // Due to code in the base ListView class, turning off CheckBoxes on a virtual + // list always throws an InvalidOperationException. We have to do some major hacking + // to get around that + if (this.VirtualMode) { + // Leave virtual mode + this.StateImageList = null; + this.VirtualListSize = 0; + this.VirtualMode = false; + + // Change the CheckBox setting while not in virtual mode + base.CheckBoxes = value; + + // Reinstate virtual mode + this.VirtualMode = true; + + // Re-enact the bits that we lost by switching to virtual mode + this.ShowGroups = this.ShowGroups; + this.BuildList(true); + } else { + base.CheckBoxes = value; + // Initialize the state image list so we can display indeterminate values. + this.InitializeStateImageList(); + } + } + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object CheckedObject { + get { + IList checkedObjects = this.CheckedObjects; + return checkedObjects.Count == 1 ? checkedObjects[0] : null; + } + set { + this.CheckedObjects = new ArrayList(new Object[] { value }); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// .NET's CheckedItems property is not helpful. It is just a short-hand for + /// iterating through the list looking for items that are checked. + /// + /// + /// The performance of the get method is O(n), where n is the number of items + /// in the control. The performance of the set method is + /// O(n + m) where m is the number of objects being checked. Be careful on long lists. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList CheckedObjects { + get { + ArrayList list = new ArrayList(); + if (this.CheckBoxes) { + for (int i = 0; i < this.GetItemCount(); i++) { + OLVListItem olvi = this.GetItem(i); + if (olvi.CheckState == CheckState.Checked) + list.Add(olvi.RowObject); + } + } + return list; + } + set { + if (!this.CheckBoxes) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + foreach (Object x in this.Objects) { + this.SetObjectCheckedness(x, table.ContainsKey(x) ? CheckState.Checked : CheckState.Unchecked); + } + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + + } + } + + /// + /// Gets or sets the checked objects from an enumerable. + /// + /// + /// Useful for checking all objects in the list. + /// + /// + /// this.olv1.CheckedObjectsEnumerable = this.olv1.Objects; + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable CheckedObjectsEnumerable { + get { + return this.CheckedObjects; + } + set { + this.CheckedObjects = ObjectListView.EnumerableToArray(value, true); + } + } + + /// + /// Gets Columns for this list. We hide the original so we can associate + /// a specialised editor with it. + /// + [Editor("BrightIdeasSoftware.Design.OLVColumnCollectionEditor", "System.Drawing.Design.UITypeEditor")] + public new ListView.ColumnHeaderCollection Columns { + get { + return base.Columns; + } + } + + /// + /// Get/set the list of columns that should be used when the list switches to tile view. + /// + [Browsable(false), + Obsolete("Use GetFilteredColumns() and OLVColumn.IsTileViewColumn instead"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public List ColumnsForTileView { + get { return this.GetFilteredColumns(View.Tile); } + } + + /// + /// Return the visible columns in the order they are displayed to the user + /// + [Browsable(false)] + public virtual List ColumnsInDisplayOrder { + get { + OLVColumn[] columnsInDisplayOrder = new OLVColumn[this.Columns.Count]; + foreach (OLVColumn col in this.Columns) { + columnsInDisplayOrder[col.DisplayIndex] = col; + } + return new List(columnsInDisplayOrder); + } + } + + + /// + /// Get the area of the control that shows the list, minus any header control + /// + [Browsable(false)] + public Rectangle ContentRectangle { + get { + Rectangle r = this.ClientRectangle; + + // If the listview has a header control, remove the header from the control area + if ((this.View == View.Details || this.ShowHeaderInAllViews) && this.HeaderControl != null) { + Rectangle hdrBounds = new Rectangle(); + NativeMethods.GetClientRect(this.HeaderControl.Handle, ref hdrBounds); + r.Y = hdrBounds.Height; + r.Height = r.Height - hdrBounds.Height; + } + + return r; + } + } + + /// + /// Gets or sets if the selected rows should be copied to the clipboard when the user presses Ctrl-C + /// + [Category("ObjectListView"), + Description("Should the control copy the selection to the clipboard when the user presses Ctrl-C?"), + DefaultValue(true)] + public virtual bool CopySelectionOnControlC { + get { return copySelectionOnControlC; } + set { copySelectionOnControlC = value; } + } + private bool copySelectionOnControlC = true; + + + /// + /// Gets or sets whether the Control-C copy to clipboard functionality should use + /// the installed DragSource to create the data object that is placed onto the clipboard. + /// + /// This is normally what is desired, unless a custom DragSource is installed + /// that does some very specialized drag-drop behaviour. + [Category("ObjectListView"), + Description("Should the Ctrl-C copy process use the DragSource to create the Clipboard data object?"), + DefaultValue(true)] + public bool CopySelectionOnControlCUsesDragSource { + get { return this.copySelectionOnControlCUsesDragSource; } + set { this.copySelectionOnControlCUsesDragSource = value; } + } + private bool copySelectionOnControlCUsesDragSource = true; + + /// + /// Gets the list of decorations that will be drawn the ListView + /// + /// + /// + /// Do not modify the contents of this list directly. Use the AddDecoration() and RemoveDecoration() methods. + /// + /// + /// A decoration scrolls with the list contents. An overlay is fixed in place. + /// + /// + [Browsable(false)] + protected IList Decorations { + get { return this.decorations; } + } + private readonly List decorations = new List(); + + /// + /// When owner drawing, this renderer will draw columns that do not have specific renderer + /// given to them + /// + /// If you try to set this to null, it will revert to a HighlightTextRenderer + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IRenderer DefaultRenderer { + get { return this.defaultRenderer; } + set { this.defaultRenderer = value ?? new HighlightTextRenderer(); } + } + private IRenderer defaultRenderer = new HighlightTextRenderer(); + + /// + /// Get the renderer to be used to draw the given cell. + /// + /// The row model for the row + /// The column to be drawn + /// The renderer used for drawing a cell. Must not return null. + public IRenderer GetCellRenderer(object model, OLVColumn column) { + IRenderer renderer = this.CellRendererGetter == null ? null : this.CellRendererGetter(model, column); + return renderer ?? column.Renderer ?? this.DefaultRenderer; + } + + /// + /// Gets or sets the style that will be applied to disabled items. + /// + /// If this is not set explicitly, will be used. + [Category("ObjectListView"), + Description("The style that will be applied to disabled items"), + DefaultValue(null)] + public SimpleItemStyle DisabledItemStyle + { + get { return disabledItemStyle; } + set { disabledItemStyle = value; } + } + private SimpleItemStyle disabledItemStyle; + + /// + /// Gets or sets the list of model objects that are disabled. + /// Disabled objects cannot be selected or activated. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable DisabledObjects + { + get + { + return disabledObjects.Keys; + } + set + { + this.disabledObjects.Clear(); + DisableObjects(value); + } + } + private readonly Hashtable disabledObjects = new Hashtable(); + + /// + /// Is this given model object disabled? + /// + /// + /// + public bool IsDisabled(object model) + { + return model != null && this.disabledObjects.ContainsKey(model); + } + + /// + /// Disable the given model object. + /// Disabled objects cannot be selected or activated. + /// + /// Must not be null + public void DisableObject(object model) { + ArrayList list = new ArrayList(); + list.Add(model); + this.DisableObjects(list); + } + + /// + /// Disable all the given model objects + /// + /// + public void DisableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model == null) + continue; + + this.disabledObjects[model] = true; + int modelIndex = this.IndexOf(model); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + this.RefreshObjects(list); + } + + /// + /// Enable the given model object, so it can be selected and activated again. + /// + /// Must not be null + public void EnableObject(object model) + { + this.disabledObjects.Remove(model); + this.RefreshObject(model); + } + + /// + /// Enable all the given model objects + /// + /// + public void EnableObjects(IEnumerable models) + { + if (models == null) + return; + ArrayList list = ObjectListView.EnumerableToArray(models, false); + foreach (object model in list) + { + if (model != null) + this.disabledObjects.Remove(model); + } + this.RefreshObjects(list); + } + + /// + /// Forget all disabled objects. This does not trigger a redraw or rebuild + /// + protected void ClearDisabledObjects() + { + this.disabledObjects.Clear(); + } + + /// + /// Gets or sets the object that controls how drags start from this control + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDragSource DragSource { + get { return this.dragSource; } + set { this.dragSource = value; } + } + private IDragSource dragSource; + + /// + /// Gets or sets the object that controls how drops are accepted and processed + /// by this ListView. + /// + /// + /// + /// If the given sink is an instance of SimpleDropSink, then events from the drop sink + /// will be automatically forwarded to the ObjectListView (which means that handlers + /// for those event can be configured within the IDE). + /// + /// If this is set to null, the control will not accept drops. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDropSink DropSink { + get { return this.dropSink; } + set { + if (this.dropSink == value) + return; + + // Stop listening for events on the old sink + SimpleDropSink oldSink = this.dropSink as SimpleDropSink; + if (oldSink != null) { + oldSink.CanDrop -= new EventHandler(this.DropSinkCanDrop); + oldSink.Dropped -= new EventHandler(this.DropSinkDropped); + oldSink.ModelCanDrop -= new EventHandler(this.DropSinkModelCanDrop); + oldSink.ModelDropped -= new EventHandler(this.DropSinkModelDropped); + } + + this.dropSink = value; + this.AllowDrop = (value != null); + if (this.dropSink != null) + this.dropSink.ListView = this; + + // Start listening for events on the new sink + SimpleDropSink newSink = value as SimpleDropSink; + if (newSink != null) { + newSink.CanDrop += new EventHandler(this.DropSinkCanDrop); + newSink.Dropped += new EventHandler(this.DropSinkDropped); + newSink.ModelCanDrop += new EventHandler(this.DropSinkModelCanDrop); + newSink.ModelDropped += new EventHandler(this.DropSinkModelDropped); + } + } + } + private IDropSink dropSink; + + // Forward events from the drop sink to the control itself + void DropSinkCanDrop(object sender, OlvDropEventArgs e) { this.OnCanDrop(e); } + void DropSinkDropped(object sender, OlvDropEventArgs e) { this.OnDropped(e); } + void DropSinkModelCanDrop(object sender, ModelDropEventArgs e) { this.OnModelCanDrop(e); } + void DropSinkModelDropped(object sender, ModelDropEventArgs e) { this.OnModelDropped(e); } + + /// + /// This registry decides what control should be used to edit what cells, based + /// on the type of the value in the cell. + /// + /// + /// All instances of ObjectListView share the same editor registry. +// ReSharper disable FieldCanBeMadeReadOnly.Global + public static EditorRegistry EditorRegistry = new EditorRegistry(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + + /// + /// Gets or sets the text that should be shown when there are no items in this list view. + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("When the list has no items, show this message in the control"), + DefaultValue(null), + Localizable(true)] + public virtual String EmptyListMsg { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Text; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) { + overlay.Text = value; + this.Invalidate(); + } + } + } + + /// + /// Gets or sets the font in which the List Empty message should be drawn + /// + /// If the EmptyListMsgOverlay has been changed to something other than a TextOverlay, + /// this property does nothing + [Category("ObjectListView"), + Description("What font should the 'list empty' message be drawn in?"), + DefaultValue(null)] + public virtual Font EmptyListMsgFont { + get { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + return overlay == null ? null : overlay.Font; + } + set { + TextOverlay overlay = this.EmptyListMsgOverlay as TextOverlay; + if (overlay != null) + overlay.Font = value; + } + } + + /// + /// Return the font for the 'list empty' message or a reasonable default + /// + [Browsable(false)] + public virtual Font EmptyListMsgFontOrDefault { + get { + return this.EmptyListMsgFont ?? new Font("Tahoma", 14); + } + } + + /// + /// Gets or sets the overlay responsible for drawing the List Empty msg. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IOverlay EmptyListMsgOverlay { + get { return this.emptyListMsgOverlay; } + set { + if (this.emptyListMsgOverlay != value) { + this.emptyListMsgOverlay = value; + this.Invalidate(); + } + } + } + private IOverlay emptyListMsgOverlay; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + /// + /// + /// This collection is the result of filtering the current list of objects. + /// It is not a snapshot of the filtered list that was last used to build the control. + /// + /// + /// Normal warnings apply when using this with virtual lists. It will work, but it + /// may take a while. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable FilteredObjects { + get { + if (this.UseFiltering) + return this.FilterObjects(this.Objects, this.ModelFilter, this.ListFilter); + + return this.Objects; + } + } + + /// + /// Gets or sets the strategy object that will be used to build the Filter menu + /// + /// If this is null, no filter menu will be built. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public FilterMenuBuilder FilterMenuBuildStrategy { + get { return filterMenuBuilder; } + set { filterMenuBuilder = value; } + } + private FilterMenuBuilder filterMenuBuilder = new FilterMenuBuilder(); + + /// + /// Gets or sets the row that has keyboard focus + /// + /// + /// + /// Setting an object to be focused does *not* select it. If you want to select and focus a row, + /// use . + /// + /// + /// This property is not generally used and is only useful in specialized situations. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object FocusedObject { + get { return this.FocusedItem == null ? null : ((OLVListItem)this.FocusedItem).RowObject; } + set { + OLVListItem item = this.ModelToItem(value); + if (item != null) + item.Focused = true; + } + } + + /// + /// Hide the Groups collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewGroupCollection Groups { + get { return base.Groups; } + } + + /// + /// Gets or sets the image list from which group header will take their images + /// + /// If this is not set, then group headers will not show any images. + [Category("ObjectListView"), + Description("The image list from which group header will take their images"), + DefaultValue(null)] + public ImageList GroupImageList { + get { return this.groupImageList; } + set { + this.groupImageList = value; + if (this.Created) { + NativeMethods.SetGroupImageList(this, value); + } + } + } + private ImageList groupImageList; + + /// + /// Gets how the group label should be formatted when a group is empty or + /// contains more than one item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group + /// + /// + /// "{0} [{1} items]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountFormat { + get { return groupWithItemCountFormat; } + set { groupWithItemCountFormat = value; } + } + private string groupWithItemCountFormat; + + /// + /// Return this.GroupWithItemCountFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountFormat) ? "{0} [{1} items]" : this.GroupWithItemCountFormat; + } + } + + /// + /// Gets how the group label should be formatted when a group contains only a single item + /// + /// + /// The given format string must have two placeholders: + /// + /// {0} - the original group title + /// {1} - the number of items in the group (always 1) + /// + /// + /// "{0} [{1} item]" + [Category("ObjectListView"), + Description("The format to use when suffixing item counts to group titles"), + DefaultValue(null), + Localizable(true)] + public virtual string GroupWithItemCountSingularFormat { + get { return groupWithItemCountSingularFormat; } + set { groupWithItemCountSingularFormat = value; } + } + private string groupWithItemCountSingularFormat; + + /// + /// Gets GroupWithItemCountSingularFormat or a reasonable default + /// + [Browsable(false)] + public virtual string GroupWithItemCountSingularFormatOrDefault { + get { + return String.IsNullOrEmpty(this.GroupWithItemCountSingularFormat) ? "{0} [{1} item]" : this.GroupWithItemCountSingularFormat; + } + } + + /// + /// Gets or sets whether or not the groups in this ObjectListView should be collapsible. + /// + /// + /// This feature only works under Vista and later. + /// + [Browsable(true), + Category("ObjectListView"), + Description("Should the groups in this control be collapsible (Vista and later only)."), + DefaultValue(true)] + public bool HasCollapsibleGroups { + get { return hasCollapsibleGroups; } + set { hasCollapsibleGroups = value; } + } + private bool hasCollapsibleGroups = true; + + /// + /// Does this listview have a message that should be drawn when the list is empty? + /// + [Browsable(false)] + public virtual bool HasEmptyListMsg { + get { return !String.IsNullOrEmpty(this.EmptyListMsg); } + } + + /// + /// Get whether there are any overlays to be drawn + /// + [Browsable(false)] + public bool HasOverlays { + get { + return (this.Overlays.Count > 2 || + this.imageOverlay.Image != null || + !String.IsNullOrEmpty(this.textOverlay.Text)); + } + } + + /// + /// Gets the header control for the ListView + /// + [Browsable(false)] + public HeaderControl HeaderControl { + get { return this.headerControl ?? (this.headerControl = new HeaderControl(this)); } + } + private HeaderControl headerControl; + + /// + /// Gets or sets the font in which the text of the column headers will be drawn + /// + /// Individual columns can override this through their HeaderFormatStyle property. + [DefaultValue(null)] + [Browsable(false)] + [Obsolete("Use a HeaderFormatStyle instead", false)] + public Font HeaderFont { + get { return this.HeaderFormatStyle == null ? null : this.HeaderFormatStyle.Normal.Font; } + set { + if (value == null && this.HeaderFormatStyle == null) + return; + + if (this.HeaderFormatStyle == null) + this.HeaderFormatStyle = new HeaderFormatStyle(); + + this.HeaderFormatStyle.SetFont(value); + } + } + + /// + /// Gets or sets the style that will be used to draw the column headers of the listview + /// + /// + /// + /// This is only used when HeaderUsesThemes is false. + /// + /// + /// Individual columns can override this through their HeaderFormatStyle property. + /// + /// + [Category("ObjectListView"), + Description("What style will be used to draw the control's header"), + DefaultValue(null)] + public HeaderFormatStyle HeaderFormatStyle { + get { return this.headerFormatStyle; } + set { this.headerFormatStyle = value; } + } + private HeaderFormatStyle headerFormatStyle; + + /// + /// Gets or sets the maximum height of the header. -1 means no maximum. + /// + [Category("ObjectListView"), + Description("What is the maximum height of the header? -1 means no maximum"), + DefaultValue(-1)] + public int HeaderMaximumHeight + { + get { return headerMaximumHeight; } + set { headerMaximumHeight = value; } + } + private int headerMaximumHeight = -1; + + /// + /// Gets or sets the minimum height of the header. -1 means no minimum. + /// + [Category("ObjectListView"), + Description("What is the minimum height of the header? -1 means no minimum"), + DefaultValue(-1)] + public int HeaderMinimumHeight + { + get { return headerMinimumHeight; } + set { headerMinimumHeight = value; } + } + private int headerMinimumHeight = -1; + + /// + /// Gets or sets whether the header will be drawn strictly according to the OS's theme. + /// + /// + /// + /// If this is set to true, the header will be rendered completely by the system, without + /// any of ObjectListViews fancy processing -- no images in header, no filter indicators, + /// no word wrapping, no header styling, no checkboxes. + /// + /// If this is set to false, ObjectListView will render the header as it thinks best. + /// If no special features are required, then ObjectListView will delegate rendering to the OS. + /// Otherwise, ObjectListView will draw the header according to the configuration settings. + /// + /// + /// The effect of not being themed will be different from OS to OS. At + /// very least, the sort indicator will not be standard. + /// + /// + [Category("ObjectListView"), + Description("Will the column headers be drawn strictly according to OS theme?"), + DefaultValue(false)] + public bool HeaderUsesThemes { + get { return this.headerUsesThemes; } + set { this.headerUsesThemes = value; } + } + private bool headerUsesThemes; + + /// + /// Gets or sets the whether the text in the header will be word wrapped. + /// + /// + /// Line breaks will be applied between words. Words that are too long + /// will still be ellipsed. + /// + /// As with all settings that make the header look different, HeaderUsesThemes must be set to false, otherwise + /// the OS will be responsible for drawing the header, and it does not allow word wrapped text. + /// + /// + [Category("ObjectListView"), + Description("Will the text of the column headers be word wrapped?"), + DefaultValue(false)] + public bool HeaderWordWrap { + get { return this.headerWordWrap; } + set { + this.headerWordWrap = value; + if (this.headerControl != null) + this.headerControl.WordWrap = value; + } + } + private bool headerWordWrap; + + /// + /// Gets the tool tip that shows tips for the column headers + /// + [Browsable(false)] + public ToolTipControl HeaderToolTip { + get { + return this.HeaderControl.ToolTip; + } + } + + /// + /// Gets the index of the row that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotRowIndex { + get { return this.hotRowIndex; } + protected set { this.hotRowIndex = value; } + } + private int hotRowIndex; + + /// + /// Gets the index of the subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int HotColumnIndex { + get { return this.hotColumnIndex; } + protected set { this.hotColumnIndex = value; } + } + private int hotColumnIndex; + + /// + /// Gets the part of the item/subitem that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocation HotCellHitLocation { + get { return this.hotCellHitLocation; } + protected set { this.hotCellHitLocation = value; } + } + private HitTestLocation hotCellHitLocation; + + /// + /// Gets an extended indication of the part of item/subitem/group that the mouse is currently over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HitTestLocationEx HotCellHitLocationEx + { + get { return this.hotCellHitLocationEx; } + protected set { this.hotCellHitLocationEx = value; } + } + private HitTestLocationEx hotCellHitLocationEx; + + /// + /// Gets the group that the mouse is over + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVGroup HotGroup + { + get { return hotGroup; } + internal set { hotGroup = value; } + } + private OLVGroup hotGroup; + + /// + /// The index of the item that is 'hot', i.e. under the cursor. -1 means no item. + /// + [Browsable(false), + Obsolete("Use HotRowIndex instead", false)] + public virtual int HotItemIndex { + get { return this.HotRowIndex; } + } + + /// + /// What sort of formatting should be applied to the row under the cursor? + /// + /// + /// + /// This only takes effect when UseHotItem is true. + /// + /// If the style has an overlay, it must be set + /// *before* assigning it to this property. Adding it afterwards will be ignored. + /// + [Category("ObjectListView"), + Description("How should the row under the cursor be highlighted"), + DefaultValue(null)] + public virtual HotItemStyle HotItemStyle { + get { return this.hotItemStyle; } + set { + if (this.HotItemStyle != null) + this.RemoveOverlay(this.HotItemStyle.Overlay); + this.hotItemStyle = value; + if (this.HotItemStyle != null) + this.AddOverlay(this.HotItemStyle.Overlay); + } + } + private HotItemStyle hotItemStyle; + + /// + /// Gets the installed hot item style or a reasonable default. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HotItemStyle HotItemStyleOrDefault { + get { return this.HotItemStyle ?? ObjectListView.DefaultHotItemStyle; } + } + + /// + /// What sort of formatting should be applied to hyperlinks? + /// + [Category("ObjectListView"), + Description("How should hyperlinks be drawn"), + DefaultValue(null)] + public virtual HyperlinkStyle HyperlinkStyle { + get { return this.hyperlinkStyle; } + set { this.hyperlinkStyle = value; } + } + private HyperlinkStyle hyperlinkStyle; + + /// + /// What color should be used for the background of selected rows? + /// + [Category("ObjectListView"), + Description("The background of selected rows when the control is owner drawn"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedBackColor { + get { return this.selectedBackColor; } + set { this.selectedBackColor = value; } + } + private Color selectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedBackColorOrDefault { + get { + return this.SelectedBackColor.IsEmpty ? SystemColors.Highlight : this.SelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows (when the control is owner drawn)"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedForeColor { + get { return this.selectedForeColor; } + set { this.selectedForeColor = value; } + } + private Color selectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows or a reasonable default + /// + [Browsable(false)] + public virtual Color SelectedForeColorOrDefault { + get { + return this.SelectedForeColor.IsEmpty ? SystemColors.HighlightText : this.SelectedForeColor; + } + } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedBackColor instead")] + public virtual Color HighlightBackgroundColor { get { return this.SelectedBackColor; } set { this.SelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedBackColorOrDefault instead")] + public virtual Color HighlightBackgroundColorOrDefault { get { return this.SelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use SelectedForeColor instead")] + public virtual Color HighlightForegroundColor { get { return this.SelectedForeColor; } set { this.SelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use SelectedForeColorOrDefault instead")] + public virtual Color HighlightForegroundColorOrDefault { get { return this.SelectedForeColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedBackColor instead")] + public virtual Color UnfocusedHighlightBackgroundColor { get { return this.UnfocusedSelectedBackColor; } set { this.UnfocusedSelectedBackColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedBackColorOrDefault instead")] + public virtual Color UnfocusedHighlightBackgroundColorOrDefault { get { return this.UnfocusedSelectedBackColorOrDefault; } } + + /// + /// + /// + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Obsolete("Use UnfocusedSelectedForeColor instead")] + public virtual Color UnfocusedHighlightForegroundColor { get { return this.UnfocusedSelectedForeColor; } set { this.UnfocusedSelectedForeColor = value; } } + + /// + /// + /// + [Obsolete("Use UnfocusedSelectedForeColorOrDefault instead")] + public virtual Color UnfocusedHighlightForegroundColorOrDefault { get { return this.UnfocusedSelectedForeColorOrDefault; } } + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied or dragged, will data in hidden columns be included in the text? If this is false, only visible columns will be included."), + DefaultValue(false)] + public virtual bool IncludeHiddenColumnsInDataTransfer + { + get { return includeHiddenColumnsInDataTransfer; } + set { includeHiddenColumnsInDataTransfer = value; } + } + private bool includeHiddenColumnsInDataTransfer; + + /// + /// Gets or sets whether or not hidden columns should be included in the text representation + /// of rows that are copied or dragged to another application. If this is false (the default), + /// only visible columns will be included. + /// + [Category("ObjectListView"), + Description("When rows are copied, will column headers be in the text?."), + DefaultValue(false)] + public virtual bool IncludeColumnHeadersInCopy + { + get { return includeColumnHeadersInCopy; } + set { includeColumnHeadersInCopy = value; } + } + private bool includeColumnHeadersInCopy; + + /// + /// Return true if a cell edit operation is currently happening + /// + [Browsable(false)] + public virtual bool IsCellEditing { + get { return this.cellEditor != null; } + } + + /// + /// Return true if the ObjectListView is being used within the development environment. + /// + [Browsable(false)] + public virtual bool IsDesignMode { + get { return this.DesignMode; } + } + + /// + /// Gets whether or not the current list is filtering its contents + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool IsFiltering { + get { return this.UseFiltering && (this.ModelFilter != null || this.ListFilter != null); } + } + + /// + /// When the user types into a list, should the values in the current sort column be searched to find a match? + /// If this is false, the primary column will always be used regardless of the sort column. + /// + /// When this is true, the behavior is like that of ITunes. + [Category("ObjectListView"), + Description("When the user types into a list, should the values in the current sort column be searched to find a match?"), + DefaultValue(true)] + public virtual bool IsSearchOnSortColumn { + get { return isSearchOnSortColumn; } + set { isSearchOnSortColumn = value; } + } + private bool isSearchOnSortColumn = true; + + /// + /// Gets or sets if this control will use a SimpleDropSink to receive drops + /// + /// + /// + /// Setting this replaces any previous DropSink. + /// + /// + /// After setting this to true, the SimpleDropSink will still need to be configured + /// to say when it can accept drops and what should happen when something is dropped. + /// The need to do these things makes this property mostly useless :( + /// + /// + [Category("ObjectListView"), + Description("Should this control will use a SimpleDropSink to receive drops."), + DefaultValue(false)] + public virtual bool IsSimpleDropSink { + get { return this.DropSink != null; } + set { + this.DropSink = value ? new SimpleDropSink() : null; + } + } + + /// + /// Gets or sets if this control will use a SimpleDragSource to initiate drags + /// + /// Setting this replaces any previous DragSource + [Category("ObjectListView"), + Description("Should this control use a SimpleDragSource to initiate drags out from this control"), + DefaultValue(false)] + public virtual bool IsSimpleDragSource { + get { return this.DragSource != null; } + set { + this.DragSource = value ? new SimpleDragSource() : null; + } + } + + /// + /// Hide the Items collection so it's not visible in the Properties grid. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public new ListViewItemCollection Items { + get { return base.Items; } + } + + /// + /// This renderer draws the items when in the list is in non-details view. + /// In details view, the renderers for the individuals columns are responsible. + /// + [Category("ObjectListView"), + Description("The owner drawn renderer that draws items when the list is in non-Details view."), + DefaultValue(null)] + public IRenderer ItemRenderer { + get { return itemRenderer; } + set { itemRenderer = value; } + } + private IRenderer itemRenderer; + + /// + /// Which column did we last sort by + /// + /// This is an alias for PrimarySortColumn + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn LastSortColumn { + get { return this.PrimarySortColumn; } + set { this.PrimarySortColumn = value; } + } + + /// + /// Which direction did we last sort + /// + /// This is an alias for PrimarySortOrder + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder LastSortOrder { + get { return this.PrimarySortOrder; } + set { this.PrimarySortOrder = value; } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// + /// + /// The list is updated immediately to reflect this filter. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IListFilter ListFilter { + get { return listFilter; } + set { + listFilter = value; + if (this.UseFiltering) + this.UpdateFiltering(); + } + } + private IListFilter listFilter; + + /// + /// Gets or sets the filter that is applied to each model objects in the list + /// + /// + /// You may want to consider using instead of this property, + /// since AdditionalFilter combines with column filtering at runtime. Setting this property simply + /// replaces any column filter the user may have given. + /// + /// The list is updated immediately to reflect this filter. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IModelFilter ModelFilter { + get { return modelFilter; } + set { + modelFilter = value; + this.NotifyNewModelFilter(); + if (this.UseFiltering) { + this.UpdateFiltering(); + + // When the filter changes, it's likely/possible that the selection has also changed. + // It's expensive to see if the selection has actually changed (for large virtual lists), + // so we just fake a selection changed event, just in case. SF #144 + this.OnSelectedIndexChanged(EventArgs.Empty); + } + } + } + private IModelFilter modelFilter; + + /// + /// Gets the hit test info last time the mouse was moved. + /// + /// Useful for hot item processing. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OlvListViewHitTestInfo MouseMoveHitTest { + get { return mouseMoveHitTest; } + private set { mouseMoveHitTest = value; } + } + private OlvListViewHitTestInfo mouseMoveHitTest; + + /// + /// Gets or sets the list of groups shown by the listview. + /// + /// + /// This property does not work like the .NET Groups property. It should + /// be treated as a read-only property. + /// Changes made to the list are NOT reflected in the ListView itself -- it is pointless to add + /// or remove groups to/from this list. Such modifications will do nothing. + /// To do such things, you must listen for + /// BeforeCreatingGroups or AboutToCreateGroups events, and change the list of + /// groups in those events. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IList OLVGroups { + get { return this.olvGroups; } + set { this.olvGroups = value; } + } + private IList olvGroups; + + /// + /// Gets or sets the collection of OLVGroups that are collapsed. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable CollapsedGroups { + get + { + if (this.OLVGroups != null) + { + foreach (OLVGroup group in this.OLVGroups) + { + if (group.Collapsed) + yield return group; + } + } + } + set + { + if (this.OLVGroups == null) + return; + + Hashtable shouldCollapse = new Hashtable(); + if (value != null) + { + foreach (OLVGroup group in value) + shouldCollapse[group.Key] = true; + } + foreach (OLVGroup group in this.OLVGroups) + { + group.Collapsed = shouldCollapse.ContainsKey(group.Key); + } + + } + } + + /// + /// Gets or sets whether the user wants to owner draw the header control + /// themselves. If this is false (the default), ObjectListView will use + /// custom drawing to render the header, if needed. + /// + /// + /// If you listen for the DrawColumnHeader event, you need to set this to true, + /// otherwise your event handler will not be called. + /// + [Category("ObjectListView"), + Description("Should the DrawColumnHeader event be triggered"), + DefaultValue(false)] + public bool OwnerDrawnHeader { + get { return ownerDrawnHeader; } + set { ownerDrawnHeader = value; } + } + private bool ownerDrawnHeader; + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// This method preserves selection, if possible. Use if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code and performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists: setting is problem-free, but if you try to get it + /// and the list has 10 million objects, it may take some time to return. + /// This collection is unfiltered. Use to access just those objects + /// that survive any installed filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Objects { + get { return this.objects; } + set { this.SetObjects(value, true); } + } + private IEnumerable objects; + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable ObjectsForClustering { + get { return this.Objects; } + } + + /// + /// Gets or sets the image that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The image that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public ImageOverlay OverlayImage { + get { return this.imageOverlay; } + set { + if (this.imageOverlay == value) + return; + + this.RemoveOverlay(this.imageOverlay); + this.imageOverlay = value; + this.AddOverlay(this.imageOverlay); + } + } + private ImageOverlay imageOverlay; + + /// + /// Gets or sets the text that will be drawn over the top of the ListView + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public TextOverlay OverlayText { + get { return this.textOverlay; } + set { + if (this.textOverlay == value) + return; + + this.RemoveOverlay(this.textOverlay); + this.textOverlay = value; + this.AddOverlay(this.textOverlay); + } + } + private TextOverlay textOverlay; + + /// + /// Gets or sets the transparency of all the overlays. + /// 0 is completely transparent, 255 is completely opaque. + /// + /// + /// This is obsolete. Use Transparency on each overlay. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int OverlayTransparency { + get { return this.overlayTransparency; } + set { this.overlayTransparency = Math.Min(255, Math.Max(0, value)); } + } + private int overlayTransparency = 128; + + /// + /// Gets the list of overlays that will be drawn on top of the ListView + /// + /// + /// You can add new overlays and remove overlays that you have added, but + /// don't mess with the overlays that you didn't create. + /// + [Browsable(false)] + protected IList Overlays { + get { return this.overlays; } + } + private readonly List overlays = new List(); + + /// + /// Gets or sets whether the ObjectListView will be owner drawn. Defaults to true. + /// + /// + /// + /// When this is true, all of ObjectListView's neat features are available. + /// + /// We have to reimplement this property, even though we just call the base + /// property, in order to change the [DefaultValue] to true. + /// + /// + [Category("Appearance"), + Description("Should the ListView do its own rendering"), + DefaultValue(true)] + public new bool OwnerDraw { + get { return base.OwnerDraw; } + set { base.OwnerDraw = value; } + } + + /// + /// Gets or sets whether or not primary checkboxes will persistent their values across list rebuild + /// and filtering operations. + /// + /// + /// + /// This property is only useful when you don't explicitly set CheckStateGetter/Putter. + /// If you use CheckStateGetter/Putter, the checkedness of a row will already be persisted + /// by those methods. + /// + /// This defaults to true. If this is false, checkboxes will lose their values when the + /// list if rebuild or filtered. + /// If you set it to false on virtual lists, + /// you have to install CheckStateGetter/Putters. + /// + [Category("ObjectListView"), + Description("Will primary checkboxes persistent their values across list rebuilds"), + DefaultValue(true)] + public virtual bool PersistentCheckBoxes { + get { return persistentCheckBoxes; } + set { + if (persistentCheckBoxes == value) + return; + persistentCheckBoxes = value; + this.ClearPersistentCheckState(); + } + } + private bool persistentCheckBoxes = true; + + /// + /// Gets or sets a dictionary that remembers the check state of model objects + /// + /// This is used when PersistentCheckBoxes is true and for virtual lists. + protected Dictionary CheckStateMap { + get { return checkStateMap ?? (checkStateMap = new Dictionary()); } + set { checkStateMap = value; } + } + private Dictionary checkStateMap; + + /// + /// Which column did we last sort by + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn PrimarySortColumn { + get { return this.primarySortColumn; } + set { + this.primarySortColumn = value; + if (this.TintSortColumn) + this.SelectedColumn = value; + } + } + private OLVColumn primarySortColumn; + + /// + /// Which direction did we last sort + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder PrimarySortOrder { + get { return primarySortOrder; } + set { primarySortOrder = value; } + } + private SortOrder primarySortOrder; + + /// + /// Gets or sets if non-editable checkboxes are drawn as disabled. Default is false. + /// + /// + /// This only has effect in owner drawn mode. + /// + [Category("ObjectListView"), + Description("Should non-editable checkboxes be drawn as disabled?"), + DefaultValue(false)] + public virtual bool RenderNonEditableCheckboxesAsDisabled { + get { return renderNonEditableCheckboxesAsDisabled; } + set { renderNonEditableCheckboxesAsDisabled = value; } + } + private bool renderNonEditableCheckboxesAsDisabled; + + /// + /// Specify the height of each row in the control in pixels. + /// + /// The row height in a listview is normally determined by the font size and the small image list size. + /// This setting allows that calculation to be overridden (within reason: you still cannot set the line height to be + /// less than the line height of the font used in the control). + /// Setting it to -1 means use the normal calculation method. + /// This feature is experimental! Strange things may happen to your program, + /// your spouse or your pet if you use it. + /// + [Category("ObjectListView"), + Description("Specify the height of each row in pixels. -1 indicates default height"), + DefaultValue(-1)] + public virtual int RowHeight { + get { return rowHeight; } + set { + if (value < 1) + rowHeight = -1; + else + rowHeight = value; + if (this.DesignMode) + return; + this.SetupBaseImageList(); + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + } + private int rowHeight = -1; + + /// + /// How many pixels high is each row? + /// + [Browsable(false)] + public virtual int RowHeightEffective { + get { + switch (this.View) { + case View.List: + case View.SmallIcon: + case View.Details: + return Math.Max(this.SmallImageSize.Height, this.Font.Height); + + case View.Tile: + return this.TileSize.Height; + + case View.LargeIcon: + if (this.LargeImageList == null) + return this.Font.Height; + + return Math.Max(this.LargeImageList.ImageSize.Height, this.Font.Height); + + default: + // This should never happen + return 0; + } + } + } + + /// + /// How many rows appear on each page of this control + /// + [Browsable(false)] + public virtual int RowsPerPage { + get { + return NativeMethods.GetCountPerPage(this); + } + } + + /// + /// Get/set the column that will be used to resolve comparisons that are equal when sorting. + /// + /// There is no user interface for this setting. It must be set programmatically. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVColumn SecondarySortColumn { + get { return this.secondarySortColumn; } + set { this.secondarySortColumn = value; } + } + private OLVColumn secondarySortColumn; + + /// + /// When the SecondarySortColumn is used, in what order will it compare results? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortOrder SecondarySortOrder { + get { return this.secondarySortOrder; } + set { this.secondarySortOrder = value; } + } + private SortOrder secondarySortOrder = SortOrder.None; + + /// + /// Gets or sets if all rows should be selected when the user presses Ctrl-A + /// + [Category("ObjectListView"), + Description("Should the control select all rows when the user presses Ctrl-A?"), + DefaultValue(true)] + public virtual bool SelectAllOnControlA { + get { return selectAllOnControlA; } + set { selectAllOnControlA = value; } + } + private bool selectAllOnControlA = true; + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose which columns will be shown in the view? + /// + /// This is just a compatibility wrapper for the SelectColumnsOnRightClickBehaviour + /// property. + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to choose which columns will be shown in the view?"), + DefaultValue(true)] + public virtual bool SelectColumnsOnRightClick { + get { return this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None; } + set { + if (value) { + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.None) + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + } else { + this.SelectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.None; + } + } + } + + /// + /// Gets or sets how the user will be able to select columns when the header is right clicked + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, how will the user be able to select columns?"), + DefaultValue(ColumnSelectBehaviour.InlineMenu)] + public virtual ColumnSelectBehaviour SelectColumnsOnRightClickBehaviour { + get { return selectColumnsOnRightClickBehaviour; } + set { selectColumnsOnRightClickBehaviour = value; } + } + private ColumnSelectBehaviour selectColumnsOnRightClickBehaviour = ColumnSelectBehaviour.InlineMenu; + + /// + /// When the column select menu is open, should it stay open after an item is selected? + /// Staying open allows the user to turn more than one column on or off at a time. + /// + /// This only works when SelectColumnsOnRightClickBehaviour is set to InlineMenu. + /// It has no effect when the behaviour is set to SubMenu. + [Category("ObjectListView"), + Description("When the column select inline menu is open, should it stay open after an item is selected?"), + DefaultValue(true)] + public virtual bool SelectColumnsMenuStaysOpen { + get { return selectColumnsMenuStaysOpen; } + set { selectColumnsMenuStaysOpen = value; } + } + private bool selectColumnsMenuStaysOpen = true; + + /// + /// Gets or sets the column that is drawn with a slight tint. + /// + /// + /// + /// If TintSortColumn is true, the sort column will automatically + /// be made the selected column. + /// + /// + /// The colour of the tint is controlled by SelectedColumnTint. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn SelectedColumn { + get { return this.selectedColumn; } + set { + this.selectedColumn = value; + if (value == null) { + this.RemoveDecoration(this.selectedColumnDecoration); + } else { + if (!this.HasDecoration(this.selectedColumnDecoration)) + this.AddDecoration(this.selectedColumnDecoration); + } + } + } + private OLVColumn selectedColumn; + private readonly TintedColumnDecoration selectedColumnDecoration = new TintedColumnDecoration(); + + /// + /// Gets or sets the decoration that will be drawn on all selected rows + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IDecoration SelectedRowDecoration { + get { return this.selectedRowDecoration; } + set { this.selectedRowDecoration = value; } + } + private IDecoration selectedRowDecoration; + + /// + /// What color should be used to tint the selected column? + /// + /// + /// The tint color must be alpha-blendable, so if the given color is solid + /// (i.e. alpha = 255), it will be changed to have a reasonable alpha value. + /// + [Category("ObjectListView"), + Description("The color that will be used to tint the selected column"), + DefaultValue(typeof(Color), "")] + public virtual Color SelectedColumnTint { + get { return selectedColumnTint; } + set { + this.selectedColumnTint = value.A == 255 ? Color.FromArgb(15, value) : value; + this.selectedColumnDecoration.Tint = this.selectedColumnTint; + } + } + private Color selectedColumnTint = Color.Empty; + + /// + /// Gets or sets the index of the row that is currently selected. + /// When getting the index, if no row is selected,or more than one is selected, return -1. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int SelectedIndex { + get { return this.SelectedIndices.Count == 1 ? this.SelectedIndices[0] : -1; } + set { + this.SelectedIndices.Clear(); + if (value >= 0 && value < this.Items.Count) + this.SelectedIndices.Add(value); + } + } + + /// + /// Gets or sets the ListViewItem that is currently selected . If no row is selected, or more than one is selected, return null. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual OLVListItem SelectedItem { + get { + return this.SelectedIndices.Count == 1 ? this.GetItem(this.SelectedIndices[0]) : null; + } + set { + this.SelectedIndices.Clear(); + if (value != null) + this.SelectedIndices.Add(value.Index); + } + } + + /// + /// Gets the model object from the currently selected row, if there is only one row selected. + /// If no row is selected, or more than one is selected, returns null. + /// When setting, this will select the row that is displaying the given model object and focus on it. + /// All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual Object SelectedObject { + get { + return this.SelectedIndices.Count == 1 ? this.GetModelObject(this.SelectedIndices[0]) : null; + } + set { + // If the given model is already selected, don't do anything else (prevents an flicker) + object selectedObject = this.SelectedObject; + if (selectedObject != null && selectedObject.Equals(value)) + return; + + this.SelectedIndices.Clear(); + this.SelectObject(value, true); + } + } + + /// + /// Get the model objects from the currently selected rows. If no row is selected, the returned List will be empty. + /// When setting this value, select the rows that is displaying the given model objects. All other rows are deselected. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IList SelectedObjects { + get { + ArrayList list = new ArrayList(); + foreach (int index in this.SelectedIndices) + list.Add(this.GetModelObject(index)); + return list; + } + set { + this.SelectedIndices.Clear(); + this.SelectObjects(value); + } + } + + /// + /// When the user right clicks on the column headers, should a menu be presented which will allow + /// them to choose common tasks to perform on the listview? + /// + [Category("ObjectListView"), + Description("When the user right clicks on the column headers, should a menu be presented which will allow them to perform common tasks on the listview?"), + DefaultValue(false)] + public virtual bool ShowCommandMenuOnRightClick { + get { return showCommandMenuOnRightClick; } + set { showCommandMenuOnRightClick = value; } + } + private bool showCommandMenuOnRightClick; + + /// + /// Gets or sets whether this ObjectListView will show Excel like filtering + /// menus when the header control is right clicked + /// + [Category("ObjectListView"), + Description("If this is true, right clicking on a column header will show a Filter menu option"), + DefaultValue(true)] + public bool ShowFilterMenuOnRightClick { + get { return showFilterMenuOnRightClick; } + set { showFilterMenuOnRightClick = value; } + } + private bool showFilterMenuOnRightClick = true; + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + public new virtual bool ShowGroups { + get { return base.ShowGroups; } + set { + this.GroupImageList = this.GroupImageList; + base.ShowGroups = value; + } + } + + /// + /// Should the list view show a bitmap in the column header to show the sort direction? + /// + /// + /// The only reason for not wanting to have sort indicators is that, on pre-XP versions of + /// Windows, having sort indicators required the ListView to have a small image list, and + /// as soon as you give a ListView a SmallImageList, the text of column 0 is bumped 16 + /// pixels to the right, even if you never used an image. + /// + [Category("ObjectListView"), + Description("Should the list view show sort indicators in the column headers?"), + DefaultValue(true)] + public virtual bool ShowSortIndicators { + get { return showSortIndicators; } + set { showSortIndicators = value; } + } + private bool showSortIndicators; + + /// + /// Should the list view show images on subitems? + /// + /// + /// Virtual lists have to be owner drawn in order to show images on subitems + /// + [Category("ObjectListView"), + Description("Should the list view show images on subitems?"), + DefaultValue(false)] + public virtual bool ShowImagesOnSubItems { + get { return showImagesOnSubItems; } + set { + showImagesOnSubItems = value; + if (this.Created) + this.ApplyExtendedStyles(); + if (value && this.VirtualMode) + this.OwnerDraw = true; + } + } + private bool showImagesOnSubItems; + + /// + /// This property controls whether group labels will be suffixed with a count of items. + /// + /// + /// The format of the suffix is controlled by GroupWithItemCountFormat/GroupWithItemCountSingularFormat properties + /// + [Category("ObjectListView"), + Description("Will group titles be suffixed with a count of the items in the group?"), + DefaultValue(false)] + public virtual bool ShowItemCountOnGroups { + get { return showItemCountOnGroups; } + set { showItemCountOnGroups = value; } + } + private bool showItemCountOnGroups; + + /// + /// Gets or sets whether the control will show column headers in all + /// views (true), or only in Details view (false) + /// + /// + /// + /// This property is not working correctly. JPP 2010/04/06. + /// It works fine if it is set before the control is created. + /// But if it turned off once the control is created, the control + /// loses its checkboxes (weird!) + /// + /// + /// To changed this setting after the control is created, things + /// are complicated. If it is off and we want it on, we have + /// to change the View and the header will appear. If it is currently + /// on and we want to turn it off, we have to both change the view + /// AND recreate the handle. Recreating the handle is a problem + /// since it makes our checkbox style disappear. + /// + /// + /// This property doesn't work on XP. + /// + [Category("ObjectListView"), + Description("Will the control will show column headers in all views?"), + DefaultValue(true)] + public bool ShowHeaderInAllViews { + get { return ObjectListView.IsVistaOrLater && showHeaderInAllViews; } + set { + if (showHeaderInAllViews == value) + return; + + showHeaderInAllViews = value; + + // If the control isn't already created, everything is fine. + if (!this.Created) + return; + + // If the header is being hidden, we have to recreate the control + // to remove the style (not sure why this is) + if (showHeaderInAllViews) + this.ApplyExtendedStyles(); + else + this.RecreateHandle(); + + // Still more complications. The change doesn't become visible until the View is changed + if (this.View != View.Details) { + View temp = this.View; + this.View = View.Details; + this.View = temp; + } + } + } + private bool showHeaderInAllViews = true; + + /// + /// Override the SmallImageList property so we can correctly shadow its operations. + /// + /// If you use the RowHeight property to specify the row height, the SmallImageList + /// must be fully initialised before setting/changing the RowHeight. If you add new images to the image + /// list after setting the RowHeight, you must assign the imagelist to the control again. Something as simple + /// as this will work: + /// listView1.SmallImageList = listView1.SmallImageList; + /// + public new ImageList SmallImageList { + get { return this.shadowedImageList; } + set { + this.shadowedImageList = value; + if (this.UseSubItemCheckBoxes) + this.SetupSubItemCheckBoxes(); + this.SetupBaseImageList(); + } + } + private ImageList shadowedImageList; + + /// + /// Return the size of the images in the small image list or a reasonable default + /// + [Browsable(false)] + public virtual Size SmallImageSize { + get { + return this.BaseSmallImageList == null ? new Size(16, 16) : this.BaseSmallImageList.ImageSize; + } + } + + /// + /// When the listview is grouped, should the items be sorted by the primary column? + /// If this is false, the items will be sorted by the same column as they are grouped. + /// + /// + /// + /// The primary column is always column 0 and is unrelated to the PrimarySort column. + /// + /// + [Category("ObjectListView"), + Description("When the listview is grouped, should the items be sorted by the primary column? If this is false, the items will be sorted by the same column as they are grouped."), + DefaultValue(true)] + public virtual bool SortGroupItemsByPrimaryColumn { + get { return this.sortGroupItemsByPrimaryColumn; } + set { this.sortGroupItemsByPrimaryColumn = value; } + } + private bool sortGroupItemsByPrimaryColumn = true; + + /// + /// When the listview is grouped, how many pixels should exist between the end of one group and the + /// beginning of the next? + /// + [Category("ObjectListView"), + Description("How many pixels of space will be between groups"), + DefaultValue(0)] + public virtual int SpaceBetweenGroups { + get { return this.spaceBetweenGroups; } + set { + if (this.spaceBetweenGroups == value) + return; + + this.spaceBetweenGroups = value; + this.SetGroupSpacing(); + } + } + private int spaceBetweenGroups; + + private void SetGroupSpacing() { + if (!this.IsHandleCreated) + return; + + NativeMethods.LVGROUPMETRICS metrics = new NativeMethods.LVGROUPMETRICS(); + metrics.cbSize = ((uint)Marshal.SizeOf(typeof(NativeMethods.LVGROUPMETRICS))); + metrics.mask = (uint)GroupMetricsMask.LVGMF_BORDERSIZE; + metrics.Bottom = (uint)this.SpaceBetweenGroups; + NativeMethods.SetGroupMetrics(this, metrics); + } + + /// + /// Should the sort column show a slight tinge? + /// + [Category("ObjectListView"), + Description("Should the sort column show a slight tinting?"), + DefaultValue(false)] + public virtual bool TintSortColumn { + get { return this.tintSortColumn; } + set { + this.tintSortColumn = value; + if (value && this.PrimarySortColumn != null) + this.SelectedColumn = this.PrimarySortColumn; + else + this.SelectedColumn = null; + } + } + private bool tintSortColumn; + + /// + /// Should each row have a tri-state checkbox? + /// + /// + /// If this is true, the user can choose the third state (normally Indeterminate). Otherwise, user clicks + /// alternate between checked and unchecked. CheckStateGetter can still return Indeterminate when this + /// setting is false. + /// + [Category("ObjectListView"), + Description("Should the primary column have a checkbox that behaves as a tri-state checkbox?"), + DefaultValue(false)] + public virtual bool TriStateCheckBoxes { + get { return triStateCheckBoxes; } + set { + triStateCheckBoxes = value; + if (value && !this.CheckBoxes) + this.CheckBoxes = true; + this.InitializeStateImageList(); + } + } + private bool triStateCheckBoxes; + + /// + /// Get or set the index of the top item of this listview + /// + /// + /// + /// This property only works when the listview is in Details view and not showing groups. + /// + /// + /// The reason that it does not work when showing groups is that, when groups are enabled, + /// the Windows msg LVM_GETTOPINDEX always returns 0, regardless of the + /// scroll position. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual int TopItemIndex { + get { + if (this.View == View.Details && this.IsHandleCreated) + return NativeMethods.GetTopIndex(this); + + return -1; + } + set { + int newTopIndex = Math.Min(value, this.GetItemCount() - 1); + if (this.View != View.Details || newTopIndex < 0) + return; + + try { + this.TopItem = this.Items[newTopIndex]; + + // Setting the TopItem sometimes gives off by one errors, + // that (bizarrely) are correct on a second attempt + if (this.TopItem != null && this.TopItem.Index != newTopIndex) + this.TopItem = this.GetItem(newTopIndex); + } + catch (NullReferenceException) { + // There is a bug in the .NET code where setting the TopItem + // will sometimes throw null reference exceptions + // There is nothing we can do to get around it. + } + } + } + + /// + /// Gets or sets whether moving the mouse over the header will trigger CellOver events. + /// Defaults to true. + /// + /// + /// Moving the mouse over the header did not previously trigger CellOver events, since the + /// header is considered a separate control. + /// If this change in behaviour causes your application problems, set this to false. + /// If you are interested in knowing when the mouse moves over the header, set this property to true (the default). + /// + [Category("ObjectListView"), + Description("Should moving the mouse over the header trigger CellOver events?"), + DefaultValue(true)] + public bool TriggerCellOverEventsWhenOverHeader + { + get { return triggerCellOverEventsWhenOverHeader; } + set { triggerCellOverEventsWhenOverHeader = value; } + } + private bool triggerCellOverEventsWhenOverHeader = true; + + /// + /// When resizing a column by dragging its divider, should any space filling columns be + /// resized at each mouse move? If this is false, the filling columns will be + /// updated when the mouse is released. + /// + /// + /// + /// If you have a space filling column + /// is in the left of the column that is being resized, this will look odd: + /// the right edge of the column will be dragged, but + /// its left edge will move since the space filling column is shrinking. + /// + /// This is logical behaviour -- it just looks wrong. + /// + /// + /// Given the above behavior is probably best to turn this property off if your space filling + /// columns aren't the right-most columns. + /// + [Category("ObjectListView"), + Description("When resizing a column by dragging its divider, should any space filling columns be resized at each mouse move?"), + DefaultValue(true)] + public virtual bool UpdateSpaceFillingColumnsWhenDraggingColumnDivider { + get { return updateSpaceFillingColumnsWhenDraggingColumnDivider; } + set { updateSpaceFillingColumnsWhenDraggingColumnDivider = value; } + } + private bool updateSpaceFillingColumnsWhenDraggingColumnDivider = true; + + /// + /// What color should be used for the background of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The background color of selected rows when the control doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedBackColor { + get { return this.unfocusedSelectedBackColor; } + set { this.unfocusedSelectedBackColor = value; } + } + private Color unfocusedSelectedBackColor = Color.Empty; + + /// + /// Return the color should be used for the background of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedBackColorOrDefault { + get { + return this.UnfocusedSelectedBackColor.IsEmpty ? SystemColors.Control : this.UnfocusedSelectedBackColor; + } + } + + /// + /// What color should be used for the foreground of selected rows when the control doesn't have the focus? + /// + [Category("ObjectListView"), + Description("The foreground color of selected rows when the control is owner drawn and doesn't have the focus"), + DefaultValue(typeof(Color), "")] + public virtual Color UnfocusedSelectedForeColor { + get { return this.unfocusedSelectedForeColor; } + set { this.unfocusedSelectedForeColor = value; } + } + private Color unfocusedSelectedForeColor = Color.Empty; + + /// + /// Return the color should be used for the foreground of selected rows when the control doesn't have the focus or a reasonable default + /// + [Browsable(false)] + public virtual Color UnfocusedSelectedForeColorOrDefault { + get { + return this.UnfocusedSelectedForeColor.IsEmpty ? SystemColors.ControlText : this.UnfocusedSelectedForeColor; + } + } + + /// + /// Gets or sets whether the list give a different background color to every second row? Defaults to false. + /// + /// The color of the alternate rows is given by AlternateRowBackColor. + /// There is a "feature" in .NET for listviews in non-full-row-select mode, where + /// selected rows are not drawn with their correct background color. + [Category("ObjectListView"), + Description("Should the list view use a different backcolor to alternate rows?"), + DefaultValue(false)] + public virtual bool UseAlternatingBackColors { + get { return useAlternatingBackColors; } + set { useAlternatingBackColors = value; } + } + private bool useAlternatingBackColors; + + /// + /// Should FormatCell events be called for each cell in the control? + /// + /// + /// In many situations, no cell level formatting is performed. ObjectListView + /// can run somewhat faster if it does not trigger a format cell event for every cell + /// unless it is required. So, by default, it does not raise an event for each cell. + /// + /// ObjectListView *does* raise a FormatRow event every time a row is rebuilt. + /// Individual rows can decide whether to raise FormatCell + /// events for every cell in row. + /// + /// + /// Regardless of this setting, FormatCell events are only raised when the ObjectListView + /// is in Details view. + /// + [Category("ObjectListView"), + Description("Should FormatCell events be triggered to every cell that is built?"), + DefaultValue(false)] + public bool UseCellFormatEvents { + get { return useCellFormatEvents; } + set { useCellFormatEvents = value; } + } + private bool useCellFormatEvents; + + /// + /// Should the selected row be drawn with non-standard foreground and background colors? + /// + /// v2.9 This property is no longer required + [Category("ObjectListView"), + Description("Should the selected row be drawn with non-standard foreground and background colors?"), + DefaultValue(false)] + public bool UseCustomSelectionColors { + get { return false; } + // ReSharper disable once ValueParameterNotUsed + set { } + } + + /// + /// Gets or sets whether this ObjectListView will use the same hot item and selection + /// mechanism that Vista Explorer does. + /// + /// + /// + /// This property has many imperfections: + /// + /// This only works on Vista and later + /// It does not work well with AlternateRowBackColors. + /// It does not play well with HotItemStyles. + /// It looks a little bit silly is FullRowSelect is false. + /// It doesn't work at all when the list is owner drawn (since the renderers + /// do all the drawing). As such, it won't work with TreeListView's since they *have to be* + /// owner drawn. You can still set it, but it's just not going to be happy. + /// + /// But if you absolutely have to look like Vista/Win7, this is your property. + /// Do not complain if settings this messes up other things. + /// + /// + /// When this property is set to true, the ObjectListView will be not owner drawn. This will + /// disable many of the pretty drawing-based features of ObjectListView. + /// + /// Because of the above, this property should never be set to true for TreeListViews, + /// since they *require* owner drawing to be rendered correctly. + /// + [Category("ObjectListView"), + Description("Should the list use the same hot item and selection mechanism as Vista?"), + DefaultValue(false)] + public bool UseExplorerTheme { + get { return useExplorerTheme; } + set { + useExplorerTheme = value; + if (this.Created) + NativeMethods.SetWindowTheme(this.Handle, value ? "explorer" : "", null); + + this.OwnerDraw = !value; + } + } + private bool useExplorerTheme; + + /// + /// Gets or sets whether the list should enable filtering + /// + [Category("ObjectListView"), + Description("Should the list enable filtering?"), + DefaultValue(false)] + public virtual bool UseFiltering { + get { return useFiltering; } + set { + if (useFiltering == value) + return; + useFiltering = value; + this.UpdateFiltering(); + } + } + private bool useFiltering; + + /// + /// Gets or sets whether the list should put an indicator into a column's header to show that + /// it is filtering on that column + /// + /// If you set this to true, HeaderUsesThemes is automatically set to false, since + /// we can only draw a filter indicator when not using a themed header. + [Category("ObjectListView"), + Description("Should an image be drawn in a column's header when that column is being used for filtering?"), + DefaultValue(false)] + public virtual bool UseFilterIndicator { + get { return useFilterIndicator; } + set { + if (this.useFilterIndicator == value) + return; + useFilterIndicator = value; + if (this.useFilterIndicator) + this.HeaderUsesThemes = false; + this.Invalidate(); + } + } + private bool useFilterIndicator; + + /// + /// Should controls (checkboxes or buttons) that are under the mouse be drawn "hot"? + /// + /// + /// If this is false, control will not be drawn differently when the mouse is over them. + /// + /// If this is false AND UseHotItem is false AND UseHyperlinks is false, then the ObjectListView + /// can skip some processing on mouse move. This make mouse move processing use almost no CPU. + /// + /// + [Category("ObjectListView"), + Description("Should controls (checkboxes or buttons) that are under the mouse be drawn hot?"), + DefaultValue(true)] + public bool UseHotControls { + get { return this.useHotControls; } + set { this.useHotControls = value; } + } + private bool useHotControls = true; + + /// + /// Should the item under the cursor be formatted in a special way? + /// + [Category("ObjectListView"), + Description("Should HotTracking be used? Hot tracking applies special formatting to the row under the cursor"), + DefaultValue(false)] + public bool UseHotItem { + get { return this.useHotItem; } + set { + this.useHotItem = value; + if (value) + this.AddOverlay(this.HotItemStyleOrDefault.Overlay); + else + this.RemoveOverlay(this.HotItemStyleOrDefault.Overlay); + } + } + private bool useHotItem; + + /// + /// Gets or sets whether this listview should show hyperlinks in the cells. + /// + [Category("ObjectListView"), + Description("Should hyperlinks be shown on this control?"), + DefaultValue(false)] + public bool UseHyperlinks { + get { return this.useHyperlinks; } + set { + this.useHyperlinks = value; + if (value && this.HyperlinkStyle == null) + this.HyperlinkStyle = new HyperlinkStyle(); + } + } + private bool useHyperlinks; + + /// + /// Should this control show overlays + /// + /// Overlays are enabled by default and would only need to be disabled + /// if they were causing problems in your development environment. + [Category("ObjectListView"), + Description("Should this control show overlays"), + DefaultValue(true)] + public bool UseOverlays { + get { return this.useOverlays; } + set { this.useOverlays = value; } + } + private bool useOverlays = true; + + /// + /// Should this control be configured to show check boxes on subitems? + /// + /// If this is set to True, the control will be given a SmallImageList if it + /// doesn't already have one. Also, if it is a virtual list, it will be set to owner + /// drawn, since virtual lists can't draw check boxes without being owner drawn. + [Category("ObjectListView"), + Description("Should this control be configured to show check boxes on subitems."), + DefaultValue(false)] + public bool UseSubItemCheckBoxes { + get { return this.useSubItemCheckBoxes; } + set { + this.useSubItemCheckBoxes = value; + if (value) + this.SetupSubItemCheckBoxes(); + } + } + private bool useSubItemCheckBoxes; + + /// + /// Gets or sets if the ObjectListView will use a translucent selection mechanism like Vista. + /// + /// + /// + /// Unlike UseExplorerTheme, this Vista-like scheme works on XP and for both + /// owner and non-owner drawn lists. + /// + /// + /// This will replace any SelectedRowDecoration that has been installed. + /// + /// + /// If you don't like the colours used for the selection, ignore this property and + /// just create your own RowBorderDecoration and assigned it to SelectedRowDecoration, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent selection mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentSelection { + get { return useTranslucentSelection; } + set { + useTranslucentSelection = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.FillBrush = new SolidBrush(Color.FromArgb(48, 163, 217, 225)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + this.SelectedRowDecoration = rbd; + } else + this.SelectedRowDecoration = null; + } + } + private bool useTranslucentSelection; + + /// + /// Gets or sets if the ObjectListView will use a translucent hot row highlighting mechanism like Vista. + /// + /// + /// + /// Setting this will replace any HotItemStyle that has been installed. + /// + /// + /// If you don't like the colours used for the hot item, ignore this property and + /// just create your own HotItemStyle, fill in the values you want, and assigned it to HotItemStyle property, + /// just like this property setter does. + /// + /// + [Category("ObjectListView"), + Description("Should the list use a translucent hot row highlighting mechanism (like Vista)"), + DefaultValue(false)] + public bool UseTranslucentHotItem { + get { return useTranslucentHotItem; } + set { + useTranslucentHotItem = value; + if (value) { + RowBorderDecoration rbd = new RowBorderDecoration(); + rbd.BorderPen = new Pen(Color.FromArgb(154, 223, 251)); + rbd.BoundsPadding = new Size(0, 0); + rbd.CornerRounding = 6.0f; + rbd.FillGradientFrom = Color.FromArgb(0, 255, 255, 255); + rbd.FillGradientTo = Color.FromArgb(64, 183, 237, 240); + HotItemStyle his = new HotItemStyle(); + his.Decoration = rbd; + this.HotItemStyle = his; + } else + this.HotItemStyle = null; + this.UseHotItem = value; + } + } + private bool useTranslucentHotItem; + + /// + /// Get/set the style of view that this listview is using + /// + /// Switching to tile or details view installs the columns appropriate to that view. + /// Confusingly, in tile view, every column is shown as a row of information. + [Category("Appearance"), + Description("Select the layout of the items within this control)"), + DefaultValue(null)] + public new View View + { + get { return base.View; } + set { + if (base.View == value) + return; + + if (this.Frozen) { + base.View = value; + this.SetupBaseImageList(); + } else { + this.Freeze(); + + if (value == View.Tile) + this.CalculateReasonableTileSize(); + + base.View = value; + this.SetupBaseImageList(); + this.Unfreeze(); + } + } + } + + #endregion + + #region Callbacks + + /// + /// This delegate fetches the checkedness of an object as a boolean only. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStateGetter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.CheckStateGetter = null; + else + this.CheckStateGetter = delegate(Object x) { + return value(x) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// This delegate sets the checkedness of an object as a boolean only. It must return + /// true or false indicating if the object was checked or not. + /// + /// Use this if you never want to worry about the + /// Indeterminate state (which is fairly common). + /// + /// This is a convenience wrapper around the CheckStatePutter property. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual BooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.CheckStatePutter = null; + else + this.CheckStatePutter = delegate(Object x, CheckState state) { + bool isChecked = (state == CheckState.Checked); + return value(x, isChecked) ? CheckState.Checked : CheckState.Unchecked; + }; + } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public virtual bool CanShowGroups { + get { + return true; + } + } + + /// + /// Gets or sets whether ObjectListView can rely on Application.Idle events + /// being raised. + /// + /// In some host environments (e.g. when running as an extension within + /// VisualStudio and possibly Office), Application.Idle events are never raised. + /// Set this to false when Idle events will not be raised, and ObjectListView will + /// raise those events itself. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool CanUseApplicationIdle { + get { return this.canUseApplicationIdle; } + set { this.canUseApplicationIdle = value; } + } + private bool canUseApplicationIdle = true; + + /// + /// This delegate fetches the renderer for a particular cell. + /// + /// + /// + /// If this returns null (or is not installed), the renderer for the column will be used. + /// If the column renderer is null, then will be used. + /// + /// + /// This is called every time any cell is drawn. It must be efficient! + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellRendererGetterDelegate CellRendererGetter + { + get { return this.cellRendererGetter; } + set { this.cellRendererGetter = value; } + } + private CellRendererGetterDelegate cellRendererGetter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular cell. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to show the full text of truncated cell values). + /// + /// + /// Displaying the full text of truncated cell values only work for FullRowSelect listviews. + /// This is MS's behavior, not mine. Don't complain to me :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CellToolTipGetterDelegate CellToolTipGetter { + get { return cellToolTipGetter; } + set { cellToolTipGetter = value; } + } + private CellToolTipGetterDelegate cellToolTipGetter; + + /// + /// The name of the property (or field) that holds whether or not a model is checked. + /// + /// + /// The property be modifiable. It must have a return type of bool (or of bool? if + /// TriStateCheckBoxes is true). + /// Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed. + /// Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence + /// over the behavior of this property. + /// + [Category("ObjectListView"), + Description("The name of the property or field that holds the 'checkedness' of the model"), + DefaultValue(null)] + public virtual string CheckedAspectName { + get { return checkedAspectName; } + set { + checkedAspectName = value; + if (String.IsNullOrEmpty(checkedAspectName)) { + this.checkedAspectMunger = null; + this.CheckStateGetter = null; + this.CheckStatePutter = null; + } else { + this.checkedAspectMunger = new Munger(checkedAspectName); + this.CheckStateGetter = delegate(Object modelObject) { + bool? result = this.checkedAspectMunger.GetValue(modelObject) as bool?; + if (result.HasValue) + return result.Value ? CheckState.Checked : CheckState.Unchecked; + return this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + }; + this.CheckStatePutter = delegate(Object modelObject, CheckState newValue) { + if (this.TriStateCheckBoxes && newValue == CheckState.Indeterminate) + this.checkedAspectMunger.PutValue(modelObject, null); + else + this.checkedAspectMunger.PutValue(modelObject, newValue == CheckState.Checked); + return this.CheckStateGetter(modelObject); + }; + } + } + } + private string checkedAspectName; + private Munger checkedAspectMunger; + + /// + /// This delegate will be called whenever the ObjectListView needs to know the check state + /// of the row associated with a given model object. + /// + /// + /// .NET has no support for indeterminate values, but as of v2.0, this class allows + /// indeterminate values. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { checkStateGetter = value; } + } + private CheckStateGetterDelegate checkStateGetter; + + /// + /// This delegate will be called whenever the user tries to change the check state of a row. + /// The delegate should return the state that was actually set, which may be different + /// to the state given. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { checkStatePutter = value; } + } + private CheckStatePutterDelegate checkStatePutter; + + /// + /// This delegate can be used to sort the table in a custom fashion. + /// + /// + /// + /// The delegate must install a ListViewItemSorter on the ObjectListView. + /// Installing the ItemSorter does the actual work of sorting the ListViewItems. + /// See ColumnComparer in the code for an example of what an ItemSorter has to do. + /// + /// + /// Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects() + /// method of the IVirtualListDataSource instead. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual SortDelegate CustomSorter { + get { return customSorter; } + set { customSorter = value; } + } + private SortDelegate customSorter; + + /// + /// This delegate is called when the list wants to show a tooltip for a particular header. + /// The delegate should return the text to display, or null to use the default behavior + /// (which is to not show any tooltip). + /// + /// + /// Installing a HeaderToolTipGetter takes precedence over any text in OLVColumn.ToolTipText. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return headerToolTipGetter; } + set { headerToolTipGetter = value; } + } + private HeaderToolTipGetterDelegate headerToolTipGetter; + + /// + /// This delegate can be used to format a OLVListItem before it is added to the control. + /// + /// + /// The model object for the row can be found through the RowObject property of the OLVListItem object. + /// All subitems normally have the same style as list item, so setting the forecolor on one + /// subitem changes the forecolor of all subitems. + /// To allow subitems to have different attributes, do this: + /// myListViewItem.UseItemStyleForSubItems = false;. + /// + /// If UseAlternatingBackColors is true, the backcolor of the listitem will be calculated + /// by the control and cannot be controlled by the RowFormatter delegate. + /// In general, trying to use a RowFormatter + /// when UseAlternatingBackColors is true does not work well. + /// As it says in the summary, this is called before the item is added to the control. + /// Many properties of the OLVListItem itself are not available at that point, including: + /// Index, Selected, Focused, Bounds, Checked, DisplayIndex. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowFormatterDelegate RowFormatter { + get { return rowFormatter; } + set { rowFormatter = value; } + } + private RowFormatterDelegate rowFormatter; + + #endregion + + #region List commands + + /// + /// Add the given model object to this control. + /// + /// The model object to be displayed + /// See AddObjects() for more details + public virtual void AddObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.AddObject(modelObject); }); + else + this.AddObjects(new object[] { modelObject }); + } + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public virtual void AddObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.AddObjects(modelObjects); }); + return; + } + this.InsertObjects(ObjectListView.EnumerableCount(this.Objects), modelObjects); + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Resize the columns to the maximum of the header width and the data. + /// + public virtual void AutoResizeColumns() { + foreach (OLVColumn c in this.Columns) { + this.AutoResizeColumn(c.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + } + } + + /// + /// Set up any automatically initialized column widths (columns that + /// have a width of 0 or -1 will be resized to the width of their + /// contents or header respectively). + /// + /// + /// Obviously, this will only work once. Once it runs, the columns widths will + /// be changed to something else (other than 0 or -1), so it wont do anything the + /// second time through. Use to force all columns + /// to change their size. + /// + public virtual void AutoSizeColumns() { + // If we are supposed to resize to content, but if there is no content, + // resize to the header size instead. + ColumnHeaderAutoResizeStyle resizeToContentStyle = this.GetItemCount() == 0 ? + ColumnHeaderAutoResizeStyle.HeaderSize : + ColumnHeaderAutoResizeStyle.ColumnContent; + foreach (ColumnHeader column in this.Columns) { + switch (column.Width) { + case 0: + this.AutoResizeColumn(column.Index, resizeToContentStyle); + break; + case -1: + this.AutoResizeColumn(column.Index, ColumnHeaderAutoResizeStyle.HeaderSize); + break; + } + } + } + + /// + /// Organise the view items into groups, based on the last sort column or the first column + /// if there is no last sort column + /// + public virtual void BuildGroups() { + this.BuildGroups(this.PrimarySortColumn, this.PrimarySortOrder == SortOrder.None ? SortOrder.Ascending : this.PrimarySortOrder); + } + + /// + /// Organise the view items into groups, based on the given column + /// + /// + /// + /// If the AlwaysGroupByColumn property is not null, + /// the list view items will be organised by that column, + /// and the 'column' parameter will be ignored. + /// + /// This method triggers sorting events: BeforeSorting and AfterSorting. + /// + /// The column whose values should be used for sorting. + /// + public virtual void BuildGroups(OLVColumn column, SortOrder order) { + // Sanity + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(column, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, + args.ColumnToSort, args.SortOrder, args.SecondaryColumnToSort, args.SecondarySortOrder); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + private BeforeSortingEventArgs BuildBeforeSortingEventArgs(OLVColumn column, SortOrder order) { + OLVColumn groupBy = this.AlwaysGroupByColumn ?? column ?? this.GetColumn(0); + SortOrder groupByOrder = this.AlwaysGroupBySortOrder; + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + if (groupByOrder == SortOrder.None) + groupByOrder = order; + + BeforeSortingEventArgs args = new BeforeSortingEventArgs( + groupBy, groupByOrder, + column, order, + this.SecondarySortColumn ?? this.GetColumn(0), + this.SecondarySortOrder == SortOrder.None ? order : this.SecondarySortOrder); + if (column != null) + args.Canceled = !column.Sortable; + return args; + } + + /// + /// Organise the view items into groups, based on the given columns + /// + /// What column will be used for grouping + /// What ordering will be used for groups + /// The column whose values should be used for sorting. Cannot be null + /// The order in which the values from column will be sorted + /// When the values from 'column' are equal, use the values provided by this column + /// How will the secondary values be sorted + /// This method does not trigger sorting events. Use BuildGroups() to do that + public virtual void BuildGroups(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn column, SortOrder order, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + // Sanity checks + if (groupByColumn == null) + return; + + // Getting the Count forces any internal cache of the ListView to be flushed. Without + // this, iterating over the Items will not work correctly if the ListView handle + // has not yet been created. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int dummy = this.Items.Count; +#pragma warning restore 168 + + // Collect all the information that governs the creation of groups + GroupingParameters parms = this.CollectGroupingParameters(groupByColumn, groupByOrder, + column, order, secondaryColumn, secondaryOrder); + + // Trigger an event to let the world create groups if they want + CreateGroupsEventArgs args = new CreateGroupsEventArgs(parms); + if (parms.GroupByColumn != null) + args.Canceled = !parms.GroupByColumn.Groupable; + this.OnBeforeCreatingGroups(args); + if (args.Canceled) + return; + + // If the event didn't create them for us, use our default strategy + if (args.Groups == null) + args.Groups = this.MakeGroups(parms); + + // Give the world a chance to munge the groups before they are created + this.OnAboutToCreateGroups(args); + if (args.Canceled) + return; + + // Create the groups now + this.OLVGroups = args.Groups; + this.CreateGroups(args.Groups); + + // Tell the world that new groups have been created + this.OnAfterCreatingGroups(args); + lastGroupingParameters = args.Parameters; + } + private GroupingParameters lastGroupingParameters; + + /// + /// Collect and return all the variables that influence the creation of groups + /// + /// + protected virtual GroupingParameters CollectGroupingParameters(OLVColumn groupByColumn, SortOrder groupByOrder, + OLVColumn sortByColumn, SortOrder sortByOrder, OLVColumn secondaryColumn, SortOrder secondaryOrder) { + + // If the user tries to group by a non-groupable column, keep the current group by + // settings, but use the non-groupable column for sorting + if (!groupByColumn.Groupable && lastGroupingParameters != null) { + sortByColumn = groupByColumn; + sortByOrder = groupByOrder; + groupByColumn = lastGroupingParameters.GroupByColumn; + groupByOrder = lastGroupingParameters.GroupByOrder; + } + + string titleFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountFormatOrDefault : null; + string titleSingularFormat = this.ShowItemCountOnGroups ? groupByColumn.GroupWithItemCountSingularFormatOrDefault : null; + GroupingParameters parms = new GroupingParameters(this, groupByColumn, groupByOrder, + sortByColumn, sortByOrder, secondaryColumn, secondaryOrder, + titleFormat, titleSingularFormat, + this.SortGroupItemsByPrimaryColumn && this.AlwaysGroupByColumn == null); + return parms; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// The list of groups to be created + /// This should not change the state of the control. It is possible that the + /// groups created will not be used. They may simply be discarded. + protected virtual IList MakeGroups(GroupingParameters parms) { + + // There is a lot of overlap between this method and FastListGroupingStrategy.MakeGroups() + // Any changes made here may need to be reflected there + + // Separate the list view items into groups, using the group key as the descrimanent + NullableDictionary> map = new NullableDictionary>(); + foreach (OLVListItem olvi in parms.ListView.Items) { + object key = parms.GroupByColumn.GetGroupKey(olvi.RowObject); + if (!map.ContainsKey(key)) + map[key] = new List(); + map[key].Add(olvi); + } + + // Sort the items within each group (unless specifically turned off) + OLVColumn sortColumn = parms.SortItemsByPrimaryColumn ? parms.ListView.GetColumn(0) : parms.PrimarySort; + if (sortColumn != null && parms.PrimarySortOrder != SortOrder.None) { + IComparer itemSorter = parms.ItemComparer ?? + new ColumnComparer(sortColumn, parms.PrimarySortOrder, parms.SecondarySort, parms.SecondarySortOrder); + foreach (object key in map.Keys) { + map[key].Sort(itemSorter); + } + } + + // Make a list of the required groups + List groups = new List(); + foreach (object key in map.Keys) { + OLVGroup lvg = parms.CreateGroup(key, map[key].Count, HasCollapsibleGroups); + lvg.Items = map[key]; + if (parms.GroupByColumn.GroupFormatter != null) + parms.GroupByColumn.GroupFormatter(lvg, parms); + groups.Add(lvg); + } + + // Sort the groups + if (parms.GroupByOrder != SortOrder.None) + groups.Sort(parms.GroupComparer ?? new OLVGroupComparer(parms.GroupByOrder)); + + return groups; + } + + /// + /// Build/rebuild all the list view items in the list, preserving as much state as is possible + /// + public virtual void BuildList() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.BuildList)); + else + this.BuildList(true); + } + + /// + /// Build/rebuild all the list view items in the list + /// + /// If this is true, the control will try to preserve the selection, + /// focused item, and the scroll position (see Remarks) + /// + /// + /// + /// Use this method in situations were the contents of the list is basically the same + /// as previously. + /// + /// + public virtual void BuildList(bool shouldPreserveState) { + if (this.Frozen) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + this.ApplyExtendedStyles(); + this.ClearHotItem(); + int previousTopIndex = this.TopItemIndex; + Point currentScrollPosition = this.LowLevelScrollPosition; + + IList previousSelection = new ArrayList(); + Object previousFocus = null; + if (shouldPreserveState && this.objects != null) { + previousSelection = this.SelectedObjects; + OLVListItem focusedItem = this.FocusedItem as OLVListItem; + if (focusedItem != null) + previousFocus = focusedItem.RowObject; + } + + IEnumerable objectsToDisplay = this.FilteredObjects; + + this.BeginUpdate(); + try { + this.Items.Clear(); + this.ListViewItemSorter = null; + + if (objectsToDisplay != null) { + // Build a list of all our items and then display them. (Building + // a list and then doing one AddRange is about 10-15% faster than individual adds) + List itemList = new List(); // use ListViewItem to avoid co-variant conversion + foreach (object rowObject in objectsToDisplay) { + OLVListItem lvi = new OLVListItem(rowObject); + this.FillInValues(lvi, rowObject); + itemList.Add(lvi); + } + this.Items.AddRange(itemList.ToArray()); + this.Sort(); + + if (shouldPreserveState) { + this.SelectedObjects = previousSelection; + this.FocusedItem = this.ModelToItem(previousFocus); + } + } + } finally { + this.EndUpdate(); + } + + this.RefreshHotItem(); + + // We can only restore the scroll position after the EndUpdate() because + // of caching that the ListView does internally during a BeginUpdate/EndUpdate pair. + if (shouldPreserveState) { + // Restore the scroll position. TopItemIndex is best, but doesn't work + // when the control is grouped. + if (this.ShowGroups) + this.LowLevelScroll(currentScrollPosition.X, currentScrollPosition.Y); + else + this.TopItemIndex = previousTopIndex; + } + + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Building list for {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + /// + /// Clear any cached info this list may have been using + /// + public virtual void ClearCachedInfo() + { + // ObjectListView doesn't currently cache information but subclass do (or might) + } + + /// + /// Apply all required extended styles to our control. + /// + /// + /// + /// Whenever .NET code sets an extended style, it erases all other extended styles + /// that it doesn't use. So, we have to explicit reapply the styles that we have + /// added. + /// + /// + /// Normally, we would override CreateParms property and update + /// the ExStyle member, but ListView seems to ignore all ExStyles that + /// it doesn't already know about. Worse, when we set the LVS_EX_HEADERINALLVIEWS + /// value, bad things happen (the control crashes!). + /// + /// + protected virtual void ApplyExtendedStyles() { + const int LVS_EX_SUBITEMIMAGES = 0x00000002; + //const int LVS_EX_TRANSPARENTBKGND = 0x00400000; + const int LVS_EX_HEADERINALLVIEWS = 0x02000000; + + const int STYLE_MASK = LVS_EX_SUBITEMIMAGES | LVS_EX_HEADERINALLVIEWS; + int style = 0; + + if (this.ShowImagesOnSubItems && !this.VirtualMode) + style ^= LVS_EX_SUBITEMIMAGES; + + if (this.ShowHeaderInAllViews) + style ^= LVS_EX_HEADERINALLVIEWS; + + NativeMethods.SetExtendedStyle(this, style, STYLE_MASK); + } + + /// + /// Give the listview a reasonable size of its tiles, based on the number of lines of + /// information that each tile is going to display. + /// + public virtual void CalculateReasonableTileSize() { + if (this.Columns.Count <= 0) + return; + + List columns = this.AllColumns.FindAll(delegate(OLVColumn x) { + return (x.Index == 0) || x.IsTileViewColumn; + }); + + int imageHeight = (this.LargeImageList == null ? 16 : this.LargeImageList.ImageSize.Height); + int dataHeight = (this.Font.Height + 1) * columns.Count; + int tileWidth = (this.TileSize.Width == 0 ? 200 : this.TileSize.Width); + int tileHeight = Math.Max(this.TileSize.Height, Math.Max(imageHeight, dataHeight)); + this.TileSize = new Size(tileWidth, tileHeight); + } + + /// + /// Rebuild this list for the given view + /// + /// + public virtual void ChangeToFilteredColumns(View view) { + // Store the state + this.SuspendSelectionEvents(); + IList previousSelection = this.SelectedObjects; + int previousTopIndex = this.TopItemIndex; + + this.Freeze(); + this.Clear(); + List columns = this.GetFilteredColumns(view); + if (view == View.Details || this.ShowHeaderInAllViews) { + // Make sure all columns have a reasonable LastDisplayIndex + for (int index = 0; index < columns.Count; index++) + { + if (columns[index].LastDisplayIndex == -1) + columns[index].LastDisplayIndex = index; + } + // ListView will ignore DisplayIndex FOR ALL COLUMNS if there are any errors, + // e.g. duplicates (two columns with the same DisplayIndex) or gaps. + // LastDisplayIndex isn't guaranteed to be unique, so we just sort the columns by + // the last position they were displayed and use that to generate a sequence + // we can use for the DisplayIndex values. + List columnsInDisplayOrder = new List(columns); + columnsInDisplayOrder.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + int i = 0; + foreach (OLVColumn col in columnsInDisplayOrder) + col.DisplayIndex = i++; + } + +// ReSharper disable once CoVariantArrayConversion + this.Columns.AddRange(columns.ToArray()); + if (view == View.Details || this.ShowHeaderInAllViews) + this.ShowSortIndicator(); + this.UpdateFiltering(); + this.Unfreeze(); + + // Restore the state + this.SelectedObjects = previousSelection; + this.TopItemIndex = previousTopIndex; + this.ResumeSelectionEvents(); + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public virtual void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else + this.SetObjects(null); + } + + /// + /// Reset the memory of which URLs have been visited + /// + public virtual void ClearUrlVisited() { + this.visitedUrlMap = new Dictionary(); + } + + /// + /// Copy a text and html representation of the selected rows onto the clipboard. + /// + /// Be careful when using this with virtual lists. If the user has selected + /// 10,000,000 rows, this method will faithfully try to copy all of them to the clipboard. + /// From the user's point of view, your program will appear to have hung. + public virtual void CopySelectionToClipboard() { + IList selection = this.SelectedObjects; + if (selection.Count == 0) + return; + + // Use the DragSource object to create the data object, if so configured. + // This relies on the assumption that DragSource will handle the selected objects only. + // It is legal for StartDrag to return null. + object data = null; + if (this.CopySelectionOnControlCUsesDragSource && this.DragSource != null) + data = this.DragSource.StartDrag(this, MouseButtons.Left, this.ModelToItem(selection[0])); + + Clipboard.SetDataObject(data ?? new OLVDataObject(this, selection)); + } + + /// + /// Copy a text and html representation of the given objects onto the clipboard. + /// + public virtual void CopyObjectsToClipboard(IList objectsToCopy) { + if (objectsToCopy.Count == 0) + return; + + // We don't know where these objects came from, so we can't use the DragSource to create + // the data object, like we do with CopySelectionToClipboard() above. + OLVDataObject dataObject = new OLVDataObject(this, objectsToCopy); + dataObject.CreateTextFormats(); + Clipboard.SetDataObject(dataObject); + } + + /// + /// Return a html representation of the given objects + /// + public virtual string ObjectsToHtml(IList objectsToConvert) { + if (objectsToConvert.Count == 0) + return String.Empty; + + OLVExporter exporter = new OLVExporter(this, objectsToConvert); + return exporter.ExportTo(OLVExporter.ExportFormat.HTML); + } + + /// + /// Deselect all rows in the listview + /// + public virtual void DeselectAll() { + NativeMethods.DeselectAllItems(this); + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A ListViewItem + public virtual OLVListItem GetNextItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + bool isFound = (itemToFind == null); + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + if (isFound) + return olvi; + isFound = (itemToFind == olvi); + } + } + return null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(0); + if (itemToFind.Index == this.GetItemCount() - 1) + return null; + return this.GetItem(itemToFind.Index + 1); + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public virtual OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return this.GetItem(this.GetItemCount() - 1); + + if (this.Groups.Count > 0) { + ListViewGroup lastGroup = this.Groups[this.Groups.Count - 1]; + if (lastGroup.Items.Count > 0) + return (OLVListItem)lastGroup.Items[lastGroup.Items.Count - 1]; + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.Groups.Count == 0) + return this.GetItem(n); + + foreach (ListViewGroup group in this.Groups) { + if (n < group.Items.Count) + return (OLVListItem)group.Items[n]; + + n -= group.Items.Count; + } + + return null; + } + + /// + /// Return the display index of the given listviewitem index. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public virtual int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups || this.Groups.Count == 0) + return itemIndex; + + // TODO: This could be optimized + int i = 0; + foreach (ListViewGroup lvg in this.Groups) { + foreach (ListViewItem lvi in lvg.Items) { + if (lvi.Index == itemIndex) + return i; + i++; + } + } + + return -1; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public virtual OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (this.ShowGroups) { + OLVListItem previousItem = null; + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem lvi in group.Items) { + if (lvi == itemToFind) + return previousItem; + + previousItem = lvi; + } + } + return itemToFind == null ? previousItem : null; + } + if (this.GetItemCount() == 0) + return null; + if (itemToFind == null) + return this.GetItem(this.GetItemCount() - 1); + if (itemToFind.Index == 0) + return null; + return this.GetItem(itemToFind.Index - 1); + } + + /// + /// Insert the given collection of objects before the given position + /// + /// Where to insert the objects + /// The objects to be inserted + /// + /// + /// This operation only makes sense of non-sorted, non-grouped + /// lists, since any subsequent sort/group operation will rearrange + /// the list. + /// + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void InsertObjects(int index, ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { + this.InsertObjects(index, modelObjects); + }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToAdd; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + // If we are filtering the list, there is no way to efficiently + // insert the objects, so just put them into our collection and rebuild. + // Sigh -- yet another ListView anomoly. In every view except Details, an item + // inserted into the Items collection always appear at the end regardless of + // their actual insertion index. + if (this.IsFiltering || this.View != View.Details) { + index = Math.Max(0, Math.Min(index, ourObjects.Count)); + ourObjects.InsertRange(index, modelObjects); + this.BuildList(true); + } else { + this.ListViewItemSorter = null; + index = Math.Max(0, Math.Min(index, this.GetItemCount())); + int i = index; + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + ourObjects.Insert(i, modelObject); + OLVListItem lvi = new OLVListItem(modelObject); + this.FillInValues(lvi, modelObject); + this.Items.Insert(i, lvi); + i++; + } + } + + for (i = index; i < this.GetItemCount(); i++) { + OLVListItem lvi = this.GetItem(i); + this.SetSubItemImages(lvi.Index, lvi); + } + + this.PostProcessRows(); + } + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Return true if the row representing the given model is selected + /// + /// The model object to look for + /// Is the row selected + public bool IsSelected(object model) { + OLVListItem item = this.ModelToItem(model); + return item != null && item.Selected; + } + + /// + /// Has the given URL been visited? + /// + /// The string to be consider + /// Has it been visited + public virtual bool IsUrlVisited(string url) { + return this.visitedUrlMap.ContainsKey(url); + } + + /// + /// Scroll the ListView by the given deltas. + /// + /// Horizontal delta + /// Vertical delta + public void LowLevelScroll(int dx, int dy) { + NativeMethods.Scroll(this, dx, dy); + } + + /// + /// Return a point that represents the current horizontal and vertical scroll positions + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Point LowLevelScrollPosition + { + get { + return new Point(NativeMethods.GetScrollPosition(this, true), NativeMethods.GetScrollPosition(this, false)); + } + } + + /// + /// Remember that the given URL has been visited + /// + /// The url to be remembered + /// This does not cause the control be redrawn + public virtual void MarkUrlVisited(string url) { + this.visitedUrlMap[url] = true; + } + + /// + /// Move the given collection of objects to the given index. + /// + /// This operation only makes sense on non-grouped ObjectListViews. + /// + /// + public virtual void MoveObjects(int index, ICollection modelObjects) { + + // We are going to remove all the given objects from our list + // and then insert them at the given location + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + + List indicesToRemove = new List(); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = this.IndexOf(modelObject); + if (i >= 0) { + indicesToRemove.Add(i); + ourObjects.Remove(modelObject); + if (i <= index) + index--; + } + } + } + + // Remove the objects in reverse order so earlier + // deletes don't change the index of later ones + indicesToRemove.Sort(); + indicesToRemove.Reverse(); + try { + this.BeginUpdate(); + foreach (int i in indicesToRemove) { + this.Items.RemoveAt(i); + } + this.InsertObjects(index, modelObjects); + } finally { + this.EndUpdate(); + } + } + + /// + /// Calculate what item is under the given point? + /// + /// + /// + /// + public new ListViewHitTestInfo HitTest(int x, int y) { + // Everything costs something. Playing with the layout of the header can cause problems + // with the hit testing. If the header shrinks, the underlying control can throw a tantrum. + try { + return base.HitTest(x, y); + } catch (ArgumentOutOfRangeException) { + return new ListViewHitTestInfo(null, null, ListViewHitTestLocations.None); + } + } + + /// + /// Perform a hit test using the Windows control's SUBITEMHITTEST message. + /// This provides information about group hits that the standard ListView.HitTest() does not. + /// + /// + /// + /// + protected OlvListViewHitTestInfo LowLevelHitTest(int x, int y) { + + // If it's not even in the control, don't bother with anything else + if (!this.ClientRectangle.Contains(x, y)) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // If there are no columns, also don't bother with anything else + if (this.Columns.Count == 0) + return new OlvListViewHitTestInfo(null, null, 0, null, 0); + + // Is the point over the header? + OlvListViewHitTestInfo.HeaderHitTestInfo headerHitTestInfo = this.HeaderControl.HitTest(x, y); + if (headerHitTestInfo != null) + return new OlvListViewHitTestInfo(this, headerHitTestInfo.ColumnIndex, headerHitTestInfo.IsOverCheckBox, headerHitTestInfo.OverDividerIndex); + + // Call the native hit test method, which is a little confusing. + NativeMethods.LVHITTESTINFO lParam = new NativeMethods.LVHITTESTINFO(); + lParam.pt_x = x; + lParam.pt_y = y; + int index = NativeMethods.HitTest(this, ref lParam); + + // Setup the various values we need to make our hit test structure + bool isGroupHit = (lParam.flags & (int)HitTestLocationEx.LVHT_EX_GROUP) != 0; + OLVListItem hitItem = isGroupHit || index == -1 ? null : this.GetItem(index); + OLVListSubItem subItem = (this.View == View.Details && hitItem != null) ? hitItem.GetSubItem(lParam.iSubItem) : null; + + // Figure out which group is involved in the hit test. This is a little complicated: + // If the list is virtual: + // - the returned value is list view item index + // - iGroup is the *index* of the hit group. + // If the list is not virtual: + // - iGroup is always -1. + // - if the point is over a group, the returned value is the *id* of the hit group. + // - if the point is not over a group, the returned value is list view item index. + OLVGroup group = null; + if (this.ShowGroups && this.OLVGroups != null) { + if (this.VirtualMode) { + group = lParam.iGroup >= 0 && lParam.iGroup < this.OLVGroups.Count ? this.OLVGroups[lParam.iGroup] : null; + } else { + if (isGroupHit) { + foreach (OLVGroup olvGroup in this.OLVGroups) { + if (olvGroup.GroupId == index) { + group = olvGroup; + break; + } + } + } + } + } + OlvListViewHitTestInfo olvListViewHitTest = new OlvListViewHitTestInfo(hitItem, subItem, lParam.flags, group, lParam.iSubItem); + // System.Diagnostics.Debug.WriteLine(String.Format("HitTest({0}, {1})=>{2}", x, y, olvListViewHitTest)); + return olvListViewHitTest; + } + + /// + /// What is under the given point? This takes the various parts of a cell into account, including + /// any custom parts that a custom renderer might use + /// + /// + /// + /// An information block about what is under the point + public virtual OlvListViewHitTestInfo OlvHitTest(int x, int y) { + OlvListViewHitTestInfo hti = this.LowLevelHitTest(x, y); + + // There is a bug/"feature" of the ListView concerning hit testing. + // If FullRowSelect is false and the point is over cell 0 but not on + // the text or icon, HitTest will not register a hit. We could turn + // FullRowSelect on, do the HitTest, and then turn it off again, but + // toggling FullRowSelect in that way messes up the tooltip in the + // underlying control. So we have to find another way. + // + // It's too hard to try to write the hit test from scratch. Grouping (for + // example) makes it just too complicated. So, we have to use HitTest + // but try to get around its limits. + // + // First step is to determine if the point was within column 0. + // If it was, then we only have to determine if there is an actual row + // under the point. If there is, then we know that the point is over cell 0. + // So we try a Battleship-style approach: is there a subcell to the right + // of cell 0? This will return a false negative if column 0 is the rightmost column, + // so we also check for a subcell to the left. But if only column 0 is visible, + // then that will fail too, so we check for something at the very left of the + // control. + // + // This will still fail under pathological conditions. If column 0 fills + // the whole listview and no part of the text column 0 is visible + // (because it is horizontally scrolled offscreen), then the hit test will fail. + + // Are we in the buggy context? Details view, not full row select, and + // failing to find anything + if (hti.Item == null && !this.FullRowSelect && this.View == View.Details) { + // Is the point within the column 0? If it is, maybe it should have been a hit. + // Let's test slightly to the right and then to left of column 0. Hopefully one + // of those will hit a subitem + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + if (x >= sides.X && x <= sides.Y) { + // We look for: + // - any subitem to the right of cell 0? + // - any subitem to the left of cell 0? + // - cell 0 at the left edge of the screen + hti = this.LowLevelHitTest(sides.Y + 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(sides.X - 4, y); + if (hti.Item == null) + hti = this.LowLevelHitTest(4, y); + + if (hti.Item != null) { + // We hit something! So, the original point must have been in cell 0 + hti.ColumnIndex = 0; + hti.SubItem = hti.Item.GetSubItem(0); + hti.Location = ListViewHitTestLocations.None; + hti.HitTestLocation = HitTestLocation.InCell; + } + } + } + + if (this.OwnerDraw) + this.CalculateOwnerDrawnHitTest(hti, x, y); + else + this.CalculateStandardHitTest(hti, x, y); + + return hti; + } + + /// + /// Perform a hit test when the control is not owner drawn + /// + /// + /// + /// + protected virtual void CalculateStandardHitTest(OlvListViewHitTestInfo hti, int x, int y) { + + // Standard hit test works fine for the primary column + if (this.View != View.Details || hti.ColumnIndex == 0 || + hti.SubItem == null || hti.Column == null) + return; + + Rectangle cellBounds = hti.SubItem.Bounds; + bool hasImage = (this.GetActualImageIndex(hti.SubItem.ImageSelector) != -1); + + // Unless we say otherwise, it was an general incell hit + hti.HitTestLocation = HitTestLocation.InCell; + + // Check if the point is over where an image should be. + // If there is a checkbox or image there, tag it and exit. + Rectangle r = cellBounds; + r.Width = this.SmallImageSize.Width; + if (r.Contains(x, y)) { + if (hti.Column.CheckBoxes) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + if (hasImage) { + hti.HitTestLocation = HitTestLocation.Image; + return; + } + } + + // Figure out where the text actually is and if the point is in it + // The standard HitTest assumes that any point inside a subitem is + // a hit on Text -- which is clearly not true. + Rectangle textBounds = cellBounds; + textBounds.X += 4; + if (hasImage) + textBounds.X += this.SmallImageSize.Width; + + Size proposedSize = new Size(textBounds.Width, textBounds.Height); + Size textSize = TextRenderer.MeasureText(hti.SubItem.Text, this.Font, proposedSize, TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix); + textBounds.Width = textSize.Width; + + switch (hti.Column.TextAlign) { + case HorizontalAlignment.Center: + textBounds.X += (cellBounds.Right - cellBounds.Left - textSize.Width) / 2; + break; + case HorizontalAlignment.Right: + textBounds.X = cellBounds.Right - textSize.Width; + break; + } + if (textBounds.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + } + } + + /// + /// Perform a hit test when the control is owner drawn. This hands off responsibility + /// to the renderer. + /// + /// + /// + /// + protected virtual void CalculateOwnerDrawnHitTest(OlvListViewHitTestInfo hti, int x, int y) { + // If the click wasn't on an item, give up + if (hti.Item == null) + return; + + // If the list is showing column, but they clicked outside the columns, also give up + if (this.View == View.Details && hti.Column == null) + return; + + // Which renderer was responsible for drawing that point + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(hti.RowObject, hti.Column) + : this.ItemRenderer; + + // We can't decide who was responsible. Give up + if (renderer == null) + return; + + // Ask the responsible renderer what is at that point + renderer.HitTest(hti, x, y); + } + + /// + /// Pause (or unpause) all animations in the list + /// + /// true to pause, false to unpause + public virtual void PauseAnimations(bool isPause) { + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + ImageRenderer renderer = col.Renderer as ImageRenderer; + if (renderer != null) { + renderer.ListView = this; + renderer.Paused = isPause; + } + } + } + + /// + /// Rebuild the columns based upon its current view and column visibility settings + /// + public virtual void RebuildColumns() { + this.ChangeToFilteredColumns(this.View); + } + + /// + /// Remove the given model object from the ListView + /// + /// The model to be removed + /// See RemoveObjects() for more details + /// This method is thread-safe. + /// + public virtual void RemoveObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.RemoveObject(modelObject); }); + else + this.RemoveObjects(new object[] { modelObject }); + } + + /// + /// Remove all of the given objects from the control. + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// This method is thread-safe. + /// + public virtual void RemoveObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.RemoveObjects(modelObjects); }); + return; + } + if (modelObjects == null) + return; + + this.BeginUpdate(); + try { + // Give the world a chance to cancel or change the added objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + modelObjects = args.ObjectsToRemove; + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { +// ReSharper disable PossibleMultipleEnumeration + int i = ourObjects.IndexOf(modelObject); + if (i >= 0) + ourObjects.RemoveAt(i); +// ReSharper restore PossibleMultipleEnumeration + i = this.IndexOf(modelObject); + if (i >= 0) + this.Items.RemoveAt(i); + } + } + this.PostProcessRows(); + + // Tell the world that the list has changed + this.UnsubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } finally { + this.EndUpdate(); + } + } + + /// + /// Select all rows in the listview + /// + public virtual void SelectAll() { + NativeMethods.SelectAllItems(this); + } + + /// + /// Set the given image to be fixed in the bottom right of the list view. + /// This image will not scroll when the list view scrolls. + /// + /// + /// + /// This method uses ListView's native ability to display a background image. + /// It has a few limitations: + /// + /// + /// It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself, + /// including its background, which covers the background image. + /// It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image. + /// It does not work at all on XP. + /// Obviously, it doesn't look good when alternate row background colors are enabled. + /// + /// + /// If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not + /// translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that + /// they work correctly even in MDI applications. + /// + /// Setting this clears any background image. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundWatermark(Image image) { + NativeMethods.SetBackgroundImage(this, image, true, false, 0, 0); + } + + /// + /// Set the given image to be background of the ListView so that it appears at the given + /// percentage offsets within the list. + /// + /// + /// This has the same limitations as described in . Make sure those limitations + /// are understood before using the method. + /// This is very similar to setting the property of the standard .NET ListView, except that the standard + /// BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This + /// method does not have that problem. + /// Setting this clears any background watermark. + /// + /// The image to be drawn. If null, any existing image will be removed. + /// The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right. + /// The vertical percentage where the image will be placed. + public void SetNativeBackgroundImage(Image image, int xOffset, int yOffset) { + NativeMethods.SetBackgroundImage(this, image, false, false, xOffset, yOffset); + } + + /// + /// Set the given image to be the tiled background of the ListView. + /// + /// + /// This has the same limitations as described in and . + /// Make sure those limitations + /// are understood before using the method. + /// + /// The image to be drawn. If null, any existing image will be removed. + public void SetNativeBackgroundTiledImage(Image image) { + NativeMethods.SetBackgroundImage(this, image, false, true, 0, 0); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + public virtual void SetObjects(IEnumerable collection) { + this.SetObjects(collection, false); + } + + /// + /// Set the collection of objects that will be shown in this list view. + /// + /// This method can safely be called from background threads. + /// The list is updated immediately + /// The objects to be displayed + /// Should the state of the list be preserved as far as is possible. + public virtual void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(this.objects, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + collection = args.NewObjects; + + // If we own the current list and they change to another list, we don't own it any more + if (this.isOwnerOfObjects && !ReferenceEquals(this.objects, collection)) + this.isOwnerOfObjects = false; + this.objects = collection; + this.BuildList(preserveState); + + // Tell the world that the list has changed + this.UpdateNotificationSubscriptions(this.objects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + + /// + /// Update the given model object into the ListView. The model will be added if it doesn't already exist. + /// + /// The model to be updated + /// + /// + /// See for more details + /// + /// This method is thread-safe. + /// This method will cause the list to be resorted. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObject(object modelObject) { + if (this.InvokeRequired) + this.Invoke((MethodInvoker)delegate() { this.UpdateObject(modelObject); }); + else + this.UpdateObjects(new object[] { modelObject }); + } + + /// + /// Update the pre-existing models that are equal to the given objects. If any of the model doesn't + /// already exist in the control, they will be added. + /// + /// Collection of objects to be updated/added + /// + /// This method will cause the list to be resorted. + /// Nulls are silently ignored. + /// This method is thread-safe. + /// This method only works on ObjectListViews and FastObjectListViews. + /// + public virtual void UpdateObjects(ICollection modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate() { this.UpdateObjects(modelObjects); }); + return; + } + if (modelObjects == null || modelObjects.Count == 0) + return; + + this.BeginUpdate(); + try { + this.UnsubscribeNotifications(modelObjects); + + ArrayList objectsToAdd = new ArrayList(); + + this.TakeOwnershipOfObjects(); + ArrayList ourObjects = ObjectListView.EnumerableToArray(this.Objects, false); + foreach (object modelObject in modelObjects) { + if (modelObject != null) { + int i = ourObjects.IndexOf(modelObject); + if (i < 0) + objectsToAdd.Add(modelObject); + else { + ourObjects[i] = modelObject; + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + olvi.RowObject = modelObject; + this.RefreshItem(olvi); + } + } + } + } + this.PostProcessRows(); + + this.AddObjects(objectsToAdd); + + // Tell the world that the list has changed + this.SubscribeNotifications(modelObjects); + this.OnItemsChanged(new ItemsChangedEventArgs()); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change any subscriptions to INotifyPropertyChanged events on our current + /// model objects so that we no longer listen for events on the old models + /// and do listen for events on the given collection. + /// + /// This does nothing if UseNotifyPropertyChanged is false. + /// + protected virtual void UpdateNotificationSubscriptions(IEnumerable collection) { + if (!this.UseNotifyPropertyChanged) + return; + + // We could calculate a symmetric difference between the old models and the new models + // except that we don't have the previous models at this point. + + this.UnsubscribeNotifications(null); + this.SubscribeNotifications(collection ?? this.Objects); + } + + /// + /// Gets or sets whether or not ObjectListView should subscribe to INotifyPropertyChanged + /// events on the model objects that it is given. + /// + /// + /// + /// This should be set before calling SetObjects(). If you set this to false, + /// ObjectListView will unsubscribe to all current model objects. + /// + /// If you set this to true on a virtual list, the ObjectListView will + /// walk all the objects in the list trying to subscribe to change notifications. + /// If you have 10,000,000 items in your virtual list, this may take some time. + /// + [Category("ObjectListView"), + Description("Should ObjectListView listen for property changed events on the model objects?"), + DefaultValue(false)] + public bool UseNotifyPropertyChanged { + get { return this.useNotifyPropertyChanged; } + set { + if (this.useNotifyPropertyChanged == value) + return; + this.useNotifyPropertyChanged = value; + if (value) + this.SubscribeNotifications(this.Objects); + else + this.UnsubscribeNotifications(null); + } + } + private bool useNotifyPropertyChanged; + + /// + /// Subscribe to INotifyPropertyChanges on the given collection of objects. + /// + /// + protected void SubscribeNotifications(IEnumerable models) { + if (!this.UseNotifyPropertyChanged || models == null) + return; + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null && !subscribedModels.ContainsKey(notifier)) { + notifier.PropertyChanged += HandleModelOnPropertyChanged; + subscribedModels[notifier] = notifier; + } + } + } + + /// + /// Unsubscribe from INotifyPropertyChanges on the given collection of objects. + /// If the given collection is null, unsubscribe from all current subscriptions + /// + /// + protected void UnsubscribeNotifications(IEnumerable models) { + if (models == null) { + foreach (INotifyPropertyChanged notifier in this.subscribedModels.Keys) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + } + subscribedModels = new Hashtable(); + } else { + foreach (object x in models) { + INotifyPropertyChanged notifier = x as INotifyPropertyChanged; + if (notifier != null) { + notifier.PropertyChanged -= HandleModelOnPropertyChanged; + subscribedModels.Remove(notifier); + } + } + } + } + + private void HandleModelOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { + // System.Diagnostics.Debug.WriteLine(String.Format("PropertyChanged: '{0}' on '{1}", propertyChangedEventArgs.PropertyName, sender)); + this.RefreshObject(sender); + } + + private Hashtable subscribedModels = new Hashtable(); + + #endregion + + #region Save/Restore State + + /// + /// Return a byte array that represents the current state of the ObjectListView, such + /// that the state can be restored by RestoreState() + /// + /// + /// The state of an ObjectListView includes the attributes that the user can modify: + /// + /// current view (i.e. Details, Tile, Large Icon...) + /// sort column and direction + /// column order + /// column widths + /// column visibility + /// + /// + /// + /// It does not include selection or the scroll position. + /// + /// + /// A byte array representing the state of the ObjectListView + public virtual byte[] SaveState() { + ObjectListViewState olvState = new ObjectListViewState(); + olvState.VersionNumber = 1; + olvState.NumberOfColumns = this.AllColumns.Count; + olvState.CurrentView = this.View; + + // If we have a sort column, it is possible that it is not currently being shown, in which + // case, it's Index will be -1. So we calculate its index directly. Technically, the sort + // column does not even have to a member of AllColumns, in which case IndexOf will return -1, + // which is works fine since we have no way of restoring such a column anyway. + if (this.PrimarySortColumn != null) + olvState.SortColumn = this.AllColumns.IndexOf(this.PrimarySortColumn); + olvState.LastSortOrder = this.PrimarySortOrder; + olvState.IsShowingGroups = this.ShowGroups; + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + foreach (OLVColumn column in this.AllColumns) { + olvState.ColumnIsVisible.Add(column.IsVisible); + olvState.ColumnDisplayIndicies.Add(column.LastDisplayIndex); + olvState.ColumnWidths.Add(column.Width); + } + + // Now that we have stored our state, convert it to a byte array + using (MemoryStream ms = new MemoryStream()) { + BinaryFormatter serializer = new BinaryFormatter(); + serializer.AssemblyFormat = FormatterAssemblyStyle.Simple; + serializer.Serialize(ms, olvState); + return ms.ToArray(); + } + } + + /// + /// Restore the state of the control from the given string, which must have been + /// produced by SaveState() + /// + /// A byte array returned from SaveState() + /// Returns true if the state was restored + public virtual bool RestoreState(byte[] state) { + using (MemoryStream ms = new MemoryStream(state)) { + BinaryFormatter deserializer = new BinaryFormatter(); + ObjectListViewState olvState; + try { + olvState = deserializer.Deserialize(ms) as ObjectListViewState; + } catch (System.Runtime.Serialization.SerializationException) { + return false; + } + // The number of columns has changed. We have no way to match old + // columns to the new ones, so we just give up. + if (olvState == null || olvState.NumberOfColumns != this.AllColumns.Count) + return false; + if (olvState.SortColumn == -1) { + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + } else { + this.PrimarySortColumn = this.AllColumns[olvState.SortColumn]; + this.PrimarySortOrder = olvState.LastSortOrder; + } + for (int i = 0; i < olvState.NumberOfColumns; i++) { + OLVColumn column = this.AllColumns[i]; + column.Width = (int)olvState.ColumnWidths[i]; + column.IsVisible = (bool)olvState.ColumnIsVisible[i]; + column.LastDisplayIndex = (int)olvState.ColumnDisplayIndicies[i]; + } +// ReSharper disable RedundantCheckBeforeAssignment + if (olvState.IsShowingGroups != this.ShowGroups) +// ReSharper restore RedundantCheckBeforeAssignment + this.ShowGroups = olvState.IsShowingGroups; + if (this.View == olvState.CurrentView) + this.RebuildColumns(); + else + this.View = olvState.CurrentView; + } + + return true; + } + + /// + /// Instances of this class are used to store the state of an ObjectListView. + /// + [Serializable] + internal class ObjectListViewState + { +// ReSharper disable NotAccessedField.Global + public int VersionNumber = 1; +// ReSharper restore NotAccessedField.Global + public int NumberOfColumns = 1; + public View CurrentView; + public int SortColumn = -1; + public bool IsShowingGroups; + public SortOrder LastSortOrder = SortOrder.None; +// ReSharper disable FieldCanBeMadeReadOnly.Global + public ArrayList ColumnIsVisible = new ArrayList(); + public ArrayList ColumnDisplayIndicies = new ArrayList(); + public ArrayList ColumnWidths = new ArrayList(); +// ReSharper restore FieldCanBeMadeReadOnly.Global + } + + #endregion + + #region Event handlers + + /// + /// The application is idle. Trigger a SelectionChanged event. + /// + /// + /// + protected virtual void HandleApplicationIdle(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(HandleApplicationIdle); + this.hasIdleHandler = false; + + this.OnSelectionChanged(new EventArgs()); + } + + /// + /// The application is idle. Handle the column resizing event. + /// + /// + /// + protected virtual void HandleApplicationIdleResizeColumns(object sender, EventArgs e) { + // Remove the handler before triggering the event + Application.Idle -= new EventHandler(this.HandleApplicationIdleResizeColumns); + this.hasResizeColumnsHandler = false; + + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// Handle the BeginScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleBeginScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + NativeMethods.NMLVSCROLL nmlvscroll = (NativeMethods.NMLVSCROLL)m.GetLParam(typeof(NativeMethods.NMLVSCROLL)); + if (nmlvscroll.dx != 0) { + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionH - nmlvscroll.dx, scrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + + // Force any empty list msg to redraw when the list is scrolled horizontally + if (this.GetItemCount() == 0) + this.Invalidate(); + } + if (nmlvscroll.dy != 0) { + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, scrollPositionV - nmlvscroll.dy, scrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + return false; + } + + /// + /// Handle the EndScroll listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleEndScroll(ref Message m) { + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + + // There is a bug in ListView under XP that causes the gridlines to be incorrectly scrolled + // when the left button is clicked to scroll. This is supposedly documented at + // KB 813791, but I couldn't find it anywhere. You can follow this thread to see the discussion + // http://www.ureader.com/msg/1484143.aspx + + if (!ObjectListView.IsVistaOrLater && ObjectListView.IsLeftMouseDown && this.GridLines) { + this.Invalidate(); + this.Update(); + } + + return false; + } + + /// + /// Handle the LinkClick listview notification + /// + /// + /// True if the event was completely handled + protected virtual bool HandleLinkClick(ref Message m) { + //System.Diagnostics.Debug.WriteLine("HandleLinkClick"); + + NativeMethods.NMLVLINK nmlvlink = (NativeMethods.NMLVLINK)m.GetLParam(typeof(NativeMethods.NMLVLINK)); + + // Find the group that was clicked and trigger an event + foreach (OLVGroup x in this.OLVGroups) { + if (x.GroupId == nmlvlink.iSubItem) { + this.OnGroupTaskClicked(new GroupTaskClickedEventArgs(x)); + return true; + } + } + + return false; + } + + /// + /// The cell tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleCellToolTipShowing(object sender, ToolTipShowingEventArgs e) { + this.BuildCellEvent(e, this.PointToClient(Cursor.Position)); + if (e.Item != null) { + e.Text = this.GetCellToolTip(e.ColumnIndex, e.RowIndex); + this.OnCellToolTip(e); + } + } + + /// + /// Allow the HeaderControl to call back into HandleHeaderToolTipShowing without making that method public + /// + /// + /// + internal void HeaderToolTipShowingCallback(object sender, ToolTipShowingEventArgs e) { + this.HandleHeaderToolTipShowing(sender, e); + } + + /// + /// The header tooltip control wants information about the tool tip that it should show. + /// + /// + /// + protected virtual void HandleHeaderToolTipShowing(object sender, ToolTipShowingEventArgs e) { + e.ColumnIndex = this.HeaderControl.ColumnIndexUnderCursor; + if (e.ColumnIndex < 0) + return; + + e.RowIndex = -1; + e.Model = null; + e.Column = this.GetColumn(e.ColumnIndex); + e.Text = this.GetHeaderToolTip(e.ColumnIndex); + e.ListView = this; + this.OnHeaderToolTip(e); + } + + /// + /// Event handler for the column click event + /// + protected virtual void HandleColumnClick(object sender, ColumnClickEventArgs e) { + if (!this.PossibleFinishCellEditing()) + return; + + // Toggle the sorting direction on successive clicks on the same column + if (this.PrimarySortColumn != null && e.Column == this.PrimarySortColumn.Index) + this.PrimarySortOrder = (this.PrimarySortOrder == SortOrder.Descending ? SortOrder.Ascending : SortOrder.Descending); + else + this.PrimarySortOrder = SortOrder.Ascending; + + this.BeginUpdate(); + try { + this.Sort(e.Column); + } finally { + this.EndUpdate(); + } + } + + #endregion + + #region Low level Windows Message handling + + /// + /// Override the basic message pump for this control + /// + /// + protected override void WndProc(ref Message m) + { + + // System.Diagnostics.Debug.WriteLine(m.Msg); + switch (m.Msg) { + case 2: // WM_DESTROY + if (!this.HandleDestroy(ref m)) + base.WndProc(ref m); + break; + //case 0x14: // WM_ERASEBKGND + // Can't do anything here since, when the control is double buffered, anything + // done here is immediately over-drawn + // break; + case 0x0F: // WM_PAINT + if (!this.HandlePaint(ref m)) + base.WndProc(ref m); + break; + case 0x46: // WM_WINDOWPOSCHANGING + if (this.PossibleFinishCellEditing() && !this.HandleWindowPosChanging(ref m)) + base.WndProc(ref m); + break; + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref m)) + base.WndProc(ref m); + break; + case 0x0100: // WM_KEY_DOWN + if (!this.HandleKeyDown(ref m)) + base.WndProc(ref m); + break; + case 0x0102: // WM_CHAR + if (!this.HandleChar(ref m)) + base.WndProc(ref m); + break; + case 0x0200: // WM_MOUSEMOVE + if (!this.HandleMouseMove(ref m)) + base.WndProc(ref m); + break; + case 0x0201: // WM_LBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x202: // WM_LBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + if (this.PossibleFinishCellEditing() && !this.HandleLButtonUp(ref m)) + base.WndProc(ref m); + break; + case 0x0203: // WM_LBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleLButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x0204: // WM_RBUTTONDOWN + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONDOWN"); + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDown(ref m)) + base.WndProc(ref m); + break; + case 0x0205: // WM_RBUTTONUP + // System.Diagnostics.Debug.WriteLine("WM_RBUTTONUP"); + base.WndProc(ref m); + break; + case 0x0206: // WM_RBUTTONDBLCLK + if (this.PossibleFinishCellEditing() && !this.HandleRButtonDoubleClick(ref m)) + base.WndProc(ref m); + break; + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref m)) + base.WndProc(ref m); + break; + case 0x114: // WM_HSCROLL: + case 0x115: // WM_VSCROLL: + //System.Diagnostics.Debug.WriteLine("WM_VSCROLL"); + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x20A: // WM_MOUSEWHEEL: + case 0x20E: // WM_MOUSEHWHEEL: + if (this.AllowCellEditorsToProcessMouseWheel && this.IsCellEditing) + break; + if (this.PossibleFinishCellEditing()) + base.WndProc(ref m); + break; + case 0x7B: // WM_CONTEXTMENU + if (!this.HandleContextMenu(ref m)) + base.WndProc(ref m); + break; + case 0x1000 + 18: // LVM_HITTEST: + //System.Diagnostics.Debug.WriteLine("LVM_HITTEST"); + if (this.skipNextHitTest) { + //System.Diagnostics.Debug.WriteLine("SKIPPING LVM_HITTEST"); + this.skipNextHitTest = false; + } else { + base.WndProc(ref m); + } + break; + default: + base.WndProc(ref m); + break; + } + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleChar(ref Message m) { + + // Trigger a normal KeyPress event, which listeners can handle if they want. + // Handling the event stops ObjectListView's fancy search-by-typing. + if (this.ProcessKeyEventArgs(ref m)) + return true; + + const int MILLISECONDS_BETWEEN_KEYPRESSES = 1000; + + // What character did the user type and was it part of a longer string? + char character = (char)m.WParam.ToInt32(); //TODO: Will this work on 64 bit or MBCS? + if (character == (char)Keys.Back) { + // Backspace forces the next key to be considered the start of a new search + this.timeLastCharEvent = 0; + return true; + } + + if (System.Environment.TickCount < (this.timeLastCharEvent + MILLISECONDS_BETWEEN_KEYPRESSES)) + this.lastSearchString += character; + else + this.lastSearchString = character.ToString(CultureInfo.InvariantCulture); + + // If this control is showing checkboxes, we want to ignore single space presses, + // since they are used to toggle the selected checkboxes. + if (this.CheckBoxes && this.lastSearchString == " ") { + this.timeLastCharEvent = 0; + return true; + } + + // Where should the search start? + int start = 0; + ListViewItem focused = this.FocusedItem; + if (focused != null) { + start = this.GetDisplayOrderOfItemIndex(focused.Index); + + // If the user presses a single key, we search from after the focused item, + // being careful not to march past the end of the list + if (this.lastSearchString.Length == 1) { + start += 1; + if (start == this.GetItemCount()) + start = 0; + } + } + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(this.lastSearchString, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return true; + + // The parameters of the search may have been changed + string searchString = args.StringToFind; + start = args.StartSearchFrom; + + // Do the actual search + int found = this.FindMatchingRow(searchString, start, SearchDirectionHint.Down); + if (found >= 0) { + // Select and focus on the found item + this.BeginUpdate(); + try { + this.SelectedIndices.Clear(); + OLVListItem lvi = this.GetNthItemInDisplayOrder(found); + if (lvi != null) { + if (lvi.Enabled) + lvi.Selected = true; + lvi.Focused = true; + this.EnsureVisible(lvi.Index); + } + } finally { + this.EndUpdate(); + } + } + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(searchString, found); + this.OnAfterSearching(args2); + if (!args2.Handled) { + if (found < 0) + System.Media.SystemSounds.Beep.Play(); + } + + // When did this event occur? + this.timeLastCharEvent = System.Environment.TickCount; + return true; + } + private int timeLastCharEvent; + private string lastSearchString; + + /// + /// The user wants to see the context menu. + /// + /// The windows m + /// A bool indicating if this m has been handled + /// + /// We want to ignore context menu requests that are triggered by right clicks on the header + /// + protected virtual bool HandleContextMenu(ref Message m) { + // Don't try to handle context menu commands at design time. + if (this.DesignMode) + return false; + + // If the context menu command was generated by the keyboard, LParam will be -1. + // We don't want to process these. + if (m.LParam == this.minusOne) + return false; + + // If the context menu came from somewhere other than the header control, + // we also don't want to ignore it + if (m.WParam != this.HeaderControl.Handle) + return false; + + // OK. Looks like a right click in the header + if (!this.PossibleFinishCellEditing()) + return true; + + int columnIndex = this.HeaderControl.ColumnIndexUnderCursor; + return this.HandleHeaderRightClick(columnIndex); + } + readonly IntPtr minusOne = new IntPtr(-1); + + /// + /// Handle the Custom draw series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleCustomDraw(ref Message m) { + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_PREERASE = 3; + const int CDDS_POSTERASE = 4; + //const int CDRF_NEWFONT = 2; + //const int CDRF_SKIPDEFAULT = 4; + const int CDDS_ITEM = 0x00010000; + const int CDDS_SUBITEM = 0x00020000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + const int CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE); + const int CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE); + const int CDDS_SUBITEMPREPAINT = (CDDS_SUBITEM | CDDS_ITEMPREPAINT); + const int CDDS_SUBITEMPOSTPAINT = (CDDS_SUBITEM | CDDS_ITEMPOSTPAINT); + const int CDRF_NOTIFYPOSTPAINT = 0x10; + //const int CDRF_NOTIFYITEMDRAW = 0x20; + //const int CDRF_NOTIFYSUBITEMDRAW = 0x20; // same value as above! + const int CDRF_NOTIFYPOSTERASE = 0x40; + + // There is a bug in owner drawn virtual lists which causes lots of custom draw messages + // to be sent to the control *outside* of a WmPaint event. AFAIK, these custom draw events + // are spurious and only serve to make the control flicker annoyingly. + // So, we ignore messages that are outside of a paint event. + if (!this.isInWmPaintEvent) + return true; + + // One more complication! Sometimes with owner drawn virtual lists, the act of drawing + // the overlays triggers a second attempt to paint the control -- which makes an annoying + // flicker. So, we only do the custom drawing once per WmPaint event. + if (!this.shouldDoCustomDrawing) + return true; + + NativeMethods.NMLVCUSTOMDRAW nmcustomdraw = (NativeMethods.NMLVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMLVCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("cd: {0:x}, {1}, {2}", nmcustomdraw.nmcd.dwDrawStage, nmcustomdraw.dwItemType, nmcustomdraw.nmcd.dwItemSpec)); + + // Ignore drawing of group items + if (nmcustomdraw.dwItemType == 1) { + // This is the basis of an idea about how to owner draw group headers + + //nmcustomdraw.clrText = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrFace = ColorTranslator.ToWin32(Color.DeepPink); + //nmcustomdraw.clrTextBk = ColorTranslator.ToWin32(Color.DeepPink); + //Marshal.StructureToPtr(nmcustomdraw, m.LParam, false); + //using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + // g.DrawRectangle(Pens.Red, Rectangle.FromLTRB(nmcustomdraw.rcText.left, nmcustomdraw.rcText.top, nmcustomdraw.rcText.right, nmcustomdraw.rcText.bottom)); + //} + //m.Result = (IntPtr)((int)m.Result | CDRF_SKIPDEFAULT); + return true; + } + + switch (nmcustomdraw.nmcd.dwDrawStage) { + case CDDS_PREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_PREPAINT"); + // Remember which items were drawn during this paint cycle + if (this.prePaintLevel == 0) + this.drawnItems = new List(); + + // If there are any items, we have to wait until at least one has been painted + // before we draw the overlays. If there aren't any items, there will never be any + // item paint events, so we can draw the overlays whenever + this.isAfterItemPaint = (this.GetItemCount() == 0); + this.prePaintLevel++; + base.WndProc(ref m); + + // Make sure that we get postpaint notifications + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_POSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTPAINT"); + this.prePaintLevel--; + + // When in group view, we have two problems. On XP, the control sends + // a whole heap of PREPAINT/POSTPAINT messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays. + // On Vista, we have a different problem. On Vista, the control nests calls + // to PREPAINT and POSTPAINT. We only want to draw overlays on the outermost + // POSTPAINT. + if (this.prePaintLevel == 0 && (this.isMarqueSelecting || this.isAfterItemPaint)) { + this.shouldDoCustomDrawing = false; + + // Draw our overlays after everything has been drawn + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + this.DrawAllDecorations(g, this.drawnItems); + } + } + break; + + case CDDS_ITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREPAINT"); + + // When in group view on XP, the control send a whole heap of PREPAINT/POSTPAINT + // messages before drawing any items. + // We have to wait until after the first item paint before we draw overlays + this.isAfterItemPaint = true; + + // This scheme of catching custom draw msgs works fine, except + // for Tile view. Something in .NET's handling of Tile view causes lots + // of invalidates and erases. So, we just ignore completely + // .NET's handling of Tile view and let the underlying control + // do its stuff. Strangely, if the Tile view is + // completely owner drawn, those erasures don't happen. + if (this.View == View.Tile) { + if (this.OwnerDraw && this.ItemRenderer != null) + base.WndProc(ref m); + } else { + base.WndProc(ref m); + } + + m.Result = (IntPtr)((int)m.Result | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYPOSTERASE); + return true; + + case CDDS_ITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTPAINT"); + // Remember which items have been drawn so we can draw any decorations for them + // once all other painting is finished + if (this.Columns.Count > 0) { + OLVListItem olvi = this.GetItem((int)nmcustomdraw.nmcd.dwItemSpec); + if (olvi != null) + this.drawnItems.Add(olvi); + } + break; + + case CDDS_SUBITEMPREPAINT: + //System.Diagnostics.Debug.WriteLine(String.Format("CDDS_SUBITEMPREPAINT ({0},{1})", (int)nmcustomdraw.nmcd.dwItemSpec, nmcustomdraw.iSubItem)); + + // There is a bug in the .NET framework which appears when column 0 of an owner drawn listview + // is dragged to another column position. + // The bounds calculation always returns the left edge of column 0 as being 0. + // The effects of this bug become apparent + // when the listview is scrolled horizontally: the control can think that column 0 + // is no longer visible (the horizontal scroll position is subtracted from the bounds, giving a + // rectangle that is offscreen). In those circumstances, column 0 is not redraw because + // the control thinks it is not visible and so does not trigger a DrawSubItem event. + + // To fix this problem, we have to detected the situation -- owner drawing column 0 in any column except 0 -- + // trigger our own DrawSubItem, and then prevent the default processing from occurring. + + // Are we owner drawing column 0 when it's in any column except 0? + if (!this.OwnerDraw) + return false; + + int columnIndex = nmcustomdraw.iSubItem; + if (columnIndex != 0) + return false; + + int displayIndex = this.Columns[0].DisplayIndex; + if (displayIndex == 0) + return false; + + int rowIndex = (int)nmcustomdraw.nmcd.dwItemSpec; + OLVListItem item = this.GetItem(rowIndex); + if (item == null) + return false; + + // OK. We have the error condition, so lets do what the .NET framework should do. + // Trigger an event to draw column 0 when it is not at display index 0 + using (Graphics g = Graphics.FromHdc(nmcustomdraw.nmcd.hdc)) { + + // Correctly calculate the bounds of cell 0 + Rectangle r = item.GetSubItemBounds(0); + + // We can hardcode "0" here since we know we are only doing this for column 0 + DrawListViewSubItemEventArgs args = new DrawListViewSubItemEventArgs(g, r, item, item.SubItems[0], rowIndex, 0, + this.Columns[0], (ListViewItemStates)nmcustomdraw.nmcd.uItemState); + this.OnDrawSubItem(args); + + // If the event handler wants to do the default processing (i.e. DrawDefault = true), we are stuck. + // There is no way we can force the default drawing because of the bug in .NET we are trying to get around. + System.Diagnostics.Trace.Assert(!args.DrawDefault, "Default drawing is impossible in this situation"); + } + m.Result = (IntPtr)4; + + return true; + + case CDDS_SUBITEMPOSTPAINT: + //System.Diagnostics.Debug.WriteLine("CDDS_SUBITEMPOSTPAINT"); + break; + + // I have included these stages, but it doesn't seem that they are sent for ListViews. + // http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-08/msg00220.html + + case CDDS_PREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_PREERASE"); + break; + + case CDDS_POSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_POSTERASE"); + break; + + case CDDS_ITEMPREERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPREERASE"); + break; + + case CDDS_ITEMPOSTERASE: + //System.Diagnostics.Debug.WriteLine("CDDS_ITEMPOSTERASE"); + break; + } + + return false; + } + bool isAfterItemPaint; + List drawnItems; + + /// + /// Handle the underlying control being destroyed + /// + /// + /// + protected virtual bool HandleDestroy(ref Message m) { + //System.Diagnostics.Debug.WriteLine(String.Format("WM_DESTROY: Disposing={0}, IsDisposed={1}, VirtualMode={2}", Disposing, IsDisposed, VirtualMode)); + + // Recreate the header control when the listview control is destroyed + this.headerControl = null; + + // When the underlying control is destroyed, we need to recreate and reconfigure its tooltip + if (this.cellToolTip != null) { + this.cellToolTip.PushSettings(); + this.BeginInvoke((MethodInvoker)delegate { + this.UpdateCellToolTipHandle(); + this.cellToolTip.PopSettings(); + }); + } + + return false; + } + + /// + /// Handle the search for item m if possible. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleFindItem(ref Message m) { + // NOTE: As far as I can see, this message is never actually sent to the control, making this + // method redundant! + + const int LVFI_STRING = 0x0002; + + NativeMethods.LVFINDINFO findInfo = (NativeMethods.LVFINDINFO)m.GetLParam(typeof(NativeMethods.LVFINDINFO)); + + // We can only handle string searches + if ((findInfo.flags & LVFI_STRING) != LVFI_STRING) + return false; + + int start = m.WParam.ToInt32(); + m.Result = (IntPtr)this.FindMatchingRow(findInfo.psz, start, SearchDirectionHint.Down); + return true; + } + + /// + /// Find the first row after the given start in which the text value in the + /// comparison column begins with the given text. The comparison column is column 0, + /// unless IsSearchOnSortColumn is true, in which case the current sort column is used. + /// + /// The text to be prefix matched + /// The index of the first row to consider + /// Which direction should be searched? + /// The index of the first row that matched, or -1 + /// The text comparison is a case-insensitive, prefix match. The search will + /// search the every row until a match is found, wrapping at the end if needed. + public virtual int FindMatchingRow(string text, int start, SearchDirectionHint direction) { + // We also can't do anything if we don't have data + if (this.Columns.Count == 0) + return -1; + int rowCount = this.GetItemCount(); + if (rowCount == 0) + return -1; + + // Which column are we going to use for our comparing? + OLVColumn column = this.GetColumn(0); + if (this.IsSearchOnSortColumn && this.View == View.Details && this.PrimarySortColumn != null) + column = this.PrimarySortColumn; + + // Do two searches if necessary to find a match. The second search is the wrap-around part of searching + int i; + if (direction == SearchDirectionHint.Down) { + i = this.FindMatchInRange(text, start, rowCount - 1, column); + if (i == -1 && start > 0) + i = this.FindMatchInRange(text, 0, start - 1, column); + } else { + i = this.FindMatchInRange(text, start, 0, column); + if (i == -1 && start != rowCount) + i = this.FindMatchInRange(text, rowCount - 1, start + 1, column); + } + + return i; + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected virtual int FindMatchInRange(string text, int first, int last, OLVColumn column) { + if (first <= last) { + for (int i = first; i <= last; i++) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } else { + for (int i = first; i >= last; i--) { + string data = column.GetStringValue(this.GetNthItemInDisplayOrder(i).RowObject); + if (data.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + return i; + } + } + + return -1; + } + + /// + /// Handle the Group Info series of notifications + /// + /// The message + /// True if the message has been handled + protected virtual bool HandleGroupInfo(ref Message m) + { + NativeMethods.NMLVGROUP nmlvgroup = (NativeMethods.NMLVGROUP)m.GetLParam(typeof(NativeMethods.NMLVGROUP)); + + //System.Diagnostics.Debug.WriteLine(String.Format("group: {0}, old state: {1}, new state: {2}", + // nmlvgroup.iGroupId, StateToString(nmlvgroup.uOldState), StateToString(nmlvgroup.uNewState))); + + // Ignore state changes that aren't related to selection, focus or collapsedness + const uint INTERESTING_STATES = (uint) (GroupState.LVGS_COLLAPSED | GroupState.LVGS_FOCUSED | GroupState.LVGS_SELECTED); + if ((nmlvgroup.uOldState & INTERESTING_STATES) == (nmlvgroup.uNewState & INTERESTING_STATES)) + return false; + + foreach (OLVGroup group in this.OLVGroups) { + if (group.GroupId == nmlvgroup.iGroupId) { + GroupStateChangedEventArgs args = new GroupStateChangedEventArgs(group, (GroupState)nmlvgroup.uOldState, (GroupState)nmlvgroup.uNewState); + this.OnGroupStateChanged(args); + break; + } + } + + return false; + } + + //private static string StateToString(uint state) + //{ + // if (state == 0) + // return Enum.GetName(typeof(GroupState), 0); + // + // List names = new List(); + // foreach (int value in Enum.GetValues(typeof(GroupState))) + // { + // if (value != 0 && (state & value) == value) + // { + // names.Add(Enum.GetName(typeof(GroupState), value)); + // } + // } + // return names.Count == 0 ? state.ToString("x") : String.Join("|", names.ToArray()); + //} + + /// + /// Handle a key down message + /// + /// + /// True if the msg has been handled + protected virtual bool HandleKeyDown(ref Message m) { + + // If this is a checkbox list, toggle the selected rows when the user presses Space + if (this.CheckBoxes && m.WParam.ToInt32() == (int)Keys.Space && this.SelectedIndices.Count > 0) { + this.ToggleSelectedRowCheckBoxes(); + return true; + } + + // Remember the scroll position so we can decide if the listview has scrolled in the + // handling of the event. + int scrollPositionH = NativeMethods.GetScrollPosition(this, true); + int scrollPositionV = NativeMethods.GetScrollPosition(this, false); + + base.WndProc(ref m); + + // It's possible that the processing in base.WndProc has actually destroyed this control + if (this.IsDisposed) + return true; + + // If the keydown processing changed the scroll position, trigger a Scroll event + int newScrollPositionH = NativeMethods.GetScrollPosition(this, true); + int newScrollPositionV = NativeMethods.GetScrollPosition(this, false); + + if (scrollPositionH != newScrollPositionH) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionH, newScrollPositionH, ScrollOrientation.HorizontalScroll); + this.OnScroll(args); + } + if (scrollPositionV != newScrollPositionV) { + ScrollEventArgs args = new ScrollEventArgs(ScrollEventType.EndScroll, + scrollPositionV, newScrollPositionV, ScrollOrientation.VerticalScroll); + this.OnScroll(args); + } + + if (scrollPositionH != newScrollPositionH || scrollPositionV != newScrollPositionV) + this.RefreshHotItem(); + + return true; + } + + /// + /// Toggle the checkedness of the selected rows + /// + /// + /// + /// Actually, this doesn't actually toggle all rows. It toggles the first row, and + /// all other rows get the check state of that first row. This is actually a much + /// more useful behaviour. + /// + /// + /// If no rows are selected, this method does nothing. + /// + /// + public void ToggleSelectedRowCheckBoxes() { + if (this.SelectedIndices.Count == 0) + return; + Object primaryModel = this.GetItem(this.SelectedIndices[0]).RowObject; + this.ToggleCheckObject(primaryModel); + CheckState? state = this.GetCheckState(primaryModel); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + /// + /// Catch the Left Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + // We have to intercept this low level message rather than the more natural + // overridding of OnMouseDown, since ListCtrl's internal mouse down behavior + // is to select (or deselect) rows when the mouse is released. We don't + // want the selection to change when the user checks or unchecks a checkbox, so if the + // mouse down event was to check/uncheck, we have to hide this mouse + // down event from the control. + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + + if (hti.Item == null) + return false; + + // If the click occurs on a button, ignore it so the row isn't selected + if (hti.HitTestLocation == HitTestLocation.Button) { + this.Invalidate(); + + return true; + } + + // If they didn't click checkbox, we can just return + if (hti.HitTestLocation != HitTestLocation.CheckBox) + return false; + + // Disabled rows cannot change checkboxes + if (!hti.Item.Enabled) + return true; + + // Did they click a sub item checkbox? + if (hti.Column != null && hti.Column.Index > 0) { + if (hti.Column.IsEditable && hti.Item.Enabled) + this.ToggleSubItemCheckBox(hti.RowObject, hti.Column); + return true; + } + + // They must have clicked the primary checkbox + this.ToggleCheckObject(hti.RowObject); + + // If they change the checkbox of a selected row, all the rows in the selection + // should be given the same state + if (hti.Item.Selected) { + CheckState? state = this.GetCheckState(hti.RowObject); + if (state.HasValue) { + foreach (Object x in this.SelectedObjects) + this.SetObjectCheckedness(x, state.Value); + } + } + + return true; + } + + /// + /// Catch the Left Button up event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonUp(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + if (this.MouseMoveHitTest == null) + return false; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + // Did they click an enabled, non-empty button? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.Button) { + // If a button was hit, Item and Column must be non-null + if (this.MouseMoveHitTest.Item.Enabled || this.MouseMoveHitTest.Column.EnableButtonWhenItemIsDisabled) { + string buttonText = this.MouseMoveHitTest.Column.GetStringValue(this.MouseMoveHitTest.RowObject); + if (!String.IsNullOrEmpty(buttonText)) { + this.Invalidate(); + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, new Point(x, y), this.MouseMoveHitTest); + this.OnButtonClick(args); + return true; + } + } + } + + // Are they trying to expand/collapse a group? + if (this.MouseMoveHitTest.HitTestLocation == HitTestLocation.GroupExpander) { + if (this.TriggerGroupExpandCollapse(this.MouseMoveHitTest.Group)) + return true; + } + + if (ObjectListView.IsVistaOrLater && this.HasCollapsibleGroups) + base.DefWndProc(ref m); + + return false; + } + + /// + /// Trigger a GroupExpandCollapse event and return true if the action was cancelled + /// + /// + /// + protected virtual bool TriggerGroupExpandCollapse(OLVGroup group) + { + GroupExpandingCollapsingEventArgs args = new GroupExpandingCollapsingEventArgs(group); + this.OnGroupExpandingCollapsing(args); + return args.Canceled; + } + + /// + /// Catch the Right Button down event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDown(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDown(this.OlvHitTest(x, y)); + } + + /// + /// Handle a left mouse down at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDown(OlvListViewHitTestInfo hti) { + if (hti.Item == null) + return false; + + // Ignore clicks on checkboxes + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the Left Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleLButtonDoubleClick(ref Message m) { + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessLButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessLButtonDoubleClick(OlvListViewHitTestInfo hti) { + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the right Button double click event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleRButtonDoubleClick(ref Message m) { + + // If there are no columns, the base ListView class can throw OutOfRange exceptions. + if (this.Columns.Count == 0) + return true; + + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + return this.ProcessRButtonDoubleClick(this.OlvHitTest(x, y)); + } + + /// + /// Handle a right mouse double click at the given hit test location + /// + /// Subclasses can override this to do something unique + /// + /// True if the message has been handled + protected virtual bool ProcessRButtonDoubleClick(OlvListViewHitTestInfo hti) { + + // If the user double clicked on a checkbox, ignore it + return (hti.HitTestLocation == HitTestLocation.CheckBox); + } + + /// + /// Catch the MouseMove event. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleMouseMove(ref Message m) + { + //int x = m.LParam.ToInt32() & 0xFFFF; + //int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + + //this.lastMouseMoveX = x; + //this.lastMouseMoveY = y; + + return false; + } + //private int lastMouseMoveX = -1; + //private int lastMouseMoveY = -1; + + /// + /// Handle notifications that have been reflected back from the parent window + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleReflectNotify(ref Message m) { + const int NM_CLICK = -2; + const int NM_DBLCLK = -3; + const int NM_RDBLCLK = -6; + const int NM_CUSTOMDRAW = -12; + const int NM_RELEASEDCAPTURE = -16; + const int LVN_FIRST = -100; + const int LVN_ITEMCHANGED = LVN_FIRST - 1; + const int LVN_ITEMCHANGING = LVN_FIRST - 0; + const int LVN_HOTTRACK = LVN_FIRST - 21; + const int LVN_MARQUEEBEGIN = LVN_FIRST - 56; + const int LVN_GETINFOTIP = LVN_FIRST - 58; + const int LVN_GETDISPINFO = LVN_FIRST - 77; + const int LVN_BEGINSCROLL = LVN_FIRST - 80; + const int LVN_ENDSCROLL = LVN_FIRST - 81; + const int LVN_LINKCLICK = LVN_FIRST - 84; + const int LVN_GROUPINFO = LVN_FIRST - 88; // undocumented + const int LVIF_STATE = 8; + //const int LVIS_FOCUSED = 1; + const int LVIS_SELECTED = 2; + + bool isMsgHandled = false; + + // TODO: Don't do any logic in this method. Create separate methods for each message + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + //System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr->code)); + + switch (nmhdr.code) { + case NM_CLICK: + // The standard ListView does some strange stuff here when the list has checkboxes. + // If you shift click on non-primary columns when FullRowSelect is true, the + // checkedness of the selected rows changes. + // We can't just not do the base class stuff because it sets up state that is used to + // determine mouse up events later on. + // So, we sabotage the base class's process of the click event. The base class does a HITTEST + // in order to determine which row was clicked -- if that fails, the base class does nothing. + // So when we get a CLICK, we know that the base class is going to send a HITTEST very soon, + // so we ignore the next HITTEST message, which will cause the click processing to fail. + //System.Diagnostics.Debug.WriteLine("NM_CLICK"); + this.skipNextHitTest = true; + break; + + case LVN_BEGINSCROLL: + //System.Diagnostics.Debug.WriteLine("LVN_BEGINSCROLL"); + isMsgHandled = this.HandleBeginScroll(ref m); + break; + + case LVN_ENDSCROLL: + isMsgHandled = this.HandleEndScroll(ref m); + break; + + case LVN_LINKCLICK: + isMsgHandled = this.HandleLinkClick(ref m); + break; + + case LVN_MARQUEEBEGIN: + //System.Diagnostics.Debug.WriteLine("LVN_MARQUEEBEGIN"); + this.isMarqueSelecting = true; + break; + + case LVN_GETINFOTIP: + //System.Diagnostics.Debug.WriteLine("LVN_GETINFOTIP"); + // When virtual lists are in SmallIcon view, they generates tooltip message with invalid item indices. + NativeMethods.NMLVGETINFOTIP nmGetInfoTip = (NativeMethods.NMLVGETINFOTIP)m.GetLParam(typeof(NativeMethods.NMLVGETINFOTIP)); + isMsgHandled = nmGetInfoTip.iItem >= this.GetItemCount() || this.Columns.Count == 0; + break; + + case NM_RELEASEDCAPTURE: + //System.Diagnostics.Debug.WriteLine("NM_RELEASEDCAPTURE"); + this.isMarqueSelecting = false; + this.Invalidate(); + break; + + case NM_CUSTOMDRAW: + //System.Diagnostics.Debug.WriteLine("NM_CUSTOMDRAW"); + isMsgHandled = this.HandleCustomDraw(ref m); + break; + + case NM_DBLCLK: + // The default behavior of a .NET ListView with checkboxes is to toggle the checkbox on + // double-click. That's just silly, if you ask me :) + if (this.CheckBoxes) { + // How do we make ListView not do that silliness? We could just ignore the message + // but the last part of the base code sets up state information, and without that + // state, the ListView doesn't trigger MouseDoubleClick events. So we fake a + // right button double click event, which sets up the same state, but without + // toggling the checkbox. + nmhdr.code = NM_RDBLCLK; + Marshal.StructureToPtr(nmhdr, m.LParam, false); + } + break; + + case LVN_ITEMCHANGED: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGED"); + NativeMethods.NMLISTVIEW nmlistviewPtr2 = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr2.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr2.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr2.uNewState); + if (currentValue != newCheckValue) + { + // Remove the state indices so that we don't trigger the OnItemChecked method + // when we call our base method after exiting this method + nmlistviewPtr2.uOldState = (nmlistviewPtr2.uOldState & 0x0FFF); + nmlistviewPtr2.uNewState = (nmlistviewPtr2.uNewState & 0x0FFF); + Marshal.StructureToPtr(nmlistviewPtr2, m.LParam, false); + } + else + { + bool isSelected = (nmlistviewPtr2.uNewState & LVIS_SELECTED) == LVIS_SELECTED; + + if (isSelected) + { + // System.Diagnostics.Debug.WriteLine(String.Format("Selected: {0}", nmlistviewPtr2.iItem)); + bool isShiftDown = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + + // -1 indicates that all rows are to be selected -- in fact, they already have been. + // We now have to deselect all the disabled objects. + if (nmlistviewPtr2.iItem == -1 || isShiftDown) { + Stopwatch sw = Stopwatch.StartNew(); + foreach (object disabledModel in this.DisabledObjects) + { + int modelIndex = this.IndexOf(disabledModel); + if (modelIndex >= 0) + NativeMethods.DeselectOneItem(this, modelIndex); + } + // System.Diagnostics.Debug.WriteLine(String.Format("PERF - Deselecting took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks)); + } + else + { + // If the object just selected is disabled, explicitly de-select it + OLVListItem olvi = this.GetItem(nmlistviewPtr2.iItem); + if (olvi != null && !olvi.Enabled) + NativeMethods.DeselectOneItem(this, nmlistviewPtr2.iItem); + } + } + } + } + break; + + case LVN_ITEMCHANGING: + //System.Diagnostics.Debug.WriteLine("LVN_ITEMCHANGING"); + NativeMethods.NMLISTVIEW nmlistviewPtr = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + if ((nmlistviewPtr.uChanged & LVIF_STATE) != 0) { + CheckState currentValue = this.CalculateCheckState(nmlistviewPtr.uOldState); + CheckState newCheckValue = this.CalculateCheckState(nmlistviewPtr.uNewState); + + if (currentValue != newCheckValue) { + // Prevent the base method from seeing the state change, + // since we handled it elsewhere + nmlistviewPtr.uChanged &= ~LVIF_STATE; + Marshal.StructureToPtr(nmlistviewPtr, m.LParam, false); + } + } + break; + + case LVN_HOTTRACK: + break; + + case LVN_GETDISPINFO: + break; + + case LVN_GROUPINFO: + //System.Diagnostics.Debug.WriteLine("reflect notify: GROUP INFO"); + isMsgHandled = this.HandleGroupInfo(ref m); + break; + + //default: + //System.Diagnostics.Debug.WriteLine(String.Format("reflect notify: {0}", nmhdr.code)); + //break; + } + + return isMsgHandled; + } + private bool skipNextHitTest; + + private CheckState CalculateCheckState(int state) { + switch ((state & 0xf000) >> 12) { + case 1: + return CheckState.Unchecked; + case 2: + return CheckState.Checked; + case 3: + return CheckState.Indeterminate; + default: + return CheckState.Checked; + } + } + + /// + /// In the notification messages, we handle attempts to change the width of our columns + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected bool HandleNotify(ref Message m) { + bool isMsgHandled = false; + + const int NM_CUSTOMDRAW = -12; + + const int HDN_FIRST = (0 - 300); + const int HDN_ITEMCHANGINGA = (HDN_FIRST - 0); + const int HDN_ITEMCHANGINGW = (HDN_FIRST - 20); + const int HDN_ITEMCLICKA = (HDN_FIRST - 2); + const int HDN_ITEMCLICKW = (HDN_FIRST - 22); + const int HDN_DIVIDERDBLCLICKA = (HDN_FIRST - 5); + const int HDN_DIVIDERDBLCLICKW = (HDN_FIRST - 25); + const int HDN_BEGINTRACKA = (HDN_FIRST - 6); + const int HDN_BEGINTRACKW = (HDN_FIRST - 26); + const int HDN_ENDTRACKA = (HDN_FIRST - 7); + const int HDN_ENDTRACKW = (HDN_FIRST - 27); + const int HDN_TRACKA = (HDN_FIRST - 8); + const int HDN_TRACKW = (HDN_FIRST - 28); + + // Handle the notification, remembering to handle both ANSI and Unicode versions + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Debug.WriteLine(String.Format("not: {0}", nmhdr->code)); + + //if (nmhdr.code < HDN_FIRST) + // System.Diagnostics.Debug.WriteLine(nmhdr.code); + + // In KB Article #183258, MS states that when a header control has the HDS_FULLDRAG style, it will receive + // ITEMCHANGING events rather than TRACK events. Under XP SP2 (at least) this is not always true, which may be + // why MS has withdrawn that particular KB article. It is true that the header is always given the HDS_FULLDRAG + // style. But even while window style set, the control doesn't always received ITEMCHANGING events. + // The controlling setting seems to be the Explorer option "Show Window Contents While Dragging"! + // In the category of "truly bizarre side effects", if the this option is turned on, we will receive + // ITEMCHANGING events instead of TRACK events. But if it is turned off, we receive lots of TRACK events and + // only one ITEMCHANGING event at the very end of the process. + // If we receive HDN_TRACK messages, it's harder to control the resizing process. If we return a result of 1, we + // cancel the whole drag operation, not just that particular track event, which is clearly not what we want. + // If we are willing to compile with unsafe code enabled, we can modify the size of the column in place, using the + // commented out code below. But without unsafe code, the best we can do is allow the user to drag the column to + // any width, and then spring it back to within bounds once they release the mouse button. UI-wise it's very ugly. + switch (nmheader.nhdr.code) { + + case NM_CUSTOMDRAW: + if (!this.OwnerDrawnHeader) + isMsgHandled = this.HeaderControl.HandleHeaderCustomDraw(ref m); + break; + + case HDN_ITEMCLICKA: + case HDN_ITEMCLICKW: + if (!this.PossibleFinishCellEditing()) + { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + break; + + case HDN_DIVIDERDBLCLICKA: + case HDN_DIVIDERDBLCLICKW: + case HDN_BEGINTRACKA: + case HDN_BEGINTRACKW: + if (!this.PossibleFinishCellEditing()) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + break; + } + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + OLVColumn column = this.GetColumn(nmheader.iItem); + // Space filling columns can't be dragged or double-click resized + if (column.FillsFreeSpace) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + break; + case HDN_ENDTRACKA: + case HDN_ENDTRACKW: + //if (this.ShowGroups) + // this.ResizeLastGroup(); + break; + case HDN_TRACKA: + case HDN_TRACKW: + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + if (hditem.cxy < column.MinimumWidth) + hditem.cxy = column.MinimumWidth; + else if (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth) + hditem.cxy = column.MaximumWidth; + Marshal.StructureToPtr(hditem, nmheader.pHDITEM, false); + } + break; + + case HDN_ITEMCHANGINGA: + case HDN_ITEMCHANGINGW: + nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (nmheader.iItem >= 0 && nmheader.iItem < this.Columns.Count) { + NativeMethods.HDITEM hditem = (NativeMethods.HDITEM)Marshal.PtrToStructure(nmheader.pHDITEM, typeof(NativeMethods.HDITEM)); + OLVColumn column = this.GetColumn(nmheader.iItem); + // Check the mask to see if the width field is valid, and if it is, make sure it's within range + if ((hditem.mask & 1) == 1) { + if (hditem.cxy < column.MinimumWidth || + (column.MaximumWidth != -1 && hditem.cxy > column.MaximumWidth)) { + m.Result = (IntPtr)1; // prevent the change from happening + isMsgHandled = true; + } + } + } + break; + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("olv TTN_SHOW"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleShow(ref m); + break; + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("olv TTN_POP"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandlePop(ref m); + break; + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("olv TTN_GETDISPINFO"); + if (this.CellToolTip.Handle == nmheader.nhdr.hwndFrom) + isMsgHandled = this.CellToolTip.HandleGetDispInfo(ref m); + break; + +// default: +// System.Diagnostics.Debug.WriteLine(String.Format("notify: {0}", nmheader.nhdr.code)); +// break; + } + + return isMsgHandled; + } + + /// + /// Create a ToolTipControl to manage the tooltip control used by the listview control + /// + protected virtual void CreateCellToolTip() { + this.cellToolTip = new ToolTipControl(); + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + this.cellToolTip.Showing += new EventHandler(HandleCellToolTipShowing); + this.cellToolTip.SetMaxWidth(); + NativeMethods.MakeTopMost(this.cellToolTip); + } + + /// + /// Update the handle used by our cell tooltip to be the tooltip used by + /// the underlying Windows listview control. + /// + protected virtual void UpdateCellToolTipHandle() { + if (this.cellToolTip != null && this.cellToolTip.Handle == IntPtr.Zero) + this.cellToolTip.AssignHandle(NativeMethods.GetTooltipControl(this)); + } + + /// + /// Handle the WM_PAINT event + /// + /// + /// Return true if the msg has been handled and nothing further should be done + protected virtual bool HandlePaint(ref Message m) { + //System.Diagnostics.Debug.WriteLine("> WMPAINT"); + + // We only want to custom draw the control within WmPaint message and only + // once per paint event. We use these bools to insure this. + this.isInWmPaintEvent = true; + this.shouldDoCustomDrawing = true; + this.prePaintLevel = 0; + + this.ShowOverlays(); + + this.HandlePrePaint(); + base.WndProc(ref m); + this.HandlePostPaint(); + this.isInWmPaintEvent = false; + //System.Diagnostics.Debug.WriteLine("< WMPAINT"); + return true; + } + private int prePaintLevel; + + /// + /// Perform any steps needed before painting the control + /// + protected virtual void HandlePrePaint() { + // When we get a WM_PAINT msg, remember the rectangle that is being updated. + // We can't get this information later, since the BeginPaint call wipes it out. + // this.lastUpdateRectangle = NativeMethods.GetUpdateRect(this); // we no longer need this, but keep the code so we can see it later + + //// When the list is empty, we want to handle the drawing of the control by ourselves. + //// Unfortunately, there is no easy way to tell our superclass that we want to do this. + //// So we resort to guile and deception. We validate the list area of the control, which + //// effectively tells our superclass that this area does not need to be painted. + //// Our superclass will then not paint the control, leaving us free to do so ourselves. + //// Without doing this trickery, the superclass will draw the list as empty, + //// and then moments later, we will draw the empty list msg, giving a nasty flicker + //if (this.GetItemCount() == 0 && this.HasEmptyListMsg) + // NativeMethods.ValidateRect(this, this.ClientRectangle); + } + + /// + /// Perform any steps needed after painting the control + /// + protected virtual void HandlePostPaint() { + // This message is no longer necessary, but we keep it for compatibility + } + + /// + /// Handle the window position changing. + /// + /// The m to be processed + /// bool to indicate if the msg has been handled + protected virtual bool HandleWindowPosChanging(ref Message m) { + const int SWP_NOSIZE = 1; + + NativeMethods.WINDOWPOS pos = (NativeMethods.WINDOWPOS)m.GetLParam(typeof(NativeMethods.WINDOWPOS)); + if ((pos.flags & SWP_NOSIZE) == 0) { + if (pos.cx < this.Bounds.Width) // only when shrinking + // pos.cx is the window width, not the client area width, so we have to subtract the border widths + this.ResizeFreeSpaceFillingColumns(pos.cx - (this.Bounds.Width - this.ClientSize.Width)); + } + + return false; + } + + #endregion + + #region Column header clicking, column hiding and resizing + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + protected virtual bool HandleHeaderRightClick(int columnIndex) { + ToolStripDropDown menu = this.MakeHeaderRightClickMenu(columnIndex); + ColumnRightClickEventArgs eventArgs = new ColumnRightClickEventArgs(columnIndex, menu, Cursor.Position); + this.OnColumnRightClick(eventArgs); + + // Did the event handler stop any further processing? + if (eventArgs.Cancel) + return false; + + return this.ShowHeaderRightClickMenu(columnIndex, eventArgs.MenuStrip, eventArgs.Location); + } + + /// + /// Show a menu that is appropriate when the given column header is clicked. + /// + /// The index of the header that was clicked. This + /// can be -1, indicating that the header was clicked outside of a column + /// Where should the menu be shown + /// True if a menu was displayed + protected virtual bool ShowHeaderRightClickMenu(int columnIndex, ToolStripDropDown menu, Point pt) { + if (menu.Items.Count > 0) { + menu.Show(pt); + return true; + } + + return false; + } + + /// + /// Create the menu that should be displayed when the user right clicks + /// on the given column header. + /// + /// Index of the column that was right clicked. + /// This can be negative, which indicates a click outside of any header. + /// The toolstrip that should be displayed + protected virtual ToolStripDropDown MakeHeaderRightClickMenu(int columnIndex) { + ToolStripDropDown m = new ContextMenuStrip(); + + if (columnIndex >= 0 && this.UseFiltering && this.ShowFilterMenuOnRightClick) + m = this.MakeFilteringMenu(m, columnIndex); + + if (columnIndex >= 0 && this.ShowCommandMenuOnRightClick) + m = this.MakeColumnCommandMenu(m, columnIndex); + + if (this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None) { + m = this.MakeColumnSelectMenu(m); + } + + return m; + } + + /// + /// The user has right clicked on the column headers. Do whatever is required + /// + /// Return true if this event has been handle + [Obsolete("Use HandleHeaderRightClick(int) instead")] + protected virtual bool HandleHeaderRightClick() { + return false; + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnSelectMenu(Point pt) { + ToolStripDropDown m = this.MakeColumnSelectMenu(new ContextMenuStrip()); + m.Show(pt); + } + + /// + /// Show a popup menu at the given point which will allow the user to choose which columns + /// are visible on this listview + /// + /// + /// Where should the menu be placed + [Obsolete("Use ShowHeaderRightClickMenu instead")] + protected virtual void ShowColumnCommandMenu(int columnIndex, Point pt) { + ToolStripDropDown m = this.MakeColumnCommandMenu(new ContextMenuStrip(), columnIndex); + if (this.SelectColumnsOnRightClick) { + if (m.Items.Count > 0) + m.Items.Add(new ToolStripSeparator()); + this.MakeColumnSelectMenu(m); + } + m.Show(pt); + } + + /// + /// Gets or set the text to be used for the sorting ascending command + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort ascending by '{0}'"), Localizable(true)] + public string MenuLabelSortAscending { + get { return this.menuLabelSortAscending; } + set { this.menuLabelSortAscending = value; } + } + private string menuLabelSortAscending = "Sort ascending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Sort descending by '{0}'"), Localizable(true)] + public string MenuLabelSortDescending { + get { return this.menuLabelSortDescending; } + set { this.menuLabelSortDescending = value; } + } + private string menuLabelSortDescending = "Sort descending by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Group by '{0}'"), Localizable(true)] + public string MenuLabelGroupBy { + get { return this.menuLabelGroupBy; } + set { this.menuLabelGroupBy = value; } + } + private string menuLabelGroupBy = "Group by '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Lock grouping on '{0}'"), Localizable(true)] + public string MenuLabelLockGroupingOn { + get { return this.menuLabelLockGroupingOn; } + set { this.menuLabelLockGroupingOn = value; } + } + private string menuLabelLockGroupingOn = "Lock grouping on '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unlock grouping from '{0}'"), Localizable(true)] + public string MenuLabelUnlockGroupingOn { + get { return this.menuLabelUnlockGroupingOn; } + set { this.menuLabelUnlockGroupingOn = value; } + } + private string menuLabelUnlockGroupingOn = "Unlock grouping from '{0}'"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Turn off groups"), Localizable(true)] + public string MenuLabelTurnOffGroups { + get { return this.menuLabelTurnOffGroups; } + set { this.menuLabelTurnOffGroups = value; } + } + private string menuLabelTurnOffGroups = "Turn off groups"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Unsort"), Localizable(true)] + public string MenuLabelUnsort { + get { return this.menuLabelUnsort; } + set { this.menuLabelUnsort = value; } + } + private string menuLabelUnsort = "Unsort"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Columns"), Localizable(true)] + public string MenuLabelColumns { + get { return this.menuLabelColumns; } + set { this.menuLabelColumns = value; } + } + private string menuLabelColumns = "Columns"; + + /// + /// + /// + [Category("Labels - ObjectListView"), DefaultValue("Select Columns..."), Localizable(true)] + public string MenuLabelSelectColumns { + get { return this.menuLabelSelectColumns; } + set { this.menuLabelSelectColumns = value; } + } + private string menuLabelSelectColumns = "Select Columns..."; + + /// + /// Gets or sets the image that will be place next to the Sort Ascending command + /// + public static Bitmap SortAscendingImage = BrightIdeasSoftware.Properties.Resources.SortAscending; + + /// + /// Gets or sets the image that will be placed next to the Sort Descending command + /// + public static Bitmap SortDescendingImage = BrightIdeasSoftware.Properties.Resources.SortDescending; + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnCommandMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + if (strip.Items.Count > 0) + strip.Items.Add(new ToolStripSeparator()); + + string label = String.Format(this.MenuLabelSortAscending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortAscendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Ascending); + }); + } + label = String.Format(this.MenuLabelSortDescending, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, ObjectListView.SortDescendingImage, (EventHandler)delegate(object sender, EventArgs args) { + this.Sort(column, SortOrder.Descending); + }); + } + if (this.CanShowGroups) { + label = String.Format(this.MenuLabelGroupBy, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.PrimarySortColumn = column; + this.PrimarySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + if (this.ShowGroups) { + if (this.AlwaysGroupByColumn == column) { + label = String.Format(this.MenuLabelUnlockGroupingOn, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.AlwaysGroupByColumn = null; + this.AlwaysGroupBySortOrder = SortOrder.None; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelLockGroupingOn, column.Text); + if (column.Groupable && !String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = true; + this.AlwaysGroupByColumn = column; + this.AlwaysGroupBySortOrder = SortOrder.Ascending; + this.BuildList(); + }); + } + } + label = String.Format(this.MenuLabelTurnOffGroups, column.Text); + if (!String.IsNullOrEmpty(label)) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.ShowGroups = false; + this.BuildList(); + }); + } + } else { + label = String.Format(this.MenuLabelUnsort, column.Text); + if (column.Sortable && !String.IsNullOrEmpty(label) && this.PrimarySortOrder != SortOrder.None) { + strip.Items.Add(label, null, (EventHandler)delegate(object sender, EventArgs args) { + this.Unsort(); + }); + } + } + + return strip; + } + + /// + /// Append the column selection menu items to the given menu strip. + /// + /// The menu to which the items will be added. + /// Return the menu to which the items were added + public virtual ToolStripDropDown MakeColumnSelectMenu(ToolStripDropDown strip) { + + System.Diagnostics.Debug.Assert(this.SelectColumnsOnRightClickBehaviour != ColumnSelectBehaviour.None); + + // Append a separator if the menu isn't empty and the last item isn't already a separator + if (strip.Items.Count > 0 && (!(strip.Items[strip.Items.Count-1] is ToolStripSeparator))) + strip.Items.Add(new ToolStripSeparator()); + + if (this.AllColumns.Count > 0 && this.AllColumns[0].LastDisplayIndex == -1) + this.RememberDisplayIndicies(); + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.ModelDialog) { + strip.Items.Add(this.MenuLabelSelectColumns, null, delegate(object sender, EventArgs args) { + (new ColumnSelectionForm()).OpenOn(this); + }); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.Submenu) { + ToolStripMenuItem menu = new ToolStripMenuItem(this.MenuLabelColumns); + menu.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Items.Add(menu); + this.AddItemsToColumnSelectMenu(menu.DropDownItems); + } + + if (this.SelectColumnsOnRightClickBehaviour == ColumnSelectBehaviour.InlineMenu) { + strip.ItemClicked += new ToolStripItemClickedEventHandler(this.ColumnSelectMenuItemClicked); + strip.Closing += new ToolStripDropDownClosingEventHandler(this.ColumnSelectMenuClosing); + this.AddItemsToColumnSelectMenu(strip.Items); + } + + return strip; + } + + /// + /// Create the menu items that will allow columns to be choosen and add them to the + /// given collection + /// + /// + protected void AddItemsToColumnSelectMenu(ToolStripItemCollection items) { + + // Sort columns by display order + List columns = new List(this.AllColumns); + columns.Sort(delegate(OLVColumn x, OLVColumn y) { return (x.LastDisplayIndex - y.LastDisplayIndex); }); + + // Build menu from sorted columns + foreach (OLVColumn col in columns) { + ToolStripMenuItem mi = new ToolStripMenuItem(col.Text); + mi.Checked = col.IsVisible; + mi.Tag = col; + + // The 'Index' property returns -1 when the column is not visible, so if the + // column isn't visible we have to enable the item. Also the first column can't be turned off + mi.Enabled = !col.IsVisible || col.CanBeHidden; + items.Add(mi); + } + } + + private void ColumnSelectMenuItemClicked(object sender, ToolStripItemClickedEventArgs e) { + this.contextMenuStaysOpen = false; + ToolStripMenuItem menuItemClicked = e.ClickedItem as ToolStripMenuItem; + if (menuItemClicked == null) + return; + OLVColumn col = menuItemClicked.Tag as OLVColumn; + if (col == null) + return; + menuItemClicked.Checked = !menuItemClicked.Checked; + col.IsVisible = menuItemClicked.Checked; + this.contextMenuStaysOpen = this.SelectColumnsMenuStaysOpen; + this.BeginInvoke(new MethodInvoker(this.RebuildColumns)); + } + private bool contextMenuStaysOpen; + + private void ColumnSelectMenuClosing(object sender, ToolStripDropDownClosingEventArgs e) { + e.Cancel = this.contextMenuStaysOpen && e.CloseReason == ToolStripDropDownCloseReason.ItemClicked; + this.contextMenuStaysOpen = false; + } + + /// + /// Create a Filtering menu + /// + /// + /// + /// + public virtual ToolStripDropDown MakeFilteringMenu(ToolStripDropDown strip, int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return strip; + + FilterMenuBuilder strategy = this.FilterMenuBuildStrategy; + if (strategy == null) + return strip; + + return strategy.MakeFilterMenu(strip, this, column); + } + + /// + /// Override the OnColumnReordered method to do what we want + /// + /// + protected override void OnColumnReordered(ColumnReorderedEventArgs e) { + base.OnColumnReordered(e); + + // The internal logic of the .NET code behind a ENDDRAG event means that, + // at this point, the DisplayIndex's of the columns are not yet as they are + // going to be. So we have to invoke a method to run later that will remember + // what the real DisplayIndex's are. + this.BeginInvoke(new MethodInvoker(this.RememberDisplayIndicies)); + } + + private void RememberDisplayIndicies() { + // Remember the display indexes so we can put them back at a later date + foreach (OLVColumn x in this.AllColumns) + x.LastDisplayIndex = x.DisplayIndex; + } + + /// + /// When the column widths are changing, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) { + if (this.UpdateSpaceFillingColumnsWhenDraggingColumnDivider && !this.GetColumn(e.ColumnIndex).FillsFreeSpace) { + // If the width of a column is increasing, resize any space filling columns allowing the extra + // space that the new column width is going to consume + int oldWidth = this.GetColumn(e.ColumnIndex).Width; + if (e.NewWidth > oldWidth) + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width - (e.NewWidth - oldWidth)); + else + this.ResizeFreeSpaceFillingColumns(); + } + } + + /// + /// When the column widths change, resize the space filling columns + /// + /// + /// + protected virtual void HandleColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { + if (!this.GetColumn(e.ColumnIndex).FillsFreeSpace) + this.ResizeFreeSpaceFillingColumns(); + } + + /// + /// When the size of the control changes, we have to resize our space filling columns. + /// + /// + /// + protected virtual void HandleLayout(object sender, LayoutEventArgs e) { + // We have to delay executing the recalculation of the columns, since virtual lists + // get terribly confused if we resize the column widths during this event. + if (!this.hasResizeColumnsHandler) { + this.hasResizeColumnsHandler = true; + this.RunWhenIdle(this.HandleApplicationIdleResizeColumns); + } + } + + private void RunWhenIdle(EventHandler eventHandler) { + Application.Idle += eventHandler; + if (!this.CanUseApplicationIdle) { + SynchronizationContext.Current.Post(delegate(object x) { Application.RaiseIdle(EventArgs.Empty); }, null); + } + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns() { + this.ResizeFreeSpaceFillingColumns(this.ClientSize.Width); + } + + /// + /// Resize our space filling columns so they fill any unoccupied width in the control + /// + protected virtual void ResizeFreeSpaceFillingColumns(int freeSpace) { + // It's too confusing to dynamically resize columns at design time. + if (this.DesignMode) + return; + + if (this.Frozen) + return; + + this.BeginUpdate(); + + // Calculate the free space available + int totalProportion = 0; + List spaceFillingColumns = new List(); + for (int i = 0; i < this.Columns.Count; i++) { + OLVColumn col = this.GetColumn(i); + if (col.FillsFreeSpace) { + spaceFillingColumns.Add(col); + totalProportion += col.FreeSpaceProportion; + } else + freeSpace -= col.Width; + } + freeSpace = Math.Max(0, freeSpace); + + // Any space filling column that would hit it's Minimum or Maximum + // width must be treated as a fixed column. + foreach (OLVColumn col in spaceFillingColumns.ToArray()) { + int newWidth = (freeSpace * col.FreeSpaceProportion) / totalProportion; + + if (col.MinimumWidth != -1 && newWidth < col.MinimumWidth) + newWidth = col.MinimumWidth; + else if (col.MaximumWidth != -1 && newWidth > col.MaximumWidth) + newWidth = col.MaximumWidth; + else + newWidth = 0; + + if (newWidth > 0) { + col.Width = newWidth; + freeSpace -= newWidth; + totalProportion -= col.FreeSpaceProportion; + spaceFillingColumns.Remove(col); + } + } + + // Distribute the free space between the columns + foreach (OLVColumn col in spaceFillingColumns) { + col.Width = (freeSpace*col.FreeSpaceProportion)/totalProportion; + } + + this.EndUpdate(); + } + + #endregion + + #region Checkboxes + + /// + /// Check all rows + /// + public virtual void CheckAll() + { + this.CheckedObjects = EnumerableToArray(this.Objects, false); + } + + /// + /// Check the checkbox in the given column header + /// + /// If the given columns header check box is linked to the cell check boxes, + /// then checkboxes in all cells will also be checked. + /// + public virtual void CheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Checked); + } + + /// + /// Mark the checkbox in the given column header as having an indeterminate value + /// + /// + public virtual void CheckIndeterminateHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Indeterminate); + } + + /// + /// Mark the given object as indeterminate check state + /// + /// The model object to be marked indeterminate + public virtual void CheckIndeterminateObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Indeterminate); + } + + /// + /// Mark the given object as checked in the list + /// + /// The model object to be checked + public virtual void CheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Checked); + } + + /// + /// Mark the given objects as checked in the list + /// + /// The model object to be checked + public virtual void CheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.CheckObject(model); + } + + /// + /// Put a check into the check box at the given cell + /// + /// + /// + public virtual void CheckSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Checked); + this.RefreshObject(rowObject); + } + + /// + /// Put an indeterminate check into the check box at the given cell + /// + /// + /// + public virtual void CheckIndeterminateSubItem(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Indeterminate); + this.RefreshObject(rowObject); + } + + /// + /// Return true of the given object is checked + /// + /// The model object whose checkedness is returned + /// Is the given object checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsChecked(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Checked; + } + + /// + /// Return true of the given object is indeterminately checked + /// + /// The model object whose checkedness is returned + /// Is the given object indeterminately checked? + /// If the given object is not in the list, this method returns false. + public virtual bool IsCheckedIndeterminate(object modelObject) { + return this.GetCheckState(modelObject) == CheckState.Indeterminate; + } + + /// + /// Is there a check at the check box at the given cell + /// + /// + /// + public virtual bool IsSubItemChecked(object rowObject, OLVColumn column) { + if (column == null || rowObject == null || !column.CheckBoxes) + return false; + return (column.GetCheckState(rowObject) == CheckState.Checked); + } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does not know and the value from the control will be used. + /// + /// + /// + protected virtual CheckState? GetCheckState(Object modelObject) { + if (this.CheckStateGetter != null) + return this.CheckStateGetter(modelObject); + return this.PersistentCheckBoxes ? this.GetPersistentCheckState(modelObject) : (CheckState?)null; + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected virtual CheckState PutCheckState(Object modelObject, CheckState state) { + if (this.CheckStatePutter != null) + return this.CheckStatePutter(modelObject, state); + return this.PersistentCheckBoxes ? this.SetPersistentCheckState(modelObject, state) : state; + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected virtual bool SetObjectCheckedness(object modelObject, CheckState state) { + + if (GetCheckState(modelObject) == state) + return false; + + OLVListItem olvi = this.ModelToItem(modelObject); + + // If we didn't find the given, we still try to record the check state. + if (olvi == null) { + this.PutCheckState(modelObject, state); + return true; + } + + // Trigger checkbox changing event + ItemCheckEventArgs ice = new ItemCheckEventArgs(olvi.Index, state, olvi.CheckState); + this.OnItemCheck(ice); + if (ice.NewValue == olvi.CheckState) + return false; + + olvi.CheckState = this.PutCheckState(modelObject, state); + this.RefreshItem(olvi); + + // Trigger check changed event + this.OnItemChecked(new ItemCheckedEventArgs(olvi)); + return true; + } + + /// + /// Toggle the checkedness of the given object. A checked object becomes + /// unchecked; an unchecked or indeterminate object becomes checked. + /// If the list has tristate checkboxes, the order is: + /// unchecked -> checked -> indeterminate -> unchecked ... + /// + /// The model object to be checked + public virtual void ToggleCheckObject(object modelObject) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi == null) + return; + + CheckState newState = CheckState.Checked; + + if (olvi.CheckState == CheckState.Checked) { + newState = this.TriStateCheckBoxes ? CheckState.Indeterminate : CheckState.Unchecked; + } else { + if (olvi.CheckState == CheckState.Indeterminate && this.TriStateCheckBoxes) + newState = CheckState.Unchecked; + } + this.SetObjectCheckedness(modelObject, newState); + } + + /// + /// Toggle the checkbox in the header of the given column + /// + /// Obviously, this is only useful if the column actually has a header checkbox. + /// + public virtual void ToggleHeaderCheckBox(OLVColumn column) { + if (column == null) + return; + + CheckState newState = CalculateToggledCheckState(column.HeaderCheckState, column.HeaderTriStateCheckBox, column.HeaderCheckBoxDisabled); + ChangeHeaderCheckBoxState(column, newState); + } + + private void ChangeHeaderCheckBoxState(OLVColumn column, CheckState newState) { + // Tell the world the checkbox was clicked + HeaderCheckBoxChangingEventArgs args = new HeaderCheckBoxChangingEventArgs(); + args.Column = column; + args.NewCheckState = newState; + + this.OnHeaderCheckBoxChanging(args); + if (args.Cancel || column.HeaderCheckState == args.NewCheckState) + return; + + Stopwatch sw = Stopwatch.StartNew(); + + column.HeaderCheckState = args.NewCheckState; + this.HeaderControl.Invalidate(column); + + if (column.HeaderCheckBoxUpdatesRowCheckBoxes) { + if (column.Index == 0) + this.UpdateAllPrimaryCheckBoxes(column); + else + this.UpdateAllSubItemCheckBoxes(column); + } + + // Debug.WriteLine(String.Format("PERF - Changing row checkboxes on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + + private void UpdateAllPrimaryCheckBoxes(OLVColumn column) { + if (!this.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + if (column.HeaderCheckState == CheckState.Checked) + CheckAll(); + else + UncheckAll(); + } + + private void UpdateAllSubItemCheckBoxes(OLVColumn column) { + if (!column.CheckBoxes || column.HeaderCheckState == CheckState.Indeterminate) + return; + + foreach (object model in this.Objects) + column.PutCheckState(model, column.HeaderCheckState); + this.BuildList(true); + } + + /// + /// Toggle the check at the check box of the given cell + /// + /// + /// + public virtual void ToggleSubItemCheckBox(object rowObject, OLVColumn column) { + CheckState currentState = column.GetCheckState(rowObject); + CheckState newState = CalculateToggledCheckState(currentState, column.TriStateCheckBoxes, false); + + SubItemCheckingEventArgs args = new SubItemCheckingEventArgs(column, this.ModelToItem(rowObject), column.Index, currentState, newState); + this.OnSubItemChecking(args); + if (args.Canceled) + return; + + switch (args.NewValue) { + case CheckState.Checked: + this.CheckSubItem(rowObject, column); + break; + case CheckState.Indeterminate: + this.CheckIndeterminateSubItem(rowObject, column); + break; + case CheckState.Unchecked: + this.UncheckSubItem(rowObject, column); + break; + } + } + + /// + /// Uncheck all rows + /// + public virtual void UncheckAll() + { + this.CheckedObjects = null; + } + + /// + /// Mark the given object as unchecked in the list + /// + /// The model object to be unchecked + public virtual void UncheckObject(object modelObject) { + this.SetObjectCheckedness(modelObject, CheckState.Unchecked); + } + + /// + /// Mark the given objects as unchecked in the list + /// + /// The model object to be checked + public virtual void UncheckObjects(IEnumerable modelObjects) { + foreach (object model in modelObjects) + this.UncheckObject(model); + } + + /// + /// Uncheck the checkbox in the given column header + /// + /// + public virtual void UncheckHeaderCheckBox(OLVColumn column) + { + if (column == null) + return; + + ChangeHeaderCheckBoxState(column, CheckState.Unchecked); + } + + /// + /// Uncheck the check at the given cell + /// + /// + /// + public virtual void UncheckSubItem(object rowObject, OLVColumn column) + { + if (column == null || rowObject == null || !column.CheckBoxes) + return; + + column.PutCheckState(rowObject, CheckState.Unchecked); + this.RefreshObject(rowObject); + } + + #endregion + + #region OLV accessing + + /// + /// Return the column at the given index + /// + /// Index of the column to be returned + /// An OLVColumn, or null if the index is out of bounds + public virtual OLVColumn GetColumn(int index) { + return (index >=0 && index < this.Columns.Count) ? (OLVColumn)this.Columns[index] : null; + } + + /// + /// Return the column at the given title. + /// + /// Name of the column to be returned + /// An OLVColumn + public virtual OLVColumn GetColumn(string name) { + foreach (ColumnHeader column in this.Columns) { + if (column.Text == name) + return (OLVColumn)column; + } + return null; + } + + /// + /// Return a collection of columns that are visible to the given view. + /// Only Tile and Details have columns; all other views have 0 columns. + /// + /// Which view are the columns being calculate for? + /// A list of columns + public virtual List GetFilteredColumns(View view) { + // For both detail and tile view, the first column must be included. Normally, we would + // use the ColumnHeader.Index property, but if the header is not currently part of a ListView + // that property returns -1. So, we track the index of + // the column header, and always include the first header. + + int index = 0; + return this.AllColumns.FindAll(delegate(OLVColumn x) { + return (index++ == 0) || x.IsVisible; + }); + } + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + /// If a filter is installed, this will return the number of items that match the filter. + public virtual int GetItemCount() { + return this.Items.Count; + } + + /// + /// Return the item at the given index + /// + /// Index of the item to be returned + /// An OLVListItem + public virtual OLVListItem GetItem(int index) { + if (index < 0 || index >= this.GetItemCount()) + return null; + + return (OLVListItem)this.Items[index]; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public virtual object GetModelObject(int index) { + OLVListItem item = this.GetItem(index); + return item == null ? null : item.RowObject; + } + + /// + /// Find the item and column that are under the given co-ords + /// + /// X co-ord + /// Y co-ord + /// The column under the given point + /// The item under the given point. Can be null. + public virtual OLVListItem GetItemAt(int x, int y, out OLVColumn hitColumn) { + hitColumn = null; + ListViewHitTestInfo info = this.HitTest(x, y); + if (info.Item == null) + return null; + + if (info.SubItem != null) { + int subItemIndex = info.Item.SubItems.IndexOf(info.SubItem); + hitColumn = this.GetColumn(subItemIndex); + } + + return (OLVListItem)info.Item; + } + + /// + /// Return the sub item at the given index/column + /// + /// Index of the item to be returned + /// Index of the subitem to be returned + /// An OLVListSubItem + public virtual OLVListSubItem GetSubItem(int index, int columnIndex) { + OLVListItem olvi = this.GetItem(index); + return olvi == null ? null : olvi.GetSubItem(columnIndex); + } + + #endregion + + #region Object manipulation + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// This does not work on virtual lists, since virtual lists don't use ListViewGroups + /// for grouping. Use instead. + /// + public virtual void EnsureGroupVisible(ListViewGroup lvg) { + if (!this.ShowGroups || lvg == null) + return; + + int groupIndex = this.Groups.IndexOf(lvg); + if (groupIndex <= 0) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + ListViewGroup previousGroup = this.Groups[groupIndex - 1]; + ListViewItem lastItemInGroup = previousGroup.Items[previousGroup.Items.Count - 1]; + Rectangle r = this.GetItemRect(lastItemInGroup.Index); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Ensure that the given model object is visible + /// + /// The model object to be revealed + public virtual void EnsureModelVisible(Object modelObject) { + int index = this.IndexOf(modelObject); + if (index >= 0) + this.EnsureVisible(index); + } + + /// + /// Return the model object of the row that is selected or null if there is no selection or more than one selection + /// + /// Model object or null + [Obsolete("Use SelectedObject property instead of this method")] + public virtual object GetSelectedObject() { + return this.SelectedObject; + } + + /// + /// Return the model objects of the rows that are selected or an empty collection if there is no selection + /// + /// ArrayList + [Obsolete("Use SelectedObjects property instead of this method")] + public virtual ArrayList GetSelectedObjects() { + return ObjectListView.EnumerableToArray(this.SelectedObjects, false); + } + + /// + /// Return the model object of the row that is checked or null if no row is checked + /// or more than one row is checked + /// + /// Model object or null + /// Use CheckedObject property instead of this method + [Obsolete("Use CheckedObject property instead of this method")] + public virtual object GetCheckedObject() { + return this.CheckedObject; + } + + /// + /// Get the collection of model objects that are checked. + /// + /// Use CheckedObjects property instead of this method + [Obsolete("Use CheckedObjects property instead of this method")] + public virtual ArrayList GetCheckedObjects() { + return ObjectListView.EnumerableToArray(this.CheckedObjects, false); + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public virtual int IndexOf(Object modelObject) { + for (int i = 0; i < this.GetItemCount(); i++) { + if (this.GetModelObject(i).Equals(modelObject)) + return i; + } + return -1; + } + + /// + /// Rebuild the given ListViewItem with the data from its associated model. + /// + /// This method does not resort or regroup the view. It simply updates + /// the displayed data of the given item + public virtual void RefreshItem(OLVListItem olvi) { + olvi.UseItemStyleForSubItems = true; + olvi.SubItems.Clear(); + this.FillInValues(olvi, olvi.RowObject); + this.PostProcessOneRow(olvi.Index, this.GetDisplayOrderOfItemIndex(olvi.Index), olvi); + } + + /// + /// Rebuild the data on the row that is showing the given object. + /// + /// + /// + /// This method does not resort or regroup the view. + /// + /// + /// The given object is *not* used as the source of data for the rebuild. + /// It is only used to locate the matching model in the collection, + /// then that matching model is used as the data source. This distinction is + /// only important in model classes that have overridden the Equals() method. + /// + /// + /// If you want the given model object to replace the pre-existing model, + /// use . + /// + /// + public virtual void RefreshObject(object modelObject) { + this.RefreshObjects(new object[] { modelObject }); + } + + /// + /// Update the rows that are showing the given objects + /// + /// + /// This method does not resort or regroup the view. + /// This method can safely be called from background threads. + /// + public virtual void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null) { + this.ReplaceModel(olvi, modelObject); + this.RefreshItem(olvi); + } + } + } + + private void ReplaceModel(OLVListItem olvi, object newModel) { + if (ReferenceEquals(olvi.RowObject, newModel)) + return; + + this.TakeOwnershipOfObjects(); + ArrayList array = ObjectListView.EnumerableToArray(this.Objects, false); + int i = array.IndexOf(olvi.RowObject); + if (i >= 0) + array[i] = newModel; + + olvi.RowObject = newModel; + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public virtual void RefreshSelectedObjects() { + foreach (ListViewItem lvi in this.SelectedItems) + this.RefreshItem((OLVListItem)lvi); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject) { + this.SelectObject(modelObject, false); + } + + /// + /// Select the row that is displaying the given model object, in addition to any current selection. + /// + /// The object to be selected + /// Should the object be focused as well? + /// Use the property to deselect all other rows + public virtual void SelectObject(object modelObject, bool setFocus) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) { + olvi.Selected = true; + if (setFocus) + olvi.Focused = true; + } + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + public virtual void SelectObjects(IList modelObjects) { + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + OLVListItem olvi = this.ModelToItem(modelObject); + if (olvi != null && olvi.Enabled) + olvi.Selected = true; + } + } + + #endregion + + #region Freezing/Suspending + + /// + /// Get or set whether or not the listview is frozen. When the listview is + /// frozen, it will not update itself. + /// + /// The Frozen property is similar to the methods Freeze()/Unfreeze() + /// except that setting Frozen property to false immediately unfreezes the control + /// regardless of the number of Freeze() calls outstanding. + /// objectListView1.Frozen = false; // unfreeze the control now! + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual bool Frozen { + get { return freezeCount > 0; } + set { + if (value) + Freeze(); + else if (freezeCount > 0) { + freezeCount = 1; + Unfreeze(); + } + } + } + private int freezeCount; + + /// + /// Freeze the listview so that it no longer updates itself. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Freeze() { + if (freezeCount == 0) + DoFreeze(); + + freezeCount++; + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Unfreeze the listview. If this call is the outermost Unfreeze(), + /// the contents of the listview will be rebuilt. + /// + /// Freeze()/Unfreeze() calls nest correctly + public virtual void Unfreeze() { + if (freezeCount <= 0) + return; + + freezeCount--; + if (freezeCount == 0) + DoUnfreeze(); + + this.OnFreezing(new FreezeEventArgs(freezeCount)); + } + + /// + /// Do the actual work required when the listview is frozen + /// + protected virtual void DoFreeze() { + this.BeginUpdate(); + } + + /// + /// Do the actual work required when the listview is unfrozen + /// + protected virtual void DoUnfreeze() + { + this.EndUpdate(); + this.ResizeFreeSpaceFillingColumns(); + this.BuildList(); + } + + /// + /// Returns true if selection events are currently suspended. + /// While selection events are suspended, neither SelectedIndexChanged + /// or SelectionChanged events will be raised. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected bool SelectionEventsSuspended { + get { return this.suspendSelectionEventCount > 0; } + } + + /// + /// Suspend selection events until a matching ResumeSelectionEvents() + /// is called. + /// + /// Calls to this method nest correctly. Every call to SuspendSelectionEvents() + /// must have a matching ResumeSelectionEvents(). + protected void SuspendSelectionEvents() { + this.suspendSelectionEventCount++; + } + + /// + /// Resume raising selection events. + /// + protected void ResumeSelectionEvents() { + Debug.Assert(this.SelectionEventsSuspended, "Mismatched called to ResumeSelectionEvents()"); + this.suspendSelectionEventCount--; + } + + /// + /// Returns a disposable that will disable selection events + /// during a using() block. + /// + /// + protected IDisposable SuspendSelectionEventsDuring() { + return new SuspendSelectionDisposable(this); + } + + /// + /// Implementation only class that suspends and resumes selection + /// events on instance creation and disposal. + /// + private class SuspendSelectionDisposable : IDisposable { + public SuspendSelectionDisposable(ObjectListView objectListView) { + this.objectListView = objectListView; + this.objectListView.SuspendSelectionEvents(); + } + + public void Dispose() { + this.objectListView.ResumeSelectionEvents(); + } + + private readonly ObjectListView objectListView; + } + + #endregion + + #region Column sorting + + /// + /// Sort the items by the last sort column and order + /// + public new void Sort() { + this.Sort(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The name of the column whose values will be used for the sorting + public virtual void Sort(string columnToSortName) { + this.Sort(this.GetColumn(columnToSortName), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The index of the column whose values will be used for the sorting + public virtual void Sort(int columnToSortIndex) { + if (columnToSortIndex >= 0 && columnToSortIndex < this.Columns.Count) + this.Sort(this.GetColumn(columnToSortIndex), this.PrimarySortOrder); + } + + /// + /// Sort the items in the list view by the values in the given column and the last sort order + /// + /// The column whose values will be used for the sorting + public virtual void Sort(OLVColumn columnToSort) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort); }); + } else { + this.Sort(columnToSort, this.PrimarySortOrder); + } + } + + /// + /// Sort the items in the list view by the values in the given column and by the given order. + /// + /// The column whose values will be used for the sorting. + /// If null, the first column will be used. + /// The ordering to be used for sorting. If this is None, + /// this.Sorting and then SortOrder.Ascending will be used + /// If ShowGroups is true, the rows will be grouped by the given column. + /// If AlwaysGroupsByColumn is not null, the rows will be grouped by that column, + /// and the rows within each group will be sorted by the given column. + public virtual void Sort(OLVColumn columnToSort, SortOrder order) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.Sort(columnToSort, order); }); + } else { + this.DoSort(columnToSort, order); + this.PostProcessRows(); + } + } + + private void DoSort(OLVColumn columnToSort, SortOrder order) { + // Sanity checks + if (this.GetItemCount() == 0 || this.Columns.Count == 0) + return; + + // Fill in default values, if the parameters don't make sense + if (this.ShowGroups) { + columnToSort = columnToSort ?? this.GetColumn(0); + if (order == SortOrder.None) { + order = this.Sorting; + if (order == SortOrder.None) + order = SortOrder.Ascending; + } + } + + // Give the world a chance to fiddle with or completely avoid the sorting process + BeforeSortingEventArgs args = this.BuildBeforeSortingEventArgs(columnToSort, order); + this.OnBeforeSorting(args); + if (args.Canceled) + return; + + // Virtual lists don't preserve selection, so we have to do it specifically + // THINK: Do we need to preserve focus too? + IList selection = this.VirtualMode ? this.SelectedObjects : null; + this.SuspendSelectionEvents(); + + this.ClearHotItem(); + + // Finally, do the work of sorting, unless an event handler has already done the sorting for us + if (!args.Handled) { + // Sanity checks + if (args.ColumnToSort != null && args.SortOrder != SortOrder.None) { + if (this.ShowGroups) + this.BuildGroups(args.ColumnToGroupBy, args.GroupByOrder, args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + else if (this.CustomSorter != null) + this.CustomSorter(args.ColumnToSort, args.SortOrder); + else + this.ListViewItemSorter = new ColumnComparer(args.ColumnToSort, args.SortOrder, + args.SecondaryColumnToSort, args.SecondarySortOrder); + } + } + + if (this.ShowSortIndicators) + this.ShowSortIndicator(args.ColumnToSort, args.SortOrder); + + this.PrimarySortColumn = args.ColumnToSort; + this.PrimarySortOrder = args.SortOrder; + + if (selection != null && selection.Count > 0) + this.SelectedObjects = selection; + this.ResumeSelectionEvents(); + + this.RefreshHotItem(); + + this.OnAfterSorting(new AfterSortingEventArgs(args)); + } + + /// + /// Put a sort indicator next to the text of the sort column + /// + public virtual void ShowSortIndicator() { + if (this.ShowSortIndicators && this.PrimarySortOrder != SortOrder.None) + this.ShowSortIndicator(this.PrimarySortColumn, this.PrimarySortOrder); + } + + /// + /// Put a sort indicator next to the text of the given column + /// + /// The column to be marked + /// The sort order in effect on that column + protected virtual void ShowSortIndicator(OLVColumn columnToSort, SortOrder sortOrder) { + int imageIndex = -1; + + if (!NativeMethods.HasBuiltinSortIndicators()) { + // If we can't use builtin image, we have to make and then locate the index of the + // sort indicator we want to use. SortOrder.None doesn't show an image. + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(SORT_INDICATOR_UP_KEY)) + MakeSortIndicatorImages(); + + if (this.SmallImageList != null) + { + string key = sortOrder == SortOrder.Ascending ? SORT_INDICATOR_UP_KEY : SORT_INDICATOR_DOWN_KEY; + imageIndex = this.SmallImageList.Images.IndexOfKey(key); + } + } + + // Set the image for each column + for (int i = 0; i < this.Columns.Count; i++) { + if (columnToSort != null && i == columnToSort.Index) + NativeMethods.SetColumnImage(this, i, sortOrder, imageIndex); + else + NativeMethods.SetColumnImage(this, i, SortOrder.None, -1); + } + } + + /// + /// The name of the image used when a column is sorted ascending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_UP_KEY = "sort-indicator-up"; + + /// + /// The name of the image used when a column is sorted descending + /// + /// This image is only used on pre-XP systems. System images are used for XP and later + public const string SORT_INDICATOR_DOWN_KEY = "sort-indicator-down"; + + /// + /// If the sort indicator images don't already exist, this method will make and install them + /// + protected virtual void MakeSortIndicatorImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + // This arrangement of points works well with (16,16) images, and OK with others + int midX = il.ImageSize.Width / 2; + int midY = (il.ImageSize.Height / 2) - 1; + int deltaX = midX - 2; + int deltaY = deltaX / 2; + + if (il.Images.IndexOfKey(SORT_INDICATOR_UP_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY + deltaY); + Point pt2 = new Point(midX, midY - deltaY - 1); + Point pt3 = new Point(midX + deltaX, midY + deltaY); + il.Images.Add(SORT_INDICATOR_UP_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + if (il.Images.IndexOfKey(SORT_INDICATOR_DOWN_KEY) == -1) { + Point pt1 = new Point(midX - deltaX, midY - deltaY); + Point pt2 = new Point(midX, midY + deltaY); + Point pt3 = new Point(midX + deltaX, midY - deltaY); + il.Images.Add(SORT_INDICATOR_DOWN_KEY, this.MakeTriangleBitmap(il.ImageSize, new Point[] { pt1, pt2, pt3 })); + } + + this.SmallImageList = il; + } + + private Bitmap MakeTriangleBitmap(Size sz, Point[] pts) { + Bitmap bm = new Bitmap(sz.Width, sz.Height); + Graphics g = Graphics.FromImage(bm); + g.FillPolygon(new SolidBrush(Color.Gray), pts); + return bm; + } + + /// + /// Remove any sorting and revert to the given order of the model objects + /// + public virtual void Unsort() { + this.ShowGroups = false; + this.PrimarySortColumn = null; + this.PrimarySortOrder = SortOrder.None; + this.BuildList(); + } + + #endregion + + #region Utilities + + private static CheckState CalculateToggledCheckState(CheckState currentState, bool isTriState, bool isDisabled) + { + if (isDisabled) + return currentState; + switch (currentState) + { + case CheckState.Checked: return isTriState ? CheckState.Indeterminate : CheckState.Unchecked; + case CheckState.Indeterminate: return CheckState.Unchecked; + default: return CheckState.Checked; + } + } + + /// + /// Do the actual work of creating the given list of groups + /// + /// + protected virtual void CreateGroups(IEnumerable groups) { + this.Groups.Clear(); + // The group must be added before it is given items, otherwise an exception is thrown (is this documented?) + foreach (OLVGroup group in groups) { + group.InsertGroupOldStyle(this); + group.SetItemsOldStyle(); + } + } + + /// + /// For some reason, UseItemStyleForSubItems doesn't work for the colors + /// when owner drawing the list, so we have to specifically give each subitem + /// the desired colors + /// + /// The item whose subitems are to be corrected + /// Cells drawn via BaseRenderer don't need this, but it is needed + /// when an owner drawn cell uses DrawDefault=true + protected virtual void CorrectSubItemColors(ListViewItem olvi) { + } + + /// + /// Fill in the given OLVListItem with values of the given row + /// + /// the OLVListItem that is to be stuff with values + /// the model object from which values will be taken + protected virtual void FillInValues(OLVListItem lvi, object rowObject) { + if (this.Columns.Count == 0) + return; + + OLVListSubItem subItem = this.MakeSubItem(rowObject, this.GetColumn(0)); + lvi.SubItems[0] = subItem; + lvi.ImageSelector = subItem.ImageSelector; + + // Give the item the same font/colors as the control + lvi.Font = this.Font; + lvi.BackColor = this.BackColor; + lvi.ForeColor = this.ForeColor; + + // Should the row be selectable? + lvi.Enabled = !this.IsDisabled(rowObject); + + // Only Details and Tile views have subitems + switch (this.View) { + case View.Details: + for (int i = 1; i < this.Columns.Count; i++) { + lvi.SubItems.Add(this.MakeSubItem(rowObject, this.GetColumn(i))); + } + break; + case View.Tile: + for (int i = 1; i < this.Columns.Count; i++) { + OLVColumn column = this.GetColumn(i); + if (column.IsTileViewColumn) + lvi.SubItems.Add(this.MakeSubItem(rowObject, column)); + } + break; + } + + // Should the row be selectable? + if (!lvi.Enabled) { + lvi.UseItemStyleForSubItems = false; + ApplyRowStyle(lvi, this.DisabledItemStyle ?? ObjectListView.DefaultDisabledItemStyle); + } + + // Set the check state of the row, if we are showing check boxes + if (this.CheckBoxes) { + CheckState? state = this.GetCheckState(lvi.RowObject); + if (state.HasValue) + lvi.CheckState = state.Value; + } + + // Give the RowFormatter a chance to mess with the item + if (this.RowFormatter != null) { + this.RowFormatter(lvi); + } + } + + private OLVListSubItem MakeSubItem(object rowObject, OLVColumn column) { + object cellValue = column.GetValue(rowObject); + OLVListSubItem subItem = new OLVListSubItem(cellValue, + column.ValueToString(cellValue), + column.GetImage(rowObject)); + if (this.UseHyperlinks && column.Hyperlink) { + IsHyperlinkEventArgs args = new IsHyperlinkEventArgs(); + args.ListView = this; + args.Model = rowObject; + args.Column = column; + args.Text = subItem.Text; + args.Url = subItem.Text; + args.IsHyperlink = !this.IsDisabled(rowObject); + this.OnIsHyperlink(args); + subItem.Url = args.IsHyperlink ? args.Url : null; + } + + return subItem; + } + + private void ApplyHyperlinkStyle(OLVListItem olvi) { + + for (int i = 0; i < this.Columns.Count; i++) { + OLVListSubItem subItem = olvi.GetSubItem(i); + if (subItem == null) + continue; + OLVColumn column = this.GetColumn(i); + if (column.Hyperlink && !String.IsNullOrEmpty(subItem.Url)) + this.ApplyCellStyle(olvi, i, this.IsUrlVisited(subItem.Url) ? this.HyperlinkStyle.Visited : this.HyperlinkStyle.Normal); + } + } + + + /// + /// Make sure the ListView has the extended style that says to display subitem images. + /// + /// This method must be called after any .NET call that update the extended styles + /// since they seem to erase this setting. + protected virtual void ForceSubItemImagesExStyle() { + // Virtual lists can't show subitem images natively, so don't turn on this flag + if (!this.VirtualMode) + NativeMethods.ForceSubItemImagesExStyle(this); + } + + /// + /// Convert the given image selector to an index into our image list. + /// Return -1 if that's not possible + /// + /// + /// Index of the image in the imageList, or -1 + protected virtual int GetActualImageIndex(Object imageSelector) { + if (imageSelector == null) + return -1; + + if (imageSelector is Int32) + return (int)imageSelector; + + String imageSelectorAsString = imageSelector as String; + if (imageSelectorAsString != null && this.SmallImageList != null) + return this.SmallImageList.Images.IndexOfKey(imageSelectorAsString); + + return -1; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given column + /// + /// The column index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetHeaderToolTip(int columnIndex) { + OLVColumn column = this.GetColumn(columnIndex); + if (column == null) + return null; + String tooltip = column.ToolTipText; + if (this.HeaderToolTipGetter != null) + tooltip = this.HeaderToolTipGetter(column); + return tooltip; + } + + /// + /// Return the tooltip that should be shown when the mouse is hovered over the given cell + /// + /// The column index whose tool tip is to be fetched + /// The row index whose tool tip is to be fetched + /// A string or null if no tool tip is to be shown + public virtual String GetCellToolTip(int columnIndex, int rowIndex) { + if (this.CellToolTipGetter != null) + return this.CellToolTipGetter(this.GetColumn(columnIndex), this.GetModelObject(rowIndex)); + + // Show the URL in the tooltip if it's different to the text + if (columnIndex >= 0) { + OLVListSubItem subItem = this.GetSubItem(rowIndex, columnIndex); + if (subItem != null && !String.IsNullOrEmpty(subItem.Url) && subItem.Url != subItem.Text && + this.HotCellHitLocation == HitTestLocation.Text) + return subItem.Url; + } + + return null; + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public virtual OLVListItem ModelToItem(object modelObject) { + if (modelObject == null) + return null; + + foreach (OLVListItem olvi in this.Items) { + if (olvi.RowObject != null && olvi.RowObject.Equals(modelObject)) + return olvi; + } + return null; + } + + /// + /// Do the work required after the items in a listview have been created + /// + protected virtual void PostProcessRows() { + // If this method is called during a BeginUpdate/EndUpdate pair, changes to the + // Items collection are cached. Getting the Count flushes that cache. +#pragma warning disable 168 +// ReSharper disable once UnusedVariable + int count = this.Items.Count; +#pragma warning restore 168 + + int i = 0; + if (this.ShowGroups) { + foreach (ListViewGroup group in this.Groups) { + foreach (OLVListItem olvi in group.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } else { + foreach (OLVListItem olvi in this.Items) { + this.PostProcessOneRow(olvi.Index, i, olvi); + i++; + } + } + } + + /// + /// Do the work required after one item in a listview have been created + /// + protected virtual void PostProcessOneRow(int rowIndex, int displayIndex, OLVListItem olvi) { + if (this.Columns.Count == 0) + return; + if (this.UseAlternatingBackColors && this.View == View.Details && olvi.Enabled) { + olvi.UseItemStyleForSubItems = true; + olvi.BackColor = displayIndex % 2 == 1 ? this.AlternateRowBackColorOrDefault : this.BackColor; + } + if (this.ShowImagesOnSubItems && !this.VirtualMode) + this.SetSubItemImages(rowIndex, olvi); + + bool needToTriggerFormatCellEvents = this.TriggerFormatRowEvent(rowIndex, displayIndex, olvi); + + // We only need cell level events if we are in details view + if (this.View != View.Details) + return; + + // If we're going to have per cell formatting, we need to copy the formatting + // of the item into each cell, before triggering the cell format events + if (needToTriggerFormatCellEvents) { + PropagateFormatFromRowToCells(olvi); + this.TriggerFormatCellEvents(rowIndex, displayIndex, olvi); + } + + // Similarly, if any cell in the row has hyperlinks, we have to copy formatting + // from the item into each cell before applying the hyperlink style + if (this.UseHyperlinks && olvi.HasAnyHyperlinks) { + PropagateFormatFromRowToCells(olvi); + this.ApplyHyperlinkStyle(olvi); + } + } + + /// + /// Prepare the listview to show alternate row backcolors + /// + /// We cannot rely on lvi.Index in this method. + /// In a straight list, lvi.Index is the display index, and can be used to determine + /// whether the row should be colored. But when organised by groups, lvi.Index is not + /// usable because it still refers to the position in the overall list, not the display order. + /// + [Obsolete("This method is no longer used. Override PostProcessOneRow() to achieve a similar result")] + protected virtual void PrepareAlternateBackColors() { + } + + /// + /// Setup all subitem images on all rows + /// + [Obsolete("This method is not longer maintained and will be removed", false)] + protected virtual void SetAllSubItemImages() { + //if (!this.ShowImagesOnSubItems || this.OwnerDraw) + // return; + + //this.ForceSubItemImagesExStyle(); + + //for (int rowIndex = 0; rowIndex < this.GetItemCount(); rowIndex++) + // SetSubItemImages(rowIndex, this.GetItem(rowIndex)); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item) { + this.SetSubItemImages(rowIndex, item, false); + } + + /// + /// Tell the underlying list control which images to show against the subitems + /// + /// the index at which the item occurs + /// the item whose subitems are to be set + /// will existing images be cleared if no new image is provided? + protected virtual void SetSubItemImages(int rowIndex, OLVListItem item, bool shouldClearImages) { + if (!this.ShowImagesOnSubItems || this.OwnerDraw) + return; + + for (int i = 1; i < item.SubItems.Count; i++) { + this.SetSubItemImage(rowIndex, i, item.GetSubItem(i), shouldClearImages); + } + } + + /// + /// Set the subitem image natively + /// + /// + /// + /// + /// + public virtual void SetSubItemImage(int rowIndex, int subItemIndex, OLVListSubItem subItem, bool shouldClearImages) { + int imageIndex = this.GetActualImageIndex(subItem.ImageSelector); + if (shouldClearImages || imageIndex != -1) + NativeMethods.SetSubItemImage(this, rowIndex, subItemIndex, imageIndex); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// This method has the intentional side-effect of converting our list of objects to an ArrayList. + /// + /// + protected virtual void TakeOwnershipOfObjects() { + if (this.isOwnerOfObjects) + return; + + this.isOwnerOfObjects = true; + + this.objects = ObjectListView.EnumerableToArray(this.objects, true); + } + + /// + /// Trigger FormatRow and possibly FormatCell events for the given item + /// + /// + /// + /// + protected virtual bool TriggerFormatRowEvent(int rowIndex, int displayIndex, OLVListItem olvi) { + FormatRowEventArgs args = new FormatRowEventArgs(); + args.ListView = this; + args.RowIndex = rowIndex; + args.DisplayIndex = displayIndex; + args.Item = olvi; + args.UseCellFormatEvents = this.UseCellFormatEvents; + this.OnFormatRow(args); + return args.UseCellFormatEvents; + } + + /// + /// Trigger FormatCell events for the given item + /// + /// + /// + /// + protected virtual void TriggerFormatCellEvents(int rowIndex, int displayIndex, OLVListItem olvi) { + + PropagateFormatFromRowToCells(olvi); + + // Fire one event per cell + FormatCellEventArgs args2 = new FormatCellEventArgs(); + args2.ListView = this; + args2.RowIndex = rowIndex; + args2.DisplayIndex = displayIndex; + args2.Item = olvi; + for (int i = 0; i < this.Columns.Count; i++) { + args2.ColumnIndex = i; + args2.Column = this.GetColumn(i); + args2.SubItem = olvi.GetSubItem(i); + this.OnFormatCell(args2); + } + } + + private static void PropagateFormatFromRowToCells(OLVListItem olvi) { + // If a cell isn't given its own colors, it *should* use the colors of the item. + // However, there is a bug in the .NET framework where the cell are given + // the colors of the ListView instead of the colors of the row. + + // If we've already done this, don't do it again + if (olvi.UseItemStyleForSubItems == false) + return; + + // So we have to explicitly give each cell the fore and back colors and the font that it should have. + olvi.UseItemStyleForSubItems = false; + Color backColor = olvi.BackColor; + Color foreColor = olvi.ForeColor; + Font font = olvi.Font; + foreach (ListViewItem.ListViewSubItem subitem in olvi.SubItems) { + subitem.BackColor = backColor; + subitem.ForeColor = foreColor; + subitem.Font = font; + } + } + + /// + /// Make the list forget everything -- all rows and all columns + /// + /// Use if you want to remove just the rows. + public virtual void Reset() { + this.Clear(); + this.AllColumns.Clear(); + this.ClearObjects(); + this.PrimarySortColumn = null; + this.SecondarySortColumn = null; + this.ClearDisabledObjects(); + this.ClearPersistentCheckState(); + this.ClearUrlVisited(); + this.ClearHotItem(); + } + + + #endregion + + #region ISupportInitialize Members + + void ISupportInitialize.BeginInit() { + this.Frozen = true; + } + + void ISupportInitialize.EndInit() { + if (this.RowHeight != -1) { + this.SmallImageList = this.SmallImageList; + if (this.CheckBoxes) + this.InitializeStateImageList(); + } + + if (this.UseSubItemCheckBoxes || (this.VirtualMode && this.CheckBoxes)) + this.SetupSubItemCheckBoxes(); + + this.Frozen = false; + } + + #endregion + + #region Image list manipulation + + /// + /// Update our externally visible image list so it holds the same images as our shadow list, but sized correctly + /// + private void SetupBaseImageList() { + // If a row height hasn't been set, or an image list has been give which is the required size, just assign it + if (rowHeight == -1 || + this.View != View.Details || + (this.shadowedImageList != null && this.shadowedImageList.ImageSize.Height == rowHeight)) + this.BaseSmallImageList = this.shadowedImageList; + else { + int width = (this.shadowedImageList == null ? 16 : this.shadowedImageList.ImageSize.Width); + this.BaseSmallImageList = this.MakeResizedImageList(width, rowHeight, shadowedImageList); + } + } + + /// + /// Return a copy of the given source image list, where each image has been resized to be height x height in size. + /// If source is null, an empty image list of the given size is returned + /// + /// Height and width of the new images + /// Height and width of the new images + /// Source of the images (can be null) + /// A new image list + private ImageList MakeResizedImageList(int width, int height, ImageList source) { + ImageList il = new ImageList(); + il.ImageSize = new Size(width, height); + + // If there's nothing to copy, just return the new list + if (source == null) + return il; + + il.TransparentColor = source.TransparentColor; + il.ColorDepth = source.ColorDepth; + + // Fill the imagelist with resized copies from the source + for (int i = 0; i < source.Images.Count; i++) { + Bitmap bm = this.MakeResizedImage(width, height, source.Images[i], source.TransparentColor); + il.Images.Add(bm); + } + + // Give each image the same key it has in the original + foreach (String key in source.Images.Keys) { + il.Images.SetKeyName(source.Images.IndexOfKey(key), key); + } + + return il; + } + + /// + /// Return a bitmap of the given height x height, which shows the given image, centred. + /// + /// Height and width of new bitmap + /// Height and width of new bitmap + /// Image to be centred + /// The background color + /// A new bitmap + private Bitmap MakeResizedImage(int width, int height, Image image, Color transparent) { + Bitmap bm = new Bitmap(width, height); + Graphics g = Graphics.FromImage(bm); + g.Clear(transparent); + int x = Math.Max(0, (bm.Size.Width - image.Size.Width) / 2); + int y = Math.Max(0, (bm.Size.Height - image.Size.Height) / 2); + g.DrawImage(image, x, y, image.Size.Width, image.Size.Height); + return bm; + } + + /// + /// Initialize the state image list with the required checkbox images + /// + protected virtual void InitializeStateImageList() { + if (this.DesignMode) + return; + + if (!this.CheckBoxes) + return; + + if (this.StateImageList == null) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight == -1 ? 16 : this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + if (this.RowHeight != -1 && + this.View == View.Details && + this.StateImageList.ImageSize.Height != this.RowHeight) { + this.StateImageList = new ImageList(); + this.StateImageList.ImageSize = new Size(16, this.RowHeight); + this.StateImageList.ColorDepth = ColorDepth.Depth32Bit; + } + + // The internal logic of ListView cycles through the state images when the primary + // checkbox is clicked. So we have to get exactly the right number of images in the + // image list. + if (this.StateImageList.Images.Count == 0) + this.AddCheckStateBitmap(this.StateImageList, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + if (this.StateImageList.Images.Count <= 1) + this.AddCheckStateBitmap(this.StateImageList, CHECKED_KEY, CheckBoxState.CheckedNormal); + if (this.TriStateCheckBoxes && this.StateImageList.Images.Count <= 2) + this.AddCheckStateBitmap(this.StateImageList, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + else { + if (this.StateImageList.Images.ContainsKey(INDETERMINATE_KEY)) + this.StateImageList.Images.RemoveByKey(INDETERMINATE_KEY); + } + } + + /// + /// The name of the image used when a check box is checked + /// + public const string CHECKED_KEY = "checkbox-checked"; + + /// + /// The name of the image used when a check box is unchecked + /// + public const string UNCHECKED_KEY = "checkbox-unchecked"; + + /// + /// The name of the image used when a check box is Indeterminate + /// + public const string INDETERMINATE_KEY = "checkbox-indeterminate"; + + /// + /// Setup this control so it can display check boxes on subitems + /// (or primary checkboxes in virtual mode) + /// + /// This gives the ListView a small image list, if it doesn't already have one. + public virtual void SetupSubItemCheckBoxes() { + this.ShowImagesOnSubItems = true; + if (this.SmallImageList == null || !this.SmallImageList.Images.ContainsKey(CHECKED_KEY)) + this.InitializeSubItemCheckBoxImages(); + } + + /// + /// Make sure the small image list for this control has checkbox images + /// (used for sub-item checkboxes). + /// + /// + /// + /// This gives the ListView a small image list, if it doesn't already have one. + /// + /// + /// ObjectListView has to manage checkboxes on subitems separate from the checkboxes on each row. + /// The underlying ListView knows about the per-row checkboxes, and to make them work, OLV has to + /// correctly configure the StateImageList. However, the ListView cannot do checkboxes in subitems, + /// so ObjectListView has to handle them in a different fashion. So, per-row checkboxes are controlled + /// by images in the StateImageList, but per-cell checkboxes are handled by images in the SmallImageList. + /// + /// + protected virtual void InitializeSubItemCheckBoxImages() { + // Don't mess with the image list in design mode + if (this.DesignMode) + return; + + ImageList il = this.SmallImageList; + if (il == null) { + il = new ImageList(); + il.ImageSize = new Size(16, 16); + il.ColorDepth = ColorDepth.Depth32Bit; + } + + this.AddCheckStateBitmap(il, CHECKED_KEY, CheckBoxState.CheckedNormal); + this.AddCheckStateBitmap(il, UNCHECKED_KEY, CheckBoxState.UncheckedNormal); + this.AddCheckStateBitmap(il, INDETERMINATE_KEY, CheckBoxState.MixedNormal); + + this.SmallImageList = il; + } + + private void AddCheckStateBitmap(ImageList il, string key, CheckBoxState boxState) { + Bitmap b = new Bitmap(il.ImageSize.Width, il.ImageSize.Height); + Graphics g = Graphics.FromImage(b); + g.Clear(il.TransparentColor); + Point location = new Point(b.Width / 2 - 5, b.Height / 2 - 6); + CheckBoxRenderer.DrawCheckBox(g, location, boxState); + il.Images.Add(key, b); + } + + #endregion + + #region Owner drawing + + /// + /// Owner draw the column header + /// + /// + protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { + e.DrawDefault = true; + base.OnDrawColumnHeader(e); + } + + /// + /// Owner draw the item + /// + /// + protected override void OnDrawItem(DrawListViewItemEventArgs e) { + if (this.View == View.Details) + e.DrawDefault = false; + else { + if (this.ItemRenderer == null) + e.DrawDefault = true; + else { + Object row = ((OLVListItem)e.Item).RowObject; + e.DrawDefault = !this.ItemRenderer.RenderItem(e, e.Graphics, e.Bounds, row); + } + } + + if (e.DrawDefault) + base.OnDrawItem(e); + } + + /// + /// Owner draw a single subitem + /// + /// + protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnDrawSubItem ({0}, {1})", e.ItemIndex, e.ColumnIndex)); + // Don't try to do owner drawing at design time + if (this.DesignMode) { + e.DrawDefault = true; + return; + } + + object rowObject = ((OLVListItem)e.Item).RowObject; + + // Calculate where the subitem should be drawn + Rectangle r = e.Bounds; + + // Get the special renderer for this column. If there isn't one, use the default draw mechanism. + OLVColumn column = this.GetColumn(e.ColumnIndex); + IRenderer renderer = this.GetCellRenderer(rowObject, column); + + // Get a graphics context for the renderer to use. + // But we have more complications. Virtual lists have a nasty habit of drawing column 0 + // whenever there is any mouse move events over a row, and doing it in an un-double-buffered manner, + // which results in nasty flickers! There are also some unbuffered draw when a mouse is first + // hovered over column 0 of a normal row. So, to avoid all complications, + // we always manually double-buffer the drawing. + // Except with Mono, which doesn't seem to handle double buffering at all :-( + BufferedGraphics buffer = BufferedGraphicsManager.Current.Allocate(e.Graphics, r); + Graphics g = buffer.Graphics; + + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + // Finally, give the renderer a chance to draw something + e.DrawDefault = !renderer.RenderSubItem(e, g, r, rowObject); + + if (!e.DrawDefault) + buffer.Render(); + buffer.Dispose(); + } + + #endregion + + #region OnEvent Handling + + /// + /// We need the click count in the mouse up event, but that is always 1. + /// So we have to remember the click count from the preceding mouse down event. + /// + /// + protected override void OnMouseDown(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseDown: {0}, {1}", e.Button, e.Clicks)); + this.lastMouseDownClickCount = e.Clicks; + this.lastMouseDownButton = e.Button; + base.OnMouseDown(e); + } + private int lastMouseDownClickCount; + private MouseButtons lastMouseDownButton; + + /// + /// When the mouse leaves the control, remove any hot item highlighting + /// + /// + protected override void OnMouseLeave(EventArgs e) { + base.OnMouseLeave(e); + + if (!this.Created) + return; + + this.UpdateHotItem(new Point(-1,-1)); + } + + // We could change the hot item on the mouse hover event, but it looks wrong. + + //protected override void OnMouseHover(EventArgs e) { + // System.Diagnostics.Debug.WriteLine(String.Format("OnMouseHover")); + // base.OnMouseHover(e); + // this.UpdateHotItem(this.PointToClient(Cursor.Position)); + //} + + /// + /// When the mouse moves, we might need to change the hot item. + /// + /// + protected override void OnMouseMove(MouseEventArgs e) { + base.OnMouseMove(e); + + if (this.Created) + HandleMouseMove(e.Location); + } + + internal void HandleMouseMove(Point pt) { + //System.Diagnostics.Debug.WriteLine(String.Format("HandleMouseMove: {0}", pt)); + + CellOverEventArgs args = new CellOverEventArgs(); + this.BuildCellEvent(args, pt); + this.OnCellOver(args); + this.MouseMoveHitTest = args.HitTest; + + if (!args.Handled) + this.UpdateHotItem(args.HitTest); + } + + /// + /// Check to see if we need to start editing a cell + /// + /// + protected override void OnMouseUp(MouseEventArgs e) { + //System.Diagnostics.Debug.WriteLine(String.Format("OnMouseUp: {0}, {1}", e.Button, e.Clicks)); + + base.OnMouseUp(e); + + if (!this.Created) + return; + + // Sigh! More complexity. e.Button is not reliable when clicking on group headers. + // The mouse up event for first click on a group header always reports e.Button as None. + // Subsequent mouse up events report the button from the previous event. + // However, mouse down events are correctly reported, so we use the button value from + // the last mouse down event. + if (this.lastMouseDownButton == MouseButtons.Right) { + this.OnRightMouseUp(e); + return; + } + + // What event should we listen for to start cell editing? + // ------------------------------------------------------ + // + // We can't use OnMouseClick, OnMouseDoubleClick, OnClick, or OnDoubleClick + // since they are not triggered for clicks on subitems without Full Row Select. + // + // We could use OnMouseDown, but selecting rows is done in OnMouseUp. This means + // that if we start the editing during OnMouseDown, the editor will automatically + // lose focus when mouse up happens. + // + + // Tell the world about a cell click. If someone handles it, don't do anything else + CellClickEventArgs args = new CellClickEventArgs(); + this.BuildCellEvent(args, e.Location); + args.ClickCount = this.lastMouseDownClickCount; + this.OnCellClick(args); + if (args.Handled) + return; + + // Did the user click a hyperlink? + if (this.UseHyperlinks && + args.HitTest.HitTestLocation == HitTestLocation.Text && + args.SubItem != null && + !String.IsNullOrEmpty(args.SubItem.Url)) { + // We have to delay the running of this process otherwise we can generate + // a series of MouseUp events (don't ask me why) + this.BeginInvoke((MethodInvoker)delegate { this.ProcessHyperlinkClicked(args); }); + } + + // No one handled it so check to see if we should start editing. + if (!this.ShouldStartCellEdit(e)) + return; + + // We only start the edit if the user clicked on the image or text. + if (args.HitTest.HitTestLocation == HitTestLocation.Nothing) + return; + + // We don't edit the primary column by single clicks -- only subitems. + if (this.CellEditActivation == CellEditActivateMode.SingleClick && args.ColumnIndex <= 0) + return; + + // Don't start a cell edit operation when the user clicks on the background of a checkbox column -- it just looks wrong. + // If the user clicks on the actual checkbox, changing the checkbox state is handled elsewhere. + if (args.Column != null && args.Column.CheckBoxes) + return; + + this.EditSubItem(args.Item, args.ColumnIndex); + } + + /// + /// Tell the world that a hyperlink was clicked and if the event isn't handled, + /// do the default processing. + /// + /// + protected virtual void ProcessHyperlinkClicked(CellClickEventArgs e) { + HyperlinkClickedEventArgs args = new HyperlinkClickedEventArgs(); + args.HitTest = e.HitTest; + args.ListView = this; + args.Location = new Point(-1, -1); + args.Item = e.Item; + args.SubItem = e.SubItem; + args.Model = e.Model; + args.ColumnIndex = e.ColumnIndex; + args.Column = e.Column; + args.RowIndex = e.RowIndex; + args.ModifierKeys = Control.ModifierKeys; + args.Url = e.SubItem.Url; + this.OnHyperlinkClicked(args); + if (!args.Handled) { + this.StandardHyperlinkClickedProcessing(args); + } + } + + /// + /// Do the default processing for a hyperlink clicked event, which + /// is to try and open the url. + /// + /// + protected virtual void StandardHyperlinkClickedProcessing(HyperlinkClickedEventArgs args) { + Cursor originalCursor = this.Cursor; + try { + this.Cursor = Cursors.WaitCursor; + System.Diagnostics.Process.Start(args.Url); + } catch (Win32Exception) { + System.Media.SystemSounds.Beep.Play(); + // ignore it + } finally { + this.Cursor = originalCursor; + } + this.MarkUrlVisited(args.Url); + this.RefreshHotItem(); + } + + /// + /// The user right clicked on the control + /// + /// + protected virtual void OnRightMouseUp(MouseEventArgs e) { + CellRightClickEventArgs args = new CellRightClickEventArgs(); + this.BuildCellEvent(args, e.Location); + this.OnCellRightClick(args); + if (!args.Handled) { + if (args.MenuStrip != null) { + args.MenuStrip.Show(this, args.Location); + } + } + } + + internal void BuildCellEvent(CellEventArgs args, Point location) { + BuildCellEvent(args, location, this.OlvHitTest(location.X, location.Y)); + } + + internal void BuildCellEvent(CellEventArgs args, Point location, OlvListViewHitTestInfo hitTest) { + args.HitTest = hitTest; + args.ListView = this; + args.Location = location; + args.Item = hitTest.Item; + args.SubItem = hitTest.SubItem; + args.Model = hitTest.RowObject; + args.ColumnIndex = hitTest.ColumnIndex; + args.Column = hitTest.Column; + if (hitTest.Item != null) + args.RowIndex = hitTest.Item.Index; + args.ModifierKeys = Control.ModifierKeys; + + // In non-details view, we want any hit on an item to act as if it was a hit + // on column 0 -- which, effectively, it was. + if (args.Item != null && args.ListView.View != View.Details) { + args.ColumnIndex = 0; + args.Column = args.ListView.GetColumn(0); + args.SubItem = args.Item.GetSubItem(0); + } + } + + /// + /// This method is called every time a row is selected or deselected. This can be + /// a pain if the user shift-clicks 100 rows. We override this method so we can + /// trigger one event for any number of select/deselects that come from one user action + /// + /// + protected override void OnSelectedIndexChanged(EventArgs e) { + if (this.SelectionEventsSuspended) + return; + + base.OnSelectedIndexChanged(e); + + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Schedule a SelectionChanged event to happen after the next idle event, + /// unless we've already scheduled that to happen. + /// + protected virtual void TriggerDeferredSelectionChangedEvent() { + if (this.SelectionEventsSuspended) + return; + + // If we haven't already scheduled an event, schedule it to be triggered + // By using idle time, we will wait until all select events for the same + // user action have finished before triggering the event. + if (!this.hasIdleHandler) { + this.hasIdleHandler = true; + this.RunWhenIdle(HandleApplicationIdle); + } + } + + /// + /// Called when the handle of the underlying control is created + /// + /// + protected override void OnHandleCreated(EventArgs e) { + //Debug.WriteLine("OnHandleCreated"); + base.OnHandleCreated(e); + + this.Invoke((MethodInvoker)this.OnControlCreated); + } + + /// + /// This method is called after the control has been fully created. + /// + protected virtual void OnControlCreated() { + + //Debug.WriteLine("OnControlCreated"); + + // Force the header control to be created when the listview handle is + HeaderControl hc = this.HeaderControl; + hc.WordWrap = this.HeaderWordWrap; + + // Make sure any overlays that are set on the hot item style take effect + this.HotItemStyle = this.HotItemStyle; + + // Arrange for any group images to be installed after the control is created + NativeMethods.SetGroupImageList(this, this.GroupImageList); + + this.UseExplorerTheme = this.UseExplorerTheme; + + this.RememberDisplayIndicies(); + this.SetGroupSpacing(); + + if (this.VirtualMode) + this.ApplyExtendedStyles(); + } + + #endregion + + #region Cell editing + + /// + /// Should we start editing the cell in response to the given mouse button event? + /// + /// + /// + protected virtual bool ShouldStartCellEdit(MouseEventArgs e) { + if (this.IsCellEditing) + return false; + + if (e.Button != MouseButtons.Left && e.Button != MouseButtons.Right) + return false; + + if ((Control.ModifierKeys & (Keys.Shift | Keys.Control | Keys.Alt)) != 0) + return false; + + if (this.lastMouseDownClickCount == 1 && ( + this.CellEditActivation == CellEditActivateMode.SingleClick || + this.CellEditActivation == CellEditActivateMode.SingleClickAlways)) + return true; + + return (this.lastMouseDownClickCount == 2 && this.CellEditActivation == CellEditActivateMode.DoubleClick); + } + + /// + /// Handle a key press on this control. We specifically look for F2 which edits the primary column, + /// or a Tab character during an edit operation, which tries to start editing on the next (or previous) cell. + /// + /// + /// + protected override bool ProcessDialogKey(Keys keyData) { + + if (this.IsCellEditing) + return this.CellEditKeyEngine.HandleKey(this, keyData); + + // Treat F2 as a request to edit the primary column + if (keyData == Keys.F2) { + this.EditSubItem((OLVListItem)this.FocusedItem, 0); + return base.ProcessDialogKey(keyData); + } + + // Treat Ctrl-C as Copy To Clipboard. + if (this.CopySelectionOnControlC && keyData == (Keys.C | Keys.Control)) { + this.CopySelectionToClipboard(); + return true; + } + + // Treat Ctrl-A as Select All. + if (this.SelectAllOnControlA && keyData == (Keys.A | Keys.Control)) { + this.SelectAll(); + return true; + } + + return base.ProcessDialogKey(keyData); + } + + /// + /// Start an editing operation on the first editable column of the given model. + /// + /// + /// + /// + /// If the model doesn't exist, or there are no editable columns, this method + /// will do nothing. + /// + /// This will start an edit operation regardless of CellActivationMode. + /// + /// + public virtual void EditModel(object rowModel) { + OLVListItem olvItem = this.ModelToItem(rowModel); + if (olvItem == null) + return; + + for (int i = 0; i < olvItem.SubItems.Count; i++) { + var olvColumn = this.GetColumn(i); + if (olvColumn != null && olvColumn.IsEditable) { + this.StartCellEdit(olvItem, i); + return; + } + } + } + + /// + /// Begin an edit operation on the given cell. + /// + /// This performs various sanity checks and passes off the real work to StartCellEdit(). + /// The row to be edited + /// The index of the cell to be edited + public virtual void EditSubItem(OLVListItem item, int subItemIndex) { + if (item == null) + return; + + if (this.CellEditActivation == CellEditActivateMode.None) + return; + + OLVColumn olvColumn = this.GetColumn(subItemIndex); + if (olvColumn == null || !olvColumn.IsEditable) + return; + + if (!item.Enabled) + return; + + this.StartCellEdit(item, subItemIndex); + } + + /// + /// Really start an edit operation on a given cell. The parameters are assumed to be sane. + /// + /// The row to be edited + /// The index of the cell to be edited + public virtual void StartCellEdit(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + if (column == null) + return; + Control c = this.GetCellEditor(item, subItemIndex); + Rectangle cellBounds = this.CalculateCellBounds(item, subItemIndex); + c.Bounds = this.CalculateCellEditorBounds(item, subItemIndex, c.PreferredSize); + + // Try to align the control as the column is aligned. Not all controls support this property + Munger.PutProperty(c, "TextAlign", column.TextAlign); + + // Give the control the value from the model + this.SetControlValue(c, column.GetValue(item.RowObject), column.GetStringValue(item.RowObject)); + + // Give the outside world the chance to munge with the process + this.CellEditEventArgs = new CellEditEventArgs(column, c, cellBounds, item, subItemIndex); + this.OnCellEditStarting(this.CellEditEventArgs); + if (this.CellEditEventArgs.Cancel) + return; + + // The event handler may have completely changed the control, so we need to remember it + this.cellEditor = this.CellEditEventArgs.Control; + + this.Invalidate(); + this.Controls.Add(this.cellEditor); + this.ConfigureControl(); + this.PauseAnimations(true); + } + private Control cellEditor; + internal CellEditEventArgs CellEditEventArgs; + + /// + /// Calculate the bounds of the edit control for the given item/column + /// + /// + /// + /// + /// + public Rectangle CalculateCellEditorBounds(OLVListItem item, int subItemIndex, Size preferredSize) { + Rectangle r = CalculateCellBounds(item, subItemIndex); + + // Calculate the width of the cell's current contents + return this.OwnerDraw + ? CalculateCellEditorBoundsOwnerDrawn(item, subItemIndex, r, preferredSize) + : CalculateCellEditorBoundsStandard(item, subItemIndex, r, preferredSize); + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsOwnerDrawn(OLVListItem item, int subItemIndex, Rectangle r, Size preferredSize) { + IRenderer renderer = this.View == View.Details + ? this.GetCellRenderer(item.RowObject, this.GetColumn(subItemIndex)) + : this.ItemRenderer; + + if (renderer == null) + return r; + + using (Graphics g = this.CreateGraphics()) { + return renderer.GetEditRectangle(g, r, item, subItemIndex, preferredSize); + } + } + + /// + /// Calculate the bounds of the edit control for the given item/column, when the listview + /// is not being owner drawn. + /// + /// + /// + /// + /// + /// A rectangle that is the bounds of the cell editor + protected Rectangle CalculateCellEditorBoundsStandard(OLVListItem item, int subItemIndex, Rectangle cellBounds, Size preferredSize) { + if (this.View == View.Tile) + return cellBounds; + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + // Only Details view needs more processing + if (this.View != View.Details) + return cellBounds; + + // Allow for image (if there is one). + int offset = 0; + object imageSelector = null; + if (subItemIndex == 0) + imageSelector = item.ImageSelector; + else { + // We only check for subitem images if we are owner drawn or showing subitem images + if (this.OwnerDraw || this.ShowImagesOnSubItems) + imageSelector = item.GetSubItem(subItemIndex).ImageSelector; + } + if (this.GetActualImageIndex(imageSelector) != -1) { + offset += this.SmallImageSize.Width + 2; + } + + // Allow for checkbox + if (this.CheckBoxes && this.StateImageList != null && subItemIndex == 0) { + offset += this.StateImageList.ImageSize.Width + 2; + } + + // Allow for indent (first column only) + if (subItemIndex == 0 && item.IndentCount > 0) { + offset += (this.SmallImageSize.Width * item.IndentCount); + } + + // Do the adjustment + if (offset > 0) { + cellBounds.X += offset; + cellBounds.Width -= offset; + } + + return cellBounds; + } + + /// + /// Try to give the given value to the provided control. Fall back to assigning a string + /// if the value assignment fails. + /// + /// A control + /// The value to be given to the control + /// The string to be given if the value doesn't work + protected virtual void SetControlValue(Control control, Object value, String stringValue) { + // Does the control implement our custom interface? + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) { + olvEditor.Value = value; + return; + } + + // Handle combobox explicitly + ComboBox cb = control as ComboBox; + if (cb != null) { + if (cb.Created) + cb.SelectedValue = value; + else + this.BeginInvoke(new MethodInvoker(delegate { + cb.SelectedValue = value; + })); + return; + } + + if (Munger.PutProperty(control, "Value", value)) + return; + + // There wasn't a Value property, or we couldn't set it, so set the text instead + try + { + String valueAsString = value as String; + control.Text = valueAsString ?? stringValue; + } + catch (ArgumentOutOfRangeException) { + // The value couldn't be set via the Text property. + } + } + + /// + /// Setup the given control to be a cell editor + /// + protected virtual void ConfigureControl() { + this.cellEditor.Validating += new CancelEventHandler(CellEditor_Validating); + this.cellEditor.Select(); + } + + /// + /// Return the value that the given control is showing + /// + /// + /// + protected virtual Object GetControlValue(Control control) { + if (control == null) + return null; + + IOlvEditor olvEditor = control as IOlvEditor; + if (olvEditor != null) + return olvEditor.Value; + + TextBox box = control as TextBox; + if (box != null) + return box.Text; + + ComboBox comboBox = control as ComboBox; + if (comboBox != null) + return comboBox.SelectedValue; + + CheckBox checkBox = control as CheckBox; + if (checkBox != null) + return checkBox.Checked; + + try { + return control.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, control, null); + } catch (MissingMethodException) { // Microsoft throws this + return control.Text; + } catch (MissingFieldException) { // Mono throws this + return control.Text; + } + } + + /// + /// Called when the cell editor could be about to lose focus. Time to commit the change + /// + /// + /// + protected virtual void CellEditor_Validating(object sender, CancelEventArgs e) { + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Control.Select(); + e.Cancel = true; + } else + FinishCellEdit(); + } + + /// + /// Return the bounds of the given cell + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex) { + + // It seems on Win7, GetSubItemBounds() does not have the same problems with + // column 0 that it did previously. + + // TODO - Check on XP + + if (this.View != View.Details) + return this.GetItemRect(item.Index, ItemBoundsPortion.Label); + + Rectangle r = item.GetSubItemBounds(subItemIndex); + r.Width -= 1; + r.Height -= 1; + return r; + + // We use ItemBoundsPortion.Label rather than ItemBoundsPortion.Item + // since Label extends to the right edge of the cell, whereas Item gives just the + // current text width. + //return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.Label); + } + + /// + /// Return the bounds of the given cell only until the edge of the current text + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Rectangle + public virtual Rectangle CalculateCellTextBounds(OLVListItem item, int subItemIndex) { + return this.CalculateCellBounds(item, subItemIndex, ItemBoundsPortion.ItemOnly); + } + + private Rectangle CalculateCellBounds(OLVListItem item, int subItemIndex, ItemBoundsPortion portion) { + // SubItem.Bounds works for every subitem, except the first. + if (subItemIndex > 0) + return item.GetSubItemBounds(subItemIndex); + + // For non detail views, we just use the requested portion + Rectangle r = this.GetItemRect(item.Index, portion); + if (r.Y < -10000000 || r.Y > 10000000) { + r.Y = item.Bounds.Y; + } + if (this.View != View.Details) + return r; + + // Finding the bounds of cell 0 should not be a difficult task, but it is. Problems: + // 1) item.SubItem[0].Bounds is always the full bounds of the entire row, not just cell 0. + // 2) if column 0 has been dragged to some other position, the bounds always has a left edge of 0. + + // We avoid both these problems by using the position of sides the column header to calculate + // the sides of the cell + Point sides = NativeMethods.GetScrolledColumnSides(this, 0); + r.X = sides.X + 4; + r.Width = sides.Y - sides.X - 5; + + return r; + } + + /// + /// Calculate the visible bounds of the given column. The column's bottom edge is + /// either the bottom of the last row or the bottom of the control. + /// + /// The bounds of the control itself + /// The column + /// A Rectangle + /// This returns an empty rectangle if the control isn't in Details mode, + /// OR has doesn't have any rows, OR if the given column is hidden. + public virtual Rectangle CalculateColumnVisibleBounds(Rectangle bounds, OLVColumn column) + { + // Sanity checks + if (column == null || + this.View != System.Windows.Forms.View.Details || + this.GetItemCount() == 0 || + !column.IsVisible) + return Rectangle.Empty; + + Point sides = NativeMethods.GetScrolledColumnSides(this, column.Index); + if (sides.X == -1) + return Rectangle.Empty; + + Rectangle columnBounds = new Rectangle(sides.X, bounds.Top, sides.Y - sides.X, bounds.Bottom); + + // Find the bottom of the last item. The column only extends to there. + OLVListItem lastItem = this.GetLastItemInDisplayOrder(); + if (lastItem != null) + { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + return columnBounds; + } + + /// + /// Return a control that can be used to edit the value of the given cell. + /// + /// The row to be edited + /// The index of the cell to be edited + /// A Control to edit the given cell + protected virtual Control GetCellEditor(OLVListItem item, int subItemIndex) { + OLVColumn column = this.GetColumn(subItemIndex); + Object value = column.GetValue(item.RowObject); + + // Does the column have its own special way of creating cell editors? + if (column.EditorCreator != null) { + Control customEditor = column.EditorCreator(item.RowObject, column, value); + if (customEditor != null) + return customEditor; + } + + // Ask the registry for an instance of the appropriate editor. + // Use a default editor if the registry can't create one for us. + Control editor = ObjectListView.EditorRegistry.GetEditor(item.RowObject, column, value ?? this.GetFirstNonNullValue(column)); + return editor ?? this.MakeDefaultCellEditor(column); + } + + /// + /// Get the first non-null value of the given column. + /// At most 1000 rows will be considered. + /// + /// + /// The first non-null value, or null if no non-null values were found + internal object GetFirstNonNullValue(OLVColumn column) { + for (int i = 0; i < Math.Min(this.GetItemCount(), 1000); i++) { + object value = column.GetValue(this.GetModelObject(i)); + if (value != null) + return value; + } + return null; + } + + /// + /// Return a TextBox that can be used as a default cell editor. + /// + /// What column does the cell belong to? + /// + protected virtual Control MakeDefaultCellEditor(OLVColumn column) { + TextBox tb = new TextBox(); + if (column.AutoCompleteEditor) + this.ConfigureAutoComplete(tb, column); + return tb; + } + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + public void ConfigureAutoComplete(TextBox tb, OLVColumn column) { + this.ConfigureAutoComplete(tb, column, 1000); + } + + + /// + /// Configure the given text box to autocomplete unique values + /// from the given column. At most 1000 rows will be considered. + /// + /// The textbox to configure + /// The column used to calculate values + /// Consider only this many rows + public void ConfigureAutoComplete(TextBox tb, OLVColumn column, int maxRows) { + // Don't consider more rows than we actually have + maxRows = Math.Min(this.GetItemCount(), maxRows); + + // Reset any existing autocomplete + tb.AutoCompleteCustomSource.Clear(); + + // CONSIDER: Should we use ClusteringStrategy here? + + // Build a list of unique values, to be used as autocomplete on the editor + Dictionary alreadySeen = new Dictionary(); + List values = new List(); + for (int i = 0; i < maxRows; i++) { + string valueAsString = column.GetStringValue(this.GetModelObject(i)); + if (!String.IsNullOrEmpty(valueAsString) && !alreadySeen.ContainsKey(valueAsString)) { + values.Add(valueAsString); + alreadySeen[valueAsString] = true; + } + } + + tb.AutoCompleteCustomSource.AddRange(values.ToArray()); + tb.AutoCompleteSource = AutoCompleteSource.CustomSource; + tb.AutoCompleteMode = column.AutoCompleteEditorMode; + } + + /// + /// Stop editing a cell and throw away any changes. + /// + public virtual void CancelCellEdit() { + if (!this.IsCellEditing) + return; + + // Let the world know that the user has cancelled the edit operation + this.CellEditEventArgs.Cancel = true; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // Now cleanup the editing process + this.CleanupCellEdit(false, this.CellEditEventArgs.AutoDispose); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + public virtual bool PossibleFinishCellEditing() { + return this.PossibleFinishCellEditing(false); + } + + /// + /// If a cell edit is in progress, finish the edit. + /// + /// Returns false if the finishing process was cancelled + /// (i.e. the cell editor is still on screen) + /// This method does not guarantee that the editing will finish. The validation + /// process can cause the finishing to be aborted. Developers should check the return value + /// or use IsCellEditing property after calling this method to see if the user is still + /// editing a cell. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual bool PossibleFinishCellEditing(bool expectingCellEdit) { + if (!this.IsCellEditing) + return true; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditorValidating(this.CellEditEventArgs); + + if (this.CellEditEventArgs.Cancel) + return false; + + this.FinishCellEdit(expectingCellEdit); + + return true; + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + public virtual void FinishCellEdit() { + this.FinishCellEdit(false); + } + + /// + /// Finish the cell edit operation, writing changed data back to the model object + /// + /// This method does not trigger a Validating event, so it always finishes + /// the cell edit. + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + public virtual void FinishCellEdit(bool expectingCellEdit) { + if (!this.IsCellEditing) + return; + + this.CellEditEventArgs.Cancel = false; + this.CellEditEventArgs.NewValue = this.GetControlValue(this.cellEditor); + this.OnCellEditFinishing(this.CellEditEventArgs); + + // If someone doesn't cancel the editing process, write the value back into the model + if (!this.CellEditEventArgs.Cancel) { + this.CellEditEventArgs.Column.PutValue(this.CellEditEventArgs.RowObject, this.CellEditEventArgs.NewValue); + this.RefreshItem(this.CellEditEventArgs.ListViewItem); + } + + this.CleanupCellEdit(expectingCellEdit, this.CellEditEventArgs.AutoDispose); + + // Tell the world that the cell has been edited + this.OnCellEditFinished(this.CellEditEventArgs); + } + + /// + /// Remove all trace of any existing cell edit operation + /// + /// True if it is likely that another cell is going to be + /// edited immediately after this cell finishes editing + /// True if the cell editor should be disposed + protected virtual void CleanupCellEdit(bool expectingCellEdit, bool disposeOfCellEditor) { + if (this.cellEditor == null) + return; + + this.cellEditor.Validating -= new CancelEventHandler(CellEditor_Validating); + + Control soonToBeOldCellEditor = this.cellEditor; + this.cellEditor = null; + + // Delay cleaning up the cell editor so that if we are immediately going to + // start a new cell edit (because the user pressed Tab) the new cell editor + // has a chance to grab the focus. Without this, the ListView gains focus + // momentarily (after the cell editor is remove and before the new one is created) + // causing the list's selection to flash momentarily. + EventHandler toBeRun = null; + toBeRun = delegate(object sender, EventArgs e) { + Application.Idle -= toBeRun; + this.Controls.Remove(soonToBeOldCellEditor); + if (disposeOfCellEditor) + soonToBeOldCellEditor.Dispose(); + this.Invalidate(); + + if (!this.IsCellEditing) { + if (this.Focused) + this.Select(); + this.PauseAnimations(false); + } + }; + + // We only want to delay the removal of the control if we are expecting another cell + // to be edited. Otherwise, we remove the control immediately. + if (expectingCellEdit) + this.RunWhenIdle(toBeRun); + else + toBeRun(null, null); + } + + #endregion + + #region Hot row and cell handling + + /// + /// Force the hot item to be recalculated + /// + public virtual void ClearHotItem() { + this.UpdateHotItem(new Point(-1, -1)); + } + + /// + /// Force the hot item to be recalculated + /// + public virtual void RefreshHotItem() { + this.UpdateHotItem(this.PointToClient(Cursor.Position)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// Where is the mouse? + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(Point pt) { + this.UpdateHotItem(this.OlvHitTest(pt.X, pt.Y)); + } + + /// + /// The mouse has moved to the given pt. See if the hot item needs to be updated + /// + /// + /// This is the main entry point for hot item handling + protected virtual void UpdateHotItem(OlvListViewHitTestInfo hti) { + + // We only need to do the work of this method when the list has hot parts + // (i.e. some element whose visual appearance changes when under the mouse)? + // Hot item decorations and hyperlinks are obvious, but if we have checkboxes + // or buttons, those are also "hot". It's difficult to quickly detect if there are any + // columns that have checkboxes or buttons, so we just abdicate responsibility and + // provide a property (UseHotControls) which lets the programmer say whether to do + // the hot processing or not. + if (!this.UseHotItem && !this.UseHyperlinks && !this.UseHotControls) + return; + + int newHotRow = hti.RowIndex; + int newHotColumn = hti.ColumnIndex; + HitTestLocation newHotCellHitLocation = hti.HitTestLocation; + HitTestLocationEx newHotCellHitLocationEx = hti.HitTestLocationEx; + OLVGroup newHotGroup = hti.Group; + + // In non-details view, we treat any hit on a row as if it were a hit + // on column 0 -- which (effectively) it is! + if (newHotRow >= 0 && this.View != View.Details) + newHotColumn = 0; + + if (this.HotRowIndex == newHotRow && + this.HotColumnIndex == newHotColumn && + this.HotCellHitLocation == newHotCellHitLocation && + this.HotCellHitLocationEx == newHotCellHitLocationEx && + this.HotGroup == newHotGroup) { + return; + } + + // Trigger the hotitem changed event + HotItemChangedEventArgs args = new HotItemChangedEventArgs(); + args.HotCellHitLocation = newHotCellHitLocation; + args.HotCellHitLocationEx = newHotCellHitLocationEx; + args.HotColumnIndex = newHotColumn; + args.HotRowIndex = newHotRow; + args.HotGroup = newHotGroup; + args.OldHotCellHitLocation = this.HotCellHitLocation; + args.OldHotCellHitLocationEx = this.HotCellHitLocationEx; + args.OldHotColumnIndex = this.HotColumnIndex; + args.OldHotRowIndex = this.HotRowIndex; + args.OldHotGroup = this.HotGroup; + this.OnHotItemChanged(args); + + // Update the state of the control + this.HotRowIndex = newHotRow; + this.HotColumnIndex = newHotColumn; + this.HotCellHitLocation = newHotCellHitLocation; + this.HotCellHitLocationEx = newHotCellHitLocationEx; + this.HotGroup = newHotGroup; + + // If the event handler handled it complete, don't do anything else + if (args.Handled) + return; + +// System.Diagnostics.Debug.WriteLine(String.Format("Changed hot item: {0}", args)); + + this.BeginUpdate(); + try { + this.Invalidate(); + if (args.OldHotRowIndex != -1) + this.UnapplyHotItem(args.OldHotRowIndex); + + if (this.HotRowIndex != -1) { + // Virtual lists apply hot item style when fetching their rows + if (this.VirtualMode) { + this.ClearCachedInfo(); + this.RedrawItems(this.HotRowIndex, this.HotRowIndex, true); + } else { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, hti.Item); + } + } + + if (this.UseHotItem && this.HotItemStyleOrDefault.Overlay != null) { + this.RefreshOverlays(); + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the given row using the current hot item information + /// + /// + protected virtual void UpdateHotRow(OLVListItem olvi) { + this.UpdateHotRow(this.HotRowIndex, this.HotColumnIndex, this.HotCellHitLocation, olvi); + } + + /// + /// Update the given row using the given hot item information + /// + /// + /// + /// + /// + protected virtual void UpdateHotRow(int rowIndex, int columnIndex, HitTestLocation hitLocation, OLVListItem olvi) { + if (rowIndex < 0 || columnIndex < 0) + return; + + // System.Diagnostics.Debug.WriteLine(String.Format("UpdateHotRow: {0}, {1}, {2}", rowIndex, columnIndex, hitLocation)); + + if (this.UseHyperlinks) { + OLVColumn column = this.GetColumn(columnIndex); + OLVListSubItem subItem = olvi.GetSubItem(columnIndex); + if (column != null && column.Hyperlink && hitLocation == HitTestLocation.Text && !String.IsNullOrEmpty(subItem.Url)) { + this.ApplyCellStyle(olvi, columnIndex, this.HyperlinkStyle.Over); + this.Cursor = this.HyperlinkStyle.OverCursor ?? Cursors.Default; + } else { + this.Cursor = Cursors.Default; + } + } + + if (this.UseHotItem) { + if (!olvi.Selected && olvi.Enabled) { + this.ApplyRowStyle(olvi, this.HotItemStyleOrDefault); + } + } + } + + /// + /// Apply a style to the given row + /// + /// + /// + public virtual void ApplyRowStyle(OLVListItem olvi, IItemStyle style) { + if (style == null) + return; + + Font font = style.Font ?? olvi.Font; + + if (style.FontStyle != FontStyle.Regular) + font = new Font(font ?? this.Font, style.FontStyle); + + if (!Equals(font, olvi.Font)) { + if (olvi.UseItemStyleForSubItems) + olvi.Font = font; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.Font = font; + } + } + + if (!style.ForeColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.ForeColor = style.ForeColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.ForeColor = style.ForeColor; + } + } + + if (!style.BackColor.IsEmpty) { + if (olvi.UseItemStyleForSubItems) + olvi.BackColor = style.BackColor; + else { + foreach (ListViewItem.ListViewSubItem x in olvi.SubItems) + x.BackColor = style.BackColor; + } + } + } + + /// + /// Apply a style to a cell + /// + /// + /// + /// + protected virtual void ApplyCellStyle(OLVListItem olvi, int columnIndex, IItemStyle style) { + if (style == null) + return; + + // Don't apply formatting to subitems when not in Details view + if (this.View != View.Details && columnIndex > 0) + return; + + olvi.UseItemStyleForSubItems = false; + + ListViewItem.ListViewSubItem subItem = olvi.SubItems[columnIndex]; + if (style.Font != null) + subItem.Font = style.Font; + + if (style.FontStyle != FontStyle.Regular) + subItem.Font = new Font(subItem.Font ?? olvi.Font ?? this.Font, style.FontStyle); + + if (!style.ForeColor.IsEmpty) + subItem.ForeColor = style.ForeColor; + + if (!style.BackColor.IsEmpty) + subItem.BackColor = style.BackColor; + } + + /// + /// Remove hot item styling from the given row + /// + /// + protected virtual void UnapplyHotItem(int index) { + this.Cursor = Cursors.Default; + // Virtual lists will apply the appropriate formatting when the row is fetched + if (this.VirtualMode) { + if (index < this.VirtualListSize) + this.RedrawItems(index, index, true); + } else { + OLVListItem olvi = this.GetItem(index); + if (olvi != null) { + //this.PostProcessOneRow(index, index, olvi); + this.RefreshItem(olvi); + } + } + } + + + #endregion + + #region Drag and drop + + /// + /// + /// + /// + protected override void OnItemDrag(ItemDragEventArgs e) { + base.OnItemDrag(e); + + if (this.DragSource == null) + return; + + Object data = this.DragSource.StartDrag(this, e.Button, (OLVListItem)e.Item); + if (data != null) { + DragDropEffects effect = this.DoDragDrop(data, this.DragSource.GetAllowedEffects(data)); + this.DragSource.EndDrag(data, effect); + } + } + + /// + /// + /// + /// + protected override void OnDragEnter(DragEventArgs args) { + base.OnDragEnter(args); + + if (this.DropSink != null) + this.DropSink.Enter(args); + } + + /// + /// + /// + /// + protected override void OnDragOver(DragEventArgs args) { + base.OnDragOver(args); + + if (this.DropSink != null) + this.DropSink.Over(args); + } + + /// + /// + /// + /// + protected override void OnDragDrop(DragEventArgs args) { + base.OnDragDrop(args); + + this.lastMouseDownClickCount = 0; // prevent drop events from becoming cell edits + + if (this.DropSink != null) + this.DropSink.Drop(args); + } + + /// + /// + /// + /// + protected override void OnDragLeave(EventArgs e) { + base.OnDragLeave(e); + + if (this.DropSink != null) + this.DropSink.Leave(); + } + + /// + /// + /// + /// + protected override void OnGiveFeedback(GiveFeedbackEventArgs args) { + base.OnGiveFeedback(args); + + if (this.DropSink != null) + this.DropSink.GiveFeedback(args); + } + + /// + /// + /// + /// + protected override void OnQueryContinueDrag(QueryContinueDragEventArgs args) { + base.OnQueryContinueDrag(args); + + if (this.DropSink != null) + this.DropSink.QueryContinue(args); + } + + #endregion + + #region Decorations and Overlays + + /// + /// Add the given decoration to those on this list and make it appear + /// + /// The decoration + /// + /// A decoration scrolls with the listview. An overlay stays fixed in place. + /// + public virtual void AddDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Add(decoration); + this.Invalidate(); + } + + /// + /// Add the given overlay to those on this list and make it appear + /// + /// The overlay + public virtual void AddOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Add(overlay); + this.Invalidate(); + } + + /// + /// Draw all the decorations + /// + /// A Graphics + /// The items that were redrawn and whose decorations should also be redrawn + protected virtual void DrawAllDecorations(Graphics g, List itemsThatWereRedrawn) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + + Rectangle contentRectangle = this.ContentRectangle; + + if (this.HasEmptyListMsg && this.GetItemCount() == 0) { + this.EmptyListMsgOverlay.Draw(this, g, contentRectangle); + } + + // Let the drop sink draw whatever feedback it likes + if (this.DropSink != null) { + this.DropSink.DrawFeedback(g, contentRectangle); + } + + // Draw our item and subitem decorations + foreach (OLVListItem olvi in itemsThatWereRedrawn) { + if (olvi.HasDecoration) { + foreach (IDecoration d in olvi.Decorations) { + d.ListItem = olvi; + d.SubItem = null; + d.Draw(this, g, contentRectangle); + } + } + foreach (OLVListSubItem subItem in olvi.SubItems) { + if (subItem.HasDecoration) { + foreach (IDecoration d in subItem.Decorations) { + d.ListItem = olvi; + d.SubItem = subItem; + d.Draw(this, g, contentRectangle); + } + } + } + if (this.SelectedRowDecoration != null && olvi.Selected && olvi.Enabled) { + this.SelectedRowDecoration.ListItem = olvi; + this.SelectedRowDecoration.SubItem = null; + this.SelectedRowDecoration.Draw(this, g, contentRectangle); + } + } + + // Now draw the specifically registered decorations + foreach (IDecoration decoration in this.Decorations) { + decoration.ListItem = null; + decoration.SubItem = null; + decoration.Draw(this, g, contentRectangle); + } + + // Finally, draw any hot item decoration + if (this.UseHotItem) { + IDecoration hotItemDecoration = this.HotItemStyleOrDefault.Decoration; + if (hotItemDecoration != null) { + hotItemDecoration.ListItem = this.GetItem(this.HotRowIndex); + if (hotItemDecoration.ListItem == null || hotItemDecoration.ListItem.Enabled) { + hotItemDecoration.SubItem = hotItemDecoration.ListItem == null ? null : hotItemDecoration.ListItem.GetSubItem(this.HotColumnIndex); + hotItemDecoration.Draw(this, g, contentRectangle); + } + } + } + + // If we are in design mode, we don't want to use the glass panels, + // so we draw the background overlays here + if (this.DesignMode) { + foreach (IOverlay overlay in this.Overlays) { + overlay.Draw(this, g, contentRectangle); + } + } + } + + /// + /// Is the given decoration shown on this list + /// + /// The overlay + public virtual bool HasDecoration(IDecoration decoration) { + return this.Decorations.Contains(decoration); + } + + /// + /// Is the given overlay shown on this list? + /// + /// The overlay + public virtual bool HasOverlay(IOverlay overlay) { + return this.Overlays.Contains(overlay); + } + + /// + /// Hide any overlays. + /// + /// + /// This is only a temporary hiding -- the overlays will be shown + /// the next time the ObjectListView redraws. + /// + public virtual void HideOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.HideGlass(); + } + } + + /// + /// Create and configure the empty list msg overlay + /// + protected virtual void InitializeEmptyListMsgOverlay() { + TextOverlay overlay = new TextOverlay(); + overlay.Alignment = System.Drawing.ContentAlignment.MiddleCenter; + overlay.TextColor = SystemColors.ControlDarkDark; + overlay.BackColor = Color.BlanchedAlmond; + overlay.BorderColor = SystemColors.ControlDark; + overlay.BorderWidth = 2.0f; + this.EmptyListMsgOverlay = overlay; + } + + /// + /// Initialize the standard image and text overlays + /// + protected virtual void InitializeStandardOverlays() { + this.OverlayImage = new ImageOverlay(); + this.AddOverlay(this.OverlayImage); + this.OverlayText = new TextOverlay(); + this.AddOverlay(this.OverlayText); + } + + /// + /// Make sure that any overlays are visible. + /// + public virtual void ShowOverlays() { + // If we shouldn't show overlays, then don't create glass panels + if (!this.ShouldShowOverlays()) + return; + + // Make sure that each overlay has its own glass panels + if (this.Overlays.Count != this.glassPanels.Count) { + foreach (IOverlay overlay in this.Overlays) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel == null) { + glassPanel = new GlassPanelForm(); + glassPanel.Bind(this, overlay); + this.glassPanels.Add(glassPanel); + } + } + } + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.ShowGlass(); + } + } + + private bool ShouldShowOverlays() { + // If we are in design mode, we dont show the overlays + if (this.DesignMode) + return false; + + // If we are explicitly not using overlays, also don't show them + if (!this.UseOverlays) + return false; + + // If there are no overlays, guess... + if (!this.HasOverlays) + return false; + + // If we don't have 32-bit display, alpha blending doesn't work, so again, no overlays + // TODO: This should actually figure out which screen(s) the control is on, and make sure + // that each one is 32-bit. + if (Screen.PrimaryScreen.BitsPerPixel < 32) + return false; + + // Finally, we can show the overlays + return true; + } + + private GlassPanelForm FindGlassPanelForOverlay(IOverlay overlay) { + return this.glassPanels.Find(delegate(GlassPanelForm x) { return x.Overlay == overlay; }); + } + + /// + /// Refresh the display of the overlays + /// + public virtual void RefreshOverlays() { + foreach (GlassPanelForm glassPanel in this.glassPanels) { + glassPanel.Invalidate(); + } + } + + /// + /// Refresh the display of just one overlays + /// + public virtual void RefreshOverlay(IOverlay overlay) { + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) + glassPanel.Invalidate(); + } + + /// + /// Remove the given decoration from this list + /// + /// The decoration to remove + public virtual void RemoveDecoration(IDecoration decoration) { + if (decoration == null) + return; + this.Decorations.Remove(decoration); + this.Invalidate(); + } + + /// + /// Remove the given overlay to those on this list + /// + /// The overlay + public virtual void RemoveOverlay(IOverlay overlay) { + if (overlay == null) + return; + this.Overlays.Remove(overlay); + GlassPanelForm glassPanel = this.FindGlassPanelForOverlay(overlay); + if (glassPanel != null) { + this.glassPanels.Remove(glassPanel); + glassPanel.Unbind(); + glassPanel.Dispose(); + } + } + + #endregion + + #region Filtering + + /// + /// Create a filter that will enact all the filtering currently installed + /// on the visible columns. + /// + public virtual IModelFilter CreateColumnFilter() { + List filters = new List(); + foreach (OLVColumn column in this.Columns) { + IModelFilter filter = column.ValueBasedFilter; + if (filter != null) + filters.Add(filter); + } + return (filters.Count == 0) ? null : new CompositeAllFilter(filters); + } + + /// + /// Do the actual work of filtering + /// + /// + /// + /// + /// + protected virtual IEnumerable FilterObjects(IEnumerable originalObjects, IModelFilter aModelFilter, IListFilter aListFilter) { + // Being cautious + originalObjects = originalObjects ?? new ArrayList(); + + // Tell the world to filter the objects. If they do so, don't do anything else +// ReSharper disable PossibleMultipleEnumeration + FilterEventArgs args = new FilterEventArgs(originalObjects); + this.OnFilter(args); + if (args.FilteredObjects != null) + return args.FilteredObjects; + + // Apply a filter to the list as a whole + if (aListFilter != null) + originalObjects = aListFilter.Filter(originalObjects); + + // Apply the object filter if there is one + if (aModelFilter != null) { + ArrayList filteredObjects = new ArrayList(); + foreach (object model in originalObjects) { + if (aModelFilter.Filter(model)) + filteredObjects.Add(model); + } + originalObjects = filteredObjects; + } + + return originalObjects; +// ReSharper restore PossibleMultipleEnumeration + } + + /// + /// Remove all column filtering. + /// + public virtual void ResetColumnFiltering() { + foreach (OLVColumn column in this.Columns) { + column.ValuesChosenForFiltering.Clear(); + } + this.UpdateColumnFiltering(); + } + + /// + /// Update the filtering of this ObjectListView based on the value filtering + /// defined in each column + /// + public virtual void UpdateColumnFiltering() { + //List filters = new List(); + //IModelFilter columnFilter = this.CreateColumnFilter(); + //if (columnFilter != null) + // filters.Add(columnFilter); + //if (this.AdditionalFilter != null) + // filters.Add(this.AdditionalFilter); + //this.ModelFilter = filters.Count == 0 ? null : new CompositeAllFilter(filters); + + if (this.AdditionalFilter == null) + this.ModelFilter = this.CreateColumnFilter(); + else { + IModelFilter columnFilter = this.CreateColumnFilter(); + if (columnFilter == null) + this.ModelFilter = this.AdditionalFilter; + else { + List filters = new List(); + filters.Add(columnFilter); + filters.Add(this.AdditionalFilter); + this.ModelFilter = new CompositeAllFilter(filters); + } + } + } + + /// + /// When some setting related to filtering changes, this method is called. + /// + protected virtual void UpdateFiltering() { + this.BuildList(true); + } + + /// + /// Update all renderers with the currently installed model filter + /// + protected virtual void NotifyNewModelFilter() { + IFilterAwareRenderer filterAware = this.DefaultRenderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + + foreach (OLVColumn column in this.AllColumns) { + filterAware = column.Renderer as IFilterAwareRenderer; + if (filterAware != null) + filterAware.Filter = this.ModelFilter; + } + } + + #endregion + + #region Persistent check state + + /// + /// Gets the checkedness of the given model. + /// + /// The model + /// The checkedness of the model. Defaults to unchecked. + protected virtual CheckState GetPersistentCheckState(object model) { + CheckState state; + if (model != null && this.CheckStateMap.TryGetValue(model, out state)) + return state; + return CheckState.Unchecked; + } + + /// + /// Remember the check state of the given model object + /// + /// The model to be remembered + /// The model's checkedness + /// The state given to the method + protected virtual CheckState SetPersistentCheckState(object model, CheckState state) { + if (model == null) + return CheckState.Unchecked; + + this.CheckStateMap[model] = state; + return state; + } + + /// + /// Forget any persistent checkbox state + /// + protected virtual void ClearPersistentCheckState() { + this.CheckStateMap = null; + } + + #endregion + + #region Implementation variables + + private bool isOwnerOfObjects; // does this ObjectListView own the Objects collection? + private bool hasIdleHandler; // has an Idle handler already been installed? + private bool hasResizeColumnsHandler; // has an idle handler been installed which will handle column resizing? + private bool isInWmPaintEvent; // is a WmPaint event currently being handled? + private bool shouldDoCustomDrawing; // should the list do its custom drawing? + private bool isMarqueSelecting; // Is a marque selection in progress? + private int suspendSelectionEventCount; // How many unmatched SuspendSelectionEvents() calls have been made? + + private readonly List glassPanels = new List(); // The transparent panel that draws overlays + private Dictionary visitedUrlMap = new Dictionary(); // Which urls have been visited? + + // TODO + //private CheckBoxSettings checkBoxSettings = new CheckBoxSettings(); + + #endregion + } +} diff --git a/ObjectListView/ObjectListView.shfb b/ObjectListView/ObjectListView.shfb new file mode 100644 index 0000000..514d58b --- /dev/null +++ b/ObjectListView/ObjectListView.shfb @@ -0,0 +1,47 @@ + + + + + + + All ObjectListView appears in this namespace + + + ObjectListViewDemo demonstrates helpful techniques when using an ObjectListView + Summary, Parameter, Returns, AutoDocumentCtors, Namespace + InheritedMembers, Protected, SealedProtected + + + .\Help\ + + + True + True + HtmlHelp1x + True + False + 2.0.50727 + True + False + True + False + + ObjectListView Reference + Documentation + en-US + + (c) Copyright 2006-2008 Phillip Piper All Rights Reserved + phillip.piper@gmail.com + + + Local + Msdn + Blank + Prototype + Guid + CSharp + False + AboveNamespaces + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.csproj b/ObjectListView/ObjectListView2019.csproj new file mode 100644 index 0000000..70e616b --- /dev/null +++ b/ObjectListView/ObjectListView2019.csproj @@ -0,0 +1,54 @@ + + + net6.0-windows + Library + BrightIdeasSoftware + ObjectListView + true + olv-keyfile.snk + %24/ObjectListView/trunk/ObjectListView + . + https://grammarian.visualstudio.com + {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} + false + true + true + + + 1 + bin\Debug\ObjectListView.XML + + + bin\Release\ObjectListView.XML + + + + + + + + + + + + + + Component + + + Component + + + + + + + Designer + + + + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.nuspec b/ObjectListView/ObjectListView2019.nuspec new file mode 100644 index 0000000..3e883c6 --- /dev/null +++ b/ObjectListView/ObjectListView2019.nuspec @@ -0,0 +1,22 @@ + + + + ObjectListView.Official + ObjectListView (Official) + 2.9.2-alpha2 + Phillip Piper + Phillip Piper + http://www.gnu.org/licenses/gpl.html + http://objectlistview.sourceforge.net + http://objectlistview.sourceforge.net/cs/_static/index-icon.png + true + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + ObjectListView is a .NET ListView wired on caffeine, guarana and steroids. + More calmly, it is a C# wrapper around a .NET ListView, which makes the ListView much easier to use and teaches it lots of neat new tricks. + v2.9.2 Fixed cell edit bounds problem in TreeListView, plus other small issues. + v2.9.1 Added CellRendererGetter to allow each cell to have a different renderer, plus fixes a few small bugs. + v2.9 adds buttons to cells, fixed some formatting bugs, and completely rewrote the demo to be much easier to understand. + Copyright 2006-2016 Bright Ideas Software + .Net WinForms Net20 Net40 ListView Controls + + \ No newline at end of file diff --git a/ObjectListView/Properties/AssemblyInfo.cs b/ObjectListView/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..515899d --- /dev/null +++ b/ObjectListView/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// 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("ObjectListView")] +[assembly: AssemblyDescription("A much easier to use ListView and friends")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Bright Ideas Software")] +[assembly: AssemblyProduct("ObjectListView")] +[assembly: AssemblyCopyright("Copyright © 2006-2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ef28c7a8-77ae-442d-abc3-bb023fa31e57")] + +// 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 Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("2.9.1.*")] +[assembly: AssemblyFileVersion("2.9.1.0")] +[assembly: AssemblyInformationalVersion("2.9.1")] +[assembly: System.CLSCompliant(true)] diff --git a/ObjectListView/Properties/Resources.Designer.cs b/ObjectListView/Properties/Resources.Designer.cs new file mode 100644 index 0000000..1b86d07 --- /dev/null +++ b/ObjectListView/Properties/Resources.Designer.cs @@ -0,0 +1,113 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace BrightIdeasSoftware.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BrightIdeasSoftware.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ClearFiltering { + get { + object obj = ResourceManager.GetObject("ClearFiltering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap ColumnFilterIndicator { + get { + object obj = ResourceManager.GetObject("ColumnFilterIndicator", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap Filtering { + get { + object obj = ResourceManager.GetObject("Filtering", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortAscending { + get { + object obj = ResourceManager.GetObject("SortAscending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap SortDescending { + get { + object obj = ResourceManager.GetObject("SortDescending", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/ObjectListView/Properties/Resources.resx b/ObjectListView/Properties/Resources.resx new file mode 100644 index 0000000..b017d6a --- /dev/null +++ b/ObjectListView/Properties/Resources.resx @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\clear-filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + + ..\Resources\filter-icons3.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\filter.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-ascending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\sort-descending.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/ObjectListView/Rendering/Adornments.cs b/ObjectListView/Rendering/Adornments.cs new file mode 100644 index 0000000..a159cfa --- /dev/null +++ b/ObjectListView/Rendering/Adornments.cs @@ -0,0 +1,743 @@ +/* + * Adornments - Adornments are the basis for overlays and decorations -- things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 16/08/2009 1:02 AM + * + * Change log: + * v2.6 + * 2012-08-18 JPP - Correctly dispose of brush and pen resources + * v2.3 + * 2009-09-22 JPP - Added Wrap property to TextAdornment, to allow text wrapping to be disabled + * - Added ShrinkToWidth property to ImageAdornment + * 2009-08-17 JPP - Initial version + * + * To do: + * - Use IPointLocator rather than Corners + * - Add RotationCenter property rather than always using middle center + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// An adornment is the common base for overlays and decorations. + /// + public class GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the corner of the adornment that will be positioned at the reference corner + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment AdornmentCorner { + get { return this.adornmentCorner; } + set { this.adornmentCorner = value; } + } + private System.Drawing.ContentAlignment adornmentCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets location within the reference rectangle where the adornment will be drawn + /// + /// This is a simplified interface to ReferenceCorner and AdornmentCorner + [Category("ObjectListView"), + Description("How will the adornment be aligned"), + DefaultValue(System.Drawing.ContentAlignment.BottomRight), + NotifyParentProperty(true)] + public System.Drawing.ContentAlignment Alignment { + get { return this.alignment; } + set { + this.alignment = value; + this.ReferenceCorner = value; + this.AdornmentCorner = value; + } + } + private System.Drawing.ContentAlignment alignment = System.Drawing.ContentAlignment.BottomRight; + + /// + /// Gets or sets the offset by which the position of the adornment will be adjusted + /// + [Category("ObjectListView"), + Description("The offset by which the position of the adornment will be adjusted"), + DefaultValue(typeof(Size), "0,0")] + public Size Offset { + get { return this.offset; } + set { this.offset = value; } + } + private Size offset = new Size(); + + /// + /// Gets or sets the point of the reference rectangle to which the adornment will be aligned. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Drawing.ContentAlignment ReferenceCorner { + get { return this.referenceCorner; } + set { this.referenceCorner = value; } + } + private System.Drawing.ContentAlignment referenceCorner = System.Drawing.ContentAlignment.MiddleCenter; + + /// + /// Gets or sets the degree of rotation by which the adornment will be transformed. + /// The centre of rotation will be the center point of the adornment. + /// + [Category("ObjectListView"), + Description("The degree of rotation that will be applied to the adornment."), + DefaultValue(0), + NotifyParentProperty(true)] + public int Rotation { + get { return this.rotation; } + set { this.rotation = value; } + } + private int rotation; + + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + [Category("ObjectListView"), + Description("The transparency of this adornment. 0 is completely transparent, 255 is completely opaque."), + DefaultValue(128)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + + #region Calculations + + /// + /// Calculate the location of rectangle of the given size, + /// so that it's indicated corner would be at the given point. + /// + /// The point + /// + /// Which corner will be positioned at the reference point + /// + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.TopLeft) -> Point(50, 100) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.MiddleCenter) -> Point(45, 90) + /// CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.BottomRight) -> Point(40, 80) + public virtual Point CalculateAlignedPosition(Point pt, Size size, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return pt; + case System.Drawing.ContentAlignment.TopCenter: + return new Point(pt.X - (size.Width / 2), pt.Y); + case System.Drawing.ContentAlignment.TopRight: + return new Point(pt.X - size.Width, pt.Y); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(pt.X, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(pt.X - size.Width, pt.Y - (size.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(pt.X, pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(pt.X - (size.Width / 2), pt.Y - size.Height); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(pt.X - size.Width, pt.Y - size.Height); + } + + // Should never reach here + return pt; + } + + /// + /// Calculate a rectangle that has the given size which is positioned so that + /// its alignment point is at the reference location of the given rect. + /// + /// + /// + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz) { + return this.CreateAlignedRectangle(r, sz, this.ReferenceCorner, this.AdornmentCorner, this.Offset); + } + + /// + /// Create a rectangle of the given size which is positioned so that + /// its indicated corner is at the indicated corner of the reference rect. + /// + /// + /// + /// + /// + /// + /// + /// + /// Creates a rectangle so that its bottom left is at the centre of the reference: + /// corner=BottomLeft, referenceCorner=MiddleCenter + /// This is a powerful concept that takes some getting used to, but is + /// very neat once you understand it. + /// + public virtual Rectangle CreateAlignedRectangle(Rectangle r, Size sz, + System.Drawing.ContentAlignment corner, System.Drawing.ContentAlignment referenceCorner, Size offset) { + Point referencePt = this.CalculateCorner(r, referenceCorner); + Point topLeft = this.CalculateAlignedPosition(referencePt, sz, corner); + return new Rectangle(topLeft + offset, sz); + } + + /// + /// Return the point at the indicated corner of the given rectangle (it doesn't + /// have to be a corner, but a named location) + /// + /// The reference rectangle + /// Which point of the rectangle should be returned? + /// A point + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.TopLeft) -> Point(0, 0) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.MiddleCenter) -> Point(25, 50) + /// CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.BottomRight) -> Point(50, 100) + public virtual Point CalculateCorner(Rectangle r, System.Drawing.ContentAlignment corner) { + switch (corner) { + case System.Drawing.ContentAlignment.TopLeft: + return new Point(r.Left, r.Top); + case System.Drawing.ContentAlignment.TopCenter: + return new Point(r.X + (r.Width / 2), r.Top); + case System.Drawing.ContentAlignment.TopRight: + return new Point(r.Right, r.Top); + case System.Drawing.ContentAlignment.MiddleLeft: + return new Point(r.Left, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleCenter: + return new Point(r.X + (r.Width / 2), r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.MiddleRight: + return new Point(r.Right, r.Top + (r.Height / 2)); + case System.Drawing.ContentAlignment.BottomLeft: + return new Point(r.Left, r.Bottom); + case System.Drawing.ContentAlignment.BottomCenter: + return new Point(r.X + (r.Width / 2), r.Bottom); + case System.Drawing.ContentAlignment.BottomRight: + return new Point(r.Right, r.Bottom); + } + + // Should never reach here + return r.Location; + } + + /// + /// Given the item and the subitem, calculate its bounds. + /// + /// + /// + /// + public virtual Rectangle CalculateItemBounds(OLVListItem item, OLVListSubItem subItem) { + if (item == null) + return Rectangle.Empty; + + if (subItem == null) + return item.Bounds; + + return item.GetSubItemBounds(item.SubItems.IndexOf(subItem)); + } + + #endregion + + #region Commands + + /// + /// Apply any specified rotation to the Graphic content. + /// + /// The Graphics to be transformed + /// The rotation will be around the centre of this rect + protected virtual void ApplyRotation(Graphics g, Rectangle r) { + if (this.Rotation == 0) + return; + + // THINK: Do we want to reset the transform? I think we want to push a new transform + g.ResetTransform(); + Matrix m = new Matrix(); + m.RotateAt(this.Rotation, new Point(r.Left + r.Width / 2, r.Top + r.Height / 2)); + g.Transform = m; + } + + /// + /// Reverse the rotation created by ApplyRotation() + /// + /// + protected virtual void UnapplyRotation(Graphics g) { + if (this.Rotation != 0) + g.ResetTransform(); + } + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + public class ImageAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the image that will be drawn + /// + [Category("ObjectListView"), + Description("The image that will be drawn"), + DefaultValue(null), + NotifyParentProperty(true)] + public Image Image { + get { return this.image; } + set { this.image = value; } + } + private Image image; + + /// + /// Gets or sets if the image will be shrunk to fit with its horizontal bounds + /// + [Category("ObjectListView"), + Description("Will the image be shrunk to fit within its width?"), + DefaultValue(false)] + public bool ShrinkToWidth { + get { return this.shrinkToWidth; } + set { this.shrinkToWidth = value; } + } + private bool shrinkToWidth; + + #endregion + + #region Commands + + /// + /// Draw the image in its specified location + /// + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void DrawImage(Graphics g, Rectangle r) { + if (this.ShrinkToWidth) + this.DrawScaledImage(g, r, this.Image, this.Transparency); + else + this.DrawImage(g, r, this.Image, this.Transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image != null) + this.DrawImage(g, r, image, image.Size, transparency); + } + + /// + /// Draw the image in its specified location + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How big should the image be? + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawImage(Graphics g, Rectangle r, Image image, Size sz, int transparency) { + if (image == null) + return; + + Rectangle adornmentBounds = this.CreateAlignedRectangle(r, sz); + try { + this.ApplyRotation(g, adornmentBounds); + this.DrawTransparentBitmap(g, adornmentBounds, image, transparency); + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Draw the image in its specified location, scaled so that it is not wider + /// than the given rectangle. Height is scaled proportional to the width. + /// + /// The image to be drawn + /// The Graphics used for drawing + /// The bounds of the rendering + /// How transparent should the image be (0 is completely transparent, 255 is opaque) + public virtual void DrawScaledImage(Graphics g, Rectangle r, Image image, int transparency) { + if (image == null) + return; + + // If the image is too wide to be drawn in the space provided, proportionally scale it down. + // Too tall images are not scaled. + Size size = image.Size; + if (image.Width > r.Width) { + float scaleRatio = (float)r.Width / (float)image.Width; + size.Height = (int)((float)image.Height * scaleRatio); + size.Width = r.Width - 1; + } + + this.DrawImage(g, r, image, size, transparency); + } + + /// + /// Utility to draw a bitmap transparently. + /// + /// + /// + /// + /// + protected virtual void DrawTransparentBitmap(Graphics g, Rectangle r, Image image, int transparency) { + ImageAttributes imageAttributes = null; + if (transparency != 255) { + imageAttributes = new ImageAttributes(); + float a = (float)transparency / 255.0f; + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 1, 0, 0}, + new float[] {0, 0, 0, a, 0}, + new float[] {0, 0, 0, 0, 1}}; + + imageAttributes.SetColorMatrix(new ColorMatrix(colorMatrixElements)); + } + + g.DrawImage(image, + r, // destination rectangle + 0, 0, image.Size.Width, image.Size.Height, // source rectangle + GraphicsUnit.Pixel, + imageAttributes); + } + + #endregion + } + + /// + /// An adornment that will draw text + /// + public class TextAdornment : GraphicAdornment + { + #region Public properties + + /// + /// Gets or sets the background color of the text + /// Set this to Color.Empty to not draw a background + /// + [Category("ObjectListView"), + Description("The background color of the text"), + DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush BackgroundBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.BackColor)); + } + } + + /// + /// Gets or sets the color of the border around the billboard. + /// Set this to Color.Empty to remove the border + /// + [Category("ObjectListView"), + Description("The color of the border around the text"), + DefaultValue(typeof(Color), "")] + public Color BorderColor { + get { return this.borderColor; } + set { this.borderColor = value; } + } + private Color borderColor = Color.Empty; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Pen BorderPen { + get { + return new Pen(Color.FromArgb(this.workingTransparency, this.BorderColor), this.BorderWidth); + } + } + + /// + /// Gets or sets the width of the border around the text + /// + [Category("ObjectListView"), + Description("The width of the border around the text"), + DefaultValue(0.0f)] + public float BorderWidth { + get { return this.borderWidth; } + set { this.borderWidth = value; } + } + private float borderWidth; + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + [Category("ObjectListView"), + Description("How rounded should the corners of the border be? 0 means no rounding."), + DefaultValue(16.0f), + NotifyParentProperty(true)] + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the font that will be used to draw the text + /// + [Category("ObjectListView"), + Description("The font that will be used to draw the text"), + DefaultValue(null), + NotifyParentProperty(true)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets the font that will be used to draw the text or a reasonable default + /// + [Browsable(false)] + public Font FontOrDefault { + get { + return this.Font ?? new Font("Tahoma", 16); + } + } + + /// + /// Does this text have a background? + /// + [Browsable(false)] + public bool HasBackground { + get { + return this.BackColor != Color.Empty; + } + } + + /// + /// Does this overlay have a border? + /// + [Browsable(false)] + public bool HasBorder { + get { + return this.BorderColor != Color.Empty && this.BorderWidth > 0; + } + } + + /// + /// Gets or sets the maximum width of the text. Text longer than this will wrap. + /// 0 means no maximum. + /// + [Category("ObjectListView"), + Description("The maximum width the text (0 means no maximum). Text longer than this will wrap"), + DefaultValue(0)] + public int MaximumTextWidth { + get { return this.maximumTextWidth; } + set { this.maximumTextWidth = value; } + } + private int maximumTextWidth; + + /// + /// Gets or sets the formatting that should be used on the text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual StringFormat StringFormat { + get { + if (this.stringFormat == null) { + this.stringFormat = new StringFormat(); + this.stringFormat.Alignment = StringAlignment.Center; + this.stringFormat.LineAlignment = StringAlignment.Center; + this.stringFormat.Trimming = StringTrimming.EllipsisCharacter; + if (!this.Wrap) + this.stringFormat.FormatFlags = StringFormatFlags.NoWrap; + } + return this.stringFormat; + } + set { this.stringFormat = value; } + } + private StringFormat stringFormat; + + /// + /// Gets or sets the text that will be drawn + /// + [Category("ObjectListView"), + Description("The text that will be drawn over the top of the ListView"), + DefaultValue(null), + NotifyParentProperty(true), + Localizable(true)] + public string Text { + get { return this.text; } + set { this.text = value; } + } + private string text; + + /// + /// Gets the brush that will be used to paint the text + /// + [Browsable(false)] + public Brush TextBrush { + get { + return new SolidBrush(Color.FromArgb(this.workingTransparency, this.TextColor)); + } + } + + /// + /// Gets or sets the color of the text + /// + [Category("ObjectListView"), + Description("The color of the text"), + DefaultValue(typeof(Color), "DarkBlue"), + NotifyParentProperty(true)] + public Color TextColor { + get { return this.textColor; } + set { this.textColor = value; } + } + private Color textColor = Color.DarkBlue; + + /// + /// Gets or sets whether the text will wrap when it exceeds its bounds + /// + [Category("ObjectListView"), + Description("Will the text wrap?"), + DefaultValue(true)] + public bool Wrap { + get { return this.wrap; } + set { this.wrap = value; } + } + private bool wrap = true; + + #endregion + + #region Implementation + + /// + /// Draw our text with our stored configuration in relation to the given + /// reference rectangle + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + public virtual void DrawText(Graphics g, Rectangle r) { + this.DrawText(g, r, this.Text, this.Transparency); + } + + /// + /// Draw the given text with our stored configuration + /// + /// The Graphics used for drawing + /// The reference rectangle in relation to which the text will be drawn + /// The text to draw + /// How opaque should be text be + public virtual void DrawText(Graphics g, Rectangle r, string s, int transparency) { + if (String.IsNullOrEmpty(s)) + return; + + Rectangle textRect = this.CalculateTextBounds(g, r, s); + this.DrawBorderedText(g, textRect, s, transparency); + } + + /// + /// Draw the text with a border + /// + /// The Graphics used for drawing + /// The bounds within which the text should be drawn + /// The text to draw + /// How opaque should be text be + protected virtual void DrawBorderedText(Graphics g, Rectangle textRect, string text, int transparency) { + Rectangle borderRect = textRect; + borderRect.Inflate((int)this.BorderWidth / 2, (int)this.BorderWidth / 2); + borderRect.Y -= 1; // Looker better a little higher + + try { + this.ApplyRotation(g, textRect); + using (GraphicsPath path = this.GetRoundedRect(borderRect, this.CornerRounding)) { + this.workingTransparency = transparency; + if (this.HasBackground) { + using (Brush b = this.BackgroundBrush) + g.FillPath(b, path); + } + + using (Brush b = this.TextBrush) + g.DrawString(text, this.FontOrDefault, b, textRect, this.StringFormat); + + if (this.HasBorder) { + using (Pen p = this.BorderPen) + g.DrawPath(p, path); + } + } + } + finally { + this.UnapplyRotation(g); + } + } + + /// + /// Return the rectangle that will be the precise bounds of the displayed text + /// + /// + /// + /// + /// The bounds of the text + protected virtual Rectangle CalculateTextBounds(Graphics g, Rectangle r, string s) { + int maxWidth = this.MaximumTextWidth <= 0 ? r.Width : this.MaximumTextWidth; + SizeF sizeF = g.MeasureString(s, this.FontOrDefault, maxWidth, this.StringFormat); + Size size = new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + return this.CreateAlignedRectangle(r, size); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected virtual GraphicsPath GetRoundedRect(Rectangle rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + + private int workingTransparency; + } +} diff --git a/ObjectListView/Rendering/Decorations.cs b/ObjectListView/Rendering/Decorations.cs new file mode 100644 index 0000000..91f21d6 --- /dev/null +++ b/ObjectListView/Rendering/Decorations.cs @@ -0,0 +1,973 @@ +/* + * Decorations - Images, text or other things that can be rendered onto an ObjectListView + * + * Author: Phillip Piper + * Date: 19/08/2009 10:56 PM + * + * Change log: + * 2018-04-30 JPP - Added ColumnEdgeDecoration. + * TintedColumnDecoration now uses common base class, ColumnDecoration. + * v2.5 + * 2011-04-04 JPP - Added ability to have a gradient background on BorderDecoration + * v2.4 + * 2010-04-15 JPP - Tweaked LightBoxDecoration a little + * v2.3 + * 2009-09-23 JPP - Added LeftColumn and RightColumn to RowBorderDecoration + * 2009-08-23 JPP - Added LightBoxDecoration + * 2009-08-19 JPP - Initial version. Separated from Overlays.cs + * + * To do: + * + * Copyright (C) 2009-2018 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A decoration is an overlay that draws itself in relation to a given row or cell. + /// Decorations scroll when the listview scrolls. + /// + public interface IDecoration : IOverlay + { + /// + /// Gets or sets the row that is to be decorated + /// + OLVListItem ListItem { get; set; } + + /// + /// Gets or sets the subitem that is to be decorated + /// + OLVListSubItem SubItem { get; set; } + } + + /// + /// An AbstractDecoration is a safe do-nothing implementation of the IDecoration interface + /// + public class AbstractDecoration : IDecoration + { + #region IDecoration Members + + /// + /// Gets or sets the row that is to be decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the subitem that is to be decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Public properties + + /// + /// Gets the bounds of the decorations row + /// + public Rectangle RowBounds { + get { + if (this.ListItem == null) + return Rectangle.Empty; + else + return this.ListItem.Bounds; + } + } + + /// + /// Get the bounds of the decorations cell + /// + public Rectangle CellBounds { + get { + if (this.ListItem == null || this.SubItem == null) + return Rectangle.Empty; + else + return this.ListItem.GetSubItemBounds(this.ListItem.SubItems.IndexOf(this.SubItem)); + } + } + + #endregion + + #region IOverlay Members + + /// + /// Draw the decoration + /// + /// + /// + /// + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + } + + + /// + /// This decoration draws something over a given column. + /// Subclasses must override DrawDecoration() + /// + public class ColumnDecoration : AbstractDecoration { + #region Constructors + + /// + /// Create a ColumnDecoration + /// + public ColumnDecoration() { + } + + /// + /// Create a ColumnDecoration + /// + /// + public ColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column ?? throw new ArgumentNullException("column"); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the column that will be decorated + /// + public OLVColumn ColumnToDecorate { + get { return this.columnToDecorate; } + set { this.columnToDecorate = value; } + } + private OLVColumn columnToDecorate; + + /// + /// Gets or sets the pen that will be used to draw the column decoration + /// + public Pen Pen { + get { + return this.pen ?? Pens.DarkSlateBlue; + } + set { + if (this.pen == value) + return; + + if (this.pen != null) { + this.pen.Dispose(); + } + + this.pen = value; + } + } + private Pen pen; + + #endregion + + #region IOverlay Members + + /// + /// Draw a decoration over our column + /// + /// + /// This overlay only works when: + /// - the list is in Details view + /// - there is at least one row + /// - there is a selected column (or a specified tint column) + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + + if (olv.View != System.Windows.Forms.View.Details) + return; + + if (olv.GetItemCount() == 0) + return; + + if (this.ColumnToDecorate == null) + return; + + Point sides = NativeMethods.GetScrolledColumnSides(olv, this.ColumnToDecorate.Index); + if (sides.X == -1) + return; + + Rectangle columnBounds = new Rectangle(sides.X, r.Top, sides.Y - sides.X, r.Bottom); + + // Find the bottom of the last item. The decoration should extend only to there. + OLVListItem lastItem = olv.GetLastItemInDisplayOrder(); + if (lastItem != null) { + Rectangle lastItemBounds = lastItem.Bounds; + if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom) + columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top; + } + + // Delegate the drawing of the actual decoration + this.DrawDecoration(olv, g, r, columnBounds); + } + + /// + /// Subclasses should override this to draw exactly what they want + /// + /// + /// + /// + /// + public virtual void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.DrawRectangle(this.Pen, columnBounds); + } + + #endregion + } + + /// + /// This decoration draws a slight tint over a column of the + /// owning listview. If no column is explicitly set, the selected + /// column in the listview will be used. + /// The selected column is normally the sort column, but does not have to be. + /// + public class TintedColumnDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a TintedColumnDecoration + /// + public TintedColumnDecoration() { + this.Tint = Color.FromArgb(15, Color.Blue); + } + + /// + /// Create a TintedColumnDecoration + /// + /// + public TintedColumnDecoration(OLVColumn column) + : this() { + this.ColumnToDecorate = column; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the color that will be 'tinted' over the selected column + /// + public Color Tint { + get { return this.tint; } + set { + if (this.tint == value) + return; + + if (this.tintBrush != null) { + this.tintBrush.Dispose(); + this.tintBrush = null; + } + + this.tint = value; + this.tintBrush = new SolidBrush(this.tint); + } + } + private Color tint; + private SolidBrush tintBrush; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + g.FillRectangle(this.tintBrush, columnBounds); + } + + #endregion + } + + /// + /// Specify on which side edge the decoration will be drawn + /// + public enum ColumnEdge { + Left, + Right + } + + /// + /// This decoration draws a line on the edge(s) of its given column + /// + /// + /// Like all decorations, this draws over the contents of list view. + /// If you set the Pen too wide enough, you may overwrite the contents + /// of the column (if alignment is Inside) or the surrounding columns (if alignment is Outside) + /// + public class ColumnEdgeDecoration : ColumnDecoration { + #region Constructors + + /// + /// Create a ColumnEdgeDecoration + /// + public ColumnEdgeDecoration() { + } + + /// + /// Create a ColumnEdgeDecoration which draws a line over the right edges of the column (by default) + /// + /// + /// + /// + /// + public ColumnEdgeDecoration(OLVColumn column, Pen pen = null, ColumnEdge edge = ColumnEdge.Right, float xOffset = 0) + : this() { + this.ColumnToDecorate = column; + this.Pen = pen; + this.Edge = edge; + this.XOffset = xOffset; + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether this decoration will draw a line on the left or right edge of the column + /// + public ColumnEdge Edge { + get { return edge; } + set { edge = value; } + } + private ColumnEdge edge = ColumnEdge.Right; + + /// + /// Gets or sets the horizontal offset from centered at which the line will be drawn + /// + public float XOffset { + get { return xOffset; } + set { xOffset = value; } + } + private float xOffset; + + #endregion + + #region IOverlay Members + + public override void DrawDecoration(ObjectListView olv, Graphics g, Rectangle r, Rectangle columnBounds) { + float left = CalculateEdge(columnBounds); + g.DrawLine(this.Pen, left, columnBounds.Top, left, columnBounds.Bottom); + + } + + private float CalculateEdge(Rectangle columnBounds) { + float tweak = this.XOffset + (this.Pen.Width <= 2 ? 0 : 1); + int x = this.Edge == ColumnEdge.Left ? columnBounds.Left : columnBounds.Right; + return tweak + x - this.Pen.Width / 2; + } + + #endregion + } + + /// + /// This decoration draws an optionally filled border around a rectangle. + /// Subclasses must override CalculateBounds(). + /// + public class BorderDecoration : AbstractDecoration + { + #region Constructors + + /// + /// Create a BorderDecoration + /// + public BorderDecoration() + : this(new Pen(Color.FromArgb(64, Color.Blue), 1)) { + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + public BorderDecoration(Pen borderPen) { + this.BorderPen = borderPen; + } + + /// + /// Create a BorderDecoration + /// + /// The pen used to draw the border + /// The brush used to fill the rectangle + public BorderDecoration(Pen borderPen, Brush fill) { + this.BorderPen = borderPen; + this.FillBrush = fill; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the pen that will be used to draw the border + /// + public Pen BorderPen { + get { return this.borderPen; } + set { this.borderPen = value; } + } + private Pen borderPen; + + /// + /// Gets or sets the padding that will be added to the bounds of the item + /// before drawing the border and fill. + /// + public Size BoundsPadding { + get { return this.boundsPadding; } + set { this.boundsPadding = value; } + } + private Size boundsPadding = new Size(-1, 2); + + /// + /// How rounded should the corners of the border be? 0 means no rounding. + /// + /// If this value is too large, the edges of the border will appear odd. + public float CornerRounding { + get { return this.cornerRounding; } + set { this.cornerRounding = value; } + } + private float cornerRounding = 16.0f; + + /// + /// Gets or sets the brush that will be used to fill the border + /// + /// This value is ignored when using gradient brush + public Brush FillBrush { + get { return this.fillBrush; } + set { this.fillBrush = value; } + } + private Brush fillBrush = new SolidBrush(Color.FromArgb(64, Color.Blue)); + + /// + /// Gets or sets the color that will be used as the start of a gradient fill. + /// + /// This and FillGradientTo must be given value to show a gradient + public Color? FillGradientFrom { + get { return this.fillGradientFrom; } + set { this.fillGradientFrom = value; } + } + private Color? fillGradientFrom; + + /// + /// Gets or sets the color that will be used as the end of a gradient fill. + /// + /// This and FillGradientFrom must be given value to show a gradient + public Color? FillGradientTo { + get { return this.fillGradientTo; } + set { this.fillGradientTo = value; } + } + private Color? fillGradientTo; + + /// + /// Gets or sets the fill mode that will be used for the gradient. + /// + public LinearGradientMode FillGradientMode { + get { return this.fillGradientMode; } + set { this.fillGradientMode = value; } + } + private LinearGradientMode fillGradientMode = LinearGradientMode.Vertical; + + #endregion + + #region IOverlay Members + + /// + /// Draw a filled border + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle bounds = this.CalculateBounds(); + if (!bounds.IsEmpty) + this.DrawFilledBorder(g, bounds); + } + + #endregion + + #region Subclass responsibility + + /// + /// Subclasses should override this to say where the border should be drawn + /// + /// + protected virtual Rectangle CalculateBounds() { + return Rectangle.Empty; + } + + #endregion + + #region Implementation utilities + + /// + /// Do the actual work of drawing the filled border + /// + /// + /// + protected void DrawFilledBorder(Graphics g, Rectangle bounds) { + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillGradientFrom != null && this.FillGradientTo != null) { + if (this.FillBrush != null) + this.FillBrush.Dispose(); + this.FillBrush = new LinearGradientBrush(bounds, this.FillGradientFrom.Value, this.FillGradientTo.Value, this.FillGradientMode); + } + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + /// + /// Create a GraphicsPath that represents a round cornered rectangle. + /// + /// + /// If this is 0 or less, the rectangle will not be rounded. + /// + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter <= 0.0f) { + path.AddRectangle(rect); + } else { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } + + return path; + } + + #endregion + } + + /// + /// Instances of this class draw a border around the decorated row + /// + public class RowBorderDecoration : BorderDecoration + { + /// + /// Gets or sets the index of the left most column to be used for the border + /// + public int LeftColumn { + get { return leftColumn; } + set { leftColumn = value; } + } + private int leftColumn = -1; + + /// + /// Gets or sets the index of the right most column to be used for the border + /// + public int RightColumn { + get { return rightColumn; } + set { rightColumn = value; } + } + private int rightColumn = -1; + + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + Rectangle bounds = this.RowBounds; + if (this.ListItem == null) + return bounds; + + if (this.LeftColumn >= 0) { + Rectangle leftCellBounds = this.ListItem.GetSubItemBounds(this.LeftColumn); + if (!leftCellBounds.IsEmpty) { + bounds.Width = bounds.Right - leftCellBounds.Left; + bounds.X = leftCellBounds.Left; + } + } + + if (this.RightColumn >= 0) { + Rectangle rightCellBounds = this.ListItem.GetSubItemBounds(this.RightColumn); + if (!rightCellBounds.IsEmpty) { + bounds.Width = rightCellBounds.Right - bounds.Left; + } + } + + return bounds; + } + } + + /// + /// Instances of this class draw a border around the decorated subitem. + /// + public class CellBorderDecoration : BorderDecoration + { + /// + /// Calculate the boundaries of the border + /// + /// + protected override Rectangle CalculateBounds() { + return this.CellBounds; + } + } + + /// + /// This decoration puts a border around the cell being edited and + /// optionally "lightboxes" the cell (makes the rest of the control dark). + /// + public class EditingCellBorderDecoration : BorderDecoration + { + #region Life and death + + /// + /// Create a EditingCellBorderDecoration + /// + public EditingCellBorderDecoration() { + this.FillBrush = null; + this.BorderPen = new Pen(Color.DarkBlue, 2); + this.CornerRounding = 8; + this.BoundsPadding = new Size(10, 8); + + } + + /// + /// Create a EditingCellBorderDecoration + /// + /// Should the decoration use a lighbox display style? + public EditingCellBorderDecoration(bool useLightBox) : this() + { + this.UseLightbox = useLightbox; + } + + #endregion + + #region Configuration properties + + /// + /// Gets or set whether the decoration should make the rest of + /// the control dark when a cell is being edited + /// + /// If this is true, FillBrush is used to overpaint + /// the control. + public bool UseLightbox { + get { return this.useLightbox; } + set { + if (this.useLightbox == value) + return; + this.useLightbox = value; + if (this.useLightbox) { + if (this.FillBrush == null) + this.FillBrush = new SolidBrush(Color.FromArgb(64, Color.Black)); + } + } + } + private bool useLightbox; + + #endregion + + #region Implementation + + /// + /// Draw the decoration + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!olv.IsCellEditing) + return; + + Rectangle bounds = olv.CellEditor.Bounds; + if (bounds.IsEmpty) + return; + + bounds.Inflate(this.BoundsPadding); + GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding); + if (this.FillBrush != null) { + if (this.UseLightbox) { + using (Region newClip = new Region(r)) { + newClip.Exclude(path); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } else { + g.FillPath(this.FillBrush, path); + } + } + if (this.BorderPen != null) + g.DrawPath(this.BorderPen, path); + } + + #endregion + } + + /// + /// This decoration causes everything *except* the row under the mouse to be overpainted + /// with a tint, making the row under the mouse stand out in comparison. + /// The darker and more opaque the fill color, the more obvious the + /// decorated row becomes. + /// + public class LightBoxDecoration : BorderDecoration + { + /// + /// Create a LightBoxDecoration + /// + public LightBoxDecoration() { + this.BoundsPadding = new Size(-1, 4); + this.CornerRounding = 8.0f; + this.FillBrush = new SolidBrush(Color.FromArgb(72, Color.Black)); + } + + /// + /// Draw a tint over everything in the ObjectListView except the + /// row under the mouse. + /// + /// + /// + /// + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (!r.Contains(olv.PointToClient(Cursor.Position))) + return; + + Rectangle bounds = this.RowBounds; + if (bounds.IsEmpty) { + if (olv.View == View.Tile) + g.FillRectangle(this.FillBrush, r); + return; + } + + using (Region newClip = new Region(r)) { + bounds.Inflate(this.BoundsPadding); + newClip.Exclude(this.GetRoundedRect(bounds, this.CornerRounding)); + Region originalClip = g.Clip; + g.Clip = newClip; + g.FillRectangle(this.FillBrush, r); + g.Clip = originalClip; + } + } + } + + /// + /// Instances of this class put an Image over the row/cell that it is decorating + /// + public class ImageDecoration : ImageAdornment, IDecoration + { + #region Constructors + + /// + /// Create an image decoration + /// + public ImageDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create an image decoration + /// + /// + public ImageDecoration(Image image) + : this() { + this.Image = image; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, int transparency) + : this() { + this.Image = image; + this.Transparency = transparency; + } + + /// + /// Create an image decoration + /// + /// + /// + public ImageDecoration(Image image, ContentAlignment alignment) + : this() { + this.Image = image; + this.Alignment = alignment; + } + + /// + /// Create an image decoration + /// + /// + /// + /// + public ImageDecoration(Image image, int transparency, ContentAlignment alignment) + : this() { + this.Image = image; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawImage(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } + + /// + /// Instances of this class draw some text over the row/cell that they are decorating + /// + public class TextDecoration : TextAdornment, IDecoration + { + #region Constructors + + /// + /// Create a TextDecoration + /// + public TextDecoration() { + this.Alignment = ContentAlignment.MiddleRight; + } + + /// + /// Create a TextDecoration + /// + /// + public TextDecoration(string text) + : this() { + this.Text = text; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, int transparency) + : this() { + this.Text = text; + this.Transparency = transparency; + } + + /// + /// Create a TextDecoration + /// + /// + /// + public TextDecoration(string text, ContentAlignment alignment) + : this() { + this.Text = text; + this.Alignment = alignment; + } + + /// + /// Create a TextDecoration + /// + /// + /// + /// + public TextDecoration(string text, int transparency, ContentAlignment alignment) + : this() { + this.Text = text; + this.Transparency = transparency; + this.Alignment = alignment; + } + + #endregion + + #region IDecoration Members + + /// + /// Gets or sets the item being decorated + /// + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + private OLVListItem listItem; + + /// + /// Gets or sets the sub item being decorated + /// + public OLVListSubItem SubItem { + get { return subItem; } + set { subItem = value; } + } + private OLVListSubItem subItem; + + + #endregion + + #region Commands + + /// + /// Draw this decoration + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + this.DrawText(g, this.CalculateItemBounds(this.ListItem, this.SubItem)); + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Overlays.cs b/ObjectListView/Rendering/Overlays.cs new file mode 100644 index 0000000..d103601 --- /dev/null +++ b/ObjectListView/Rendering/Overlays.cs @@ -0,0 +1,302 @@ +/* + * Overlays - Images, text or other things that can be rendered over the top of a ListView + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * v2.3 + * 2009-08-17 JPP - Overlays now use Adornments + * - Added ITransparentOverlay interface. Overlays can now have separate transparency levels + * 2009-08-10 JPP - Moved decoration related code to new file + * v2.2.1 + * 200-07-24 JPP - TintedColumnDecoration now works when last item is a member of a collapsed + * group (well, it no longer crashes). + * v2.2 + * 2009-06-01 JPP - Make sure that TintedColumnDecoration reaches to the last item in group view + * 2009-05-05 JPP - Unified BillboardOverlay text rendering with that of TextOverlay + * 2009-04-30 JPP - Added TintedColumnDecoration + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +namespace BrightIdeasSoftware +{ + /// + /// The interface for an object which can draw itself over the top of + /// an ObjectListView. + /// + public interface IOverlay + { + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + void Draw(ObjectListView olv, Graphics g, Rectangle r); + } + + /// + /// An interface for an overlay that supports variable levels of transparency + /// + public interface ITransparentOverlay : IOverlay + { + /// + /// Gets or sets the transparency of the overlay. + /// 0 is completely transparent, 255 is completely opaque. + /// + int Transparency { get; set; } + } + + /// + /// A null implementation of the IOverlay interface + /// + public class AbstractOverlay : ITransparentOverlay + { + #region IOverlay Members + + /// + /// Draw this overlay + /// + /// The ObjectListView that is being overlaid + /// The Graphics onto the given OLV + /// The content area of the OLV + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + } + + #endregion + + #region ITransparentOverlay Members + + /// + /// How transparent should this overlay be? + /// + [Category("ObjectListView"), + Description("How transparent should this overlay be"), + DefaultValue(128), + NotifyParentProperty(true)] + public int Transparency { + get { return this.transparency; } + set { this.transparency = Math.Min(255, Math.Max(0, value)); } + } + private int transparency = 128; + + #endregion + } + + /// + /// An overlay that will draw an image over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class ImageOverlay : ImageAdornment, ITransparentOverlay + { + /// + /// Create an ImageOverlay + /// + public ImageOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawImage(g, insetRect, this.Image, 255); + } + + #endregion + } + + /// + /// An overlay that will draw text over the top of the ObjectListView + /// + [TypeConverter("BrightIdeasSoftware.Design.OverlayConverter")] + public class TextOverlay : TextAdornment, ITransparentOverlay + { + /// + /// Create a TextOverlay + /// + public TextOverlay() { + this.Alignment = System.Drawing.ContentAlignment.BottomRight; + } + + #region Public properties + + /// + /// Gets or sets the horizontal inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("The horizontal inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetX { + get { return this.insetX; } + set { this.insetX = Math.Max(0, value); } + } + private int insetX = 20; + + /// + /// Gets or sets the vertical inset by which the position of the overlay will be adjusted + /// + [Category("ObjectListView"), + Description("Gets or sets the vertical inset by which the position of the overlay will be adjusted"), + DefaultValue(20), + NotifyParentProperty(true)] + public int InsetY { + get { return this.insetY; } + set { this.insetY = Math.Max(0, value); } + } + private int insetY = 20; + + /// + /// Gets or sets whether the border will be drawn with rounded corners + /// + [Browsable(false), + Obsolete("Use CornerRounding instead", false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool RoundCorneredBorder { + get { return this.CornerRounding > 0; } + set { + if (value) + this.CornerRounding = 16.0f; + else + this.CornerRounding = 0.0f; + } + } + + #endregion + + #region Commands + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + Rectangle insetRect = r; + insetRect.Inflate(-this.InsetX, -this.InsetY); + // We hard code a transparency of 255 here since transparency is handled by the glass panel + this.DrawText(g, insetRect, this.Text, 255); + } + + #endregion + } + + /// + /// A Billboard overlay is a TextOverlay positioned at an absolute point + /// + public class BillboardOverlay : TextOverlay + { + /// + /// Create a BillboardOverlay + /// + public BillboardOverlay() { + this.Transparency = 255; + this.BackColor = Color.PeachPuff; + this.TextColor = Color.Black; + this.BorderColor = Color.Empty; + this.Font = new Font("Tahoma", 10); + } + + /// + /// Gets or sets where should the top left of the billboard be placed + /// + public Point Location { + get { return this.location; } + set { this.location = value; } + } + private Point location; + + /// + /// Draw this overlay + /// + /// The ObjectListView being decorated + /// The Graphics used for drawing + /// The bounds of the rendering + public override void Draw(ObjectListView olv, Graphics g, Rectangle r) { + if (String.IsNullOrEmpty(this.Text)) + return; + + // Calculate the bounds of the text, and then move it to where it should be + Rectangle textRect = this.CalculateTextBounds(g, r, this.Text); + textRect.Location = this.Location; + + // Make sure the billboard is within the bounds of the List, as far as is possible + if (textRect.Right > r.Width) + textRect.X = Math.Max(r.Left, r.Width - textRect.Width); + if (textRect.Bottom > r.Height) + textRect.Y = Math.Max(r.Top, r.Height - textRect.Height); + + this.DrawBorderedText(g, textRect, this.Text, 255); + } + } +} diff --git a/ObjectListView/Rendering/Renderers.cs b/ObjectListView/Rendering/Renderers.cs new file mode 100644 index 0000000..dac6a62 --- /dev/null +++ b/ObjectListView/Rendering/Renderers.cs @@ -0,0 +1,3887 @@ +/* + * Renderers - A collection of useful renderers that are used to owner draw a cell in an ObjectListView + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2018-10-06 JPP - Fix rendering so that OLVColumn.WordWrap works when using customised Renderers + * 2018-05-01 JPP - Use ITextMatchFilter interface rather than TextMatchFilter concrete class. + * v2.9.2 + * 2016-06-02 JPP - CalculateImageWidth() no longer adds 2 to the image width + * 2016-05-29 JPP - Fix calculation of cell edit boundaries on TreeListView controls + * v2.9 + * 2015-08-22 JPP - Allow selected row back/fore colours to be specified for each row + * 2015-06-23 JPP - Added ColumnButtonRenderer plus general support for Buttons + * 2015-06-22 JPP - Added BaseRenderer.ConfigureItem() and ConfigureSubItem() to easily allow + * other renderers to be chained for use within a primary renderer. + * - Lots of tightening of hit tests and edit rectangles + * 2015-05-15 JPP - Handle rendering an Image when that Image is returned as an aspect. + * v2.8 + * 2014-09-26 JPP - Dispose of animation timer in a more robust fashion. + * 2014-05-20 JPP - Handle rendering disabled rows + * v2.7 + * 2013-04-29 JPP - Fixed bug where Images were not vertically aligned + * v2.6 + * 2012-10-26 JPP - Hit detection will no longer report check box hits on columns without checkboxes. + * 2012-07-13 JPP - [Breaking change] Added preferedSize parameter to IRenderer.GetEditRectangle(). + * v2.5.1 + * 2012-07-14 JPP - Added CellPadding to various places. Replaced DescribedTaskRenderer.CellPadding. + * 2012-07-11 JPP - Added CellVerticalAlignment to various places allow cell contents to be vertically + * aligned (rather than always being centered). + * v2.5 + * 2010-08-24 JPP - CheckBoxRenderer handles hot boxes and correctly vertically centers the box. + * 2010-06-23 JPP - Major rework of HighlightTextRenderer. Now uses TextMatchFilter directly. + * Draw highlighting underneath text to improve legibility. Works with new + * TextMatchFilter capabilities. + * v2.4 + * 2009-10-30 JPP - Plugged possible resource leak by using using() with CreateGraphics() + * v2.3 + * 2009-09-28 JPP - Added DescribedTaskRenderer + * 2009-09-01 JPP - Correctly handle an ImageRenderer's handling of an aspect that holds + * the image to be displayed at Byte[]. + * 2009-08-29 JPP - Fixed bug where some of a cell's background was not erased. + * 2009-08-15 JPP - Correctly MeasureText() using the appropriate graphic context + * - Handle translucent selection setting + * v2.2.1 + * 2009-07-24 JPP - Try to honour CanWrap setting when GDI rendering text. + * 2009-07-11 JPP - Correctly calculate edit rectangle for subitems of a tree view + * (previously subitems were indented in the same way as the primary column) + * v2.2 + * 2009-06-06 JPP - Tweaked text rendering so that column 0 isn't ellipsed unnecessarily. + * 2009-05-05 JPP - Added Unfocused foreground and background colors + * (thanks to Christophe Hosten) + * 2009-04-21 JPP - Fixed off-by-1 error when calculating text widths. This caused + * middle and right aligned columns to always wrap one character + * when printed using ListViewPrinter (SF#2776634). + * 2009-04-11 JPP - Correctly renderer checkboxes when RowHeight is non-standard + * 2009-04-06 JPP - Allow for item indent when calculating edit rectangle + * v2.1 + * 2009-02-24 JPP - Work properly with ListViewPrinter again + * 2009-01-26 JPP - AUSTRALIA DAY (why aren't I on holidays!) + * - Major overhaul of renderers. Now uses IRenderer interface. + * - ImagesRenderer and FlagsRenderer are now defunct. + * The names are retained for backward compatibility. + * 2009-01-23 JPP - Align bitmap AND text according to column alignment (previously + * only text was aligned and bitmap was always to the left). + * 2009-01-21 JPP - Changed to use TextRenderer rather than native GDI routines. + * 2009-01-20 JPP - Draw images directly from image list if possible. 30% faster! + * - Tweaked some spacings to look more like native ListView + * - Text highlight for non FullRowSelect is now the right color + * when the control doesn't have focus. + * - Commented out experimental animations. Still needs work. + * 2009-01-19 JPP - Changed to draw text using GDI routines. Looks more like + * native control this way. Set UseGdiTextRendering to false to + * revert to previous behavior. + * 2009-01-15 JPP - Draw background correctly when control is disabled + * - Render checkboxes using CheckBoxRenderer + * v2.0.1 + * 2008-12-29 JPP - Render text correctly when HideSelection is true. + * 2008-12-26 JPP - BaseRenderer now works correctly in all Views + * 2008-12-23 JPP - Fixed two small bugs in BarRenderer + * v2.0 + * 2008-10-26 JPP - Don't owner draw when in Design mode + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2018 Phillip Piper + * + * TO DO: + * - Hit detection on renderers doesn't change the controls standard selection behavior + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using Timer = System.Threading.Timer; + +namespace BrightIdeasSoftware { + /// + /// Renderers are the mechanism used for owner drawing cells. As such, they can also handle + /// hit detection and positioning of cell editing rectangles. + /// + public interface IRenderer { + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, Object rowObject); + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, Object rowObject); + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + void HitTest(OlvListViewHitTestInfo hti, int x, int y); + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize); + } + + /// + /// Renderers that implement this interface will have the filter property updated, + /// each time the filter on the ObjectListView is updated. + /// + public interface IFilterAwareRenderer + { + /// + /// Gets or sets the filter that is currently active + /// + IModelFilter Filter { get; set; } + } + + /// + /// An AbstractRenderer is a do-nothing implementation of the IRenderer interface. + /// + [Browsable(true), + ToolboxItem(false)] + public class AbstractRenderer : Component, IRenderer { + #region IRenderer Members + + /// + /// Render the whole item within an ObjectListView. This is only used in non-Details views. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the item + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject) { + return true; + } + + /// + /// Render one cell within an ObjectListView when it is in Details mode. + /// + /// The event + /// A Graphics for rendering + /// The bounds of the cell + /// The model object to be drawn + /// Return true to indicate that the event was handled and no further processing is needed. + public virtual bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + return false; + } + + /// + /// What is under the given point? + /// + /// + /// x co-ordinate + /// y co-ordinate + /// This method should only alter HitTestLocation and/or UserData. + public virtual void HitTest(OlvListViewHitTestInfo hti, int x, int y) {} + + /// + /// When the value in the given cell is to be edited, where should the edit rectangle be placed? + /// + /// + /// + /// + /// + /// + /// + public virtual Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return cellBounds; + } + + #endregion + } + + /// + /// This class provides compatibility for v1 RendererDelegates + /// + [ToolboxItem(false)] + internal class Version1Renderer : AbstractRenderer { + public Version1Renderer(RenderDelegate renderDelegate) { + this.RenderDelegate = renderDelegate; + } + + /// + /// The renderer delegate that this renderer wraps + /// + public RenderDelegate RenderDelegate; + + #region IRenderer Members + + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object rowObject) { + if (this.RenderDelegate == null) + return base.RenderSubItem(e, g, cellBounds, rowObject); + else + return this.RenderDelegate(e, g, cellBounds, rowObject); + } + + #endregion + } + + /// + /// A BaseRenderer provides useful base level functionality for any custom renderer. + /// + /// + /// Subclasses will normally override the Render or OptionalRender method, and use the other + /// methods as helper functions. + /// + [Browsable(true), + ToolboxItem(true)] + public class BaseRenderer : AbstractRenderer { + internal const TextFormatFlags NormalTextFormatFlags = TextFormatFlags.NoPrefix | + TextFormatFlags.EndEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + + #region Configuration Properties + + /// + /// Can the renderer wrap lines that do not fit completely within the cell? + /// + /// + /// If this is not set specifically, the value will be taken from Column.WordWrap + /// + /// Wrapping text doesn't work with the GDI renderer, so if this set to true, GDI+ rendering will used. + /// The difference between GDI and GDI+ rendering can give word wrapped columns a slight different appearance. + /// + /// + [Category("Appearance"), + Description("Can the renderer wrap text that does not fit completely within the cell"), + DefaultValue(null)] + public bool? CanWrap { + get { return canWrap; } + set { canWrap = value; } + } + + private bool? canWrap; + + /// + /// Get the actual value that should be used right now for CanWrap + /// + [Browsable(false)] + protected bool CanWrapOrDefault { + get { + return this.CanWrap ?? this.Column != null && this.Column.WordWrap; + } + } + /// + /// Gets or sets how many pixels will be left blank around this cell + /// + /// + /// + /// This setting only takes effect when the control is owner drawn. + /// + /// for more details. + /// + [Category("ObjectListView"), + Description("The number of pixels that renderer will leave empty around the edge of the cell"), + DefaultValue(null)] + public Rectangle? CellPadding { + get { return this.cellPadding; } + set { this.cellPadding = value; } + } + private Rectangle? cellPadding; + + /// + /// Gets the horizontal alignment of the column + /// + [Browsable(false)] + public HorizontalAlignment CellHorizontalAlignment + { + get { return this.Column == null ? HorizontalAlignment.Left : this.Column.TextAlign; } + } + + /// + /// Gets or sets how cells drawn by this renderer will be vertically aligned. + /// + /// + /// + /// If this is not set, the value from the column or control itself will be used. + /// + /// + [Category("ObjectListView"), + Description("How will cell values be vertically aligned?"), + DefaultValue(null)] + public virtual StringAlignment? CellVerticalAlignment { + get { return this.cellVerticalAlignment; } + set { this.cellVerticalAlignment = value; } + } + private StringAlignment? cellVerticalAlignment; + + /// + /// Gets the optional padding that this renderer should apply before drawing. + /// This property considers all possible sources of padding + /// + [Browsable(false)] + protected virtual Rectangle? EffectiveCellPadding { + get { + if (this.cellPadding.HasValue) + return this.cellPadding.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellPadding.HasValue) + return this.OLVSubItem.CellPadding.Value; + + if (this.ListItem != null && this.ListItem.CellPadding.HasValue) + return this.ListItem.CellPadding.Value; + + if (this.Column != null && this.Column.CellPadding.HasValue) + return this.Column.CellPadding.Value; + + if (this.ListView != null && this.ListView.CellPadding.HasValue) + return this.ListView.CellPadding.Value; + + return null; + } + } + + /// + /// Gets the vertical cell alignment that should govern the rendering. + /// This property considers all possible sources. + /// + [Browsable(false)] + protected virtual StringAlignment EffectiveCellVerticalAlignment { + get { + if (this.cellVerticalAlignment.HasValue) + return this.cellVerticalAlignment.Value; + + if (this.OLVSubItem != null && this.OLVSubItem.CellVerticalAlignment.HasValue) + return this.OLVSubItem.CellVerticalAlignment.Value; + + if (this.ListItem != null && this.ListItem.CellVerticalAlignment.HasValue) + return this.ListItem.CellVerticalAlignment.Value; + + if (this.Column != null && this.Column.CellVerticalAlignment.HasValue) + return this.Column.CellVerticalAlignment.Value; + + if (this.ListView != null) + return this.ListView.CellVerticalAlignment; + + return StringAlignment.Center; + } + } + + /// + /// Gets or sets the image list from which keyed images will be fetched + /// + [Category("Appearance"), + Description("The image list from which keyed images will be fetched for drawing. If this is not given, the small ImageList from the ObjectListView will be used"), + DefaultValue(null)] + public ImageList ImageList { + get { return imageList; } + set { imageList = value; } + } + + private ImageList imageList; + + /// + /// When rendering multiple images, how many pixels should be between each image? + /// + [Category("Appearance"), + Description("When rendering multiple images, how many pixels should be between each image?"), + DefaultValue(1)] + public int Spacing { + get { return spacing; } + set { spacing = value; } + } + + private int spacing = 1; + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + /// Even if this is set to true, it will return false if the renderer + /// is set to word wrap, since GDI doesn't handle wrapping. + [Category("Appearance"), + Description("Should text be rendered using GDI routines?"), + DefaultValue(true)] + public virtual bool UseGdiTextRendering { + get { + // Can't use GDI routines on a GDI+ printer context or when word wrapping is required + return !this.IsPrinting && !this.CanWrapOrDefault && useGdiTextRendering; + } + set { useGdiTextRendering = value; } + } + private bool useGdiTextRendering = true; + + #endregion + + #region State Properties + + /// + /// Get or set the aspect of the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object Aspect { + get { + if (aspect == null) + aspect = column.GetValue(this.rowObject); + return aspect; + } + set { aspect = value; } + } + + private Object aspect; + + /// + /// What are the bounds of the cell that is being drawn? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Rectangle Bounds { + get { return bounds; } + set { bounds = value; } + } + + private Rectangle bounds; + + /// + /// Get or set the OLVColumn that this renderer will draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVColumn Column { + get { return column; } + set { column = value; } + } + + private OLVColumn column; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewItemEventArgs DrawItemEvent { + get { return drawItemEventArgs; } + set { drawItemEventArgs = value; } + } + + private DrawListViewItemEventArgs drawItemEventArgs; + + /// + /// Get/set the event that caused this renderer to be called + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public DrawListViewSubItemEventArgs Event { + get { return eventArgs; } + set { eventArgs = value; } + } + + private DrawListViewSubItemEventArgs eventArgs; + + /// + /// Gets or sets the font to be used for text in this cell + /// + /// + /// + /// In general, this property should be treated as internal. + /// If you do set this, the given font will be used without any other consideration. + /// All other factors -- selection state, hot item, hyperlinks -- will be ignored. + /// + /// + /// A better way to set the font is to change either ListItem.Font or SubItem.Font + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Font Font { + get { + if (this.font != null || this.ListItem == null) + return this.font; + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.Font; + + return this.SubItem.Font; + } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets the image list from which keyed images will be fetched + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ImageList ImageListOrDefault { + get { return this.ImageList ?? this.ListView.SmallImageList; } + } + + /// + /// Should this renderer fill in the background before drawing? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDrawBackground { + get { return !this.IsPrinting; } + } + + /// + /// Cache whether or not our item is selected + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsItemSelected { + get { return isItemSelected; } + set { isItemSelected = value; } + } + + private bool isItemSelected; + + /// + /// Is this renderer being used on a printer context? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrinting { + get { return isPrinting; } + set { isPrinting = value; } + } + + private bool isPrinting; + + /// + /// Get or set the listitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListItem ListItem { + get { return listItem; } + set { listItem = value; } + } + + private OLVListItem listItem; + + /// + /// Get/set the listview for which the drawing is to be done + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + + private ObjectListView objectListView; + + /// + /// Get the specialized OLVSubItem that this renderer is drawing + /// + /// This returns null for column 0. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem OLVSubItem { + get { return listSubItem as OLVListSubItem; } + } + + /// + /// Get or set the model object that this renderer should draw + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object RowObject { + get { return rowObject; } + set { rowObject = value; } + } + + private Object rowObject; + + /// + /// Get or set the list subitem that this renderer will be drawing + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OLVListSubItem SubItem { + get { return listSubItem; } + set { listSubItem = value; } + } + + private OLVListSubItem listSubItem; + + /// + /// The brush that will be used to paint the text + /// + /// + /// + /// In general, this property should be treated as internal. It will be reset after each render. + /// + /// + /// + /// In particular, don't set it to configure the color of the text on the control. That should be done via SubItem.ForeColor + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush TextBrush { + get { + if (textBrush == null) + return new SolidBrush(this.GetForegroundColor()); + else + return this.textBrush; + } + set { textBrush = value; } + } + + private Brush textBrush; + + /// + /// Will this renderer use the custom images from the parent ObjectListView + /// to draw the checkbox images. + /// + /// + /// + /// If this is true, the renderer will use the images from the + /// StateImageList to represent checkboxes. 0 - unchecked, 1 - checked, 2 - indeterminate. + /// + /// If this is false (the default), then the renderer will use .NET's standard + /// CheckBoxRenderer. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool UseCustomCheckboxImages { + get { return useCustomCheckboxImages; } + set { useCustomCheckboxImages = value; } + } + + private bool useCustomCheckboxImages; + + private void ClearState() { + this.Event = null; + this.DrawItemEvent = null; + this.Aspect = null; + this.TextBrush = null; + } + + #endregion + + #region Utilities + + /// + /// Align the second rectangle with the first rectangle, + /// according to the alignment of the column + /// + /// The cell's bounds + /// The rectangle to be aligned within the bounds + /// An aligned rectangle + protected virtual Rectangle AlignRectangle(Rectangle outer, Rectangle inner) { + Rectangle r = new Rectangle(outer.Location, inner.Size); + + // Align horizontally depending on the column alignment + if (inner.Width < outer.Width) { + r.X = AlignHorizontally(outer, inner); + } + + // Align vertically too + if (inner.Height < outer.Height) { + r.Y = AlignVertically(outer, inner); + } + + return r; + } + + /// + /// Calculate the left edge of the rectangle that aligns the outer rectangle with the inner one + /// according to this renderer's horizontal alignment + /// + /// + /// + /// + protected int AlignHorizontally(Rectangle outer, Rectangle inner) { + HorizontalAlignment alignment = this.CellHorizontalAlignment; + switch (alignment) { + case HorizontalAlignment.Left: + return outer.Left + 1; + case HorizontalAlignment.Center: + return outer.Left + ((outer.Width - inner.Width) / 2); + case HorizontalAlignment.Right: + return outer.Right - inner.Width - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with the inner rectangle + /// according to this renders vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, Rectangle inner) { + return AlignVertically(outer, inner.Height); + } + + /// + /// Calculate the top of the rectangle that aligns the outer rectangle with a rectangle of the given height + /// according to this renderer's vertical alignment + /// + /// + /// + /// + protected int AlignVertically(Rectangle outer, int innerHeight) { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return outer.Top + 1; + case StringAlignment.Center: + return outer.Top + ((outer.Height - innerHeight) / 2); + case StringAlignment.Far: + return outer.Bottom - innerHeight - 1; + default: + throw new ArgumentOutOfRangeException(); + } + } + + /// + /// Calculate the space that our rendering will occupy and then align that space + /// with the given rectangle, according to the Column alignment + /// + /// + /// Pre-padded bounds of the cell + /// + protected virtual Rectangle CalculateAlignedRectangle(Graphics g, Rectangle r) { + if (this.Column == null) + return r; + + Rectangle contentRectangle = new Rectangle(Point.Empty, this.CalculateContentSize(g, r)); + return this.AlignRectangle(r, contentRectangle); + } + + /// + /// Calculate the size of the content of this cell. + /// + /// + /// Pre-padded bounds of the cell + /// The width and height of the content + protected virtual Size CalculateContentSize(Graphics g, Rectangle r) + { + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + Size imageSize = this.CalculateImageSize(g, this.GetImageSelector()); + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width - (checkBoxSize.Width + imageSize.Width)); + + // If the combined width is greater than the whole cell, we just use the cell itself + + int width = Math.Min(r.Width, checkBoxSize.Width + imageSize.Width + textSize.Width); + int componentMaxHeight = Math.Max(checkBoxSize.Height, Math.Max(imageSize.Height, textSize.Height)); + int height = Math.Min(r.Height, componentMaxHeight); + + return new Size(width, height); + } + + /// + /// Calculate the bounds of a checkbox given the (pre-padded) cell bounds + /// + /// + /// Pre-padded cell bounds + /// + protected Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + return this.AlignRectangle(cellBounds, new Rectangle(0, 0, checkBoxSize.Width, checkBoxSize.Height)); + } + + + /// + /// How much space will the check box for this cell occupy? + /// + /// Only column 0 can have check boxes. Sub item checkboxes are + /// treated as images + /// + /// + protected virtual Size CalculateCheckBoxSize(Graphics g) + { + if (UseCustomCheckboxImages && this.ListView.StateImageList != null) + return this.ListView.StateImageList.ImageSize; + + return CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); + } + + /// + /// How much space will the check box for this row occupy? + /// If the list doesn't have checkboxes, or this isn't the primary column, + /// this returns an empty size. + /// + /// + /// + protected virtual Size CalculatePrimaryCheckBoxSize(Graphics g) { + if (!this.ListView.CheckBoxes || !this.ColumnIsPrimary) + return Size.Empty; + + Size size = this.CalculateCheckBoxSize(g); + size.Width += 6; + return size; + } + + /// + /// How much horizontal space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageWidth(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Width; + } + + /// + /// How much vertical space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual int CalculateImageHeight(Graphics g, object imageSelector) + { + return this.CalculateImageSize(g, imageSelector).Height; + } + + /// + /// How much space will the image of this cell occupy? + /// + /// + /// + /// + protected virtual Size CalculateImageSize(Graphics g, object imageSelector) + { + if (imageSelector == null || imageSelector == DBNull.Value) + return Size.Empty; + + // Check for the image in the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) + { + int selectorAsInt = -1; + + if (imageSelector is Int32) + selectorAsInt = (Int32)imageSelector; + else + { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + if (selectorAsInt >= 0) + return il.ImageSize; + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image != null) + return image.Size; + + return Size.Empty; + } + + /// + /// How much horizontal space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual int CalculateTextWidth(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return 0; + + return CalculateTextSize(g, txt, width).Width; + } + + /// + /// How much space will the text of this cell occupy? + /// + /// + /// + /// + /// + protected virtual Size CalculateTextSize(Graphics g, string txt, int width) + { + if (String.IsNullOrEmpty(txt)) + return Size.Empty; + + if (this.UseGdiTextRendering) + { + Size proposedSize = new Size(width, Int32.MaxValue); + return TextRenderer.MeasureText(g, txt, this.Font, proposedSize, NormalTextFormatFlags); + } + + // Using GDI+ rendering + using (StringFormat fmt = new StringFormat()) { + fmt.Trimming = StringTrimming.EllipsisCharacter; + SizeF sizeF = g.MeasureString(txt, this.Font, width, fmt); + return new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height); + } + } + + /// + /// Return the Color that is the background color for this item's cell + /// + /// The background color of the subitem + public virtual Color GetBackgroundColor() { + if (!this.ListView.Enabled) + return SystemColors.Control; + + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection && this.ListView.FullRowSelect) + return this.GetSelectedBackgroundColor(); + + if (this.SubItem == null || this.ListItem.UseItemStyleForSubItems) + return this.ListItem.BackColor; + + return this.SubItem.BackColor; + } + + /// + /// Return the color of the background color when the item is selected + /// + /// The background color of the subitem + public virtual Color GetSelectedBackgroundColor() { + if (this.ListView.Focused) + return this.ListItem.SelectedBackColor ?? this.ListView.SelectedBackColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedBackColorOrDefault; + + return this.ListItem.BackColor; + } + + /// + /// Return the color to be used for text in this cell + /// + /// The text color of the subitem + public virtual Color GetForegroundColor() { + if (this.IsItemSelected && + !this.ListView.UseTranslucentSelection && + (this.ColumnIsPrimary || this.ListView.FullRowSelect)) + return this.GetSelectedForegroundColor(); + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the color of the foreground color when the item is selected + /// + /// The foreground color of the subitem + public virtual Color GetSelectedForegroundColor() + { + if (this.ListView.Focused) + return this.ListItem.SelectedForeColor ?? this.ListView.SelectedForeColorOrDefault; + + if (!this.ListView.HideSelection) + return this.ListView.UnfocusedSelectedForeColorOrDefault; + + return this.SubItem == null || this.ListItem.UseItemStyleForSubItems ? this.ListItem.ForeColor : this.SubItem.ForeColor; + } + + /// + /// Return the image that should be drawn against this subitem + /// + /// An Image or null if no image should be drawn. + protected virtual Image GetImage() { + return this.GetImage(this.GetImageSelector()); + } + + /// + /// Return the actual image that should be drawn when keyed by the given image selector. + /// An image selector can be: + /// an int, giving the index into the image list + /// a string, giving the image key into the image list + /// an Image, being the image itself + /// + /// + /// The value that indicates the image to be used + /// An Image or null + protected virtual Image GetImage(Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return null; + + ImageList il = this.ImageListOrDefault; + if (il != null) { + if (imageSelector is Int32) { + Int32 index = (Int32) imageSelector; + if (index < 0 || index >= il.Images.Count) + return null; + + return il.Images[index]; + } + + String str = imageSelector as String; + if (str != null) { + if (il.Images.ContainsKey(str)) + return il.Images[str]; + + return null; + } + } + + return imageSelector as Image; + } + + /// + /// + protected virtual Object GetImageSelector() { + return this.ColumnIsPrimary ? this.ListItem.ImageSelector : this.OLVSubItem.ImageSelector; + } + + /// + /// Return the string that should be drawn within this + /// + /// + protected virtual string GetText() { + return this.SubItem == null ? this.ListItem.Text : this.SubItem.Text; + } + + /// + /// Return the Color that is the background color for this item's text + /// + /// The background color of the subitem's text + [Obsolete("Use GetBackgroundColor() instead")] + protected virtual Color GetTextBackgroundColor() { + return Color.Red; // just so it shows up if it is used + } + + #endregion + + #region IRenderer members + + /// + /// Render the whole item in a non-details view. + /// + /// + /// + /// + /// + /// + public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object model) { + this.ConfigureItem(e, itemBounds, model); + return this.OptionalRender(g, itemBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureItem(DrawListViewItemEventArgs e, Rectangle itemBounds, object model) + { + this.ClearState(); + + this.DrawItemEvent = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = null; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = this.ListView.GetColumn(0); + this.RowObject = model; + this.Bounds = itemBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Render one cell + /// + /// + /// + /// + /// + /// + public override bool RenderSubItem(DrawListViewSubItemEventArgs e, Graphics g, Rectangle cellBounds, object model) { + this.ConfigureSubItem(e, cellBounds, model); + return this.OptionalRender(g, cellBounds); + } + + /// + /// Prepare this renderer to draw in response to the given event + /// + /// + /// + /// + /// Use this if you want to chain a second renderer within a primary renderer. + public virtual void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + this.ClearState(); + + this.Event = e; + this.ListItem = (OLVListItem)e.Item; + this.SubItem = (OLVListSubItem)e.SubItem; + this.ListView = (ObjectListView)this.ListItem.ListView; + this.Column = (OLVColumn)e.Header; + this.RowObject = model; + this.Bounds = cellBounds; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + } + + /// + /// Calculate which part of this cell was hit + /// + /// + /// + /// + public override void HitTest(OlvListViewHitTestInfo hti, int x, int y) { + this.ClearState(); + + this.ListView = hti.ListView; + this.ListItem = hti.Item; + this.SubItem = hti.SubItem; + this.Column = hti.Column; + this.RowObject = hti.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + if (this.SubItem == null) + this.Bounds = this.ListItem.Bounds; + else + this.Bounds = this.ListItem.GetSubItemBounds(this.Column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) { + this.HandleHitTest(g, hti, x, y); + } + } + + /// + /// Calculate the edit rectangle + /// + /// + /// + /// + /// + /// + /// + public override Rectangle GetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + this.ClearState(); + + this.ListView = (ObjectListView) item.ListView; + this.ListItem = item; + this.SubItem = item.GetSubItem(subItemIndex); + this.Column = this.ListView.GetColumn(subItemIndex); + this.RowObject = item.RowObject; + this.IsItemSelected = this.ListItem.Selected && this.ListItem.Enabled; + this.Bounds = cellBounds; + + return this.HandleGetEditRectangle(g, cellBounds, item, subItemIndex, preferredSize); + } + + #endregion + + #region IRenderer implementation + + // Subclasses will probably want to override these methods rather than the IRenderer + // interface methods. + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method. + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + /// Returns whether the rendering has already taken place. + /// If this returns false, the default processing will take over. + /// + public virtual bool OptionalRender(Graphics g, Rectangle r) { + if (this.ListView.View != View.Details) + return false; + + this.Render(g, r); + return true; + } + + /// + /// Draw our data into the given rectangle using the given graphics context. + /// + /// + /// Subclasses should override this method if they never want + /// to fall back on the default processing + /// The graphics context that should be used for drawing + /// The bounds of the subitem cell + public virtual void Render(Graphics g, Rectangle r) { + this.StandardRender(g, r); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected virtual void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateAlignedRectangle(g, ApplyCellPadding(this.Bounds)); + this.StandardHitTest(g, hti, r, x, y); + } + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected virtual Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + // MAINTAINER NOTE: This type testing is wrong (design-wise). The base class should return cell bounds, + // and a more specialized class should return StandardGetEditRectangle(). But BaseRenderer is used directly + // to draw most normal cells, as well as being directly subclassed for user implemented renderers. And this + // method needs to return different bounds in each of those cases. We should have a StandardRenderer and make + // BaseRenderer into an ABC -- but that would break too much existing code. And so we have this hack :( + + // If we are a standard renderer, return the position of the text, otherwise, use the whole cell. + if (this.GetType() == typeof (BaseRenderer)) + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + + // Center the editor vertically + if (cellBounds.Height != preferredSize.Height) + cellBounds.Y += (cellBounds.Height - preferredSize.Height) / 2; + + return cellBounds; + } + + #endregion + + #region Standard IRenderer implementations + + /// + /// Draw the standard "[checkbox] [image] [text]" cell after the state properties have been initialized. + /// + /// + /// + protected void StandardRender(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + // Adjust the first columns rectangle to match the padding used by the native mode of the ListView + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left ) { + r.X += 3; + r.Width -= 1; + } + r = this.ApplyCellPadding(r); + this.DrawAlignedImageAndText(g, r); + + // Show where the bounds of the cell padding are (debugging) + if (ObjectListView.ShowCellPaddingBounds) + g.DrawRectangle(Pens.Purple, r); + } + + /// + /// Change the bounds of the given rectangle to take any cell padding into account + /// + /// + /// + public virtual Rectangle ApplyCellPadding(Rectangle r) { + Rectangle? padding = this.EffectiveCellPadding; + if (!padding.HasValue) + return r; + // The two subtractions below look wrong, but are correct! + Rectangle paddingRectangle = padding.Value; + r.Width -= paddingRectangle.Right; + r.Height -= paddingRectangle.Bottom; + r.Offset(paddingRectangle.Location); + return r; + } + + /// + /// Perform normal hit testing relative to the given aligned content bounds + /// + /// + /// + /// + /// + /// + protected virtual void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle alignedContentRectangle, int x, int y) { + Rectangle r = alignedContentRectangle; + + // Match tweaking from renderer + if (this.ColumnIsPrimary && this.CellHorizontalAlignment == HorizontalAlignment.Left && !(this is TreeListView.TreeRenderer)) { + r.X += 3; + r.Width -= 1; + } + int width = 0; + + // Did they hit a check box on the primary column? + if (this.ColumnIsPrimary && this.ListView.CheckBoxes) { + Size checkBoxSize = this.CalculateCheckBoxSize(g); + int checkBoxTop = this.AlignVertically(r, checkBoxSize.Height); + Rectangle r3 = new Rectangle(r.X, checkBoxTop, checkBoxSize.Width, checkBoxSize.Height); + width = r3.Width + 6; + // g.DrawRectangle(Pens.DarkGreen, r3); + if (r3.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.CheckBox; + return; + } + } + + // Did they hit the image? If they hit the image of a + // non-primary column that has a checkbox, it counts as a + // checkbox hit + r.X += width; + r.Width -= width; + width = this.CalculateImageWidth(g, this.GetImageSelector()); + Rectangle rTwo = r; + rTwo.Width = width; + //g.DrawRectangle(Pens.Red, rTwo); + if (rTwo.Contains(x, y)) { + if (this.Column != null && (this.Column.Index > 0 && this.Column.CheckBoxes)) + hti.HitTestLocation = HitTestLocation.CheckBox; + else + hti.HitTestLocation = HitTestLocation.Image; + return; + } + + // Did they hit the text? + r.X += width; + r.Width -= width; + width = this.CalculateTextWidth(g, this.GetText(), r.Width); + rTwo = r; + rTwo.Width = width; + // g.DrawRectangle(Pens.Blue, rTwo); + if (rTwo.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.Text; + return; + } + + hti.HitTestLocation = HitTestLocation.InCell; + } + + /// + /// This method calculates the bounds of the text within a standard layout + /// (i.e. optional checkbox, optional image, text) + /// + /// This method only works correctly if the state of the renderer + /// has been fully initialized (see BaseRenderer.GetEditRectangle) + /// + /// + /// + /// + protected virtual Rectangle StandardGetEditRectangle(Graphics g, Rectangle cellBounds, Size preferredSize) { + + Size contentSize = this.CalculateContentSize(g, cellBounds); + int contentWidth = this.Column.CellEditUseWholeCellEffective ? cellBounds.Width : contentSize.Width; + Rectangle editControlBounds = this.CalculatePaddedAlignedBounds(g, cellBounds, new Size(contentWidth, preferredSize.Height)); + + Size checkBoxSize = this.CalculatePrimaryCheckBoxSize(g); + int imageWidth = this.CalculateImageWidth(g, this.GetImageSelector()); + + int width = checkBoxSize.Width + imageWidth + 2; + + // Indent the primary column by the required amount + if (this.ColumnIsPrimary && this.ListItem.IndentCount > 0) { + int indentWidth = this.ListView.SmallImageSize.Width * this.ListItem.IndentCount; + editControlBounds.X += indentWidth; + } + + editControlBounds.X += width; + editControlBounds.Width -= width; + + if (editControlBounds.Width < 50) + editControlBounds.Width = 50; + if (editControlBounds.Right > cellBounds.Right) + editControlBounds.Width = cellBounds.Right - editControlBounds.Left; + + return editControlBounds; + } + + /// + /// Apply any padding to the given bounds, and then align a rectangle of the given + /// size within that padded area. + /// + /// + /// + /// + /// + protected Rectangle CalculatePaddedAlignedBounds(Graphics g, Rectangle cellBounds, Size preferredSize) { + Rectangle r = ApplyCellPadding(cellBounds); + r = this.AlignRectangle(r, new Rectangle(Point.Empty, preferredSize)); + return r; + } + + #endregion + + #region Drawing routines + + /// + /// Draw the given image aligned horizontally within the column. + /// + /// + /// Over tall images are scaled to fit. Over-wide images are + /// truncated. This is by design! + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The image to be drawn + protected virtual void DrawAlignedImage(Graphics g, Rectangle r, Image image) { + if (image == null) + return; + + // By default, the image goes in the top left of the rectangle + Rectangle imageBounds = new Rectangle(r.Location, image.Size); + + // If the image is too tall to be drawn in the space provided, proportionally scale it down. + // Too wide images are not scaled. + if (image.Height > r.Height) { + float scaleRatio = (float) r.Height / (float) image.Height; + imageBounds.Width = (int) ((float) image.Width * scaleRatio); + imageBounds.Height = r.Height - 1; + } + + // Align and draw our (possibly scaled) image + Rectangle alignRectangle = this.AlignRectangle(r, imageBounds); + if (this.ListItem.Enabled) + g.DrawImage(image, alignRectangle); + else + ControlPaint.DrawImageDisabled(g, image, alignRectangle.X, alignRectangle.Y, GetBackgroundColor()); + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Pre-padded bounds of the cell + protected virtual void DrawAlignedImageAndText(Graphics g, Rectangle r) { + this.DrawImageAndText(g, this.CalculateAlignedRectangle(g, r)); + } + + /// + /// Fill in the background of this cell + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawBackground(Graphics g, Rectangle r) { + if (!this.IsDrawBackground) + return; + + Color backgroundColor = this.GetBackgroundColor(); + + using (Brush brush = new SolidBrush(backgroundColor)) { + g.FillRectangle(brush, r.X - 1, r.Y - 1, r.Width + 2, r.Height + 2); + } + } + + /// + /// Draw the primary check box of this row (checkboxes in other sub items use a different method) + /// + /// Graphics context to use for drawing + /// The pre-aligned and padded target rectangle + protected virtual int DrawCheckBox(Graphics g, Rectangle r) { + // The odd constants are to match checkbox placement in native mode (on XP at least) + // TODO: Unify this with CheckStateRenderer + + // The rectangle r is already horizontally aligned. We still need to align it vertically. + Size checkBoxSize = this.CalculateCheckBoxSize(g); + Point checkBoxLocation = new Point(r.X, this.AlignVertically(r, checkBoxSize.Height)); + + if (this.IsPrinting || this.UseCustomCheckboxImages) { + int imageIndex = this.ListItem.StateImageIndex; + if (this.ListView.StateImageList == null || imageIndex < 0 || imageIndex >= this.ListView.StateImageList.Images.Count) + return 0; + + return this.DrawImage(g, new Rectangle(checkBoxLocation, checkBoxSize), this.ListView.StateImageList.Images[imageIndex]) + 4; + } + + CheckBoxState boxState = this.GetCheckBoxState(this.ListItem.CheckState); + CheckBoxRenderer.DrawCheckBox(g, checkBoxLocation, boxState); + return checkBoxSize.Width; + } + + /// + /// Calculate the CheckBoxState we need to correctly draw the given state + /// + /// + /// + protected virtual CheckBoxState GetCheckBoxState(CheckState checkState) { + + // Should the checkbox be drawn as disabled? + if (this.IsCheckBoxDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the cursor currently over this checkbox? + if (this.IsCheckboxHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + + } + + /// + /// Should this checkbox be drawn as disabled? + /// + protected virtual bool IsCheckBoxDisabled { + get { + if (this.ListItem != null && !this.ListItem.Enabled) + return true; + + if (!this.ListView.RenderNonEditableCheckboxesAsDisabled) + return false; + + return (this.ListView.CellEditActivation == ObjectListView.CellEditActivateMode.None || + (this.Column != null && !this.Column.IsEditable)); + } + } + + /// + /// Is the current item hot (i.e. under the mouse)? + /// + protected bool IsCellHot { + get { + return this.ListView != null && + this.ListView.HotRowIndex == this.ListItem.Index && + this.ListView.HotColumnIndex == (this.Column == null ? 0 : this.Column.Index); + } + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsCheckboxHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.CheckBox; + } + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The optional image to be drawn + protected virtual int DrawImage(Graphics g, Rectangle r, Object imageSelector) { + if (imageSelector == null || imageSelector == DBNull.Value) + return 0; + + // Draw from the image list (most common case) + ImageList il = this.ImageListOrDefault; + if (il != null) { + + // Try to translate our imageSelector into a valid ImageList index + int selectorAsInt = -1; + if (imageSelector is Int32) { + selectorAsInt = (Int32) imageSelector; + if (selectorAsInt >= il.Images.Count) + selectorAsInt = -1; + } else { + String selectorAsString = imageSelector as String; + if (selectorAsString != null) + selectorAsInt = il.Images.IndexOfKey(selectorAsString); + } + + // If we found a valid index into the ImageList, draw it. + // We want to draw using the native DrawImageList calls, since that let's us do some nice effects + // But the native call does not work on PrinterDCs, so if we're printing we have to skip this bit. + if (selectorAsInt >= 0) { + if (!this.IsPrinting) { + if (il.ImageSize.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, il.ImageSize)); + + // If we are not printing, it's probable that the given Graphics object is double buffered using a BufferedGraphics object. + // But the ImageList.Draw method doesn't honor the Translation matrix that's probably in effect on the buffered + // graphics. So we have to calculate our drawing rectangle, relative to the cells natural boundaries. + // This effectively simulates the Translation matrix. + + Rectangle r2 = new Rectangle(r.X - this.Bounds.X, r.Y - this.Bounds.Y, r.Width, r.Height); + NativeMethods.DrawImageList(g, il, selectorAsInt, r2.X, r2.Y, this.IsItemSelected, !this.ListItem.Enabled); + return il.ImageSize.Width; + } + + // For some reason, printing from an image list doesn't work onto a printer context + // So get the image from the list and FALL THROUGH to the "print an image" case + imageSelector = il.Images[selectorAsInt]; + } + } + + // Is the selector actually an image? + Image image = imageSelector as Image; + if (image == null) + return 0; // no, give up + + if (image.Size.Height < r.Height) + r.Y = this.AlignVertically(r, new Rectangle(Point.Empty, image.Size)); + + if (this.ListItem.Enabled) + g.DrawImageUnscaled(image, r.X, r.Y); + else + ControlPaint.DrawImageDisabled(g, image, r.X, r.Y, GetBackgroundColor()); + + return image.Width; + } + + /// + /// Draw our subitems image and text + /// + /// Graphics context to use for drawing + /// Bounds of the cell + protected virtual void DrawImageAndText(Graphics g, Rectangle r) { + int offset = 0; + if (this.ListView.CheckBoxes && this.ColumnIsPrimary) { + offset = this.DrawCheckBox(g, r) + 6; + r.X += offset; + r.Width -= offset; + } + + offset = this.DrawImage(g, r, this.GetImageSelector()); + r.X += offset; + r.Width -= offset; + + this.DrawText(g, r, this.GetText()); + } + + /// + /// Draw the given collection of image selectors + /// + /// + /// + /// + protected virtual int DrawImages(Graphics g, Rectangle r, ICollection imageSelectors) { + // Collect the non-null images + List images = new List(); + foreach (Object selector in imageSelectors) { + Image image = this.GetImage(selector); + if (image != null) + images.Add(image); + } + + // Figure out how much space they will occupy + int width = 0; + int height = 0; + foreach (Image image in images) { + width += (image.Width + this.Spacing); + height = Math.Max(height, image.Height); + } + + // Align the collection of images within the cell + Rectangle r2 = this.AlignRectangle(r, new Rectangle(0, 0, width, height)); + + // Finally, draw all the images in their correct location + Color backgroundColor = GetBackgroundColor(); + Point pt = r2.Location; + foreach (Image image in images) { + if (this.ListItem.Enabled) + g.DrawImage(image, pt); + else + ControlPaint.DrawImageDisabled(g, image, pt.X, pt.Y, backgroundColor); + pt.X += (image.Width + this.Spacing); + } + + // Return the width that the images occupy + return width; + } + + /// + /// Draw the given text and optional image in the "normal" fashion + /// + /// Graphics context to use for drawing + /// Bounds of the cell + /// The string to be drawn + public virtual void DrawText(Graphics g, Rectangle r, String txt) { + if (String.IsNullOrEmpty(txt)) + return; + + if (this.UseGdiTextRendering) + this.DrawTextGdi(g, r, txt); + else + this.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Print the given text in the given rectangle using only GDI routines + /// + /// + /// + /// + /// + /// The native list control uses GDI routines to do its drawing, so using them + /// here makes the owner drawn mode looks more natural. + /// This method doesn't honour the CanWrap setting on the renderer. All + /// text is single line + /// + protected virtual void DrawTextGdi(Graphics g, Rectangle r, String txt) { + Color backColor = Color.Transparent; + if (this.IsDrawBackground && this.IsItemSelected && ColumnIsPrimary && !this.ListView.FullRowSelect) + backColor = this.GetSelectedBackgroundColor(); + + TextFormatFlags flags = NormalTextFormatFlags | this.CellVerticalAlignmentAsTextFormatFlag; + + // I think there is a bug in the TextRenderer. Setting or not setting SingleLine doesn't make + // any difference -- it is always single line. + if (!this.CanWrapOrDefault) + flags |= TextFormatFlags.SingleLine; + TextRenderer.DrawText(g, txt, this.Font, r, this.GetForegroundColor(), backColor, flags); + } + + private bool ColumnIsPrimary { + get { return this.Column != null && this.Column.Index == 0; } + } + + /// + /// Gets the cell's vertical alignment as a TextFormatFlag + /// + /// + protected TextFormatFlags CellVerticalAlignmentAsTextFormatFlag { + get { + switch (this.EffectiveCellVerticalAlignment) { + case StringAlignment.Near: + return TextFormatFlags.Top; + case StringAlignment.Center: + return TextFormatFlags.VerticalCenter; + case StringAlignment.Far: + return TextFormatFlags.Bottom; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + /// + /// Gets the StringFormat needed when drawing text using GDI+ + /// + protected virtual StringFormat StringFormatForGdiPlus { + get { + StringFormat fmt = new StringFormat(); + fmt.LineAlignment = this.EffectiveCellVerticalAlignment; + fmt.Trimming = StringTrimming.EllipsisCharacter; + fmt.Alignment = this.Column == null ? StringAlignment.Near : this.Column.TextStringAlign; + if (!this.CanWrapOrDefault) + fmt.FormatFlags = StringFormatFlags.NoWrap; + return fmt; + } + } + + /// + /// Print the given text in the given rectangle using normal GDI+ .NET methods + /// + /// Printing to a printer dc has to be done using this method. + protected virtual void DrawTextGdiPlus(Graphics g, Rectangle r, String txt) { + using (StringFormat fmt = this.StringFormatForGdiPlus) { + // Draw the background of the text as selected, if it's the primary column + // and it's selected and it's not in FullRowSelect mode. + Font f = this.Font; + if (this.IsDrawBackground && this.IsItemSelected && this.ColumnIsPrimary && !this.ListView.FullRowSelect) { + SizeF size = g.MeasureString(txt, f, r.Width, fmt); + Rectangle r2 = r; + r2.Width = (int) size.Width + 1; + using (Brush brush = new SolidBrush(this.GetSelectedBackgroundColor())) { + g.FillRectangle(brush, r2); + } + } + RectangleF rf = r; + g.DrawString(txt, f, this.TextBrush, rf, fmt); + } + + // We should put a focus rectangle around the column 0 text if it's selected -- + // but we don't because: + // - I really dislike this UI convention + // - we are using buffered graphics, so the DrawFocusRecatangle method of the event doesn't work + + //if (this.ColumnIsPrimary) { + // Size size = TextRenderer.MeasureText(this.SubItem.Text, this.ListView.ListFont); + // if (r.Width > size.Width) + // r.Width = size.Width; + // this.Event.DrawFocusRectangle(r); + //} + } + + #endregion + } + + /// + /// This renderer highlights substrings that match a given text filter. + /// + /// + /// Implementation note: + /// This renderer uses the functionality of BaseRenderer to draw the text, and + /// then draws a translucent frame over the top of the already rendered text glyphs. + /// There's no way to draw the matching text in a different font or color in this + /// implementation. + /// + public class HighlightTextRenderer : BaseRenderer, IFilterAwareRenderer { + #region Life and death + + /// + /// Create a HighlightTextRenderer + /// + public HighlightTextRenderer() { + this.FramePen = Pens.DarkGreen; + this.FillBrush = Brushes.Yellow; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + public HighlightTextRenderer(ITextMatchFilter filter) + : this() { + this.Filter = filter; + } + + /// + /// Create a HighlightTextRenderer + /// + /// + [Obsolete("Use HighlightTextRenderer(TextMatchFilter) instead", true)] + public HighlightTextRenderer(string text) {} + + #endregion + + #region Configuration properties + + /// + /// Gets or set how rounded will be the corners of the text match frame + /// + [Category("Appearance"), + DefaultValue(3.0f), + Description("How rounded will be the corners of the text match frame?")] + public float CornerRoundness { + get { return cornerRoundness; } + set { cornerRoundness = value; } + } + + private float cornerRoundness = 3.0f; + + /// + /// Gets or set the brush will be used to paint behind the matched substrings. + /// Set this to null to not fill the frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush FillBrush { + get { return fillBrush; } + set { fillBrush = value; } + } + + private Brush fillBrush; + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter { + get { return filter; } + set { filter = value; } + } + private ITextMatchFilter filter; + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter + { + get { return filter; } + set { RegisterNewFilter(value); } + } + + internal void RegisterNewFilter(IModelFilter newFilter) { + TextMatchFilter textFilter = newFilter as TextMatchFilter; + if (textFilter != null) + { + Filter = textFilter; + return; + } + CompositeFilter composite = newFilter as CompositeFilter; + if (composite != null) + { + foreach (TextMatchFilter textSubFilter in composite.TextFilters) + { + Filter = textSubFilter; + return; + } + } + Filter = null; + } + + /// + /// Gets or set the pen will be used to frame the matched substrings. + /// Set this to null to not draw a frame. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen FramePen { + get { return framePen; } + set { framePen = value; } + } + + private Pen framePen; + + /// + /// Gets or sets whether the frame around a text match will have rounded corners + /// + [Category("Appearance"), + DefaultValue(true), + Description("Will the frame around a text match will have rounded corners?")] + public bool UseRoundedRectangle { + get { return useRoundedRectangle; } + set { useRoundedRectangle = value; } + } + + private bool useRoundedRectangle = true; + + #endregion + + #region Compatibility properties + + /// + /// Gets or set the text that will be highlighted + /// + [Obsolete("Set the Filter directly rather than just the text", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string TextToHighlight { + get { return String.Empty; } + set { } + } + + /// + /// Gets or sets the manner in which substring will be compared. + /// + /// + /// Use this to control if substring matches are case sensitive or insensitive. + [Obsolete("Set the Filter directly rather than just this setting", true)] + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public StringComparison StringComparison { + get { return StringComparison.CurrentCultureIgnoreCase; } + set { } + } + + #endregion + + #region IRenderer interface overrides + + /// + /// Handle a HitTest request after all state information has been initialized + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + + #endregion + + #region Rendering + + // This class has two implement two highlighting schemes: one for GDI, another for GDI+. + // Naturally, GDI+ makes the task easier, but we have to provide something for GDI + // since that it is what is normally used. + + /// + /// Draw text using GDI + /// + /// + /// + /// + protected override void DrawTextGdi(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiTextHighlighting(g, r, txt); + + base.DrawTextGdi(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI + /// + /// + /// + /// + protected virtual void DrawGdiTextHighlighting(Graphics g, Rectangle r, string txt) { + + // TextRenderer puts horizontal padding around the strings, so we need to take + // that into account when measuring strings + const int paddingAdjustment = 6; + + // Cache the font + Font f = this.Font; + + foreach (CharacterRange range in this.Filter.FindAllMatchedRanges(txt)) { + // Measure the text that comes before our substring + Size precedingTextSize = Size.Empty; + if (range.First > 0) { + string precedingText = txt.Substring(0, range.First); + precedingTextSize = TextRenderer.MeasureText(g, precedingText, f, r.Size, NormalTextFormatFlags); + precedingTextSize.Width -= paddingAdjustment; + } + + // Measure the length of our substring (may be different each time due to case differences) + string highlightText = txt.Substring(range.First, range.Length); + Size textToHighlightSize = TextRenderer.MeasureText(g, highlightText, f, r.Size, NormalTextFormatFlags); + textToHighlightSize.Width -= paddingAdjustment; + + float textToHighlightLeft = r.X + precedingTextSize.Width + 1; + float textToHighlightTop = this.AlignVertically(r, textToHighlightSize.Height); + + // Draw a filled frame around our substring + this.DrawSubstringFrame(g, textToHighlightLeft, textToHighlightTop, textToHighlightSize.Width, textToHighlightSize.Height); + } + } + + /// + /// Draw an indication around the given frame that shows a text match + /// + /// + /// + /// + /// + /// + protected virtual void DrawSubstringFrame(Graphics g, float x, float y, float width, float height) { + if (this.UseRoundedRectangle) { + using (GraphicsPath path = this.GetRoundedRect(x, y, width, height, 3.0f)) { + if (this.FillBrush != null) + g.FillPath(this.FillBrush, path); + if (this.FramePen != null) + g.DrawPath(this.FramePen, path); + } + } else { + if (this.FillBrush != null) + g.FillRectangle(this.FillBrush, x, y, width, height); + if (this.FramePen != null) + g.DrawRectangle(this.FramePen, x, y, width, height); + } + } + + /// + /// Draw the text using GDI+ + /// + /// + /// + /// + protected override void DrawTextGdiPlus(Graphics g, Rectangle r, string txt) { + if (this.ShouldDrawHighlighting) + this.DrawGdiPlusTextHighlighting(g, r, txt); + + base.DrawTextGdiPlus(g, r, txt); + } + + /// + /// Draw the highlighted text using GDI+ + /// + /// + /// + /// + protected virtual void DrawGdiPlusTextHighlighting(Graphics g, Rectangle r, string txt) { + // Find the substrings we want to highlight + List ranges = new List(this.Filter.FindAllMatchedRanges(txt)); + + if (ranges.Count == 0) + return; + + using (StringFormat fmt = this.StringFormatForGdiPlus) { + RectangleF rf = r; + fmt.SetMeasurableCharacterRanges(ranges.ToArray()); + Region[] stringRegions = g.MeasureCharacterRanges(txt, this.Font, rf, fmt); + + foreach (Region region in stringRegions) { + RectangleF bounds = region.GetBounds(g); + this.DrawSubstringFrame(g, bounds.X - 1, bounds.Y - 1, bounds.Width + 2, bounds.Height); + } + } + } + + #endregion + + #region Utilities + + /// + /// Gets whether the renderer should actually draw highlighting + /// + protected bool ShouldDrawHighlighting { + get { return this.Column == null || (this.Column.Searchable && this.Filter != null); } + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + /// + /// + /// + /// + /// + protected GraphicsPath GetRoundedRect(float x, float y, float width, float height, float diameter) { + return GetRoundedRect(new RectangleF(x, y, width, height), diameter); + } + + /// + /// Return a GraphicPath that is a round cornered rectangle + /// + /// The rectangle + /// The diameter of the corners + /// A round cornered rectangle path + /// If I could rely on people using C# 3.0+, this should be + /// an extension method of GraphicsPath. + protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) { + GraphicsPath path = new GraphicsPath(); + + if (diameter > 0) { + RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter); + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + path.CloseFigure(); + } else { + path.AddRectangle(rect); + } + + return path; + } + + #endregion + } + + /// + /// This class maps a data value to an image that should be drawn for that value. + /// + /// It is useful for drawing data that is represented as an enum or boolean. + public class MappedImageRenderer : BaseRenderer { + /// + /// Return a renderer that draw boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// A Renderer + public static MappedImageRenderer Boolean(Object trueImage, Object falseImage) { + return new MappedImageRenderer(true, trueImage, false, falseImage); + } + + /// + /// Return a renderer that draw tristate boolean values using the given images + /// + /// Draw this when our data value is true + /// Draw this when our data value is false + /// Draw this when our data value is null + /// A Renderer + public static MappedImageRenderer TriState(Object trueImage, Object falseImage, Object nullImage) { + return new MappedImageRenderer(new Object[] {true, trueImage, false, falseImage, null, nullImage}); + } + + /// + /// Make a new empty renderer + /// + public MappedImageRenderer() { + map = new System.Collections.Hashtable(); + } + + /// + /// Make a new renderer that will show the given image when the given key is the aspect value + /// + /// The data value to be matched + /// The image to be shown when the key is matched + public MappedImageRenderer(Object key, Object image) + : this() { + this.Add(key, image); + } + + /// + /// Make a new renderer that will show the given images when it receives the given keys + /// + /// + /// + /// + /// + public MappedImageRenderer(Object key1, Object image1, Object key2, Object image2) + : this() { + this.Add(key1, image1); + this.Add(key2, image2); + } + + /// + /// Build a renderer from the given array of keys and their matching images + /// + /// An array of key/image pairs + public MappedImageRenderer(Object[] keysAndImages) + : this() { + if ((keysAndImages.GetLength(0) % 2) != 0) + throw new ArgumentException("Array must have key/image pairs"); + + for (int i = 0; i < keysAndImages.GetLength(0); i += 2) + this.Add(keysAndImages[i], keysAndImages[i + 1]); + } + + /// + /// Register the image that should be drawn when our Aspect has the data value. + /// + /// Value that the Aspect must match + /// An ImageSelector -- an int, string or image + public void Add(Object value, Object image) { + if (value == null) + this.nullImage = image; + else + map[value] = image; + } + + /// + /// Render our value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + ICollection aspectAsCollection = this.Aspect as ICollection; + if (aspectAsCollection == null) + this.RenderOne(g, r, this.Aspect); + else + this.RenderCollection(g, r, aspectAsCollection); + } + + /// + /// Draw a collection of images + /// + /// + /// + /// + protected void RenderCollection(Graphics g, Rectangle r, ICollection imageSelectors) { + ArrayList images = new ArrayList(); + Image image = null; + foreach (Object selector in imageSelectors) { + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + else + image = null; + + if (image != null) + images.Add(image); + } + + this.DrawImages(g, r, images); + } + + /// + /// Draw one image + /// + /// + /// + /// + protected void RenderOne(Graphics g, Rectangle r, Object selector) { + Image image = null; + if (selector == null) + image = this.GetImage(this.nullImage); + else if (map.ContainsKey(selector)) + image = this.GetImage(map[selector]); + + if (image != null) + this.DrawAlignedImage(g, r, image); + } + + #region Private variables + + private Hashtable map; // Track the association between values and images + private Object nullImage; // image to be drawn for null values (since null can't be a key) + + #endregion + } + + /// + /// This renderer draws just a checkbox to match the check state of our model object. + /// + public class CheckStateRenderer : BaseRenderer { + /// + /// Draw our cell + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + if (this.Column == null) + return; + r = this.ApplyCellPadding(r); + CheckState state = this.Column.GetCheckState(this.RowObject); + if (this.IsPrinting) { + // Renderers don't work onto printer DCs, so we have to draw the image ourselves + string key = ObjectListView.CHECKED_KEY; + if (state == CheckState.Unchecked) + key = ObjectListView.UNCHECKED_KEY; + if (state == CheckState.Indeterminate) + key = ObjectListView.INDETERMINATE_KEY; + this.DrawAlignedImage(g, r, this.ImageListOrDefault.Images[key]); + } else { + r = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, r.Location, this.GetCheckBoxState(state)); + } + } + + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Rectangle r = this.CalculateCheckBoxBounds(g, this.Bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.CheckBox; + } + } + + /// + /// Render an image that comes from our data source. + /// + /// The image can be sourced from: + /// + /// a byte-array (normally when the image to be shown is + /// stored as a value in a database) + /// an int, which is treated as an index into the image list + /// a string, which is treated first as a file name, and failing that as an index into the image list + /// an ICollection of ints or strings, which will be drawn as consecutive images + /// + /// If an image is an animated GIF, it's state is stored in the SubItem object. + /// By default, the image renderer does not render animations (it begins life with animations paused). + /// To enable animations, you must call Unpause(). + /// In the current implementation (2009-09), each column showing animated gifs must have a + /// different instance of ImageRenderer assigned to it. You cannot share the same instance of + /// an image renderer between two animated gif columns. If you do, only the last column will be + /// animated. + /// + public class ImageRenderer : BaseRenderer { + /// + /// Make an empty image renderer + /// + public ImageRenderer() { + this.stopwatch = new Stopwatch(); + } + + /// + /// Make an empty image renderer that begins life ready for animations + /// + public ImageRenderer(bool startAnimations) + : this() { + this.Paused = !startAnimations; + } + + /// + /// Finalizer + /// + protected override void Dispose(bool disposing) { + Paused = true; + base.Dispose(disposing); + } + + #region Properties + + /// + /// Should the animations in this renderer be paused? + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool Paused { + get { return isPaused; } + set { + if (this.isPaused == value) + return; + + this.isPaused = value; + if (this.isPaused) { + this.StopTickler(); + this.stopwatch.Stop(); + } else { + this.Tickler.Change(1, Timeout.Infinite); + this.stopwatch.Start(); + } + } + } + + private bool isPaused = true; + + private void StopTickler() { + if (this.tickler == null) + return; + + this.tickler.Dispose(); + this.tickler = null; + } + + /// + /// Gets a timer that can be used to trigger redraws on animations + /// + protected Timer Tickler { + get { + if (this.tickler == null) + this.tickler = new System.Threading.Timer(new TimerCallback(this.OnTimer), null, Timeout.Infinite, Timeout.Infinite); + return this.tickler; + } + } + + #endregion + + #region Commands + + /// + /// Pause any animations + /// + public void Pause() { + this.Paused = true; + } + + /// + /// Unpause any animations + /// + public void Unpause() { + this.Paused = false; + } + + #endregion + + #region Drawing + + /// + /// Draw our image + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + if (this.Aspect == null || this.Aspect == System.DBNull.Value) + return; + r = this.ApplyCellPadding(r); + + if (this.Aspect is System.Byte[]) { + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + } else { + ICollection imageSelectors = this.Aspect as ICollection; + if (imageSelectors == null) + this.DrawAlignedImage(g, r, this.GetImageFromAspect()); + else + this.DrawImages(g, r, imageSelectors); + } + } + + /// + /// Translate our Aspect into an image. + /// + /// The strategy is: + /// If its a byte array, we treat it as an in-memory image + /// If it's an int, we use that as an index into our image list + /// If it's a string, we try to load a file by that name. If we can't, + /// we use the string as an index into our image list. + /// + /// An image + protected Image GetImageFromAspect() { + // If we've already figured out the image, don't do it again + if (this.OLVSubItem != null && this.OLVSubItem.ImageSelector is Image) { + if (this.OLVSubItem.AnimationState == null) + return (Image) this.OLVSubItem.ImageSelector; + else + return this.OLVSubItem.AnimationState.image; + } + + // Try to convert our Aspect into an Image + // If its a byte array, we treat it as an in-memory image + // If it's an int, we use that as an index into our image list + // If it's a string, we try to find a file by that name. + // If we can't, we use the string as an index into our image list. + Image image = this.Aspect as Image; + if (image != null) { + // Don't do anything else + } else if (this.Aspect is System.Byte[]) { + using (MemoryStream stream = new MemoryStream((System.Byte[]) this.Aspect)) { + try { + image = Image.FromStream(stream); + } + catch (ArgumentException) { + // ignore + } + } + } else if (this.Aspect is Int32) { + image = this.GetImage(this.Aspect); + } else { + String str = this.Aspect as String; + if (!String.IsNullOrEmpty(str)) { + try { + image = Image.FromFile(str); + } + catch (FileNotFoundException) { + image = this.GetImage(this.Aspect); + } + catch (OutOfMemoryException) { + image = this.GetImage(this.Aspect); + } + } + } + + // If this image is an animation, initialize the animation process + if (this.OLVSubItem != null && AnimationState.IsAnimation(image)) { + this.OLVSubItem.AnimationState = new AnimationState(image); + } + + // Cache the image so we don't repeat this dreary process + if (this.OLVSubItem != null) + this.OLVSubItem.ImageSelector = image; + + return image; + } + + #endregion + + #region Events + + /// + /// This is the method that is invoked by the timer. It basically switches control to the listview thread. + /// + /// not used + public void OnTimer(Object state) { + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + if (this.ListView.InvokeRequired) + this.ListView.Invoke((MethodInvoker) delegate { this.OnTimer(state); }); + else + this.OnTimerInThread(); + } + + private bool IsListViewDead { + get { + // Apply a whole heap of sanity checks, which basically ensure that the ListView is still alive + return this.ListView == null || + this.ListView.Disposing || + this.ListView.IsDisposed || + !this.ListView.IsHandleCreated; + } + } + + /// + /// This is the OnTimer callback, but invoked in the same thread as the creator of the ListView. + /// This method can use all of ListViews methods without creating a CrossThread exception. + /// + protected void OnTimerInThread() { + // MAINTAINER NOTE: This method must renew the tickler. If it doesn't the animations will stop. + + // If this listview has been destroyed, we can't do anything, so we return without + // renewing the tickler, effectively killing all animations on this renderer + + if (this.IsListViewDead) + return; + + if (this.Paused) + return; + + // If we're not in Detail view or our column has been removed from the list, + // we can't do anything at the moment, but we still renew the tickler because the view may change later. + if (this.ListView.View != System.Windows.Forms.View.Details || this.Column == null || this.Column.Index < 0) { + this.Tickler.Change(1000, Timeout.Infinite); + return; + } + + long elapsedMilliseconds = this.stopwatch.ElapsedMilliseconds; + int subItemIndex = this.Column.Index; + long nextCheckAt = elapsedMilliseconds + 1000; // wait at most one second before checking again + Rectangle updateRect = new Rectangle(); // what part of the view must be updated to draw the changed gifs? + + // Run through all the subitems in the view for our column, and for each one that + // has an animation attached to it, see if the frame needs updating. + + for (int i = 0; i < this.ListView.GetItemCount(); i++) { + OLVListItem lvi = this.ListView.GetItem(i); + + // Get the animation state from the subitem. If there isn't an animation state, skip this row. + OLVListSubItem lvsi = lvi.GetSubItem(subItemIndex); + AnimationState state = lvsi.AnimationState; + if (state == null || !state.IsValid) + continue; + + // Has this frame of the animation expired? + if (elapsedMilliseconds >= state.currentFrameExpiresAt) { + state.AdvanceFrame(elapsedMilliseconds); + + // Track the area of the view that needs to be redrawn to show the changed images + if (updateRect.IsEmpty) + updateRect = lvsi.Bounds; + else + updateRect = Rectangle.Union(updateRect, lvsi.Bounds); + } + + // Remember the minimum time at which a frame is next due to change + nextCheckAt = Math.Min(nextCheckAt, state.currentFrameExpiresAt); + } + + // Update the part of the listview where frames have changed + if (!updateRect.IsEmpty) + this.ListView.Invalidate(updateRect); + + // Renew the tickler in time for the next frame change + this.Tickler.Change(nextCheckAt - elapsedMilliseconds, Timeout.Infinite); + } + + #endregion + + /// + /// Instances of this class kept track of the animation state of a single image. + /// + internal class AnimationState { + private const int PropertyTagTypeShort = 3; + private const int PropertyTagTypeLong = 4; + private const int PropertyTagFrameDelay = 0x5100; + private const int PropertyTagLoopCount = 0x5101; + + /// + /// Is the given image an animation + /// + /// The image to be tested + /// Is the image an animation? + public static bool IsAnimation(Image image) { + if (image == null) + return false; + else + return (new List(image.FrameDimensionsList)).Contains(FrameDimension.Time.Guid); + } + + /// + /// Create an AnimationState in a quiet state + /// + public AnimationState() { + this.imageDuration = new List(); + } + + /// + /// Create an animation state for the given image, which may or may not + /// be an animation + /// + /// The image to be rendered + public AnimationState(Image image) + : this() { + if (!AnimationState.IsAnimation(image)) + return; + + // How many frames in the animation? + this.image = image; + this.frameCount = this.image.GetFrameCount(FrameDimension.Time); + + // Find the delay between each frame. + // The delays are stored an array of 4-byte ints. Each int is the + // number of 1/100th of a second that should elapsed before the frame expires + foreach (PropertyItem pi in this.image.PropertyItems) { + if (pi.Id == PropertyTagFrameDelay) { + for (int i = 0; i < pi.Len; i += 4) { + //TODO: There must be a better way to convert 4-bytes to an int + int delay = (pi.Value[i + 3] << 24) + (pi.Value[i + 2] << 16) + (pi.Value[i + 1] << 8) + pi.Value[i]; + this.imageDuration.Add(delay * 10); // store delays as milliseconds + } + break; + } + } + + // There should be as many frame durations as frames + Debug.Assert(this.imageDuration.Count == this.frameCount, "There should be as many frame durations as there are frames."); + } + + /// + /// Does this state represent a valid animation + /// + public bool IsValid { + get { return (this.image != null && this.frameCount > 0); } + } + + /// + /// Advance our images current frame and calculate when it will expire + /// + public void AdvanceFrame(long millisecondsNow) { + this.currentFrame = (this.currentFrame + 1) % this.frameCount; + this.currentFrameExpiresAt = millisecondsNow + this.imageDuration[this.currentFrame]; + this.image.SelectActiveFrame(FrameDimension.Time, this.currentFrame); + } + + internal int currentFrame; + internal long currentFrameExpiresAt; + internal Image image; + internal List imageDuration; + internal int frameCount; + } + + #region Private variables + + private System.Threading.Timer tickler; // timer used to tickle the animations + private Stopwatch stopwatch; // clock used to time the animation frame changes + + #endregion + } + + /// + /// Render our Aspect as a progress bar + /// + public class BarRenderer : BaseRenderer { + #region Constructors + + /// + /// Make a BarRenderer + /// + public BarRenderer() + : base() {} + + /// + /// Make a BarRenderer for the given range of data values + /// + public BarRenderer(int minimum, int maximum) + : this() { + this.MinimumValue = minimum; + this.MaximumValue = maximum; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(Pen pen, Brush brush) + : this() { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer using a custom bar scheme + /// + public BarRenderer(int minimum, int maximum, Pen pen, Brush brush) + : this(minimum, maximum) { + this.Pen = pen; + this.Brush = brush; + this.UseStandardBar = false; + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(Pen pen, Color start, Color end) + : this() { + this.Pen = pen; + this.SetGradient(start, end); + } + + /// + /// Make a BarRenderer that uses a horizontal gradient + /// + public BarRenderer(int minimum, int maximum, Pen pen, Color start, Color end) + : this(minimum, maximum) { + this.Pen = pen; + this.SetGradient(start, end); + } + + #endregion + + #region Configuration Properties + + /// + /// Should this bar be drawn in the system style? + /// + [Category("ObjectListView"), + Description("Should this bar be drawn in the system style?"), + DefaultValue(true)] + public bool UseStandardBar { + get { return useStandardBar; } + set { useStandardBar = value; } + } + + private bool useStandardBar = true; + + /// + /// How many pixels in from our cell border will this bar be drawn + /// + [Category("ObjectListView"), + Description("How many pixels in from our cell border will this bar be drawn"), + DefaultValue(2)] + public int Padding { + get { return padding; } + set { padding = value; } + } + + private int padding = 2; + + /// + /// What color will be used to fill the interior of the control before the + /// progress bar is drawn? + /// + [Category("ObjectListView"), + Description("The color of the interior of the bar"), + DefaultValue(typeof (Color), "AliceBlue")] + public Color BackgroundColor { + get { return backgroundColor; } + set { backgroundColor = value; } + } + + private Color backgroundColor = Color.AliceBlue; + + /// + /// What color should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("What color should the frame of the progress bar be"), + DefaultValue(typeof (Color), "Black")] + public Color FrameColor { + get { return frameColor; } + set { frameColor = value; } + } + + private Color frameColor = Color.Black; + + /// + /// How many pixels wide should the frame of the progress bar be? + /// + [Category("ObjectListView"), + Description("How many pixels wide should the frame of the progress bar be"), + DefaultValue(1.0f)] + public float FrameWidth { + get { return frameWidth; } + set { frameWidth = value; } + } + + private float frameWidth = 1.0f; + + /// + /// What color should the 'filled in' part of the progress bar be? + /// + /// This is only used if GradientStartColor is Color.Empty + [Category("ObjectListView"), + Description("What color should the 'filled in' part of the progress bar be"), + DefaultValue(typeof (Color), "BlueViolet")] + public Color FillColor { + get { return fillColor; } + set { fillColor = value; } + } + + private Color fillColor = Color.BlueViolet; + + /// + /// Use a gradient to fill the progress bar starting with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar starting with this color"), + DefaultValue(typeof (Color), "CornflowerBlue")] + public Color GradientStartColor { + get { return startColor; } + set { startColor = value; } + } + + private Color startColor = Color.CornflowerBlue; + + /// + /// Use a gradient to fill the progress bar ending with this color + /// + [Category("ObjectListView"), + Description("Use a gradient to fill the progress bar ending with this color"), + DefaultValue(typeof (Color), "DarkBlue")] + public Color GradientEndColor { + get { return endColor; } + set { endColor = value; } + } + + private Color endColor = Color.DarkBlue; + + /// + /// Regardless of how wide the column become the progress bar will never be wider than this + /// + [Category("Behavior"), + Description("The progress bar will never be wider than this"), + DefaultValue(100)] + public int MaximumWidth { + get { return maximumWidth; } + set { maximumWidth = value; } + } + + private int maximumWidth = 100; + + /// + /// Regardless of how high the cell is the progress bar will never be taller than this + /// + [Category("Behavior"), + Description("The progress bar will never be taller than this"), + DefaultValue(16)] + public int MaximumHeight { + get { return maximumHeight; } + set { maximumHeight = value; } + } + + private int maximumHeight = 16; + + /// + /// The minimum data value expected. Values less than this will given an empty bar + /// + [Category("Behavior"), + Description("The minimum data value expected. Values less than this will given an empty bar"), + DefaultValue(0.0)] + public double MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private double minimumValue = 0.0; + + /// + /// The maximum value for the range. Values greater than this will give a full bar + /// + [Category("Behavior"), + Description("The maximum value for the range. Values greater than this will give a full bar"), + DefaultValue(100.0)] + public double MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private double maximumValue = 100.0; + + #endregion + + #region Public Properties (non-IDE) + + /// + /// The Pen that will draw the frame surrounding this bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Pen Pen { + get { + if (this.pen == null && !this.FrameColor.IsEmpty) + return new Pen(this.FrameColor, this.FrameWidth); + else + return this.pen; + } + set { this.pen = value; } + } + + private Pen pen; + + /// + /// The brush that will be used to fill the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush Brush { + get { + if (this.brush == null && !this.FillColor.IsEmpty) + return new SolidBrush(this.FillColor); + else + return this.brush; + } + set { this.brush = value; } + } + + private Brush brush; + + /// + /// The brush that will be used to fill the background of the bar + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Brush BackgroundBrush { + get { + if (this.backgroundBrush == null && !this.BackgroundColor.IsEmpty) + return new SolidBrush(this.BackgroundColor); + else + return this.backgroundBrush; + } + set { this.backgroundBrush = value; } + } + + private Brush backgroundBrush; + + #endregion + + /// + /// Draw this progress bar using a gradient + /// + /// + /// + public void SetGradient(Color start, Color end) { + this.GradientStartColor = start; + this.GradientEndColor = end; + } + + /// + /// Draw our aspect + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + r = this.ApplyCellPadding(r); + + Rectangle frameRect = Rectangle.Inflate(r, 0 - this.Padding, 0 - this.Padding); + frameRect.Width = Math.Min(frameRect.Width, this.MaximumWidth); + frameRect.Height = Math.Min(frameRect.Height, this.MaximumHeight); + frameRect = this.AlignRectangle(r, frameRect); + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + Rectangle fillRect = Rectangle.Inflate(frameRect, -1, -1); + if (aspectValue <= this.MinimumValue) + fillRect.Width = 0; + else if (aspectValue < this.MaximumValue) + fillRect.Width = (int) (fillRect.Width * (aspectValue - this.MinimumValue) / this.MaximumValue); + + // MS-themed progress bars don't work when printing + if (this.UseStandardBar && ProgressBarRenderer.IsSupported && !this.IsPrinting) { + ProgressBarRenderer.DrawHorizontalBar(g, frameRect); + ProgressBarRenderer.DrawHorizontalChunks(g, fillRect); + } else { + g.FillRectangle(this.BackgroundBrush, frameRect); + if (fillRect.Width > 0) { + // FillRectangle fills inside the given rectangle, so expand it a little + fillRect.Width++; + fillRect.Height++; + if (this.GradientStartColor == Color.Empty) + g.FillRectangle(this.Brush, fillRect); + else { + using (LinearGradientBrush gradient = new LinearGradientBrush(frameRect, this.GradientStartColor, this.GradientEndColor, LinearGradientMode.Horizontal)) { + g.FillRectangle(gradient, fillRect); + } + } + } + g.DrawRectangle(this.Pen, frameRect); + } + } + + /// + /// Handle the GetEditRectangle request + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.CalculatePaddedAlignedBounds(g, cellBounds, preferredSize); + } + } + + + /// + /// An ImagesRenderer draws zero or more images depending on the data returned by its Aspect. + /// + /// This renderer's Aspect must return a ICollection of ints, strings or Images, + /// each of which will be drawn horizontally one after the other. + /// As of v2.1, this functionality has been absorbed into ImageRenderer and this is now an + /// empty shell, solely for backwards compatibility. + /// + [ToolboxItem(false)] + public class ImagesRenderer : ImageRenderer {} + + /// + /// A MultiImageRenderer draws the same image a number of times based on our data value + /// + /// The stars in the Rating column of iTunes is a good example of this type of renderer. + public class MultiImageRenderer : BaseRenderer { + /// + /// Make a quiet renderer + /// + public MultiImageRenderer() + : base() {} + + /// + /// Make an image renderer that will draw the indicated image, at most maxImages times. + /// + /// + /// + /// + /// + public MultiImageRenderer(Object imageSelector, int maxImages, int minValue, int maxValue) + : this() { + this.ImageSelector = imageSelector; + this.MaxNumberImages = maxImages; + this.MinimumValue = minValue; + this.MaximumValue = maxValue; + } + + #region Configuration Properties + + /// + /// The index of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(-1)] + public int ImageIndex { + get { + if (imageSelector is Int32) + return (Int32) imageSelector; + else + return -1; + } + set { imageSelector = value; } + } + + /// + /// The name of the image that should be drawn + /// + [Category("Behavior"), + Description("The index of the image that should be drawn"), + DefaultValue(null)] + public string ImageName { + get { return imageSelector as String; } + set { imageSelector = value; } + } + + /// + /// The image selector that will give the image to be drawn + /// + /// Like all image selectors, this can be an int, string or Image + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Object ImageSelector { + get { return imageSelector; } + set { imageSelector = value; } + } + + private Object imageSelector; + + /// + /// What is the maximum number of images that this renderer should draw? + /// + [Category("Behavior"), + Description("The maximum number of images that this renderer should draw"), + DefaultValue(10)] + public int MaxNumberImages { + get { return maxNumberImages; } + set { maxNumberImages = value; } + } + + private int maxNumberImages = 10; + + /// + /// Values less than or equal to this will have 0 images drawn + /// + [Category("Behavior"), + Description("Values less than or equal to this will have 0 images drawn"), + DefaultValue(0)] + public int MinimumValue { + get { return minimumValue; } + set { minimumValue = value; } + } + + private int minimumValue = 0; + + /// + /// Values greater than or equal to this will have MaxNumberImages images drawn + /// + [Category("Behavior"), + Description("Values greater than or equal to this will have MaxNumberImages images drawn"), + DefaultValue(100)] + public int MaximumValue { + get { return maximumValue; } + set { maximumValue = value; } + } + + private int maximumValue = 100; + + #endregion + + /// + /// Draw our data value + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + + Image image = this.GetImage(this.ImageSelector); + if (image == null) + return; + + // Convert our aspect to a numeric value + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + double aspectValue = convertable.ToDouble(NumberFormatInfo.InvariantInfo); + + // Calculate how many images we need to draw to represent our aspect value + int numberOfImages; + if (aspectValue <= this.MinimumValue) + numberOfImages = 0; + else if (aspectValue < this.MaximumValue) + numberOfImages = 1 + (int) (this.MaxNumberImages * (aspectValue - this.MinimumValue) / this.MaximumValue); + else + numberOfImages = this.MaxNumberImages; + + // If we need to shrink the image, what will its on-screen dimensions be? + int imageScaledWidth = image.Width; + int imageScaledHeight = image.Height; + if (r.Height < image.Height) { + imageScaledWidth = (int) ((float) image.Width * (float) r.Height / (float) image.Height); + imageScaledHeight = r.Height; + } + // Calculate where the images should be drawn + Rectangle imageBounds = r; + imageBounds.Width = (this.MaxNumberImages * (imageScaledWidth + this.Spacing)) - this.Spacing; + imageBounds.Height = imageScaledHeight; + imageBounds = this.AlignRectangle(r, imageBounds); + + // Finally, draw the images + Rectangle singleImageRect = new Rectangle(imageBounds.X, imageBounds.Y, imageScaledWidth, imageScaledHeight); + Color backgroundColor = GetBackgroundColor(); + for (int i = 0; i < numberOfImages; i++) { + if (this.ListItem.Enabled) { + this.DrawImage(g, singleImageRect, this.ImageSelector); + } else + ControlPaint.DrawImageDisabled(g, image, singleImageRect.X, singleImageRect.Y, backgroundColor); + singleImageRect.X += (imageScaledWidth + this.Spacing); + } + } + } + + + /// + /// A class to render a value that contains a bitwise-OR'ed collection of values. + /// + public class FlagRenderer : BaseRenderer { + /// + /// Register the given image to the given value + /// + /// When this flag is present... + /// ...draw this image + public void Add(Object key, Object imageSelector) { + Int32 k2 = ((IConvertible) key).ToInt32(NumberFormatInfo.InvariantInfo); + + this.imageMap[k2] = imageSelector; + this.keysInOrder.Remove(k2); + this.keysInOrder.Add(k2); + } + + /// + /// Draw the flags + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + r = this.ApplyCellPadding(r); + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + ArrayList images = new ArrayList(); + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) + images.Add(image); + } + } + if (images.Count > 0) + this.DrawImages(g, r, images); + } + + /// + /// Do the actual work of hit testing. Subclasses should override this rather than HitTest() + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + IConvertible convertable = this.Aspect as IConvertible; + if (convertable == null) + return; + + Int32 v2 = convertable.ToInt32(NumberFormatInfo.InvariantInfo); + + Point pt = this.Bounds.Location; + foreach (Int32 key in this.keysInOrder) { + if ((v2 & key) == key) { + Image image = this.GetImage(this.imageMap[key]); + if (image != null) { + Rectangle imageRect = new Rectangle(pt, image.Size); + if (imageRect.Contains(x, y)) { + hti.UserData = key; + return; + } + pt.X += (image.Width + this.Spacing); + } + } + } + } + + private List keysInOrder = new List(); + private Dictionary imageMap = new Dictionary(); + } + + /// + /// This renderer draws an image, a single line title, and then multi-line description + /// under the title. + /// + /// + /// This class works best with FullRowSelect = true. + /// It's not designed to work with cell editing -- it will work but will look odd. + /// + /// It's not RightToLeft friendly. + /// + /// + public class DescribedTaskRenderer : BaseRenderer, IFilterAwareRenderer + { + private readonly StringFormat noWrapStringFormat; + private readonly HighlightTextRenderer highlightTextRenderer = new HighlightTextRenderer(); + + /// + /// Create a DescribedTaskRenderer + /// + public DescribedTaskRenderer() { + this.noWrapStringFormat = new StringFormat(StringFormatFlags.NoWrap); + this.noWrapStringFormat.Trimming = StringTrimming.EllipsisCharacter; + this.noWrapStringFormat.Alignment = StringAlignment.Near; + this.noWrapStringFormat.LineAlignment = StringAlignment.Near; + this.highlightTextRenderer.CellVerticalAlignment = StringAlignment.Near; + } + + #region Configuration properties + + /// + /// Should text be rendered using GDI routines? This makes the text look more + /// like a native List view control. + /// + public override bool UseGdiTextRendering + { + get { return base.UseGdiTextRendering; } + set + { + base.UseGdiTextRendering = value; + this.highlightTextRenderer.UseGdiTextRendering = value; + } + } + + /// + /// Gets or set the font that will be used to draw the title of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the title of the task"), + DefaultValue(null)] + public Font TitleFont { + get { return titleFont; } + set { titleFont = value; } + } + + private Font titleFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font TitleFontOrDefault { + get { return this.TitleFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the title of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the title"), + DefaultValue(typeof (Color), "")] + public Color TitleColor { + get { return titleColor; } + set { titleColor = value; } + } + + private Color titleColor; + + /// + /// Return the color of the title of the task or a reasonable default + /// + [Browsable(false)] + public Color TitleColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected || this.TitleColor.IsEmpty) + return this.GetForegroundColor(); + + return this.TitleColor; + } + } + + /// + /// Gets or set the font that will be used to draw the description of the task + /// + /// If this is null, the ListView's font will be used + [Category("ObjectListView"), + Description("The font that will be used to draw the description of the task"), + DefaultValue(null)] + public Font DescriptionFont { + get { return descriptionFont; } + set { descriptionFont = value; } + } + + private Font descriptionFont; + + /// + /// Return a font that has been set for the title or a reasonable default + /// + [Browsable(false)] + public Font DescriptionFontOrDefault { + get { return this.DescriptionFont ?? this.ListView.Font; } + } + + /// + /// Gets or set the color of the description of the task + /// + /// This color is used when the task is not selected or when the listview + /// has a translucent selection mechanism. + [Category("ObjectListView"), + Description("The color of the description"), + DefaultValue(typeof (Color), "")] + public Color DescriptionColor { + get { return descriptionColor; } + set { descriptionColor = value; } + } + private Color descriptionColor = Color.Empty; + + /// + /// Return the color of the description of the task or a reasonable default + /// + [Browsable(false)] + public Color DescriptionColorOrDefault { + get { + if (!this.ListItem.Enabled) + return this.SubItem.ForeColor; + if (this.IsItemSelected && !this.ListView.UseTranslucentSelection) + return this.GetForegroundColor(); + return this.DescriptionColor.IsEmpty ? defaultDescriptionColor : this.DescriptionColor; + } + } + private static Color defaultDescriptionColor = Color.FromArgb(45, 46, 49); + + /// + /// Gets or sets the number of pixels that will be left between the image and the text + /// + [Category("ObjectListView"), + Description("The number of pixels that will be left between the image and the text"), + DefaultValue(4)] + public int ImageTextSpace + { + get { return imageTextSpace; } + set { imageTextSpace = value; } + } + private int imageTextSpace = 4; + + /// + /// Gets or sets the number of pixels that will be left between the title and the description + /// + [Category("ObjectListView"), + Description("The number of pixels that that will be left between the title and the description"), + DefaultValue(2)] + public int TitleDescriptionSpace + { + get { return titleDescriptionSpace; } + set { titleDescriptionSpace = value; } + } + private int titleDescriptionSpace = 2; + + /// + /// Gets or sets the name of the aspect of the model object that contains the task description + /// + [Category("ObjectListView"), + Description("The name of the aspect of the model object that contains the task description"), + DefaultValue(null)] + public string DescriptionAspectName { + get { return descriptionAspectName; } + set { descriptionAspectName = value; } + } + private string descriptionAspectName; + + #endregion + + #region Text highlighting + + /// + /// Gets or sets the filter that is filtering the ObjectListView and for + /// which this renderer should highlight text + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ITextMatchFilter Filter + { + get { return this.highlightTextRenderer.Filter; } + set { this.highlightTextRenderer.Filter = value; } + } + + /// + /// When a filter changes, keep track of the text matching filters + /// + IModelFilter IFilterAwareRenderer.Filter { + get { return this.Filter; } + set { this.highlightTextRenderer.RegisterNewFilter(value); } + } + + #endregion + + #region Calculating + + /// + /// Fetch the description from the model class + /// + /// + /// + public virtual string GetDescription(object model) { + if (String.IsNullOrEmpty(this.DescriptionAspectName)) + return String.Empty; + + if (this.descriptionGetter == null) + this.descriptionGetter = new Munger(this.DescriptionAspectName); + + return this.descriptionGetter.GetValue(model) as string; + } + private Munger descriptionGetter; + + #endregion + + #region Rendering + + /// + /// + /// + /// + /// + /// + public override void ConfigureSubItem(DrawListViewSubItemEventArgs e, Rectangle cellBounds, object model) { + base.ConfigureSubItem(e, cellBounds, model); + this.highlightTextRenderer.ConfigureSubItem(e, cellBounds, model); + } + + /// + /// Draw our item + /// + /// + /// + public override void Render(Graphics g, Rectangle r) { + this.DrawBackground(g, r); + r = this.ApplyCellPadding(r); + this.DrawDescribedTask(g, r, this.GetText(), this.GetDescription(this.RowObject), this.GetImageSelector()); + } + + /// + /// Draw the task + /// + /// + /// + /// + /// + /// + protected virtual void DrawDescribedTask(Graphics g, Rectangle r, string title, string description, object imageSelector) { + + //Debug.WriteLine(String.Format("DrawDescribedTask({0}, {1}, {2}, {3})", r, title, description, imageSelector)); + + // Draw the image if one's been given + Rectangle textBounds = r; + if (imageSelector != null) { + int imageWidth = this.DrawImage(g, r, imageSelector); + int gapToText = imageWidth + this.ImageTextSpace; + textBounds.X += gapToText; + textBounds.Width -= gapToText; + } + + // Draw the title + if (!String.IsNullOrEmpty(title)) { + using (SolidBrush b = new SolidBrush(this.TitleColorOrDefault)) { + this.highlightTextRenderer.CanWrap = false; + this.highlightTextRenderer.Font = this.TitleFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, title); + } + + // How tall was the title? + SizeF size = g.MeasureString(title, this.TitleFontOrDefault, textBounds.Width, this.noWrapStringFormat); + int pixelsToDescription = this.TitleDescriptionSpace + (int)size.Height; + textBounds.Y += pixelsToDescription; + textBounds.Height -= pixelsToDescription; + } + + // Draw the description + if (!String.IsNullOrEmpty(description)) { + using (SolidBrush b = new SolidBrush(this.DescriptionColorOrDefault)) { + this.highlightTextRenderer.CanWrap = true; + this.highlightTextRenderer.Font = this.DescriptionFontOrDefault; + this.highlightTextRenderer.TextBrush = b; + this.highlightTextRenderer.DrawText(g, textBounds, description); + } + } + + //g.DrawRectangle(Pens.OrangeRed, r); + } + + #endregion + + #region Hit Testing + + /// + /// Handle the HitTest request + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + if (this.Bounds.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Text; + } + + #endregion + } + + /// + /// This renderer draws a functioning button in its cell + /// + public class ColumnButtonRenderer : BaseRenderer { + + #region Properties + + /// + /// Gets or sets how each button will be sized + /// + [Category("ObjectListView"), + Description("How each button will be sized"), + DefaultValue(OLVColumn.ButtonSizingMode.TextBounds)] + public OLVColumn.ButtonSizingMode SizingMode + { + get { return this.sizingMode; } + set { this.sizingMode = value; } + } + private OLVColumn.ButtonSizingMode sizingMode = OLVColumn.ButtonSizingMode.TextBounds; + + /// + /// Gets or sets the size of the button when the SizingMode is FixedBounds + /// + /// If this is not set, the bounds of the cell will be used + [Category("ObjectListView"), + Description("The size of the button when the SizingMode is FixedBounds"), + DefaultValue(null)] + public Size? ButtonSize + { + get { return this.buttonSize; } + set { this.buttonSize = value; } + } + private Size? buttonSize; + + /// + /// Gets or sets the extra space that surrounds the cell when the SizingMode is TextBounds + /// + [Category("ObjectListView"), + Description("The extra space that surrounds the cell when the SizingMode is TextBounds")] + public Size? ButtonPadding + { + get { return this.buttonPadding; } + set { this.buttonPadding = value; } + } + private Size? buttonPadding = new Size(10, 10); + + private Size ButtonPaddingOrDefault { + get { return this.ButtonPadding ?? new Size(10, 10); } + } + + /// + /// Gets or sets the maximum width that a button can occupy. + /// -1 means there is no maximum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The maximum width that a button can occupy when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MaxButtonWidth + { + get { return this.maxButtonWidth; } + set { this.maxButtonWidth = value; } + } + private int maxButtonWidth = -1; + + /// + /// Gets or sets the minimum width that a button can occupy. + /// -1 means there is no minimum width. + /// + /// This is only considered when the SizingMode is TextBounds + [Category("ObjectListView"), + Description("The minimum width that a button can be when the SizingMode is TextBounds"), + DefaultValue(-1)] + public int MinButtonWidth { + get { return this.minButtonWidth; } + set { this.minButtonWidth = value; } + } + private int minButtonWidth = -1; + + #endregion + + #region Rendering + + /// + /// Calculate the size of the contents + /// + /// + /// + /// + protected override Size CalculateContentSize(Graphics g, Rectangle r) { + if (this.SizingMode == OLVColumn.ButtonSizingMode.CellBounds) + return r.Size; + + if (this.SizingMode == OLVColumn.ButtonSizingMode.FixedBounds) + return this.ButtonSize ?? r.Size; + + // Ok, SizingMode must be TextBounds. So figure out the size of the text + Size textSize = this.CalculateTextSize(g, this.GetText(), r.Width); + + // Allow for padding and max width + textSize.Height += this.ButtonPaddingOrDefault.Height * 2; + textSize.Width += this.ButtonPaddingOrDefault.Width * 2; + if (this.MaxButtonWidth != -1 && textSize.Width > this.MaxButtonWidth) + textSize.Width = this.MaxButtonWidth; + if (textSize.Width < this.MinButtonWidth) + textSize.Width = this.MinButtonWidth; + + return textSize; + } + + /// + /// Draw the button + /// + /// + /// + protected override void DrawImageAndText(Graphics g, Rectangle r) { + TextFormatFlags textFormatFlags = TextFormatFlags.HorizontalCenter | + TextFormatFlags.VerticalCenter | + TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPadding | + TextFormatFlags.SingleLine | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.ListView.RightToLeftLayout) + textFormatFlags |= TextFormatFlags.RightToLeft; + + string buttonText = GetText(); + if (!String.IsNullOrEmpty(buttonText)) + ButtonRenderer.DrawButton(g, r, buttonText, this.Font, textFormatFlags, false, CalculatePushButtonState()); + } + + /// + /// What part of the control is under the given point? + /// + /// + /// + /// + /// + /// + protected override void StandardHitTest(Graphics g, OlvListViewHitTestInfo hti, Rectangle bounds, int x, int y) { + Rectangle r = ApplyCellPadding(bounds); + if (r.Contains(x, y)) + hti.HitTestLocation = HitTestLocation.Button; + } + + /// + /// What is the state of the button? + /// + /// + protected PushButtonState CalculatePushButtonState() { + if (!this.ListItem.Enabled && !this.Column.EnableButtonWhenItemIsDisabled) + return PushButtonState.Disabled; + + if (this.IsButtonHot) + return ObjectListView.IsLeftMouseDown ? PushButtonState.Pressed : PushButtonState.Hot; + + return PushButtonState.Normal; + } + + /// + /// Is the mouse over the button? + /// + protected bool IsButtonHot { + get { + return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.Button; + } + } + + #endregion + } +} diff --git a/ObjectListView/Rendering/Styles.cs b/ObjectListView/Rendering/Styles.cs new file mode 100644 index 0000000..bc1daa2 --- /dev/null +++ b/ObjectListView/Rendering/Styles.cs @@ -0,0 +1,400 @@ +/* + * Styles - A style is a group of formatting attributes that can be applied to a row or a cell + * + * Author: Phillip Piper + * Date: 29/07/2009 23:09 + * + * Change log: + * v2.4 + * 2010-03-23 JPP - Added HeaderFormatStyle and support + * v2.3 + * 2009-08-15 JPP - Added Decoration and Overlay properties to HotItemStyle + * 2009-07-29 JPP - Initial version + * + * To do: + * - These should be more generally available. It should be possible to do something like this: + * this.olv.GetItem(i).Style = new ItemStyle(); + * this.olv.GetItem(i).GetSubItem(j).Style = new CellStyle(); + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// The common interface supported by all style objects + /// + public interface IItemStyle + { + /// + /// Gets or set the font that will be used by this style + /// + Font Font { get; set; } + + /// + /// Gets or set the font style + /// + FontStyle FontStyle { get; set; } + + /// + /// Gets or sets the ForeColor + /// + Color ForeColor { get; set; } + + /// + /// Gets or sets the BackColor + /// + Color BackColor { get; set; } + } + + /// + /// Basic implementation of IItemStyle + /// + public class SimpleItemStyle : System.ComponentModel.Component, IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font + { + get { return this.font; } + set { this.font = value; } + } + + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle + { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color ForeColor + { + get { return this.foreColor; } + set { this.foreColor = value; } + } + + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof (Color), "")] + public Color BackColor + { + get { return this.backColor; } + set { this.backColor = value; } + } + + private Color backColor; + } + + + /// + /// Instances of this class specify how should "hot items" (non-selected + /// rows under the cursor) be rendered. + /// + public class HotItemStyle : SimpleItemStyle + { + /// + /// Gets or sets the overlay that should be drawn as part of the hot item + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IOverlay Overlay { + get { return this.overlay; } + set { this.overlay = value; } + } + private IOverlay overlay; + + /// + /// Gets or sets the decoration that should be drawn as part of the hot item + /// + /// A decoration is different from an overlay in that an decoration + /// scrolls with the listview contents, whilst an overlay does not. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IDecoration Decoration { + get { return this.decoration; } + set { this.decoration = value; } + } + private IDecoration decoration; + } + + /// + /// This class defines how a cell should be formatted + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class CellStyle : IItemStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the style of font that will be applied by this style + /// + [DefaultValue(FontStyle.Regular)] + public FontStyle FontStyle { + get { return this.fontStyle; } + set { this.fontStyle = value; } + } + private FontStyle fontStyle; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + } + + /// + /// Instances of this class describe how hyperlinks will appear + /// + public class HyperlinkStyle : System.ComponentModel.Component + { + /// + /// Create a HyperlinkStyle + /// + public HyperlinkStyle() { + this.Normal = new CellStyle(); + this.Normal.ForeColor = Color.Blue; + this.Over = new CellStyle(); + this.Over.FontStyle = FontStyle.Underline; + this.Visited = new CellStyle(); + this.Visited.ForeColor = Color.Purple; + this.OverCursor = Cursors.Hand; + } + + /// + /// What sort of formatting should be applied to hyperlinks in their normal state? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn")] + public CellStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private CellStyle normalStyle; + + /// + /// What sort of formatting should be applied to hyperlinks when the mouse is over them? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn when the mouse is over them?")] + public CellStyle Over { + get { return this.overStyle; } + set { this.overStyle = value; } + } + private CellStyle overStyle; + + /// + /// What sort of formatting should be applied to hyperlinks after they have been clicked? + /// + [Category("Appearance"), + Description("How should hyperlinks be drawn after they have been clicked")] + public CellStyle Visited { + get { return this.visitedStyle; } + set { this.visitedStyle = value; } + } + private CellStyle visitedStyle; + + /// + /// Gets or sets the cursor that should be shown when the mouse is over a hyperlink. + /// + [Category("Appearance"), + Description("What cursor should be shown when the mouse is over a link?")] + public Cursor OverCursor { + get { return this.overCursor; } + set { this.overCursor = value; } + } + private Cursor overCursor; + } + + /// + /// Instances of this class control one the styling of one particular state + /// (normal, hot, pressed) of a header control + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public class HeaderStateStyle + { + /// + /// Gets or sets the font that will be applied by this style + /// + [DefaultValue(null)] + public Font Font { + get { return this.font; } + set { this.font = value; } + } + private Font font; + + /// + /// Gets or sets the color of the text that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color ForeColor { + get { return this.foreColor; } + set { this.foreColor = value; } + } + private Color foreColor; + + /// + /// Gets or sets the background color that will be applied by this style + /// + [DefaultValue(typeof(Color), "")] + public Color BackColor { + get { return this.backColor; } + set { this.backColor = value; } + } + private Color backColor; + + /// + /// Gets or sets the color in which a frame will be drawn around the header for this column + /// + [DefaultValue(typeof(Color), "")] + public Color FrameColor { + get { return this.frameColor; } + set { this.frameColor = value; } + } + private Color frameColor; + + /// + /// Gets or sets the width of the frame that will be drawn around the header for this column + /// + [DefaultValue(0.0f)] + public float FrameWidth { + get { return this.frameWidth; } + set { this.frameWidth = value; } + } + private float frameWidth; + } + + /// + /// This class defines how a header should be formatted in its various states. + /// + public class HeaderFormatStyle : System.ComponentModel.Component + { + /// + /// Create a new HeaderFormatStyle + /// + public HeaderFormatStyle() { + this.Hot = new HeaderStateStyle(); + this.Normal = new HeaderStateStyle(); + this.Pressed = new HeaderStateStyle(); + } + + /// + /// What sort of formatting should be applied to a column header when the mouse is over it? + /// + [Category("Appearance"), + Description("How should the header be drawn when the mouse is over it?")] + public HeaderStateStyle Hot { + get { return this.hotStyle; } + set { this.hotStyle = value; } + } + private HeaderStateStyle hotStyle; + + /// + /// What sort of formatting should be applied to a column header in its normal state? + /// + [Category("Appearance"), + Description("How should a column header normally be drawn")] + public HeaderStateStyle Normal { + get { return this.normalStyle; } + set { this.normalStyle = value; } + } + private HeaderStateStyle normalStyle; + + /// + /// What sort of formatting should be applied to a column header when pressed? + /// + [Category("Appearance"), + Description("How should a column header be drawn when it is pressed")] + public HeaderStateStyle Pressed { + get { return this.pressedStyle; } + set { this.pressedStyle = value; } + } + private HeaderStateStyle pressedStyle; + + /// + /// Set the font for all three states + /// + /// + public void SetFont(Font font) { + this.Normal.Font = font; + this.Hot.Font = font; + this.Pressed.Font = font; + } + + /// + /// Set the fore color for all three states + /// + /// + public void SetForeColor(Color color) { + this.Normal.ForeColor = color; + this.Hot.ForeColor = color; + this.Pressed.ForeColor = color; + } + + /// + /// Set the back color for all three states + /// + /// + public void SetBackColor(Color color) { + this.Normal.BackColor = color; + this.Hot.BackColor = color; + this.Pressed.BackColor = color; + } + } +} diff --git a/ObjectListView/Rendering/TreeRenderer.cs b/ObjectListView/Rendering/TreeRenderer.cs new file mode 100644 index 0000000..a3bef8a --- /dev/null +++ b/ObjectListView/Rendering/TreeRenderer.cs @@ -0,0 +1,309 @@ +/* + * TreeRenderer - Draw the major column in a TreeListView + * + * Author: Phillip Piper + * Date: 27/06/2015 + * + * Change log: + * 2016-07-17 JPP - Added TreeRenderer.UseTriangles and IsShowGlyphs + * 2015-06-27 JPP - Split out from TreeListView.cs + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; + +namespace BrightIdeasSoftware { + + public partial class TreeListView { + /// + /// This class handles drawing the tree structure of the primary column. + /// + public class TreeRenderer : HighlightTextRenderer { + /// + /// Create a TreeRenderer + /// + public TreeRenderer() { + this.LinePen = new Pen(Color.Blue, 1.0f); + this.LinePen.DashStyle = DashStyle.Dot; + } + + #region Configuration properties + + /// + /// Should the renderer draw glyphs at the expansion points? + /// + /// The expansion points will still function to expand/collapse even if this is false. + public bool IsShowGlyphs + { + get { return isShowGlyphs; } + set { isShowGlyphs = value; } + } + private bool isShowGlyphs = true; + + /// + /// Should the renderer draw lines connecting siblings? + /// + public bool IsShowLines + { + get { return isShowLines; } + set { isShowLines = value; } + } + private bool isShowLines = true; + + /// + /// Return the pen that will be used to draw the lines between branches + /// + public Pen LinePen + { + get { return linePen; } + set { linePen = value; } + } + private Pen linePen; + + /// + /// Should the renderer draw triangles as the expansion glyphs? + /// + /// + /// This looks best with ShowLines = false + /// + public bool UseTriangles + { + get { return useTriangles; } + set { useTriangles = value; } + } + private bool useTriangles = false; + + #endregion + + /// + /// Return the branch that the renderer is currently drawing. + /// + private Branch Branch { + get { + return this.TreeListView.TreeModel.GetBranch(this.RowObject); + } + } + + /// + /// Return the TreeListView for which the renderer is being used. + /// + public TreeListView TreeListView { + get { + return (TreeListView)this.ListView; + } + } + + /// + /// How many pixels will be reserved for each level of indentation? + /// + public static int PIXELS_PER_LEVEL = 16 + 1; + + /// + /// The real work of drawing the tree is done in this method + /// + /// + /// + public override void Render(System.Drawing.Graphics g, System.Drawing.Rectangle r) { + this.DrawBackground(g, r); + + Branch br = this.Branch; + + Rectangle paddedRectangle = this.ApplyCellPadding(r); + + Rectangle expandGlyphRectangle = paddedRectangle; + expandGlyphRectangle.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + expandGlyphRectangle.Width = PIXELS_PER_LEVEL; + expandGlyphRectangle.Height = PIXELS_PER_LEVEL; + expandGlyphRectangle.Y = this.AlignVertically(paddedRectangle, expandGlyphRectangle); + int expandGlyphRectangleMidVertical = expandGlyphRectangle.Y + (expandGlyphRectangle.Height/2); + + if (this.IsShowLines) + this.DrawLines(g, r, this.LinePen, br, expandGlyphRectangleMidVertical); + + if (br.CanExpand && this.IsShowGlyphs) + this.DrawExpansionGlyph(g, expandGlyphRectangle, br.IsExpanded); + + int indent = br.Level * PIXELS_PER_LEVEL; + paddedRectangle.Offset(indent, 0); + paddedRectangle.Width -= indent; + + this.DrawImageAndText(g, paddedRectangle); + } + + /// + /// Draw the expansion indicator + /// + /// + /// + /// + protected virtual void DrawExpansionGlyph(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseStyles) { + this.DrawExpansionGlyphStyled(g, r, isExpanded); + } else { + this.DrawExpansionGlyphManual(g, r, isExpanded); + } + } + + /// + /// Gets whether or not we should render using styles + /// + protected virtual bool UseStyles { + get { + return !this.IsPrinting && Application.RenderWithVisualStyles; + } + } + + /// + /// Draw the expansion indicator using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphStyled(Graphics g, Rectangle r, bool isExpanded) { + if (this.UseTriangles && this.IsShowLines) { + using (SolidBrush b = new SolidBrush(GetBackgroundColor())) { + Rectangle r2 = r; + r2.Inflate(-2, -2); + g.FillRectangle(b, r2); + } + } + + VisualStyleRenderer renderer = new VisualStyleRenderer(DecideVisualElement(isExpanded)); + renderer.DrawBackground(g, r); + } + + private VisualStyleElement DecideVisualElement(bool isExpanded) { + string klass = this.UseTriangles ? "Explorer::TreeView" : "TREEVIEW"; + int part = this.UseTriangles && this.IsExpansionHot ? 4 : 2; + int state = isExpanded ? 2 : 1; + return VisualStyleElement.CreateElement(klass, part, state); + } + + /// + /// Is the mouse over a checkbox in this cell? + /// + protected bool IsExpansionHot { + get { return this.IsCellHot && this.ListView.HotCellHitLocation == HitTestLocation.ExpandButton; } + } + + /// + /// Draw the expansion indicator without using styles + /// + /// + /// + /// + protected virtual void DrawExpansionGlyphManual(Graphics g, Rectangle r, bool isExpanded) { + int h = 8; + int w = 8; + int x = r.X + 4; + int y = r.Y + (r.Height / 2) - 4; + + g.DrawRectangle(new Pen(SystemBrushes.ControlDark), x, y, w, h); + g.FillRectangle(Brushes.White, x + 1, y + 1, w - 1, h - 1); + g.DrawLine(Pens.Black, x + 2, y + 4, x + w - 2, y + 4); + + if (!isExpanded) + g.DrawLine(Pens.Black, x + 4, y + 2, x + 4, y + h - 2); + } + + /// + /// Draw the lines of the tree + /// + /// + /// + /// + /// + /// + protected virtual void DrawLines(Graphics g, Rectangle r, Pen p, Branch br, int glyphMidVertical) { + Rectangle r2 = r; + r2.Width = PIXELS_PER_LEVEL; + + // Vertical lines have to start on even points, otherwise the dotted line looks wrong. + // This is only needed if pen is dotted. + int top = r2.Top; + //if (p.DashStyle == DashStyle.Dot && (top & 1) == 0) + // top += 1; + + // Draw lines for ancestors + int midX; + IList ancestors = br.Ancestors; + foreach (Branch ancestor in ancestors) { + if (!ancestor.IsLastChild && !ancestor.IsOnlyBranch) { + midX = r2.Left + r2.Width / 2; + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + r2.Offset(PIXELS_PER_LEVEL, 0); + } + + // Draw lines for this branch + midX = r2.Left + r2.Width / 2; + + // Horizontal line first + g.DrawLine(p, midX, glyphMidVertical, r2.Right, glyphMidVertical); + + // Vertical line second + if (br.IsFirstBranch) { + if (!br.IsLastChild && !br.IsOnlyBranch) + g.DrawLine(p, midX, glyphMidVertical, midX, r2.Bottom); + } else { + if (br.IsLastChild) + g.DrawLine(p, midX, top, midX, glyphMidVertical); + else + g.DrawLine(p, midX, top, midX, r2.Bottom); + } + } + + /// + /// Do the hit test + /// + /// + /// + /// + /// + protected override void HandleHitTest(Graphics g, OlvListViewHitTestInfo hti, int x, int y) { + Branch br = this.Branch; + + Rectangle r = this.ApplyCellPadding(this.Bounds); + if (br.CanExpand) { + r.Offset((br.Level - 1) * PIXELS_PER_LEVEL, 0); + r.Width = PIXELS_PER_LEVEL; + if (r.Contains(x, y)) { + hti.HitTestLocation = HitTestLocation.ExpandButton; + return; + } + } + + r = this.Bounds; + int indent = br.Level * PIXELS_PER_LEVEL; + r.X += indent; + r.Width -= indent; + + // Ignore events in the indent zone + if (x < r.Left) { + hti.HitTestLocation = HitTestLocation.Nothing; + } else { + this.StandardHitTest(g, hti, r, x, y); + } + } + + /// + /// Calculate the edit rect + /// + /// + /// + /// + /// + /// + /// + protected override Rectangle HandleGetEditRectangle(Graphics g, Rectangle cellBounds, OLVListItem item, int subItemIndex, Size preferredSize) { + return this.StandardGetEditRectangle(g, cellBounds, preferredSize); + } + } + } +} \ No newline at end of file diff --git a/ObjectListView/Resources/clear-filter.png b/ObjectListView/Resources/clear-filter.png new file mode 100644 index 0000000000000000000000000000000000000000..2ddf7073b0c3de5791448e7a8effdf05f2c25e77 GIT binary patch literal 1381 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu3$w13IYNSK;YpJ;1K`>2|$pMP*6~?L4aXGMZtoMfCCZ?4-^DGXfXWOVECXR@E?dQ z1pYfH{P$4!A7F4Hz~MoF!-oim{|OHNGaUXG1pKcE_)wAXABY+fK6DiP? zKrmy%f&~jUtk?hoJ2qU{vEjpnh7U6u{?BN50A#ON@L|J(4?8v-*m2;)feiRR|N(hXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr_kFdQ zoeld1Cq2lBJ3DomuG-I@|6fF&{HffzJymf>EyJTdrCUYrF&?;bSL@WRXdYXZ8L_8& z<{G4lv8T+tYq*RrCy!C_(dAdCziTk7Os_f-vdCUx*~%@3S$j_~ZHe|x2$B30aO11n q@yq4if(I79Qcsd^-jTfMt#}vzTCZ0dwIzWLW$<+Mb6Mw<&;$TKY4H>Q literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/coffee.jpg b/ObjectListView/Resources/coffee.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6032d83fc7a5e1db6b76067d8de98e2bce6619c4 GIT binary patch literal 73464 zcmeFY1yG#Lwl@0W7TkinTX2T}!G;Wk!96&GyGsN@u;A|Q5Zoa_gS!R@5+Jy{-O0Dl z+50=E&i~(g{#$jcZk;sD@O1a;?zNs?Q>=G&&*R+V3V;KWQA? z3AF$KFc@G3000$$4~7DWFa!sy@a&KSD6qdzV0A{=3n1Tty`la_f65;Q{xI-|fjD!z zOIcVl0~SdbyoB02z~caboxQ6wL|&R&TSu1~Wds&`paIALHvkx$x;TQ>T1GD`l^A9Zf8=KkLo55t%VA#>j&g?htg5i(uZsstI zpajDo+@a>zXewZed{|Y6Wu-TXR=ej#tK}Hpb3o z)G`isj>h(0z&}j>JqW=2O)WKyV*zeq0RavkP8j?DEdSfie@gxD!SAj8hs3GsUt0!8 zH1w~we~tZDn?nu&2*GGUi27HXNiqO51OdR)g@3itX8{0qAOO^l{>>hu-|k}N>gp)M z#pU7Q!3i}t<^0X(Kg<8Ez&|Db*WhpKasFQKpWIQuFt;#vvvsBZO{%Gbt%I90wTq*% zsW~;rfA-=3u-9nL(DDAoz3lGOKHNK3~Fx)+iiO@s4LXLo*HWZzuMvd!(o5Z z0RaBt)UYP}ya#~5h!emWB>)iihX6!;3;;nt1J(og&s}?orV0H1*lAI1{ln@1n(D8Q zGVB8r39J2nNcm@Rfm%}kuE;>tsZHIS-T%>n`1=nMfDT~89%o1ZN`MYv1~>p7KoAfG zo&&M~2v7mk0Uf{)Fa@jtJHQ$60DOVBzy}}wpt6ciE^HWYCb6%=C>SCkJZ$tYzg9Vinh8z@(( z7^qaJJg9Q0x~TT3?@$v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}^L*~7Y~)H_ z*GvAcdnK{TZ83Ht!tRZI(}Ok7=4m;={}=?c4|s{sbwRNKtacss!X_wm&)}wGjH{ zGnHKJ6j$lp>Qez9Yg>Knp8nY+N5{G-Own;6Vs7ZQ>%SI;{~K#^ z#9&}JZnwl^)SBRh2emxT`bQ`Iu{Wbj`3#}kuFQDHMOd8B87~my<^d`>{x3QAzxN9N zewO8lcF!^=ImW2-(=sc1ao_{cqU_k!{_*qLcp=b&S~KQDwda))^t9c(W#*v77eeug zdqyjU;}6c2v~v_C@`k)3^h8mf&hyFrnd$zsFZ%a){m-+<4m|u^m;>K zOVLAH zwqMUPvObT@b~-;Q{6Bpz7C+9@8hgTdK96qMrWwP>?eOq4NKl zxczybKf?jjqkcZxxDCR`NTJZs*gEz}&eiO%6&U?uP(Hm8&9515nCeje+=@8zDZFZCzP{>*a=dy$?G%>Nq@B0eCa7sd#J7IkJq zm!0f+-PaeoT3G()iv|47jiZ>>>!|Tjs!_^hsvDcmGmXrLhma$air4Pwtw&y@*TW!J z92IMU3%Q#;{TZUvNV&xE6sGWTcOMk8Arr7!U5B}ML-s_`t!wa*0)so)8?@@0?e$U7 zoZzmaPpL}$QSg)45*y=dbm@xm3&Ey$DAO~{cpgiQ|I(xWcQ1fq6;BUin661Sykgs5 ullEp5c{-Ly7?1km;*=ymtZauJUEbUWocnWm|MR!>f11Mohu8jo`o92pXb&|2 literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/filter-icons3.png b/ObjectListView/Resources/filter-icons3.png new file mode 100644 index 0000000000000000000000000000000000000000..80178919d5b63ab83df2b7c669ab0779a49aa2aa GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^+(695!3-or^+GlRDVB6cUq=Rpjs4tz5?L7-m>B|m zLR>-OY^*$7-1heN&W=uQZf+hP9-f|_-hqLkp`l@6VHp`2`FT0T#l=NMCB?<1B}K(e zO)YJ0ZTkrW0Q7{?;10DkVe@>jlz`)2*666>Be`EuO;P33J zzzE?i@Q5sCVBk9h!i=ICUJXD&$r9IylHmNblJdl&REB`W%)AmkKi3e2GGjecJqvT| zhFG8?MUW!rqSVBa%=|oskj&gv1|tJQLn{LlD?>vCBSR}gBP(MQ&19DgK*fQcE{-7* z;jU-hg&GtXm>qO(2x@=3_wWB9j=m(lnN#F*)B0@kMOI+Vn;qXQmn}9~_T~=D z+XX%QB%0i|8O%7kPm;e@o7oiiks3xCpOkgD9y%{jLaR6H_xy85}S Ib4q9e03rsV#sB~S literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-ascending.png b/ObjectListView/Resources/sort-ascending.png new file mode 100644 index 0000000000000000000000000000000000000000..a21be93fa9f9415cfb652bd3f1fea9f14d09338c GIT binary patch literal 1364 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1E30yA9S={>)b#X{vND5!2?h}ptRkldbB_{`{(WMnzDc9vUQs_&0BM1<bo1Nd^W+hLRw^;Qu2VFa&>RR|SSK zXMsm#F#`kNArNL1)$nQn3QCr^MwA5Sr=C^PE^0&oV$SnRjJ>Se)@el9KzgPb(xGQ0`HCE5kgy}D{ z`~Ouz>UtNs#CGW&tXB%1p1&yert|7m7J~gd`a(DPrKwMx!92N9ht=$^ar1VS;Aj5% zj}5qGI!+k)v>%we)P+^=ZeLFF8>M517RUD-ikl)^c|iKt?Ty_hV~;%rx{JZn)z4*} HQ$iB}j@iab literal 0 HcmV?d00001 diff --git a/ObjectListView/Resources/sort-descending.png b/ObjectListView/Resources/sort-descending.png new file mode 100644 index 0000000000000000000000000000000000000000..92dbe63f20afc6c51cf837b3aa6b0de64bfd126d GIT binary patch literal 1371 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U~1D=Pzs0xPd_tHAPdYaI_y&(!qvlCm-bj|PW`1wjezAz8Cy3uk*KEb+`(5>mJ_ zzIa_`?dFp19SsHwZPq$dt*v|9EvGtJPjGOU;1Mu2FmhH_{erCc1!=j<%W^iBl`XC9 zUtQhMFk$`t#fzse-MhMN`o{iwySt|BpSf(^rcI02A6d8a^twH#_Z~dB@6@g1%a)zk zwD#DAn

      dzjor>jk9NOoV#%O_LIwZpWS`@{PE+*Po6w|`R*Oi*`r`I1Sk&yjoeww z7#J8CN`m}?|Br0I5d5886&RwN1s;*b3=DjSK$uZf!>a)(C|TkfQ4*Y=R#Ki=l*$m0 zn3-3i=jR%tP-d)Ws%K$t-4F{@qzF>vT$Gwvl9`{U5R#dj%3x$*XlP|%Vr6KgU|?xw zWMXAtBrKh33{*VX)5S4FBRIB?o$rtVkE^f7?kRgUb8oi9nmze<{a1>@M6*p#p1k~N z-Eu`SL2~V)lb*#tCz*=Q4?JJNw&&=s+HH*Mod1ib@bvsXa8~LjPfF4c_V0OmAFLZw zPrO#0*_f`&8uipQN%z&d#SVpjdlp=i+dJcJioJkf_=1P$=Bx_(H07fFXSt;FNoxyO jXDxlJeOk+k^#@aL!J4$pI`)r1=P`J?`njxgN@xNAhOF7) literal 0 HcmV?d00001 diff --git a/ObjectListView/SubControls/GlassPanelForm.cs b/ObjectListView/SubControls/GlassPanelForm.cs new file mode 100644 index 0000000..bcaba67 --- /dev/null +++ b/ObjectListView/SubControls/GlassPanelForm.cs @@ -0,0 +1,459 @@ +/* + * GlassPanelForm - A transparent form that is placed over an ObjectListView + * to allow flicker-free overlay images during scrolling. + * + * Author: Phillip Piper + * Date: 14/04/2009 4:36 PM + * + * Change log: + * 2010-08-18 JPP - Added WS_EX_TOOLWINDOW style so that the form won't appear in Alt-Tab list. + * v2.4 + * 2010-03-11 JPP - Work correctly in MDI applications -- more or less. Actually, less than more. + * They don't crash but they don't correctly handle overlapping MDI children. + * Overlays from one control are shown on top of the other windows. + * 2010-03-09 JPP - Correctly Unbind() when the related ObjectListView is disposed. + * 2009-10-28 JPP - Use FindForm() rather than TopMostControl, since the latter doesn't work + * as I expected when the OLV is part of an MDI child window. Thanks to + * wvd_vegt who tracked this down. + * v2.3 + * 2009-08-19 JPP - Only hide the glass pane on resize, not on move + * - Each glass panel now only draws one overlays + * v2.2 + * 2009-06-05 JPP - Handle when owning window is a topmost window + * 2009-04-14 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + ///

      + /// A GlassPanelForm sits transparently over an ObjectListView to show overlays. + /// + internal partial class GlassPanelForm : Form + { + public GlassPanelForm() { + this.Name = "GlassPanelForm"; + this.Text = "GlassPanelForm"; + + ClientSize = new System.Drawing.Size(0, 0); + ControlBox = false; + FormBorderStyle = FormBorderStyle.None; + SizeGripStyle = SizeGripStyle.Hide; + StartPosition = FormStartPosition.Manual; + MaximizeBox = false; + MinimizeBox = false; + ShowIcon = false; + ShowInTaskbar = false; + FormBorderStyle = FormBorderStyle.None; + + SetStyle(ControlStyles.Selectable, false); + + this.Opacity = 0.5f; + this.BackColor = Color.FromArgb(255, 254, 254, 254); + this.TransparencyKey = this.BackColor; + this.HideGlass(); + NativeMethods.ShowWithoutActivate(this); + } + + protected override void Dispose(bool disposing) { + if (disposing) + this.Unbind(); + + base.Dispose(disposing); + } + + #region Properties + + /// + /// Get the low-level windows flag that will be given to CreateWindow. + /// + protected override CreateParams CreateParams { + get { + CreateParams cp = base.CreateParams; + cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT + cp.ExStyle |= 0x80; // WS_EX_TOOLWINDOW + return cp; + } + } + + #endregion + + #region Commands + + /// + /// Attach this form to the given ObjectListView + /// + public void Bind(ObjectListView olv, IOverlay overlay) { + if (this.objectListView != null) + this.Unbind(); + + this.objectListView = olv; + this.Overlay = overlay; + this.mdiClient = null; + this.mdiOwner = null; + + if (this.objectListView == null) + return; + + // NOTE: If you listen to any events here, you *must* stop listening in Unbind() + + this.objectListView.Disposed += new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged += new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged += new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged += new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged += new EventHandler(objectListView_ParentChanged); + + // Collect our ancestors in the widget hierarchy + if (this.ancestors == null) + this.ancestors = new List(); + Control parent = this.objectListView.Parent; + while (parent != null) { + this.ancestors.Add(parent); + parent = parent.Parent; + } + + // Listen for changes in the hierarchy + foreach (Control ancestor in this.ancestors) { + ancestor.ParentChanged += new EventHandler(objectListView_ParentChanged); + TabControl tabControl = ancestor as TabControl; + if (tabControl != null) { + tabControl.Selected += new TabControlEventHandler(tabControl_Selected); + } + } + + // Listen for changes in our owning form + this.Owner = this.objectListView.FindForm(); + this.myOwner = this.Owner; + if (this.Owner != null) { + this.Owner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.Owner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.Owner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.Owner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + if (this.Owner.TopMost) { + // We can't do this.TopMost = true; since that will activate the panel, + // taking focus away from the owner of the listview + NativeMethods.MakeTopMost(this); + } + + // We need special code to handle MDI + this.mdiOwner = this.Owner.MdiParent; + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged += new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged += new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin += new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd += new EventHandler(Owner_ResizeEnd); + + // Find the MDIClient control, which houses all MDI children + foreach (Control c in this.mdiOwner.Controls) { + this.mdiClient = c as MdiClient; + if (this.mdiClient != null) { + break; + } + } + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged += new EventHandler(myMdiClient_ClientSizeChanged); + } + } + } + + this.UpdateTransparency(); + } + + void myMdiClient_ClientSizeChanged(object sender, EventArgs e) { + this.RecalculateBounds(); + this.Invalidate(); + } + + /// + /// Made the overlay panel invisible + /// + public void HideGlass() { + if (!this.isGlassShown) + return; + this.isGlassShown = false; + this.Bounds = new Rectangle(-10000, -10000, 1, 1); + } + + /// + /// Show the overlay panel in its correctly location + /// + /// + /// If the panel is always shown, this method does nothing. + /// If the panel is being resized, this method also does nothing. + /// + public void ShowGlass() { + if (this.isGlassShown || this.isDuringResizeSequence) + return; + + this.isGlassShown = true; + this.RecalculateBounds(); + } + + /// + /// Detach this glass panel from its previous ObjectListView + /// + /// + /// You should unbind the overlay panel before making any changes to the + /// widget hierarchy. + /// + public void Unbind() { + if (this.objectListView != null) { + this.objectListView.Disposed -= new EventHandler(objectListView_Disposed); + this.objectListView.LocationChanged -= new EventHandler(objectListView_LocationChanged); + this.objectListView.SizeChanged -= new EventHandler(objectListView_SizeChanged); + this.objectListView.VisibleChanged -= new EventHandler(objectListView_VisibleChanged); + this.objectListView.ParentChanged -= new EventHandler(objectListView_ParentChanged); + this.objectListView = null; + } + + if (this.ancestors != null) { + foreach (Control parent in this.ancestors) { + parent.ParentChanged -= new EventHandler(objectListView_ParentChanged); + TabControl tabControl = parent as TabControl; + if (tabControl != null) { + tabControl.Selected -= new TabControlEventHandler(tabControl_Selected); + } + } + this.ancestors = null; + } + + if (this.myOwner != null) { + this.myOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.myOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.myOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.myOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.myOwner = null; + } + + if (this.mdiOwner != null) { + this.mdiOwner.LocationChanged -= new EventHandler(Owner_LocationChanged); + this.mdiOwner.SizeChanged -= new EventHandler(Owner_SizeChanged); + this.mdiOwner.ResizeBegin -= new EventHandler(Owner_ResizeBegin); + this.mdiOwner.ResizeEnd -= new EventHandler(Owner_ResizeEnd); + this.mdiOwner = null; + } + + if (this.mdiClient != null) { + this.mdiClient.ClientSizeChanged -= new EventHandler(myMdiClient_ClientSizeChanged); + this.mdiClient = null; + } + } + + #endregion + + #region Event Handlers + + void objectListView_Disposed(object sender, EventArgs e) { + this.Unbind(); + } + + /// + /// Handle when the form that owns the ObjectListView begins to be resized + /// + /// + /// + void Owner_ResizeBegin(object sender, EventArgs e) { + // When the top level window is being resized, we just want to hide + // the overlay window. When the resizing finishes, we want to show + // the overlay window, if it was shown before the resize started. + this.isDuringResizeSequence = true; + this.wasGlassShownBeforeResize = this.isGlassShown; + } + + /// + /// Handle when the form that owns the ObjectListView finished to be resized + /// + /// + /// + void Owner_ResizeEnd(object sender, EventArgs e) { + this.isDuringResizeSequence = false; + if (this.wasGlassShownBeforeResize) + this.ShowGlass(); + } + + /// + /// The owning form has moved. Move the overlay panel too. + /// + /// + /// + void Owner_LocationChanged(object sender, EventArgs e) { + if (this.mdiOwner != null) + this.HideGlass(); + else + this.RecalculateBounds(); + } + + /// + /// The owning form is resizing. Hide our overlay panel until the resizing stops + /// + /// + /// + void Owner_SizeChanged(object sender, EventArgs e) { + this.HideGlass(); + } + + + /// + /// Handle when the bound OLV changes its location. The overlay panel must + /// be moved too, IFF it is currently visible. + /// + /// + /// + void objectListView_LocationChanged(object sender, EventArgs e) { + if (this.isGlassShown) { + this.RecalculateBounds(); + } + } + + /// + /// Handle when the bound OLV changes size. The overlay panel must + /// resize too, IFF it is currently visible. + /// + /// + /// + void objectListView_SizeChanged(object sender, EventArgs e) { + // This event is triggered in all sorts of places, and not always when the size changes. + //if (this.isGlassShown) { + // this.Size = this.objectListView.ClientSize; + //} + } + + /// + /// Handle when the bound OLV is part of a TabControl and that + /// TabControl changes tabs. The overlay panel is hidden. The + /// first time the bound OLV is redrawn, the overlay panel will + /// be shown again. + /// + /// + /// + void tabControl_Selected(object sender, TabControlEventArgs e) { + this.HideGlass(); + } + + /// + /// Somewhere the parent of the bound OLV has changed. Update + /// our events. + /// + /// + /// + void objectListView_ParentChanged(object sender, EventArgs e) { + ObjectListView olv = this.objectListView; + IOverlay overlay = this.Overlay; + this.Unbind(); + this.Bind(olv, overlay); + } + + /// + /// Handle when the bound OLV changes its visibility. + /// The overlay panel should match the OLV's visibility. + /// + /// + /// + void objectListView_VisibleChanged(object sender, EventArgs e) { + if (this.objectListView.Visible) + this.ShowGlass(); + else + this.HideGlass(); + } + + #endregion + + #region Implementation + + protected override void OnPaint(PaintEventArgs e) { + if (this.objectListView == null || this.Overlay == null) + return; + + Graphics g = e.Graphics; + g.TextRenderingHint = ObjectListView.TextRenderingHint; + g.SmoothingMode = ObjectListView.SmoothingMode; + //g.DrawRectangle(new Pen(Color.Green, 4.0f), this.ClientRectangle); + + // If we are part of an MDI app, make sure we don't draw outside the bounds + if (this.mdiClient != null) { + Rectangle r = mdiClient.RectangleToScreen(mdiClient.ClientRectangle); + Rectangle r2 = this.objectListView.RectangleToClient(r); + g.SetClip(r2, System.Drawing.Drawing2D.CombineMode.Intersect); + } + + this.Overlay.Draw(this.objectListView, g, this.objectListView.ClientRectangle); + } + + protected void RecalculateBounds() { + if (!this.isGlassShown) + return; + + Rectangle rect = this.objectListView.ClientRectangle; + rect.X = 0; + rect.Y = 0; + this.Bounds = this.objectListView.RectangleToScreen(rect); + } + + internal void UpdateTransparency() { + ITransparentOverlay transparentOverlay = this.Overlay as ITransparentOverlay; + if (transparentOverlay == null) + this.Opacity = this.objectListView.OverlayTransparency / 255.0f; + else + this.Opacity = transparentOverlay.Transparency / 255.0f; + } + + protected override void WndProc(ref Message m) { + const int WM_NCHITTEST = 132; + const int HTTRANSPARENT = -1; + switch (m.Msg) { + // Ignore all mouse interactions + case WM_NCHITTEST: + m.Result = (IntPtr)HTTRANSPARENT; + break; + } + base.WndProc(ref m); + } + + #endregion + + #region Implementation variables + + internal IOverlay Overlay; + + #endregion + + #region Private variables + + private ObjectListView objectListView; + private bool isDuringResizeSequence; + private bool isGlassShown; + private bool wasGlassShownBeforeResize; + + // Cache these so we can unsubscribe from events even when the OLV has been disposed. + private Form myOwner; + private Form mdiOwner; + private List ancestors; + MdiClient mdiClient; + + #endregion + + } +} diff --git a/ObjectListView/SubControls/HeaderControl.cs b/ObjectListView/SubControls/HeaderControl.cs new file mode 100644 index 0000000..298680b --- /dev/null +++ b/ObjectListView/SubControls/HeaderControl.cs @@ -0,0 +1,1230 @@ +/* + * HeaderControl - A limited implementation of HeaderControl + * + * Author: Phillip Piper + * Date: 25/11/2008 17:15 + * + * Change log: + * 2015-06-12 JPP - Use HeaderTextAlignOrDefault instead of HeaderTextAlign + * 2014-09-07 JPP - Added ability to have checkboxes in headers + * + * 2011-05-11 JPP - Fixed bug that prevented columns from being resized in IDE Designer + * by dragging the column divider + * 2011-04-12 JPP - Added ability to draw filter indicator in a column's header + * v2.4.1 + * 2010-08-23 JPP - Added ability to draw header vertically (thanks to Mark Fenwick) + * - Uses OLVColumn.HeaderTextAlign to decide how to align the column's header + * 2010-08-08 JPP - Added ability to have image in header + * v2.4 + * 2010-03-22 JPP - Draw header using header styles + * 2009-10-30 JPP - Plugged GDI resource leak, where font handles were created during custom + * drawing, but never destroyed + * v2.3 + * 2009-10-03 JPP - Handle when ListView.HeaderFormatStyle is None + * 2009-08-24 JPP - Handle the header being destroyed + * v2.2.1 + * 2009-08-16 JPP - Correctly handle header themes + * 2009-08-15 JPP - Added formatting capabilities: font, color, word wrap + * v2.2 + * 2009-06-01 JPP - Use ToolTipControl + * 2009-05-10 JPP - Removed all unsafe code + * 2008-11-25 JPP - Initial version + * + * TO DO: + * - Put drawing code into header style object, so that it can be easily customized. + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Drawing; +using System.Runtime.Remoting; +using System.Windows.Forms; +using System.Runtime.InteropServices; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Drawing2D; +using BrightIdeasSoftware.Properties; +using System.Security.Permissions; + +namespace BrightIdeasSoftware { + + /// + /// Class used to capture window messages for the header of the list view + /// control. + /// + public class HeaderControl : NativeWindow { + /// + /// Create a header control for the given ObjectListView. + /// + /// + public HeaderControl(ObjectListView olv) { + this.ListView = olv; + this.AssignHandle(NativeMethods.GetHeaderControl(olv)); + } + + #region Properties + + /// + /// Return the index of the column under the current cursor position, + /// or -1 if the cursor is not over a column + /// + /// Index of the column under the cursor, or -1 + public int ColumnIndexUnderCursor { + get { + Point pt = this.ScrolledCursorPosition; + return NativeMethods.GetColumnUnderPoint(this.Handle, pt); + } + } + + /// + /// Return the Windows handle behind this control + /// + /// + /// When an ObjectListView is initialized as part of a UserControl, the + /// GetHeaderControl() method returns 0 until the UserControl is + /// completely initialized. So the AssignHandle() call in the constructor + /// doesn't work. So we override the Handle property so value is always + /// current. + /// + public new IntPtr Handle { + get { return NativeMethods.GetHeaderControl(this.ListView); } + } + + //TODO: The Handle property may no longer be necessary. CHECK! 2008/11/28 + + /// + /// Gets or sets a style that should be applied to the font of the + /// column's header text when the mouse is over that column + /// + /// THIS IS EXPERIMENTAL. USE AT OWN RISK. August 2009 + [Obsolete("Use HeaderStyle.Hot.FontStyle instead")] + public FontStyle HotFontStyle { + get { return FontStyle.Regular; } + set { } + } + + /// + /// Gets the index of the column under the cursor if the cursor is over it's checkbox + /// + protected int GetColumnCheckBoxUnderCursor() { + Point pt = this.ScrolledCursorPosition; + + int columnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + return this.IsPointOverHeaderCheckBox(columnIndex, pt) ? columnIndex : -1; + } + + /// + /// Gets the client rectangle for the header + /// + public Rectangle ClientRectangle { + get { + Rectangle r = new Rectangle(); + NativeMethods.GetClientRect(this.Handle, ref r); + return r; + } + } + + /// + /// Return true if the given point is over the checkbox for the given column. + /// + /// + /// + /// + protected bool IsPointOverHeaderCheckBox(int columnIndex, Point pt) { + if (columnIndex < 0 || columnIndex >= this.ListView.Columns.Count) + return false; + + OLVColumn column = this.ListView.GetColumn(columnIndex); + if (!this.HasCheckBox(column)) + return false; + + Rectangle r = this.GetCheckBoxBounds(column); + r.Inflate(1, 1); // make the target slightly bigger + return r.Contains(pt); + } + + /// + /// Gets whether the cursor is over a "locked" divider, i.e. + /// one that cannot be dragged by the user. + /// + protected bool IsCursorOverLockedDivider { + get { + Point pt = this.ScrolledCursorPosition; + int dividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + if (dividerIndex >= 0 && dividerIndex < this.ListView.Columns.Count) { + OLVColumn column = this.ListView.GetColumn(dividerIndex); + return column.IsFixedWidth || column.FillsFreeSpace; + } else + return false; + } + } + + private Point ScrolledCursorPosition { + get { + Point pt = this.ListView.PointToClient(Cursor.Position); + pt.X += this.ListView.LowLevelScrollPosition.X; + return pt; + } + } + + /// + /// Gets or sets the listview that this header belongs to + /// + protected ObjectListView ListView { + get { return this.listView; } + set { this.listView = value; } + } + + private ObjectListView listView; + + /// + /// Gets the maximum height of the header. -1 means no maximum. + /// + public int MaximumHeight + { + get { return this.ListView.HeaderMaximumHeight; } + } + + /// + /// Gets the minimum height of the header. -1 means no minimum. + /// + public int MinimumHeight + { + get { return this.ListView.HeaderMinimumHeight; } + } + + /// + /// Get or set the ToolTip that shows tips for the header + /// + public ToolTipControl ToolTip { + get { + if (this.toolTip == null) { + this.CreateToolTip(); + } + return this.toolTip; + } + protected set { this.toolTip = value; } + } + + private ToolTipControl toolTip; + + /// + /// Gets or sets whether the text in column headers should be word + /// wrapped when it is too long to fit within the column + /// + public bool WordWrap { + get { return this.wordWrap; } + set { this.wordWrap = value; } + } + + private bool wordWrap; + + #endregion + + #region Commands + + /// + /// Calculate how height the header needs to be + /// + /// Height in pixels + protected int CalculateHeight(Graphics g) { + TextFormatFlags flags = this.TextFormatFlags; + int columnUnderCursor = this.ColumnIndexUnderCursor; + float height = this.MinimumHeight; + for (int i = 0; i < this.ListView.Columns.Count; i++) { + OLVColumn column = this.ListView.GetColumn(i); + height = Math.Max(height, CalculateColumnHeight(g, column, flags, columnUnderCursor == i, i)); + } + return this.MaximumHeight == -1 ? (int) height : Math.Min(this.MaximumHeight, (int) height); + } + + private float CalculateColumnHeight(Graphics g, OLVColumn column, TextFormatFlags flags, bool isHot, int i) { + Font f = this.CalculateFont(column, isHot, false); + if (column.IsHeaderVertical) + return TextRenderer.MeasureText(g, column.Text, f, new Size(10000, 10000), flags).Width; + + const int fudge = 9; // 9 is a magic constant that makes it perfectly match XP behavior + if (!this.WordWrap) + return f.Height + fudge; + + Rectangle r = this.GetHeaderDrawRect(i); + if (this.HasNonThemedSortIndicator(column)) + r.Width -= 16; + if (column.HasHeaderImage) + r.Width -= column.ImageList.ImageSize.Width + 3; + if (this.HasFilterIndicator(column)) + r.Width -= this.CalculateFilterIndicatorWidth(r); + if (this.HasCheckBox(column)) + r.Width -= this.CalculateCheckBoxBounds(g, r).Width; + SizeF size = TextRenderer.MeasureText(g, column.Text, f, new Size(r.Width, 100), flags); + return size.Height + fudge; + } + + /// + /// Get the bounds of the checkbox against the given column + /// + /// + /// + public Rectangle GetCheckBoxBounds(OLVColumn column) { + Rectangle r = this.GetHeaderDrawRect(column.Index); + + using (Graphics g = this.ListView.CreateGraphics()) + return this.CalculateCheckBoxBounds(g, r); + } + + /// + /// Should the given column be drawn with a checkbox against it? + /// + /// + /// + public bool HasCheckBox(OLVColumn column) { + return column.HeaderCheckBox || column.HeaderTriStateCheckBox; + } + + /// + /// Should the given column show a sort indicator? + /// + /// + /// + protected bool HasSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + return column == this.ListView.LastSortColumn && this.ListView.LastSortOrder != SortOrder.None; + } + + /// + /// Should the given column be drawn with a filter indicator against it? + /// + /// + /// + protected bool HasFilterIndicator(OLVColumn column) { + return (this.ListView.UseFiltering && this.ListView.UseFilterIndicator && column.HasFilterIndicator); + } + + /// + /// Should the given column show a non-themed sort indicator? + /// + /// + /// + protected bool HasNonThemedSortIndicator(OLVColumn column) { + if (!this.ListView.ShowSortIndicators) + return false; + if (VisualStyleRenderer.IsSupported) + return !VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp) && + this.HasSortIndicator(column); + else + return this.HasSortIndicator(column); + } + + /// + /// Return the bounds of the item with the given index + /// + /// + /// + public Rectangle GetItemRect(int itemIndex) { + const int HDM_FIRST = 0x1200; + const int HDM_GETITEMRECT = HDM_FIRST + 7; + NativeMethods.RECT r = new NativeMethods.RECT(); + NativeMethods.SendMessageRECT(this.Handle, HDM_GETITEMRECT, itemIndex, ref r); + return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); + } + + /// + /// Return the bounds within which the given column will be drawn + /// + /// + /// + public Rectangle GetHeaderDrawRect(int itemIndex) { + Rectangle r = this.GetItemRect(itemIndex); + + // Tweak the text rectangle a little to improve aesthetics + r.Inflate(-3, 0); + r.Y -= 2; + + return r; + } + + /// + /// Force the header to redraw by invalidating it + /// + public void Invalidate() { + NativeMethods.InvalidateRect(this.Handle, 0, true); + } + + /// + /// Force the header to redraw a single column by invalidating it + /// + public void Invalidate(OLVColumn column) { + NativeMethods.InvalidateRect(this.Handle, 0, true); // todo + } + + #endregion + + #region Tooltip + + /// + /// Create a native tool tip control for this listview + /// + protected virtual void CreateToolTip() { + this.ToolTip = new ToolTipControl(); + this.ToolTip.Create(this.Handle); + this.ToolTip.AddTool(this); + this.ToolTip.Showing += new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + + #endregion + + #region Windows messaging + + /// + /// Override the basic message pump + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + protected override void WndProc(ref Message m) { + const int WM_DESTROY = 2; + const int WM_SETCURSOR = 0x20; + const int WM_NOTIFY = 0x4E; + const int WM_MOUSEMOVE = 0x200; + const int WM_LBUTTONDOWN = 0x201; + const int WM_LBUTTONUP = 0x202; + const int WM_MOUSELEAVE = 675; + const int HDM_FIRST = 0x1200; + const int HDM_LAYOUT = (HDM_FIRST + 5); + + // System.Diagnostics.Debug.WriteLine(String.Format("WndProc: {0}", m.Msg)); + + switch (m.Msg) { + case WM_SETCURSOR: + if (!this.HandleSetCursor(ref m)) + return; + break; + + case WM_NOTIFY: + if (!this.HandleNotify(ref m)) + return; + break; + + case WM_MOUSEMOVE: + if (!this.HandleMouseMove(ref m)) + return; + break; + + case WM_MOUSELEAVE: + if (!this.HandleMouseLeave(ref m)) + return; + break; + + case HDM_LAYOUT: + if (!this.HandleLayout(ref m)) + return; + break; + + case WM_DESTROY: + if (!this.HandleDestroy(ref m)) + return; + break; + + case WM_LBUTTONDOWN: + if (!this.HandleLButtonDown(ref m)) + return; + break; + + case WM_LBUTTONUP: + if (!this.HandleLButtonUp(ref m)) + return; + break; + } + + base.WndProc(ref m); + } + + private bool HandleReflectNotify(ref Message m) + { + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + // System.Diagnostics.Debug.WriteLine(String.Format("rn: {0}", nmhdr.code)); + return true; + } + + /// + /// Handle the LButtonDown windows message + /// + /// + /// + protected bool HandleLButtonDown(ref Message m) + { + // Was there a header checkbox under the cursor? + this.columnIndexCheckBoxMouseDown = this.GetColumnCheckBoxUnderCursor(); + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Redraw the header so the checkbox redraws + this.Invalidate(); + + // Force the owning control to ignore this mouse click + // We don't want to sort the listview when they click the checkbox + m.Result = (IntPtr)1; + return false; + } + + private int columnIndexCheckBoxMouseDown = -1; + + /// + /// Handle the LButtonUp windows message + /// + /// + /// + protected bool HandleLButtonUp(ref Message m) { + //System.Diagnostics.Debug.WriteLine("WM_LBUTTONUP"); + + // Was the mouse released over a header checkbox? + if (this.columnIndexCheckBoxMouseDown < 0) + return true; + + // Was the mouse released over the same checkbox on which it was pressed? + if (this.columnIndexCheckBoxMouseDown != this.GetColumnCheckBoxUnderCursor()) + return true; + + // Toggle the header's checkbox + OLVColumn column = this.ListView.GetColumn(this.columnIndexCheckBoxMouseDown); + this.ListView.ToggleHeaderCheckBox(column); + + return true; + } + + /// + /// Handle the SetCursor windows message + /// + /// + /// + protected bool HandleSetCursor(ref Message m) { + if (this.IsCursorOverLockedDivider) { + m.Result = (IntPtr) 1; // Don't change the cursor + return false; + } + return true; + } + + /// + /// Handle the MouseMove windows message + /// + /// + /// + protected bool HandleMouseMove(ref Message m) { + + // Forward the mouse move event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) { + int x = m.LParam.ToInt32() & 0xFFFF; + int y = (m.LParam.ToInt32() >> 16) & 0xFFFF; + this.ListView.HandleMouseMove(new Point(x, y)); + } + + int columnIndex = this.ColumnIndexUnderCursor; + + // If the mouse has moved to a different header, pop the current tip (if any) + // For some reason, references this.ToolTip when in design mode, causes the + // columns to not be resizable by dragging the divider in the Designer. No idea why. + if (columnIndex != this.columnShowingTip && !this.ListView.IsDesignMode) { + this.ToolTip.PopToolTip(this); + this.columnShowingTip = columnIndex; + } + + // If the mouse has moved onto or away from a checkbox, we need to draw + int checkBoxUnderCursor = this.GetColumnCheckBoxUnderCursor(); + if (checkBoxUnderCursor != this.lastCheckBoxUnderCursor) { + this.Invalidate(); + this.lastCheckBoxUnderCursor = checkBoxUnderCursor; + } + + return true; + } + + private int columnShowingTip = -1; + private int lastCheckBoxUnderCursor = -1; + + /// + /// Handle the MouseLeave windows message + /// + /// + /// + protected bool HandleMouseLeave(ref Message m) { + // Forward the mouse leave event to the ListView itself + if (this.ListView.TriggerCellOverEventsWhenOverHeader) + this.ListView.HandleMouseMove(new Point(-1, -1)); + + return true; + } + + /// + /// Handle the Notify windows message + /// + /// + /// + protected bool HandleNotify(ref Message m) { + // Can this ever happen? JPP 2009-05-22 + if (m.LParam == IntPtr.Zero) + return false; + + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (nmhdr.code) + { + + case ToolTipControl.TTN_SHOW: + //System.Diagnostics.Debug.WriteLine("hdr TTN_SHOW"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleShow(ref m); + + case ToolTipControl.TTN_POP: + //System.Diagnostics.Debug.WriteLine("hdr TTN_POP"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandlePop(ref m); + + case ToolTipControl.TTN_GETDISPINFO: + //System.Diagnostics.Debug.WriteLine("hdr TTN_GETDISPINFO"); + //System.Diagnostics.Trace.Assert(this.ToolTip.Handle == nmhdr.hwndFrom); + return this.ToolTip.HandleGetDispInfo(ref m); + } + + return false; + } + + /// + /// Handle the CustomDraw windows message + /// + /// + /// + internal virtual bool HandleHeaderCustomDraw(ref Message m) { + const int CDRF_NEWFONT = 2; + const int CDRF_SKIPDEFAULT = 4; + const int CDRF_NOTIFYPOSTPAINT = 0x10; + const int CDRF_NOTIFYITEMDRAW = 0x20; + + const int CDDS_PREPAINT = 1; + const int CDDS_POSTPAINT = 2; + const int CDDS_ITEM = 0x00010000; + const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT); + const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT); + + NativeMethods.NMCUSTOMDRAW nmcustomdraw = (NativeMethods.NMCUSTOMDRAW) m.GetLParam(typeof (NativeMethods.NMCUSTOMDRAW)); + //System.Diagnostics.Debug.WriteLine(String.Format("header cd: {0:x}, {1}, {2:x}", nmcustomdraw.dwDrawStage, nmcustomdraw.dwItemSpec, nmcustomdraw.uItemState)); + switch (nmcustomdraw.dwDrawStage) { + case CDDS_PREPAINT: + this.cachedNeedsCustomDraw = this.NeedsCustomDraw(); + m.Result = (IntPtr) CDRF_NOTIFYITEMDRAW; + return true; + + case CDDS_ITEMPREPAINT: + int columnIndex = nmcustomdraw.dwItemSpec.ToInt32(); + OLVColumn column = this.ListView.GetColumn(columnIndex); + + // These don't work when visual styles are enabled + //NativeMethods.SetBkColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Red)); + //NativeMethods.SetTextColor(nmcustomdraw.hdc, ColorTranslator.ToWin32(Color.Blue)); + //m.Result = IntPtr.Zero; + + if (this.cachedNeedsCustomDraw) { + using (Graphics g = Graphics.FromHdc(nmcustomdraw.hdc)) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + this.CustomDrawHeaderCell(g, columnIndex, nmcustomdraw.uItemState); + } + m.Result = (IntPtr) CDRF_SKIPDEFAULT; + } else { + const int CDIS_SELECTED = 1; + bool isPressed = ((nmcustomdraw.uItemState & CDIS_SELECTED) == CDIS_SELECTED); + + // We don't need to modify this based on checkboxes, since there can't be checkboxes if we are here + bool isHot = columnIndex == this.ColumnIndexUnderCursor; + + Font f = this.CalculateFont(column, isHot, isPressed); + + this.fontHandle = f.ToHfont(); + NativeMethods.SelectObject(nmcustomdraw.hdc, this.fontHandle); + + m.Result = (IntPtr) (CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT); + } + + return true; + + case CDDS_ITEMPOSTPAINT: + if (this.fontHandle != IntPtr.Zero) { + NativeMethods.DeleteObject(this.fontHandle); + this.fontHandle = IntPtr.Zero; + } + break; + } + + return false; + } + + private bool cachedNeedsCustomDraw; + private IntPtr fontHandle; + + /// + /// The message divides a ListView's space between the header and the rows of the listview. + /// The WINDOWPOS structure controls the headers bounds, the RECT controls the listview bounds. + /// + /// + /// + protected bool HandleLayout(ref Message m) { + if (this.ListView.HeaderStyle == ColumnHeaderStyle.None) + return true; + + NativeMethods.HDLAYOUT hdlayout = (NativeMethods.HDLAYOUT) m.GetLParam(typeof (NativeMethods.HDLAYOUT)); + NativeMethods.RECT rect = (NativeMethods.RECT) Marshal.PtrToStructure(hdlayout.prc, typeof (NativeMethods.RECT)); + NativeMethods.WINDOWPOS wpos = (NativeMethods.WINDOWPOS) Marshal.PtrToStructure(hdlayout.pwpos, typeof (NativeMethods.WINDOWPOS)); + + using (Graphics g = this.ListView.CreateGraphics()) { + g.TextRenderingHint = ObjectListView.TextRenderingHint; + int height = this.CalculateHeight(g); + wpos.hwnd = this.Handle; + wpos.hwndInsertAfter = IntPtr.Zero; + wpos.flags = NativeMethods.SWP_FRAMECHANGED; + wpos.x = rect.left; + wpos.y = rect.top; + wpos.cx = rect.right - rect.left; + wpos.cy = height; + + rect.top = height; + + Marshal.StructureToPtr(rect, hdlayout.prc, false); + Marshal.StructureToPtr(wpos, hdlayout.pwpos, false); + } + + this.ListView.BeginInvoke((MethodInvoker) delegate { + this.Invalidate(); + this.ListView.Invalidate(); + }); + return false; + } + + /// + /// Handle when the underlying header control is destroyed + /// + /// + /// + protected bool HandleDestroy(ref Message m) { + if (this.toolTip != null) { + this.toolTip.Showing -= new EventHandler(this.ListView.HeaderToolTipShowingCallback); + } + return false; + } + + #endregion + + #region Rendering + + /// + /// Does this header need to be custom drawn? + /// + /// Word wrapping and colored text require custom drawing. Funnily enough, we + /// can change the font natively. + protected bool NeedsCustomDraw() { + if (this.WordWrap) + return true; + + if (this.ListView.HeaderUsesThemes) + return false; + + if (this.NeedsCustomDraw(this.ListView.HeaderFormatStyle)) + return true; + + foreach (OLVColumn column in this.ListView.Columns) { + if (column.HasHeaderImage || + !column.ShowTextInHeader || + column.IsHeaderVertical || + this.HasFilterIndicator(column) || + this.HasCheckBox(column) || + column.TextAlign != column.HeaderTextAlignOrDefault || + (column.Index == 0 && column.HeaderTextAlignOrDefault != HorizontalAlignment.Left) || + this.NeedsCustomDraw(column.HeaderFormatStyle)) + return true; + } + + return false; + } + + private bool NeedsCustomDraw(HeaderFormatStyle style) { + if (style == null) + return false; + + return (this.NeedsCustomDraw(style.Normal) || + this.NeedsCustomDraw(style.Hot) || + this.NeedsCustomDraw(style.Pressed)); + } + + private bool NeedsCustomDraw(HeaderStateStyle style) { + if (style == null) + return false; + + // If we want fancy colors or frames, we have to custom draw. Oddly enough, we + // can handle font changes without custom drawing. + if (!style.BackColor.IsEmpty) + return true; + + if (style.FrameWidth > 0f && !style.FrameColor.IsEmpty) + return true; + + return (!style.ForeColor.IsEmpty && style.ForeColor != Color.Black); + } + + /// + /// Draw one cell of the header + /// + /// + /// + /// + protected void CustomDrawHeaderCell(Graphics g, int columnIndex, int itemState) { + OLVColumn column = this.ListView.GetColumn(columnIndex); + + bool hasCheckBox = this.HasCheckBox(column); + bool isMouseOverCheckBox = columnIndex == this.lastCheckBoxUnderCursor; + bool isMouseDownOnCheckBox = isMouseOverCheckBox && Control.MouseButtons == MouseButtons.Left; + bool isHot = (columnIndex == this.ColumnIndexUnderCursor) && (!(hasCheckBox && isMouseOverCheckBox)); + + const int CDIS_SELECTED = 1; + bool isPressed = ((itemState & CDIS_SELECTED) == CDIS_SELECTED); + + // System.Diagnostics.Debug.WriteLine(String.Format("{2:hh:mm:ss.ff} - HeaderCustomDraw: {0}, {1}", columnIndex, itemState, DateTime.Now)); + + // Calculate which style should be used for the header + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + + // If there is an owner drawn delegate installed, give it a chance to draw the header + Rectangle fullCellBounds = this.GetItemRect(columnIndex); + if (column.HeaderDrawing != null) + { + if (!column.HeaderDrawing(g, fullCellBounds, columnIndex, column, isPressed, stateStyle)) + return; + } + + // Draw the background + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot); + else + this.DrawUnthemedBackground(g, fullCellBounds, columnIndex, isPressed, isHot, stateStyle); + + Rectangle r = this.GetHeaderDrawRect(columnIndex); + + // Draw the sort indicator if this column has one + if (this.HasSortIndicator(column)) { + if (this.ListView.HeaderUsesThemes && + VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.SortArrow.SortedUp)) + this.DrawThemedSortIndicator(g, r); + else + r = this.DrawUnthemedSortIndicator(g, r); + } + + if (this.HasFilterIndicator(column)) + r = this.DrawFilterIndicator(g, r); + + if (hasCheckBox) + r = this.DrawCheckBox(g, r, column.HeaderCheckState, column.HeaderCheckBoxDisabled, isMouseOverCheckBox, isMouseDownOnCheckBox); + + // Debugging - Where is the text going to be drawn + // g.DrawRectangle(Pens.Blue, r); + + // Finally draw the text + this.DrawHeaderImageAndText(g, r, column, stateStyle); + } + + private Rectangle DrawCheckBox(Graphics g, Rectangle r, CheckState checkState, bool isDisabled, bool isHot, + bool isPressed) { + CheckBoxState checkBoxState = this.GetCheckBoxState(checkState, isDisabled, isHot, isPressed); + Rectangle checkBoxBounds = this.CalculateCheckBoxBounds(g, r); + CheckBoxRenderer.DrawCheckBox(g, checkBoxBounds.Location, checkBoxState); + + // Move the left edge without changing the right edge + int newX = checkBoxBounds.Right + 3; + r.Width -= (newX - r.X); + r.X = newX; + + return r; + } + + private Rectangle CalculateCheckBoxBounds(Graphics g, Rectangle cellBounds) { + Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.CheckedNormal); + + // Vertically center the checkbox + int topOffset = (cellBounds.Height - checkBoxSize.Height)/2; + return new Rectangle(cellBounds.X + 3, cellBounds.Y + topOffset, checkBoxSize.Width, checkBoxSize.Height); + } + + private CheckBoxState GetCheckBoxState(CheckState checkState, bool isDisabled, bool isHot, bool isPressed) { + // Should the checkbox be drawn as disabled? + if (isDisabled) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedDisabled; + case CheckState.Unchecked: + return CheckBoxState.UncheckedDisabled; + default: + return CheckBoxState.MixedDisabled; + } + } + + // Is the mouse button currently down? + if (isPressed) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedPressed; + case CheckState.Unchecked: + return CheckBoxState.UncheckedPressed; + default: + return CheckBoxState.MixedPressed; + } + } + + // Is the cursor currently over this checkbox? + if (isHot) { + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedHot; + case CheckState.Unchecked: + return CheckBoxState.UncheckedHot; + default: + return CheckBoxState.MixedHot; + } + } + + // Not hot and not disabled -- just draw it normally + switch (checkState) { + case CheckState.Checked: + return CheckBoxState.CheckedNormal; + case CheckState.Unchecked: + return CheckBoxState.UncheckedNormal; + default: + return CheckBoxState.MixedNormal; + } + } + + /// + /// Draw a background for the header, without using Themes. + /// + /// + /// + /// + /// + /// + /// + protected void DrawUnthemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot, HeaderStateStyle stateStyle) { + if (stateStyle.BackColor.IsEmpty) + // I know we're supposed to be drawing the unthemed background, but let's just see if we + // can draw something more interesting than the dull raised block + if (VisualStyleRenderer.IsSupported && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.Item.Normal)) + this.DrawThemedBackground(g, r, columnIndex, isPressed, isHot); + else + ControlPaint.DrawBorder3D(g, r, Border3DStyle.RaisedInner); + else { + using (Brush b = new SolidBrush(stateStyle.BackColor)) + g.FillRectangle(b, r); + } + + // Draw the frame if the style asks for one + if (!stateStyle.FrameColor.IsEmpty && stateStyle.FrameWidth > 0f) { + RectangleF r2 = r; + r2.Inflate(-stateStyle.FrameWidth, -stateStyle.FrameWidth); + using (Pen pen = new Pen(stateStyle.FrameColor, stateStyle.FrameWidth)) + g.DrawRectangle(pen, r2.X, r2.Y, r2.Width, r2.Height); + } + } + + /// + /// Draw a more-or-less pure themed header background. + /// + /// + /// + /// + /// + /// + protected void DrawThemedBackground(Graphics g, Rectangle r, int columnIndex, bool isPressed, bool isHot) { + int part = 1; // normal item + if (columnIndex == 0 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemLeft.Normal)) + part = 2; // left item + if (columnIndex == this.ListView.Columns.Count - 1 && + VisualStyleRenderer.IsElementDefined(VisualStyleElement.Header.ItemRight.Normal)) + part = 3; // right item + + int state = 1; // normal state + if (isPressed) + state = 3; // pressed + else if (isHot) + state = 2; // hot + + VisualStyleRenderer renderer = new VisualStyleRenderer("HEADER", part, state); + renderer.DrawBackground(g, r); + } + + /// + /// Draw a sort indicator using themes + /// + /// + /// + protected void DrawThemedSortIndicator(Graphics g, Rectangle r) { + VisualStyleRenderer renderer2 = null; + if (this.ListView.LastSortOrder == SortOrder.Ascending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedUp); + if (this.ListView.LastSortOrder == SortOrder.Descending) + renderer2 = new VisualStyleRenderer(VisualStyleElement.Header.SortArrow.SortedDown); + if (renderer2 != null) { + Size sz = renderer2.GetPartSize(g, ThemeSizeType.True); + Point pt = renderer2.GetPoint(PointProperty.Offset); + // GetPoint() should work, but if it doesn't, put the arrow in the top middle + if (pt.X == 0 && pt.Y == 0) + pt = new Point(r.X + (r.Width/2) - (sz.Width/2), r.Y); + renderer2.DrawBackground(g, new Rectangle(pt, sz)); + } + } + + /// + /// Draw a sort indicator without using themes + /// + /// + /// + /// + protected Rectangle DrawUnthemedSortIndicator(Graphics g, Rectangle r) { + // No theme support for sort indicators. So, we draw a triangle at the right edge + // of the column header. + const int triangleHeight = 16; + const int triangleWidth = 16; + const int midX = triangleWidth/2; + const int midY = (triangleHeight/2) - 1; + const int deltaX = midX - 2; + const int deltaY = deltaX/2; + + Point triangleLocation = new Point(r.Right - triangleWidth - 2, r.Top + (r.Height - triangleHeight)/2); + Point[] pts = new Point[] {triangleLocation, triangleLocation, triangleLocation}; + + if (this.ListView.LastSortOrder == SortOrder.Ascending) { + pts[0].Offset(midX - deltaX, midY + deltaY); + pts[1].Offset(midX, midY - deltaY - 1); + pts[2].Offset(midX + deltaX, midY + deltaY); + } else { + pts[0].Offset(midX - deltaX, midY - deltaY); + pts[1].Offset(midX, midY + deltaY); + pts[2].Offset(midX + deltaX, midY - deltaY); + } + + g.FillPolygon(Brushes.SlateGray, pts); + r.Width = r.Width - triangleWidth; + return r; + } + + /// + /// Draw an indication that this column has a filter applied to it + /// + /// + /// + /// + protected Rectangle DrawFilterIndicator(Graphics g, Rectangle r) { + int width = this.CalculateFilterIndicatorWidth(r); + if (width <= 0) + return r; + + Image indicator = Resources.ColumnFilterIndicator; + int x = r.Right - width; + int y = r.Top + (r.Height - indicator.Height)/2; + g.DrawImageUnscaled(indicator, x, y); + + r.Width -= width; + return r; + } + + private int CalculateFilterIndicatorWidth(Rectangle r) { + if (Resources.ColumnFilterIndicator == null || r.Width < 48) + return 0; + return Resources.ColumnFilterIndicator.Width + 1; + } + + /// + /// Draw the header's image and text + /// + /// + /// + /// + /// + protected void DrawHeaderImageAndText(Graphics g, Rectangle r, OLVColumn column, HeaderStateStyle stateStyle) { + + TextFormatFlags flags = this.TextFormatFlags; + flags |= TextFormatFlags.VerticalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + flags |= TextFormatFlags.HorizontalCenter; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + flags |= TextFormatFlags.Right; + + Font f = this.ListView.HeaderUsesThemes ? this.ListView.Font : stateStyle.Font ?? this.ListView.Font; + Color color = this.ListView.HeaderUsesThemes ? Color.Black : stateStyle.ForeColor; + if (color.IsEmpty) + color = Color.Black; + + const int imageTextGap = 3; + + if (column.IsHeaderVertical) { + DrawVerticalText(g, r, column, f, color); + } else { + // Does the column have a header image and is there space for it? + if (column.HasHeaderImage && r.Width > column.ImageList.ImageSize.Width*2) + DrawImageAndText(g, r, column, flags, f, color, imageTextGap); + else + DrawText(g, r, column, flags, f, color); + } + } + + private void DrawText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, Color color) { + if (column.ShowTextInHeader) + TextRenderer.DrawText(g, column.Text, f, r, color, Color.Transparent, flags); + } + + private void DrawImageAndText(Graphics g, Rectangle r, OLVColumn column, TextFormatFlags flags, Font f, + Color color, int imageTextGap) { + Rectangle textRect = r; + textRect.X += (column.ImageList.ImageSize.Width + imageTextGap); + textRect.Width -= (column.ImageList.ImageSize.Width + imageTextGap); + + Size textSize = Size.Empty; + if (column.ShowTextInHeader) + textSize = TextRenderer.MeasureText(g, column.Text, f, textRect.Size, flags); + + int imageY = r.Top + ((r.Height - column.ImageList.ImageSize.Height)/2); + int imageX = textRect.Left; + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Center) + imageX = textRect.Left + ((textRect.Width - textSize.Width)/2); + if (column.HeaderTextAlignOrDefault == HorizontalAlignment.Right) + imageX = textRect.Right - textSize.Width; + imageX -= (column.ImageList.ImageSize.Width + imageTextGap); + + column.ImageList.Draw(g, imageX, imageY, column.ImageList.Images.IndexOfKey(column.HeaderImageKey)); + + this.DrawText(g, textRect, column, flags, f, color); + } + + private static void DrawVerticalText(Graphics g, Rectangle r, OLVColumn column, Font f, Color color) { + try { + // Create a matrix transformation that will rotate the text 90 degrees vertically + // AND place the text in the middle of where it was previously. [Think of tipping + // a box over by its bottom left edge -- you have to move it back a bit so it's + // in the same place as it started] + Matrix m = new Matrix(); + m.RotateAt(-90, new Point(r.X, r.Bottom)); + m.Translate(0, r.Height); + g.Transform = m; + StringFormat fmt = new StringFormat(StringFormatFlags.NoWrap); + fmt.Alignment = StringAlignment.Near; + fmt.LineAlignment = column.HeaderTextAlignAsStringAlignment; + //fmt.Trimming = StringTrimming.EllipsisCharacter; + + // The drawing is rotated 90 degrees, so switch our text boundaries + Rectangle textRect = r; + textRect.Width = r.Height; + textRect.Height = r.Width; + using (Brush b = new SolidBrush(color)) + g.DrawString(column.Text, f, b, textRect, fmt); + } + finally { + g.ResetTransform(); + } + } + + /// + /// Return the header format that should be used for the given column + /// + /// + /// + protected HeaderFormatStyle CalculateHeaderStyle(OLVColumn column) { + return column.HeaderFormatStyle ?? this.ListView.HeaderFormatStyle ?? new HeaderFormatStyle(); + } + + /// + /// What style should be applied to the header? + /// + /// + /// + /// + /// + protected HeaderStateStyle CalculateStateStyle(OLVColumn column, bool isHot, bool isPressed) { + HeaderFormatStyle headerStyle = this.CalculateHeaderStyle(column); + if (this.ListView.IsDesignMode) + return headerStyle.Normal; + if (isPressed) + return headerStyle.Pressed; + if (isHot) + return headerStyle.Hot; + return headerStyle.Normal; + } + + /// + /// What font should be used to draw the header text? + /// + /// + /// + /// + /// + protected Font CalculateFont(OLVColumn column, bool isHot, bool isPressed) { + HeaderStateStyle stateStyle = this.CalculateStateStyle(column, isHot, isPressed); + return stateStyle.Font ?? this.ListView.Font; + } + + /// + /// What flags will be used when drawing text + /// + protected TextFormatFlags TextFormatFlags { + get { + TextFormatFlags flags = TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPrefix | + TextFormatFlags.WordEllipsis | + TextFormatFlags.PreserveGraphicsTranslateTransform; + if (this.WordWrap) + flags |= TextFormatFlags.WordBreak; + else + flags |= TextFormatFlags.SingleLine; + if (this.ListView.RightToLeft == RightToLeft.Yes) + flags |= TextFormatFlags.RightToLeft; + + return flags; + } + } + + /// + /// Perform a HitTest for the header control + /// + /// + /// + /// Null if the given point isn't over the header + internal OlvListViewHitTestInfo.HeaderHitTestInfo HitTest(int x, int y) + { + Rectangle r = this.ClientRectangle; + if (!r.Contains(x, y)) + return null; + + Point pt = new Point(x + this.ListView.LowLevelScrollPosition.X, y); + + OlvListViewHitTestInfo.HeaderHitTestInfo hti = new OlvListViewHitTestInfo.HeaderHitTestInfo(); + hti.ColumnIndex = NativeMethods.GetColumnUnderPoint(this.Handle, pt); + hti.IsOverCheckBox = this.IsPointOverHeaderCheckBox(hti.ColumnIndex, pt); + hti.OverDividerIndex = NativeMethods.GetDividerUnderPoint(this.Handle, pt); + + return hti; + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolStripCheckedListBox.cs b/ObjectListView/SubControls/ToolStripCheckedListBox.cs new file mode 100644 index 0000000..e8eab01 --- /dev/null +++ b/ObjectListView/SubControls/ToolStripCheckedListBox.cs @@ -0,0 +1,189 @@ +/* + * ToolStripCheckedListBox - Puts a CheckedListBox into a tool strip menu item + * + * Author: Phillip Piper + * Date: 4-March-2011 11:59 pm + * + * Change log: + * 2011-03-04 JPP - First version + * + * Copyright (C) 2011-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace BrightIdeasSoftware { + + /// + /// Instances of this class put a CheckedListBox into a tool strip menu item. + /// + public class ToolStripCheckedListBox : ToolStripControlHost { + + /// + /// Create a ToolStripCheckedListBox + /// + public ToolStripCheckedListBox() + : base(new CheckedListBox()) { + this.CheckedListBoxControl.MaximumSize = new Size(400, 700); + this.CheckedListBoxControl.ThreeDCheckBoxes = true; + this.CheckedListBoxControl.CheckOnClick = true; + this.CheckedListBoxControl.SelectionMode = SelectionMode.One; + } + + /// + /// Gets the control embedded in the menu + /// + public CheckedListBox CheckedListBoxControl { + get { + return Control as CheckedListBox; + } + } + + /// + /// Gets the items shown in the checkedlistbox + /// + public CheckedListBox.ObjectCollection Items { + get { + return this.CheckedListBoxControl.Items; + } + } + + /// + /// Gets or sets whether an item should be checked when it is clicked + /// + public bool CheckedOnClick { + get { + return this.CheckedListBoxControl.CheckOnClick; + } + set { + this.CheckedListBoxControl.CheckOnClick = value; + } + } + + /// + /// Gets a collection of the checked items + /// + public CheckedListBox.CheckedItemCollection CheckedItems { + get { + return this.CheckedListBoxControl.CheckedItems; + } + } + + /// + /// Add a possibly checked item to the control + /// + /// + /// + public void AddItem(object item, bool isChecked) { + this.Items.Add(item); + if (isChecked) + this.CheckedListBoxControl.SetItemChecked(this.Items.Count - 1, true); + } + + /// + /// Add an item with the given state to the control + /// + /// + /// + public void AddItem(object item, CheckState state) { + this.Items.Add(item); + this.CheckedListBoxControl.SetItemCheckState(this.Items.Count - 1, state); + } + + /// + /// Gets the checkedness of the i'th item + /// + /// + /// + public CheckState GetItemCheckState(int i) { + return this.CheckedListBoxControl.GetItemCheckState(i); + } + + /// + /// Set the checkedness of the i'th item + /// + /// + /// + public void SetItemState(int i, CheckState checkState) { + if (i >= 0 && i < this.Items.Count) + this.CheckedListBoxControl.SetItemCheckState(i, checkState); + } + + /// + /// Check all the items in the control + /// + public void CheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, true); + } + + /// + /// Unchecked all the items in the control + /// + public void UncheckAll() { + for (int i = 0; i < this.Items.Count; i++) + this.CheckedListBoxControl.SetItemChecked(i, false); + } + + #region Events + + /// + /// Listen for events on the underlying control + /// + /// + protected override void OnSubscribeControlEvents(Control c) { + base.OnSubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck += new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Stop listening for events on the underlying control + /// + /// + protected override void OnUnsubscribeControlEvents(Control c) { + base.OnUnsubscribeControlEvents(c); + + CheckedListBox control = (CheckedListBox)c; + control.ItemCheck -= new ItemCheckEventHandler(OnItemCheck); + } + + /// + /// Tell the world that an item was checked + /// + public event ItemCheckEventHandler ItemCheck; + + /// + /// Trigger the ItemCheck event + /// + /// + /// + private void OnItemCheck(object sender, ItemCheckEventArgs e) { + if (ItemCheck != null) { + ItemCheck(this, e); + } + } + + #endregion + } +} diff --git a/ObjectListView/SubControls/ToolTipControl.cs b/ObjectListView/SubControls/ToolTipControl.cs new file mode 100644 index 0000000..22c1f63 --- /dev/null +++ b/ObjectListView/SubControls/ToolTipControl.cs @@ -0,0 +1,699 @@ +/* + * ToolTipControl - A limited wrapper around a Windows tooltip control + * + * For some reason, the ToolTip class in the .NET framework is implemented in a significantly + * different manner to other controls. For our purposes, the worst of these problems + * is that we cannot get the Handle, so we cannot send Windows level messages to the control. + * + * Author: Phillip Piper + * Date: 2009-05-17 7:22PM + * + * Change log: + * v2.3 + * 2009-06-13 JPP - Moved ToolTipShowingEventArgs to Events.cs + * v2.2 + * 2009-06-06 JPP - Fixed some Vista specific problems + * 2009-05-17 JPP - Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using System.Security.Permissions; + +namespace BrightIdeasSoftware +{ + /// + /// A limited wrapper around a Windows tooltip window. + /// + public class ToolTipControl : NativeWindow + { + #region Constants + + /// + /// These are the standard icons that a tooltip can display. + /// + public enum StandardIcons + { + /// + /// No icon + /// + None = 0, + + /// + /// Info + /// + Info = 1, + + /// + /// Warning + /// + Warning = 2, + + /// + /// Error + /// + Error = 3, + + /// + /// Large info (Vista and later only) + /// + InfoLarge = 4, + + /// + /// Large warning (Vista and later only) + /// + WarningLarge = 5, + + /// + /// Large error (Vista and later only) + /// + ErrorLarge = 6 + } + + const int GWL_STYLE = -16; + const int WM_GETFONT = 0x31; + const int WM_SETFONT = 0x30; + const int WS_BORDER = 0x800000; + const int WS_EX_TOPMOST = 8; + + const int TTM_ADDTOOL = 0x432; + const int TTM_ADJUSTRECT = 0x400 + 31; + const int TTM_DELTOOL = 0x433; + const int TTM_GETBUBBLESIZE = 0x400 + 30; + const int TTM_GETCURRENTTOOL = 0x400 + 59; + const int TTM_GETTIPBKCOLOR = 0x400 + 22; + const int TTM_GETTIPTEXTCOLOR = 0x400 + 23; + const int TTM_GETDELAYTIME = 0x400 + 21; + const int TTM_NEWTOOLRECT = 0x400 + 52; + const int TTM_POP = 0x41c; + const int TTM_SETDELAYTIME = 0x400 + 3; + const int TTM_SETMAXTIPWIDTH = 0x400 + 24; + const int TTM_SETTIPBKCOLOR = 0x400 + 19; + const int TTM_SETTIPTEXTCOLOR = 0x400 + 20; + const int TTM_SETTITLE = 0x400 + 33; + const int TTM_SETTOOLINFO = 0x400 + 54; + + const int TTF_IDISHWND = 1; + //const int TTF_ABSOLUTE = 0x80; + const int TTF_CENTERTIP = 2; + const int TTF_RTLREADING = 4; + const int TTF_SUBCLASS = 0x10; + //const int TTF_TRACK = 0x20; + //const int TTF_TRANSPARENT = 0x100; + const int TTF_PARSELINKS = 0x1000; + + const int TTS_NOPREFIX = 2; + const int TTS_BALLOON = 0x40; + const int TTS_USEVISUALSTYLE = 0x100; + + const int TTN_FIRST = -520; + + /// + /// + /// + public const int TTN_SHOW = (TTN_FIRST - 1); + + /// + /// + /// + public const int TTN_POP = (TTN_FIRST - 2); + + /// + /// + /// + public const int TTN_LINKCLICK = (TTN_FIRST - 3); + + /// + /// + /// + public const int TTN_GETDISPINFO = (TTN_FIRST - 10); + + const int TTDT_AUTOMATIC = 0; + const int TTDT_RESHOW = 1; + const int TTDT_AUTOPOP = 2; + const int TTDT_INITIAL = 3; + + #endregion + + #region Properties + + /// + /// Get or set if the style of the tooltip control + /// + internal int WindowStyle { + get { + return (int)NativeMethods.GetWindowLong(this.Handle, GWL_STYLE); + } + set { + NativeMethods.SetWindowLong(this.Handle, GWL_STYLE, value); + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool IsBalloon { + get { + return (this.WindowStyle & TTS_BALLOON) == TTS_BALLOON; + } + set { + if (this.IsBalloon == value) + return; + + int windowStyle = this.WindowStyle; + if (value) { + windowStyle |= (TTS_BALLOON | TTS_USEVISUALSTYLE); + // On XP, a border makes the balloon look wrong + if (!ObjectListView.IsVistaOrLater) + windowStyle &= ~WS_BORDER; + } else { + windowStyle &= ~(TTS_BALLOON | TTS_USEVISUALSTYLE); + if (!ObjectListView.IsVistaOrLater) { + if (this.hasBorder) + windowStyle |= WS_BORDER; + else + windowStyle &= ~WS_BORDER; + } + } + this.WindowStyle = windowStyle; + } + } + + /// + /// Get or set if the tooltip should be shown as a balloon + /// + public bool HasBorder { + get { + return this.hasBorder; + } + set { + if (this.hasBorder == value) + return; + + if (value) { + this.WindowStyle |= WS_BORDER; + } else { + this.WindowStyle &= ~WS_BORDER; + } + } + } + private bool hasBorder = true; + + /// + /// Get or set the background color of the tooltip + /// + public Color BackColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPBKCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPBKCOLOR, color, 0); + //int x2 = Marshal.GetLastWin32Error(); + } + } + } + + /// + /// Get or set the color of the text and border on the tooltip. + /// + public Color ForeColor { + get { + int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPTEXTCOLOR, 0, 0); + return ColorTranslator.FromWin32(color); + } + set { + // For some reason, setting the color fails on Vista and messes up later ops. + // So we don't even try to set it. + if (!ObjectListView.IsVistaOrLater) { + int color = ColorTranslator.ToWin32(value); + NativeMethods.SendMessage(this.Handle, TTM_SETTIPTEXTCOLOR, color, 0); + } + } + } + + /// + /// Get or set the title that will be shown on the tooltip. + /// + public string Title { + get { + return this.title; + } + set { + if (String.IsNullOrEmpty(value)) + this.title = String.Empty; + else + if (value.Length >= 100) + this.title = value.Substring(0, 99); + else + this.title = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private string title; + + /// + /// Get or set the icon that will be shown on the tooltip. + /// + public StandardIcons StandardIcon { + get { + return this.standardIcon; + } + set { + this.standardIcon = value; + NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); + } + } + private StandardIcons standardIcon; + + /// + /// Gets or sets the font that will be used to draw this control. + /// is still. + /// + /// Setting this to null reverts to the default font. + public Font Font { + get { + IntPtr hfont = NativeMethods.SendMessage(this.Handle, WM_GETFONT, 0, 0); + if (hfont == IntPtr.Zero) + return Control.DefaultFont; + else + return Font.FromHfont(hfont); + } + set { + Font newFont = value ?? Control.DefaultFont; + if (newFont == this.font) + return; + + this.font = newFont; + IntPtr hfont = this.font.ToHfont(); // THINK: When should we delete this hfont? + NativeMethods.SendMessage(this.Handle, WM_SETFONT, hfont, 0); + } + } + private Font font; + + /// + /// Gets or sets how many milliseconds the tooltip will remain visible while the mouse + /// is still. + /// + public int AutoPopDelay { + get { return this.GetDelayTime(TTDT_AUTOPOP); } + set { this.SetDelayTime(TTDT_AUTOPOP, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown. + /// + public int InitialDelay { + get { return this.GetDelayTime(TTDT_INITIAL); } + set { this.SetDelayTime(TTDT_INITIAL, value); } + } + + /// + /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown again. + /// + public int ReshowDelay { + get { return this.GetDelayTime(TTDT_RESHOW); } + set { this.SetDelayTime(TTDT_RESHOW, value); } + } + + private int GetDelayTime(int which) { + return (int)NativeMethods.SendMessage(this.Handle, TTM_GETDELAYTIME, which, 0); + } + + private void SetDelayTime(int which, int value) { + NativeMethods.SendMessage(this.Handle, TTM_SETDELAYTIME, which, value); + } + + #endregion + + #region Commands + + /// + /// Create the underlying control. + /// + /// The parent of the tooltip + /// This does nothing if the control has already been created + public void Create(IntPtr parentHandle) { + if (this.Handle != IntPtr.Zero) + return; + + CreateParams cp = new CreateParams(); + cp.ClassName = "tooltips_class32"; + cp.Style = TTS_NOPREFIX; + cp.ExStyle = WS_EX_TOPMOST; + cp.Parent = parentHandle; + this.CreateHandle(cp); + + // Ensure that multiline tooltips work correctly + this.SetMaxWidth(); + } + + /// + /// Take a copy of the current settings and restore them when the + /// tooltip is popped. + /// + /// + /// This call cannot be nested. Subsequent calls to this method will be ignored + /// until PopSettings() is called. + /// + public void PushSettings() { + // Ignore any nested calls + if (this.settings != null) + return; + this.settings = new Hashtable(); + this.settings["IsBalloon"] = this.IsBalloon; + this.settings["HasBorder"] = this.HasBorder; + this.settings["BackColor"] = this.BackColor; + this.settings["ForeColor"] = this.ForeColor; + this.settings["Title"] = this.Title; + this.settings["StandardIcon"] = this.StandardIcon; + this.settings["AutoPopDelay"] = this.AutoPopDelay; + this.settings["InitialDelay"] = this.InitialDelay; + this.settings["ReshowDelay"] = this.ReshowDelay; + this.settings["Font"] = this.Font; + } + private Hashtable settings; + + /// + /// Restore the settings of the tooltip as they were when PushSettings() + /// was last called. + /// + public void PopSettings() { + if (this.settings == null) + return; + + this.IsBalloon = (bool)this.settings["IsBalloon"]; + this.HasBorder = (bool)this.settings["HasBorder"]; + this.BackColor = (Color)this.settings["BackColor"]; + this.ForeColor = (Color)this.settings["ForeColor"]; + this.Title = (string)this.settings["Title"]; + this.StandardIcon = (StandardIcons)this.settings["StandardIcon"]; + this.AutoPopDelay = (int)this.settings["AutoPopDelay"]; + this.InitialDelay = (int)this.settings["InitialDelay"]; + this.ReshowDelay = (int)this.settings["ReshowDelay"]; + this.Font = (Font)this.settings["Font"]; + + this.settings = null; + } + + /// + /// Add the given window to those for whom this tooltip will show tips + /// + /// The window + public void AddTool(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_ADDTOOL, 0, lParam); + } + + /// + /// Hide any currently visible tooltip + /// + /// + public void PopToolTip(IWin32Window window) { + NativeMethods.SendMessage(this.Handle, TTM_POP, 0, 0); + } + + //public void Munge() { + // NativeMethods.TOOLINFO tool = new NativeMethods.TOOLINFO(); + // IntPtr result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETCURRENTTOOL, 0, tool); + // System.Diagnostics.Trace.WriteLine("-"); + // System.Diagnostics.Trace.WriteLine(result); + // result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETBUBBLESIZE, 0, tool); + // System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", result.ToInt32() >> 16, result.ToInt32() & 0xFFFF)); + // NativeMethods.ChangeSize(this, result.ToInt32() & 0xFFFF, result.ToInt32() >> 16); + // //NativeMethods.RECT r = new NativeMethods.RECT(); + // //r.right + // //IntPtr x = NativeMethods.SendMessageRECT(this.Handle, TTM_ADJUSTRECT, true, ref r); + + // //System.Diagnostics.Trace.WriteLine(String.Format("{0} {1} {2} {3}", r.left, r.top, r.right, r.bottom)); + //} + + /// + /// Remove the given window from those managed by this tooltip + /// + /// + public void RemoveToolTip(IWin32Window window) { + NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); + NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_DELTOOL, 0, lParam); + } + + /// + /// Set the maximum width of a tooltip string. + /// + public void SetMaxWidth() { + this.SetMaxWidth(SystemInformation.MaxWindowTrackSize.Width); + } + + /// + /// Set the maximum width of a tooltip string. + /// + /// Setting this ensures that line breaks in the tooltip are honoured. + public void SetMaxWidth(int maxWidth) { + NativeMethods.SendMessage(this.Handle, TTM_SETMAXTIPWIDTH, 0, maxWidth); + } + + #endregion + + #region Implementation + + /// + /// Make a TOOLINFO structure for the given window + /// + /// + /// A filled in TOOLINFO + private NativeMethods.TOOLINFO MakeToolInfoStruct(IWin32Window window) { + + NativeMethods.TOOLINFO toolinfo_tooltip = new NativeMethods.TOOLINFO(); + toolinfo_tooltip.hwnd = window.Handle; + toolinfo_tooltip.uFlags = TTF_IDISHWND | TTF_SUBCLASS; + toolinfo_tooltip.uId = window.Handle; + toolinfo_tooltip.lpszText = (IntPtr)(-1); // LPSTR_TEXTCALLBACK + + return toolinfo_tooltip; + } + + /// + /// Handle a WmNotify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleNotify(ref Message msg) { + + //THINK: What do we have to do here? Nothing it seems :) + + //NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + //System.Diagnostics.Trace.WriteLine("HandleNotify"); + //System.Diagnostics.Trace.WriteLine(nmheader.nhdr.code); + + //switch (nmheader.nhdr.code) { + //} + + return false; + } + + /// + /// Handle a get display info message + /// + /// The msg + /// True if the message has been handled + public virtual bool HandleGetDispInfo(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleGetDispInfo"); + this.SetMaxWidth(); + ToolTipShowingEventArgs args = new ToolTipShowingEventArgs(); + args.ToolTipControl = this; + this.OnShowing(args); + if (String.IsNullOrEmpty(args.Text)) + return false; + + this.ApplyEventFormatting(args); + + NativeMethods.NMTTDISPINFO dispInfo = (NativeMethods.NMTTDISPINFO)msg.GetLParam(typeof(NativeMethods.NMTTDISPINFO)); + dispInfo.lpszText = args.Text; + dispInfo.hinst = IntPtr.Zero; + if (args.RightToLeft == RightToLeft.Yes) + dispInfo.uFlags |= TTF_RTLREADING; + Marshal.StructureToPtr(dispInfo, msg.LParam, false); + + return true; + } + + private void ApplyEventFormatting(ToolTipShowingEventArgs args) { + if (!args.IsBalloon.HasValue && + !args.BackColor.HasValue && + !args.ForeColor.HasValue && + args.Title == null && + !args.StandardIcon.HasValue && + !args.AutoPopDelay.HasValue && + args.Font == null) + return; + + this.PushSettings(); + if (args.IsBalloon.HasValue) + this.IsBalloon = args.IsBalloon.Value; + if (args.BackColor.HasValue) + this.BackColor = args.BackColor.Value; + if (args.ForeColor.HasValue) + this.ForeColor = args.ForeColor.Value; + if (args.StandardIcon.HasValue) + this.StandardIcon = args.StandardIcon.Value; + if (args.AutoPopDelay.HasValue) + this.AutoPopDelay = args.AutoPopDelay.Value; + if (args.Font != null) + this.Font = args.Font; + if (args.Title != null) + this.Title = args.Title; + } + + /// + /// Handle a TTN_LINKCLICK message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleLinkClick(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleLinkClick"); + return false; + } + + /// + /// Handle a TTN_POP message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandlePop(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandlePop"); + this.PopSettings(); + return true; + } + + /// + /// Handle a TTN_SHOW message + /// + /// The msg + /// True if the message has been handled + /// This cannot call base.WndProc() since the msg may have come from another control. + public virtual bool HandleShow(ref Message msg) { + //System.Diagnostics.Trace.WriteLine("HandleShow"); + return false; + } + + /// + /// Handle a reflected notify message + /// + /// The msg + /// True if the message has been handled + protected virtual bool HandleReflectNotify(ref Message msg) { + + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); + switch (nmheader.nhdr.code) { + case TTN_SHOW: + //System.Diagnostics.Trace.WriteLine("reflect TTN_SHOW"); + if (this.HandleShow(ref msg)) + return true; + break; + case TTN_POP: + //System.Diagnostics.Trace.WriteLine("reflect TTN_POP"); + if (this.HandlePop(ref msg)) + return true; + break; + case TTN_LINKCLICK: + //System.Diagnostics.Trace.WriteLine("reflect TTN_LINKCLICK"); + if (this.HandleLinkClick(ref msg)) + return true; + break; + case TTN_GETDISPINFO: + //System.Diagnostics.Trace.WriteLine("reflect TTN_GETDISPINFO"); + if (this.HandleGetDispInfo(ref msg)) + return true; + break; + } + + return false; + } + + /// + /// Mess with the basic message pump of the tooltip + /// + /// + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + override protected void WndProc(ref Message msg) { + //System.Diagnostics.Trace.WriteLine(String.Format("xx {0:x}", msg.Msg)); + switch (msg.Msg) { + case 0x4E: // WM_NOTIFY + if (!this.HandleNotify(ref msg)) + return; + break; + + case 0x204E: // WM_REFLECT_NOTIFY + if (!this.HandleReflectNotify(ref msg)) + return; + break; + } + + base.WndProc(ref msg); + } + + #endregion + + #region Events + + /// + /// Tell the world that a tooltip is about to show + /// + public event EventHandler Showing; + + /// + /// Tell the world that a tooltip is about to disappear + /// + public event EventHandler Pop; + + /// + /// + /// + /// + protected virtual void OnShowing(ToolTipShowingEventArgs e) { + if (this.Showing != null) + this.Showing(this, e); + } + + /// + /// + /// + /// + protected virtual void OnPop(EventArgs e) { + if (this.Pop != null) + this.Pop(this, e); + } + + #endregion + } + +} \ No newline at end of file diff --git a/ObjectListView/TreeListView.cs b/ObjectListView/TreeListView.cs new file mode 100644 index 0000000..0b52c63 --- /dev/null +++ b/ObjectListView/TreeListView.cs @@ -0,0 +1,2269 @@ +/* + * TreeListView - A listview that can show a tree of objects in a column + * + * Author: Phillip Piper + * Date: 23/09/2008 11:15 AM + * + * Change log: + * 2018-05-03 JPP - Added ITreeModel to allow models to provide the required information to TreeListView. + * 2018-04-30 JPP - Fix small visual glitch where connecting lines were not correctly drawn when filters changed + * v2.9.2 + * 2016-06-02 JPP - Added bounds check to GetNthObject(). + * v2.9 + * 2015-08-02 JPP - Fixed buy with hierarchical checkboxes where setting the checkedness of a deeply + * nested object would sometimes not correctly calculate the changes in the hierarchy. SF #150. + * 2015-06-27 JPP - Corrected small UI glitch when focus was lost and HideSelection was false. SF #135. + * v2.8.1 + * 2014-11-28 JPP - Fixed issue in RefreshObject() where a model with less children than previous that could not + * longer be expanded would cause an exception. + * 2014-11-23 JPP - Fixed an issue where collapsing a branch could leave the internal object->index map out of date. + * v2.8 + * 2014-10-08 JPP - Fixed an issue where pre-expanded branches would not initially expand properly + * 2014-09-29 JPP - Fixed issue where RefreshObject() on a root object could cause exceptions + * - Fixed issue where CollapseAll() while filtering could cause exception + * 2014-03-09 JPP - Fixed issue where removing a branches only child and then calling RefreshObject() + * could throw an exception. + * v2.7 + * 2014-02-23 JPP - Added Reveal() method to show a deeply nested models. + * 2014-02-05 JPP - Fix issue where refreshing a non-root item would collapse all expanded children of that item + * 2014-02-01 JPP - ClearObjects() now actually, you know, clears objects :) + * - Corrected issue where Expanded event was being raised twice. + * - RebuildChildren() no longer checks if CanExpand is true before rebuilding. + * 2014-01-16 JPP - Corrected an off-by-1 error in hit detection, which meant that clicking in the last 16 pixels + * of an items label was being ignored. + * 2013-11-20 JPP - Moved event triggers into Collapse() and Expand() so that the events are always triggered. + * - CheckedObjects now includes objects that are in a branch that is currently collapsed + * - CollapseAll() and ExpandAll() now trigger cancellable events + * 2013-09-29 JPP - Added TreeFactory to allow the underlying Tree to be replaced by another implementation. + * 2013-09-23 JPP - Fixed long standing issue where RefreshObject() would not work on root objects + * which overrode Equals()/GetHashCode(). + * 2013-02-23 JPP - Added HierarchicalCheckboxes. When this is true, the checkedness of a parent + * is an synopsis of the checkedness of its children. When all children are checked, + * the parent is checked. When all children are unchecked, the parent is unchecked. + * If some children are checked and some are not, the parent is indeterminate. + * v2.6 + * 2012-10-25 JPP - Circumvent annoying issue in ListView control where changing + * selection would leave artefacts on the control. + * 2012-08-10 JPP - Don't trigger selection changed events during expands + * + * v2.5.1 + * 2012-04-30 JPP - Fixed issue where CheckedObjects would return model objects that had been filtered out. + * - Allow any column to render the tree, not just column 0 (still not sure about this one) + * v2.5.0 + * 2011-04-20 JPP - Added ExpandedObjects property and RebuildAll() method. + * 2011-04-09 JPP - Added Expanding, Collapsing, Expanded and Collapsed events. + * The ..ing events are cancellable. These are only fired in response + * to user actions. + * v2.4.1 + * 2010-06-15 JPP - Fixed issue in Tree.RemoveObjects() which resulted in removed objects + * being reported as still existing. + * v2.3 + * 2009-09-01 JPP - Fixed off-by-one error that was messing up hit detection + * 2009-08-27 JPP - Fixed issue when dragging a node from one place to another in the tree + * v2.2.1 + * 2009-07-14 JPP - Clicks to the left of the expander in tree cells are now ignored. + * v2.2 + * 2009-05-12 JPP - Added tree traverse operations: GetParent and GetChildren. + * - Added DiscardAllState() to completely reset the TreeListView. + * 2009-05-10 JPP - Removed all unsafe code + * 2009-05-09 JPP - Fixed issue where any command (Expand/Collapse/Refresh) on a model + * object that was once visible but that is currently in a collapsed branch + * would cause the control to crash. + * 2009-05-07 JPP - Fixed issue where RefreshObjects() would fail when none of the given + * objects were present/visible. + * 2009-04-20 JPP - Fixed issue where calling Expand() on an already expanded branch confused + * the display of the children (SF#2499313) + * 2009-03-06 JPP - Calculate edit rectangle on column 0 more accurately + * v2.1 + * 2009-02-24 JPP - All commands now work when the list is empty (SF #2631054) + * - TreeListViews can now be printed with ListViewPrinter + * 2009-01-27 JPP - Changed to use new Renderer and HitTest scheme + * 2009-01-22 JPP - Added RevealAfterExpand property. If this is true (the default), + * after expanding a branch, the control scrolls to reveal as much of the + * expanded branch as possible. + * 2009-01-13 JPP - Changed TreeRenderer to work with visual styles are disabled + * v2.0.1 + * 2009-01-07 JPP - Made all public and protected methods virtual + * - Changed some classes from 'internal' to 'protected' so that they + * can be accessed by subclasses of TreeListView. + * 2008-12-22 JPP - Added UseWaitCursorWhenExpanding property + * - Made TreeRenderer public so that it can be subclassed + * - Added LinePen property to TreeRenderer to allow the connection drawing + * pen to be changed + * - Fixed some rendering issues where the text highlight rect was miscalculated + * - Fixed connection line problem when there is only a single root + * v2.0 + * 2008-12-10 JPP - Expand/collapse with mouse now works when there is no SmallImageList. + * 2008-12-01 JPP - Search-by-typing now works. + * 2008-11-26 JPP - Corrected calculation of expand/collapse icon (SF#2338819) + * - Fixed ugliness with dotted lines in renderer (SF#2332889) + * - Fixed problem with custom selection colors (SF#2338805) + * 2008-11-19 JPP - Expand/collapse now preserve the selection -- more or less :) + * - Overrode RefreshObjects() to rebuild the given objects and their children + * 2008-11-05 JPP - Added ExpandAll() and CollapseAll() commands + * - CanExpand is no longer cached + * - Renamed InitialBranches to RootModels since it deals with model objects + * 2008-09-23 JPP Initial version + * + * TO DO: + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// A TreeListView combines an expandable tree structure with list view columns. + /// + /// + /// To support tree operations, two delegates must be provided: + /// + /// + /// + /// CanExpandGetter + /// + /// + /// This delegate must accept a model object and return a boolean indicating + /// if that model should be expandable. + /// + /// + /// + /// + /// ChildrenGetter + /// + /// + /// This delegate must accept a model object and return an IEnumerable of model + /// objects that will be displayed as children of the parent model. This delegate will only be called + /// for a model object if the CanExpandGetter has already returned true for that model. + /// + /// + /// + /// + /// ParentGetter + /// + /// + /// This delegate must accept a model object and return the parent model. + /// This delegate will only be called when HierarchicalCheckboxes is true OR when Reveal() is called. + /// + /// + /// + /// + /// The top level branches of the tree are set via the Roots property. SetObjects(), AddObjects() + /// and RemoveObjects() are interpreted as operations on this collection of roots. + /// + /// + /// To add new children to an existing branch, make changes to your model objects and then + /// call RefreshObject() on the parent. + /// + /// The tree must be a directed acyclic graph -- no cycles are allowed. Put more mundanely, + /// each model object must appear only once in the tree. If the same model object appears in two + /// places in the tree, the control will become confused. + /// + public partial class TreeListView : VirtualObjectListView + { + /// + /// Make a default TreeListView + /// + public TreeListView() { + this.OwnerDraw = true; + this.View = View.Details; + this.CheckedObjectsMustStillExistInList = false; + +// ReSharper disable DoNotCallOverridableMethodsInConstructor + this.RegenerateTree(); + this.TreeColumnRenderer = new TreeRenderer(); +// ReSharper restore DoNotCallOverridableMethodsInConstructor + + // This improves hit detection even if we don't have any state image + this.SmallImageList = new ImageList(); + // this.StateImageList.ImageSize = new Size(6, 6); + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + /// + /// + /// This is called *often* -- on every mouse move when required. It must be fast. + /// Don't do database lookups, linear searches, or pi calculations. Just return the + /// value of a property. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't make + /// calls back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual CanExpandGetterDelegate CanExpandGetter { + get { return this.TreeModel.CanExpandGetter; } + set { this.TreeModel.CanExpandGetter = value; } + } + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + return false; + } + } + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + /// + /// + /// When this delegate is called, the TreeListView is not in a stable state. Don't do anything + /// that will result in calls being made back into the control. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual ChildrenGetterDelegate ChildrenGetter { + get { return this.TreeModel.ChildrenGetter; } + set { this.TreeModel.ChildrenGetter = value; } + } + + /// + /// This is the delegate that will be used to fetch the parent of a model object + /// + /// The parent of the given model, or null if the model doesn't exist or + /// if the model is a root + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ParentGetterDelegate ParentGetter { + get { return parentGetter ?? Tree.DefaultParentGetter; } + set { parentGetter = value; } + } + private ParentGetterDelegate parentGetter; + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + public override IList CheckedObjects { + get { + return base.CheckedObjects; + } + set { + ArrayList objectsToRecalculate = new ArrayList(this.CheckedObjects); + if (value != null) + objectsToRecalculate.AddRange(value); + + base.CheckedObjects = value; + + if (this.HierarchicalCheckboxes) + RecalculateHierarchicalCheckBoxGraph(objectsToRecalculate); + } + } + + /// + /// Gets or sets the model objects that are expanded. + /// + /// + /// This can be used to expand model objects before they are seen. + /// + /// Setting this does *not* force the control to rebuild + /// its display. You need to call RebuildAll(true). + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IEnumerable ExpandedObjects { + get { + return this.TreeModel.mapObjectToExpanded.Keys; + } + set { + this.TreeModel.mapObjectToExpanded.Clear(); + if (value != null) { + foreach (object x in value) + this.TreeModel.SetModelExpanded(x, true); + } + } + } + + /// + /// Gets or sets the filter that is applied to our whole list of objects. + /// TreeListViews do not currently support whole list filters. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IListFilter ListFilter { + get { return null; } + set { + System.Diagnostics.Debug.Assert(value == null, "TreeListView do not support ListFilters"); + } + } + + /// + /// Gets or sets whether this tree list view will display hierarchical checkboxes. + /// Hierarchical checkboxes is when a parent's "checkedness" is calculated from + /// the "checkedness" of its children. If all children are checked, the parent + /// will be checked. If all children are unchecked, the parent will also be unchecked. + /// If some children are checked and others are not, the parent will be indeterminate. + /// + /// + /// Hierarchical checkboxes don't work with either CheckStateGetters or CheckedAspectName + /// (which is basically the same thing). This is because it is too expensive to build the + /// initial state of the control if these are installed, since the control would have to walk + /// *every* branch recursively since a single bottom level leaf could change the checkedness + /// of the top root. + /// + [Category("ObjectListView"), + Description("Show hierarchical checkboxes be enabled?"), + DefaultValue(false)] + public virtual bool HierarchicalCheckboxes { + get { return this.hierarchicalCheckboxes; } + set { + if (this.hierarchicalCheckboxes == value) + return; + + this.hierarchicalCheckboxes = value; + this.CheckBoxes = value; + if (value) + this.TriStateCheckBoxes = false; + } + } + private bool hierarchicalCheckboxes; + + /// + /// Gets or sets the collection of root objects of the tree + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { return this.Roots; } + set { this.Roots = value; } + } + + /// + /// Gets the collection of objects that will be considered when creating clusters + /// (which are used to generate Excel-like column filters) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable ObjectsForClustering { + get { + for (int i = 0; i < this.TreeModel.GetObjectCount(); i++) + yield return this.TreeModel.GetNthObject(i); + } + } + + /// + /// After expanding a branch, should the TreeListView attempts to show as much of the + /// revealed descendants as possible. + /// + [Category("ObjectListView"), + Description("Should the parent of an expand subtree be scrolled to the top revealing the children?"), + DefaultValue(true)] + public bool RevealAfterExpand { + get { return revealAfterExpand; } + set { revealAfterExpand = value; } + } + private bool revealAfterExpand = true; + + /// + /// The model objects that form the top level branches of the tree. + /// + /// Setting this does NOT reset the state of the control. + /// In particular, it does not collapse branches. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IEnumerable Roots { + get { return this.TreeModel.RootObjects; } + set { + this.TreeColumnRenderer = this.TreeColumnRenderer; + this.TreeModel.RootObjects = value ?? new ArrayList(); + this.UpdateVirtualListSize(); + } + } + + /// + /// Make sure that at least one column is displaying a tree. + /// If no columns is showing the tree, make column 0 do it. + /// + protected virtual void EnsureTreeRendererPresent(TreeRenderer renderer) { + if (this.Columns.Count == 0) + return; + + foreach (OLVColumn col in this.Columns) { + if (col.Renderer is TreeRenderer) { + col.Renderer = renderer; + return; + } + } + + // No column held a tree renderer, so give column 0 one + OLVColumn columnZero = this.GetColumn(0); + columnZero.Renderer = renderer; + columnZero.WordWrap = columnZero.WordWrap; + } + + /// + /// Gets or sets the renderer that will be used to draw the tree structure. + /// Setting this to null resets the renderer to default. + /// + /// If a column is currently rendering the tree, the renderer + /// for that column will be replaced. If no column is rendering the tree, + /// column 0 will be given this renderer. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual TreeRenderer TreeColumnRenderer { + get { return treeRenderer ?? (treeRenderer = new TreeRenderer()); } + set { + treeRenderer = value ?? new TreeRenderer(); + EnsureTreeRendererPresent(treeRenderer); + } + } + private TreeRenderer treeRenderer; + + /// + /// This is the delegate that will be used to create the underlying Tree structure + /// that the TreeListView uses to manage the information about the tree. + /// + /// + /// The factory must not return null. + /// + /// Most users of TreeListView will never have to use this delegate. + /// + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public TreeFactoryDelegate TreeFactory { + get { return treeFactory; } + set { treeFactory = value; } + } + private TreeFactoryDelegate treeFactory; + + /// + /// Should a wait cursor be shown when a branch is being expanded? + /// + /// When this is true, the wait cursor will be shown whilst the children of the + /// branch are being fetched. If the children of the branch have already been cached, + /// the cursor will not change. + [Category("ObjectListView"), + Description("Should a wait cursor be shown when a branch is being expanded?"), + DefaultValue(true)] + public virtual bool UseWaitCursorWhenExpanding { + get { return useWaitCursorWhenExpanding; } + set { useWaitCursorWhenExpanding = value; } + } + private bool useWaitCursorWhenExpanding = true; + + /// + /// Gets the model that is used to manage the tree structure + /// + /// + /// Don't mess with this property unless you really know what you are doing. + /// If you don't already know what it's for, you don't need it. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Tree TreeModel { + get { return this.treeModel; } + protected set { this.treeModel = value; } + } + private Tree treeModel; + + //------------------------------------------------------------------------------------------ + // Accessing + + /// + /// Return true if the branch at the given model is expanded + /// + /// + /// + public virtual bool IsExpanded(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.IsExpanded); + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// + public virtual void Collapse(Object model) { + if (this.GetItemCount() == 0) + return; + + OLVListItem item = this.ModelToItem(model); + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(model, item); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.Collapse(model); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(model, item)); + } + } + + /// + /// Collapse all subtrees within this control + /// + public virtual void CollapseAll() { + if (this.GetItemCount() == 0) + return; + + TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(null, null); + this.OnCollapsing(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.CollapseAll(); + if (index >= 0) { + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + if (index < this.GetItemCount()) + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnCollapsed(new TreeBranchCollapsedEventArgs(null, null)); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.Roots = null; + this.DiscardAllState(); + } + } + + /// + /// Collapse all roots and forget everything we know about all models + /// + public virtual void DiscardAllState() { + this.CheckStateMap.Clear(); + this.RebuildAll(false); + } + + /// + /// Expand the subtree underneath the given model object + /// + /// + public virtual void Expand(Object model) { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + OLVListItem item = this.ModelToItem(model); + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(model, item); + this.OnExpanding(args); + if (args.Canceled) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // Expand the model first + int index = this.TreeModel.Expand(model); + if (index < 0) + return; + + // Update the size of the list and restore the selection + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + + // Redraw the items that were changed by the expand operation + this.RedrawItems(index, this.GetItemCount() - 1, true); + + this.OnExpanded(new TreeBranchExpandedEventArgs(model, item)); + + if (this.RevealAfterExpand && index > 0) { + // TODO: This should be a separate method + this.BeginUpdate(); + try { + int countPerPage = NativeMethods.GetCountPerPage(this); + int descedentCount = this.TreeModel.GetVisibleDescendentCount(model); + // If all of the descendants can be shown in the window, make sure that last one is visible. + // If all the descendants can't fit into the window, move the model to the top of the window + // (which will show as many of the descendants as possible) + if (descedentCount < countPerPage) { + this.EnsureVisible(index + descedentCount); + } else { + this.TopItemIndex = index; + } + } + finally { + this.EndUpdate(); + } + } + } + + /// + /// Expand all the branches within this tree recursively. + /// + /// Be careful: this method could take a long time for large trees. + public virtual void ExpandAll() { + if (this.GetItemCount() == 0) + return; + + // Give the world a chance to cancel the expansion + TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(null, null); + this.OnExpanding(args); + if (args.Canceled) + return; + + IList selection = this.SelectedObjects; + int index = this.TreeModel.ExpandAll(); + if (index < 0) + return; + + this.UpdateVirtualListSize(); + using (this.SuspendSelectionEventsDuring()) + this.SelectedObjects = selection; + this.RedrawItems(index, this.GetItemCount() - 1, true); + this.OnExpanded(new TreeBranchExpandedEventArgs(null, null)); + } + + /// + /// Completely rebuild the tree structure + /// + /// If true, the control will try to preserve selection and expansion + public virtual void RebuildAll(bool preserveState) { + int previousTopItemIndex = preserveState ? this.TopItemIndex : -1; + + this.RebuildAll( + preserveState ? this.SelectedObjects : null, + preserveState ? this.ExpandedObjects : null, + preserveState ? this.CheckedObjects : null); + + if (preserveState) + this.TopItemIndex = previousTopItemIndex; + } + + /// + /// Completely rebuild the tree structure + /// + /// If not null, this list of objects will be selected after the tree is rebuilt + /// If not null, this collection of objects will be expanded after the tree is rebuilt + /// If not null, this collection of objects will be checked after the tree is rebuilt + protected virtual void RebuildAll(IList selected, IEnumerable expanded, IList checkedObjects) { + // Remember the bits of info we don't want to forget (anyone ever see Memento?) + IEnumerable roots = this.Roots; + CanExpandGetterDelegate canExpand = this.CanExpandGetter; + ChildrenGetterDelegate childrenGetter = this.ChildrenGetter; + + try { + this.BeginUpdate(); + + // Give ourselves a new data structure + this.RegenerateTree(); + + // Put back the bits we didn't want to forget + this.CanExpandGetter = canExpand; + this.ChildrenGetter = childrenGetter; + if (expanded != null) + this.ExpandedObjects = expanded; + this.Roots = roots; + if (selected != null) + this.SelectedObjects = selected; + if (checkedObjects != null) + this.CheckedObjects = checkedObjects; + } + finally { + this.EndUpdate(); + } + } + + /// + /// Unroll all the ancestors of the given model and make sure it is then visible. + /// + /// This works best when a ParentGetter is installed. + /// The object to be revealed + /// If true, the model will be selected and focused after being revealed + /// True if the object was found and revealed. False if it was not found. + public virtual void Reveal(object modelToReveal, bool selectAfterReveal) { + // Collect all the ancestors of the model + ArrayList ancestors = new ArrayList(); + foreach (object ancestor in this.GetAncestors(modelToReveal)) + ancestors.Add(ancestor); + + // Arrange them from root down to the model's immediate parent + ancestors.Reverse(); + try { + this.BeginUpdate(); + foreach (object ancestor in ancestors) + this.Expand(ancestor); + this.EnsureModelVisible(modelToReveal); + if (selectAfterReveal) + this.SelectObject(modelToReveal, true); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker) delegate { this.RefreshObjects(modelObjects); }); + return; + } + // There is no point in refreshing anything if the list is empty + if (this.GetItemCount() == 0) + return; + + // Remember the selection so we can put it back later + IList selection = this.SelectedObjects; + + // We actually need to refresh the parents. + // Refreshes on root objects have to be handled differently + ArrayList updatedRoots = new ArrayList(); + Hashtable modelsAndParents = new Hashtable(); + foreach (Object model in modelObjects) { + if (model == null) + continue; + modelsAndParents[model] = true; + object parent = GetParent(model); + if (parent == null) { + updatedRoots.Add(model); + } else { + modelsAndParents[parent] = true; + } + } + + // Update any changed roots + if (updatedRoots.Count > 0) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.Roots, false); + bool changed = false; + foreach (Object model in updatedRoots) { + int index = newRoots.IndexOf(model); + if (index >= 0 && !ReferenceEquals(newRoots[index], model)) { + newRoots[index] = model; + changed = true; + } + } + if (changed) + this.Roots = newRoots; + } + + // Refresh each object, remembering where the first update occurred + int firstChange = Int32.MaxValue; + foreach (Object model in modelsAndParents.Keys) { + if (model != null) { + int index = this.TreeModel.RebuildChildren(model); + if (index >= 0) + firstChange = Math.Min(firstChange, index); + } + } + + // If we didn't refresh any objects, don't do anything else + if (firstChange >= this.GetItemCount()) + return; + + this.ClearCachedInfo(); + this.UpdateVirtualListSize(); + this.SelectedObjects = selection; + + // Redraw everything from the first update to the end of the list + this.RedrawItems(firstChange, this.GetItemCount() - 1, true); + } + + /// + /// Change the check state of the given object to be the given state. + /// + /// + /// If the given model object isn't in the list, we still try to remember + /// its state, in case it is referenced in the future. + /// + /// + /// True if the checkedness of the model changed + protected override bool SetObjectCheckedness(object modelObject, CheckState state) { + // If the checkedness of the given model changes AND this tree has + // hierarchical checkboxes, then we need to update the checkedness of + // its children, and recalculate the checkedness of the parent (recursively) + if (!base.SetObjectCheckedness(modelObject, state)) + return false; + + if (!this.HierarchicalCheckboxes) + return true; + + // Give each child the same checkedness as the model + + CheckState? checkedness = this.GetCheckState(modelObject); + if (!checkedness.HasValue || checkedness.Value == CheckState.Indeterminate) + return true; + + foreach (object child in this.GetChildrenWithoutExpanding(modelObject)) { + this.SetObjectCheckedness(child, checkedness.Value); + } + + ArrayList args = new ArrayList(); + args.Add(modelObject); + this.RecalculateHierarchicalCheckBoxGraph(args); + + return true; + } + + + private IEnumerable GetChildrenWithoutExpanding(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + return br.Children; + } + + /// + /// Toggle the expanded state of the branch at the given model object + /// + /// + public virtual void ToggleExpansion(Object model) { + if (this.IsExpanded(model)) + this.Collapse(model); + else + this.Expand(model); + } + + //------------------------------------------------------------------------------------------ + // Commands - Tree traversal + + /// + /// Return whether or not the given model can expand. + /// + /// + /// The given model must have already been seen in the tree + public virtual bool CanExpand(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return (br != null && br.CanExpand); + } + + /// + /// Return the model object that is the parent of the given model object. + /// + /// + /// + /// The given model must have already been seen in the tree. + public virtual Object GetParent(Object model) { + Branch br = this.TreeModel.GetBranch(model); + return br == null || br.ParentBranch == null ? null : br.ParentBranch.Model; + } + + /// + /// Return the collection of model objects that are the children of the + /// given model as they exist in the tree at the moment. + /// + /// + /// + /// + /// This method returns the collection of children as the tree knows them. If the given + /// model has never been presented to the user (e.g. it belongs to a parent that has + /// never been expanded), then this method will return an empty collection. + /// + /// Because of this, if you want to traverse the whole tree, this is not the method to use. + /// It's better to traverse the your data model directly. + /// + /// + /// If the given model has not already been seen in the tree or + /// if it is not expandable, an empty collection will be returned. + /// + /// + public virtual IEnumerable GetChildren(Object model) { + Branch br = this.TreeModel.GetBranch(model); + if (br == null || !br.CanExpand) + return new ArrayList(); + + br.FetchChildren(); + + return br.Children; + } + + //------------------------------------------------------------------------------------------ + // Delegates + + /// + /// Delegates of this type are use to decide if the given model object can be expanded + /// + /// The model under consideration + /// Can the given model be expanded? + public delegate bool CanExpandGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the children of the given model object + /// + /// The parent whose children should be fetched + /// An enumerable over the children + public delegate IEnumerable ChildrenGetterDelegate(Object model); + + /// + /// Delegates of this type are used to fetch the parent of the given model object. + /// + /// The child whose parent should be fetched + /// The parent of the child or null if the child is a root + public delegate Object ParentGetterDelegate(Object model); + + /// + /// Delegates of this type are used to create a new underlying Tree structure. + /// + /// The view for which the Tree is being created + /// A subclass of Tree + public delegate Tree TreeFactoryDelegate(TreeListView view); + + //------------------------------------------------------------------------------------------ + #region Implementation + + /// + /// Handle a left button down event + /// + /// + /// + protected override bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { + // Did they click in the expander? + if (hti.HitTestLocation == HitTestLocation.ExpandButton) { + this.PossibleFinishCellEditing(); + this.ToggleExpansion(hti.RowObject); + return true; + } + + return base.ProcessLButtonDown(hti); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + /// This differs from the base method by also setting up the IndentCount property. + public override OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvItem = base.MakeListViewItem(itemIndex); + Branch br = this.TreeModel.GetBranch(olvItem.RowObject); + if (br != null) + olvItem.IndentCount = br.Level; + return olvItem; + } + + /// + /// Reinitialise the Tree structure + /// + protected virtual void RegenerateTree() { + this.TreeModel = this.TreeFactory == null ? new Tree(this) : this.TreeFactory(this); + Trace.Assert(this.TreeModel != null); + this.VirtualListDataSource = this.TreeModel; + } + + /// + /// Recalculate the state of the checkboxes of all the items in the given list + /// and their ancestors. + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateHierarchicalCheckBoxGraph(IList toCheck) { + if (toCheck == null || toCheck.Count == 0) + return; + + // Avoid recursive calculations + if (isRecalculatingHierarchicalCheckBox) + return; + + try { + isRecalculatingHierarchicalCheckBox = true; + foreach (object ancestor in CalculateDistinctAncestors(toCheck)) + this.RecalculateSingleHierarchicalCheckBox(ancestor); + } + finally { + isRecalculatingHierarchicalCheckBox = false; + } + + } + private bool isRecalculatingHierarchicalCheckBox; + + /// + /// Recalculate the hierarchy state of the given item and its ancestors + /// + /// This only makes sense when HierarchicalCheckboxes is true. + /// + protected virtual void RecalculateSingleHierarchicalCheckBox(object modelObject) { + + if (modelObject == null) + return; + + // Only branches have calculated check states. Leaf node checkedness is not calculated + if (!this.CanExpandUncached(modelObject)) + return; + + // Set the checkedness of the given model based on the state of its children. + CheckState? aggregate = null; + foreach (object child in this.GetChildrenUncached(modelObject)) { + CheckState? checkedness = this.GetCheckState(child); + if (!checkedness.HasValue) + continue; + + if (aggregate.HasValue) { + if (aggregate.Value != checkedness.Value) { + aggregate = CheckState.Indeterminate; + break; + } + } else + aggregate = checkedness; + } + + base.SetObjectCheckedness(modelObject, aggregate ?? CheckState.Indeterminate); + } + + private bool CanExpandUncached(object model) { + return this.CanExpandGetter != null && model != null && this.CanExpandGetter(model); + } + + private IEnumerable GetChildrenUncached(object model) { + return this.ChildrenGetter != null && model != null ? this.ChildrenGetter(model) : new ArrayList(); + } + + /// + /// Yield the unique ancestors of the given collection of objects. + /// The order of the ancestors is guaranteed to be deeper objects first. + /// Roots will always be last. + /// + /// + /// Unique ancestors of the given objects + protected virtual IEnumerable CalculateDistinctAncestors(IList toCheck) { + + if (toCheck.Count == 1) { + foreach (object ancestor in this.GetAncestors(toCheck[0])) { + yield return ancestor; + } + } else { + // WARNING - Clever code + + // Example: Root --> GP +--> P +--> A + // | +--> B + // | + // +--> Q +--> X + // +--> Y + // + // Calculate ancestors of A, B, X and Y + + // Build a list of all ancestors of all objects we need to check + ArrayList allAncestors = new ArrayList(); + foreach (object child in toCheck) { + foreach (object ancestor in this.GetAncestors(child)) { + allAncestors.Add(ancestor); + } + } + + // allAncestors = { P, GP, Root, P, GP, Root, Q, GP, Root, Q, GP, Root } + + // Reverse them so "higher" ancestors come first + allAncestors.Reverse(); + + // allAncestors = { Root, GP, Q, Root, GP, Q, Root, GP, P, Root, GP, P } + + ArrayList uniqueAncestors = new ArrayList(); + Dictionary alreadySeen = new Dictionary(); + foreach (object ancestor in allAncestors) { + if (!alreadySeen.ContainsKey(ancestor)) { + alreadySeen[ancestor] = true; + uniqueAncestors.Add(ancestor); + } + } + + // uniqueAncestors = { Root, GP, Q, P } + + uniqueAncestors.Reverse(); + foreach (object x in uniqueAncestors) + yield return x; + } + } + + /// + /// Return all the ancestors of the given model + /// + /// + /// + /// This uses ParentGetter if possible. + /// + /// If the given model is a root OR if the model doesn't exist, the collection will be empty + /// + /// The model whose ancestors should be calculated + /// Return a collection of ancestors of the given model. + protected virtual IEnumerable GetAncestors(object model) { + ParentGetterDelegate parentGetterDelegate = this.ParentGetter ?? this.GetParent; + + object parent = parentGetterDelegate(model); + while (parent != null) { + yield return parent; + parent = parentGetterDelegate(parent); + } + } + + #endregion + + //------------------------------------------------------------------------------------------ + #region Event handlers + + /// + /// The application is idle and a SelectionChanged event has been scheduled + /// + /// + /// + protected override void HandleApplicationIdle(object sender, EventArgs e) { + base.HandleApplicationIdle(sender, e); + + // There is an annoying redraw issue on ListViews that use indentation and + // that have full row select enabled. When the selection reduces to a subset + // of previously selected rows, or when the selection is extended using + // shift-pageup/down, then the space occupied by the indentation is not + // invalidated, and hence remains highlighted. + // Ideally we'd want to know exactly which rows were selected or deselected + // and then invalidate just the indentation region of those rows, + // but that's too much work. So just redraw the control. + // Actually... the selection issues show just slightly for non-full row select + // controls as well. So, always redraw the control after the selection + // changes. + this.Invalidate(); + } + + /// + /// Decide if the given key event should be handled as a normal key input to the control? + /// + /// + /// + protected override bool IsInputKey(Keys keyData) { + // We want to handle Left and Right keys within the control + Keys key = keyData & Keys.KeyCode; + if (key == Keys.Left || key == Keys.Right) + return true; + + return base.IsInputKey(keyData); + } + + /// + /// Handle focus being lost, including making sure that the whole control is redrawn. + /// + /// + protected override void OnLostFocus(EventArgs e) + { + // When this focus is lost, the normal invalidation logic doesn't invalid the region + // of the control created by the IndentLevel on each row. This makes the control + // look wrong when HideSelection is false, since part of the selected row's background + // correctly changes colour to the "inactive" colour, but the left part of the row + // created by IndentLevel doesn't change colour. + // SF #135. + + this.Invalidate(); + } + + /// + /// Handle the keyboard input to mimic a TreeView. + /// + /// + /// Was the key press handled? + protected override void OnKeyDown(KeyEventArgs e) { + OLVListItem focused = this.FocusedItem as OLVListItem; + if (focused == null) { + base.OnKeyDown(e); + return; + } + + Object modelObject = focused.RowObject; + Branch br = this.TreeModel.GetBranch(modelObject); + + switch (e.KeyCode) { + case Keys.Left: + // If the branch is expanded, collapse it. If it's collapsed, + // select the parent of the branch. + if (br.IsExpanded) + this.Collapse(modelObject); + else { + if (br.ParentBranch != null && br.ParentBranch.Model != null) + this.SelectObject(br.ParentBranch.Model, true); + } + e.Handled = true; + break; + + case Keys.Right: + // If the branch is expanded, select the first child. + // If it isn't expanded and can be, expand it. + if (br.IsExpanded) { + List filtered = br.FilteredChildBranches; + if (filtered.Count > 0) + this.SelectObject(filtered[0].Model, true); + } else { + if (br.CanExpand) + this.Expand(modelObject); + } + e.Handled = true; + break; + } + + base.OnKeyDown(e); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Support classes + + /// + /// A Tree object represents a tree structure data model that supports both + /// tree and flat list operations as well as fast access to branches. + /// + /// If you create a subclass of Tree, you must install it in the TreeListView + /// via the TreeFactory delegate. + public class Tree : IVirtualListDataSource, IFilterableDataSource + { + /// + /// Create a Tree + /// + /// + public Tree(TreeListView treeView) { + this.treeView = treeView; + this.trunk = new Branch(null, this, null); + this.trunk.IsExpanded = true; + } + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// This is the delegate that will be used to decide if a model object can be expanded. + /// + public CanExpandGetterDelegate CanExpandGetter { + get { return canExpandGetter ?? DefaultCanExpandGetter; } + set { canExpandGetter = value; } + } + private CanExpandGetterDelegate canExpandGetter; + + + /// + /// This is the delegate that will be used to fetch the children of a model object + /// + /// This delegate will only be called if the CanExpand delegate has + /// returned true for the model object. + public ChildrenGetterDelegate ChildrenGetter { + get { return childrenGetter ?? DefaultChildrenGetter; } + set { childrenGetter = value; } + } + private ChildrenGetterDelegate childrenGetter; + + /// + /// Get or return the top level model objects in the tree + /// + public IEnumerable RootObjects { + get { return this.trunk.Children; } + set { + this.trunk.Children = value; + foreach (Branch br in this.trunk.ChildBranches) + br.RefreshChildren(); + this.RebuildList(); + } + } + + /// + /// What tree view is this Tree the model for? + /// + public TreeListView TreeView { + get { return this.treeView; } + } + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Collapse the subtree underneath the given model + /// + /// The model to be collapsed. If the model isn't in the tree, + /// or if it is already collapsed, the command does nothing. + /// The index of the model in flat list version of the tree + public virtual int Collapse(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.IsExpanded) + return -1; + + // Remember that the branch is collapsed, even if it's currently not visible + if (!br.Visible) { + br.Collapse(); + return -1; + } + + int count = br.NumberVisibleDescendents; + br.Collapse(); + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + this.objectList.RemoveRange(index + 1, count); + this.RebuildObjectMap(0); + return index; + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual int CollapseAll() { + this.trunk.CollapseAll(); + this.RebuildList(); + return 0; + } + + /// + /// Expand the subtree underneath the given model object + /// + /// The model to be expanded. + /// The index of the model in flat list version of the tree + /// + /// If the model isn't in the tree, + /// if it cannot be expanded or if it is already expanded, the command does nothing. + /// + public virtual int Expand(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.CanExpand || br.IsExpanded) + return -1; + + // Remember that the branch is expanded, even if it's currently not visible + br.Expand(); + if (!br.Visible) + { + return -1; + } + + int index = this.GetObjectIndex(model); + this.InsertChildren(br, index + 1); + return index; + } + + /// + /// Expand all branches in this tree + /// + /// Return the index of the first branch that was expanded + public virtual int ExpandAll() { + this.trunk.ExpandAll(); + this.Sort(this.lastSortColumn, this.lastSortOrder); + return 0; + } + + /// + /// Return the Branch object that represents the given model in the tree + /// + /// The model whose branches is to be returned + /// The branch that represents the given model, or null if the model + /// isn't in the tree. + public virtual Branch GetBranch(object model) { + if (model == null) + return null; + + Branch br; + this.mapObjectToBranch.TryGetValue(model, out br); + return br; + } + + /// + /// Return the number of visible descendants that are below the given model. + /// + /// The model whose descendent count is to be returned + /// The number of visible descendants. 0 if the model doesn't exist or is collapsed + public virtual int GetVisibleDescendentCount(object model) + { + Branch br = this.GetBranch(model); + return br == null || !br.IsExpanded ? 0 : br.NumberVisibleDescendents; + } + + /// + /// Rebuild the children of the given model, refreshing any cached information held about the given object + /// + /// + /// The index of the model in flat list version of the tree + public virtual int RebuildChildren(Object model) { + Branch br = this.GetBranch(model); + if (br == null || !br.Visible) + return -1; + + int count = br.NumberVisibleDescendents; + + // Remove the visible descendants from after the branch itself + int index = this.GetObjectIndex(model); + if (count > 0) + this.objectList.RemoveRange(index + 1, count); + + // Refresh our knowledge of our children (do this even if CanExpand is false, because + // the branch have already collected some children and that information could be stale) + br.RefreshChildren(); + + // Insert the refreshed children if the branch can expand and is expanded + if (br.CanExpand && br.IsExpanded) + this.InsertChildren(br, index + 1); + else + this.RebuildObjectMap(index); + + return index; + } + + //------------------------------------------------------------------------------------------ + // Implementation + + private static bool DefaultCanExpandGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel != null && treeModel.TreeCanExpand; + } + + private static IEnumerable DefaultChildrenGetter(object model) { + ITreeModelWithChildren treeModel = model as ITreeModelWithChildren; + return treeModel == null ? new ArrayList() : treeModel.TreeChildren; + } + + internal static object DefaultParentGetter(object model) { + ITreeModelWithParent treeModel = model as ITreeModelWithParent; + return treeModel == null ? null : treeModel.TreeParent; + } + + /// + /// Is the given model expanded? + /// + /// + /// + internal bool IsModelExpanded(object model) { + // Special case: model == null is the container for the roots. This is always expanded + if (model == null) + return true; + bool isExpanded; + this.mapObjectToExpanded.TryGetValue(model, out isExpanded); + return isExpanded; + } + + /// + /// Remember whether or not the given model was expanded + /// + /// + /// + internal void SetModelExpanded(object model, bool isExpanded) { + if (model == null) return; + + if (isExpanded) + this.mapObjectToExpanded[model] = true; + else + this.mapObjectToExpanded.Remove(model); + } + + /// + /// Insert the children of the given branch into the given position + /// + /// The branch whose children should be inserted + /// The index where the children should be inserted + protected virtual void InsertChildren(Branch br, int index) { + // Expand the branch + br.Expand(); + br.Sort(this.GetBranchComparer()); + + // Insert the branch's visible descendants after the branch itself + this.objectList.InsertRange(index, br.Flatten()); + this.RebuildObjectMap(index); + } + + /// + /// Rebuild our flat internal list of objects. + /// + protected virtual void RebuildList() { + this.objectList = ArrayList.Adapter(this.trunk.Flatten()); + List filtered = this.trunk.FilteredChildBranches; + if (filtered.Count > 0) { + filtered[0].IsFirstBranch = true; + filtered[0].IsOnlyBranch = (filtered.Count == 1); + } + this.RebuildObjectMap(0); + } + + /// + /// Rebuild our reverse index that maps an object to its location + /// in the filteredObjectList array. + /// + /// + protected virtual void RebuildObjectMap(int startIndex) { + if (startIndex == 0) + this.mapObjectToIndex.Clear(); + for (int i = startIndex; i < this.objectList.Count; i++) + this.mapObjectToIndex[this.objectList[i]] = i; + } + + /// + /// Create a new branch within this tree + /// + /// + /// + /// + internal Branch MakeBranch(Branch parent, object model) { + Branch br = new Branch(parent, this, model); + + // Remember that the given branch is part of this tree. + this.mapObjectToBranch[model] = br; + return br; + } + + //------------------------------------------------------------------------------------------ + + #region IVirtualListDataSource Members + + /// + /// + /// + /// + /// + public virtual object GetNthObject(int n) { + if (n >= 0 && n < this.objectList.Count) + return this.objectList[n]; + return null; + } + + /// + /// + /// + /// + public virtual int GetObjectCount() { + return this.trunk.NumberVisibleDescendents; + } + + /// + /// + /// + /// + /// + public virtual int GetObjectIndex(object model) + { + int index; + if (model != null && this.mapObjectToIndex.TryGetValue(model, out index)) + return index; + + return -1; + } + + /// + /// + /// + /// + /// + public virtual void PrepareCache(int first, int last) { + } + + /// + /// + /// + /// + /// + /// + /// + /// + public virtual int SearchText(string value, int first, int last, OLVColumn column) { + return AbstractVirtualListDataSource.DefaultSearchText(value, first, last, column, this); + } + + /// + /// Sort the tree on the given column and in the given order + /// + /// + /// + public virtual void Sort(OLVColumn column, SortOrder order) { + this.lastSortColumn = column; + this.lastSortOrder = order; + + // TODO: Need to raise an AboutToSortEvent here + + // Sorting is going to change the order of the branches so clear + // the "first branch" flag + foreach (Branch b in this.trunk.ChildBranches) + b.IsFirstBranch = false; + + this.trunk.Sort(this.GetBranchComparer()); + this.RebuildList(); + } + + /// + /// + /// + /// + protected virtual BranchComparer GetBranchComparer() { + if (this.lastSortColumn == null) + return null; + + return new BranchComparer(new ModelObjectComparer( + this.lastSortColumn, + this.lastSortOrder, + this.treeView.SecondarySortColumn ?? this.treeView.GetColumn(0), + this.treeView.SecondarySortColumn == null ? this.lastSortOrder : this.treeView.SecondarySortOrder)); + } + + /// + /// Add the given collection of objects to the roots of this tree + /// + /// + public virtual void AddObjects(ICollection modelObjects) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, true); + foreach (Object x in modelObjects) + newRoots.Add(x); + this.SetObjects(newRoots); + } + + /// + /// + /// + /// + /// + public void InsertObjects(int index, ICollection modelObjects) { + throw new NotImplementedException(); + } + + /// + /// Remove all of the given objects from the roots of the tree. + /// Any objects that is not already in the roots collection is ignored. + /// + /// + public virtual void RemoveObjects(ICollection modelObjects) { + ArrayList newRoots = new ArrayList(); + foreach (Object x in this.treeView.Roots) + newRoots.Add(x); + foreach (Object x in modelObjects) { + newRoots.Remove(x); + this.mapObjectToIndex.Remove(x); + } + this.SetObjects(newRoots); + } + + /// + /// Set the roots of this tree to be the given collection + /// + /// + public virtual void SetObjects(IEnumerable collection) { + // We interpret a SetObjects() call as setting the roots of the tree + this.treeView.Roots = collection; + } + + /// + /// Update/replace the nth object with the given object + /// + /// + /// + public void UpdateObject(int index, object modelObject) { + ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, false); + if (index < newRoots.Count) + newRoots[index] = modelObject; + SetObjects(newRoots); + } + + #endregion + + #region IFilterableDataSource Members + + /// + /// + /// + /// + /// + public void ApplyFilters(IModelFilter mFilter, IListFilter lFilter) { + this.modelFilter = mFilter; + this.listFilter = lFilter; + this.RebuildList(); + } + + /// + /// Is this list currently being filtered? + /// + internal bool IsFiltering { + get { + return this.treeView.UseFiltering && (this.modelFilter != null || this.listFilter != null); + } + } + + /// + /// Should the given model be included in this control? + /// + /// The model to consider + /// True if it will be included + internal bool IncludeModel(object model) { + if (!this.treeView.UseFiltering) + return true; + + if (this.modelFilter == null) + return true; + + return this.modelFilter.Filter(model); + } + + #endregion + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private OLVColumn lastSortColumn; + private SortOrder lastSortOrder; + private readonly Dictionary mapObjectToBranch = new Dictionary(); +// ReSharper disable once InconsistentNaming + internal Dictionary mapObjectToExpanded = new Dictionary(); + private readonly Dictionary mapObjectToIndex = new Dictionary(); + private ArrayList objectList = new ArrayList(); + private readonly TreeListView treeView; + private readonly Branch trunk; + + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IModelFilter modelFilter; + /// + /// + /// +// ReSharper disable once InconsistentNaming + protected IListFilter listFilter; + } + + /// + /// A Branch represents a sub-tree within a tree + /// + public class Branch + { + /// + /// Indicators for branches + /// + [Flags] + public enum BranchFlags + { + /// + /// FirstBranch of tree + /// + FirstBranch = 1, + + /// + /// LastChild of parent + /// + LastChild = 2, + + /// + /// OnlyBranch of tree + /// + OnlyBranch = 4 + } + + #region Life and death + + /// + /// Create a Branch + /// + /// + /// + /// + public Branch(Branch parent, Tree tree, Object model) { + this.ParentBranch = parent; + this.Tree = tree; + this.Model = model; + } + + #endregion + + #region Public properties + + //------------------------------------------------------------------------------------------ + // Properties + + /// + /// Get the ancestor branches of this branch, with the 'oldest' ancestor first. + /// + public virtual IList Ancestors { + get { + List ancestors = new List(); + if (this.ParentBranch != null) + this.ParentBranch.PushAncestors(ancestors); + return ancestors; + } + } + + private void PushAncestors(IList list) { + // This is designed to ignore the trunk (which has no parent) + if (this.ParentBranch != null) { + this.ParentBranch.PushAncestors(list); + list.Add(this); + } + } + + /// + /// Can this branch be expanded? + /// + public virtual bool CanExpand { + get { + if (this.Tree.CanExpandGetter == null || this.Model == null) + return false; + + return this.Tree.CanExpandGetter(this.Model); + } + } + + /// + /// Gets or sets our children + /// + public List ChildBranches { + get { return this.childBranches; } + set { this.childBranches = value; } + } + private List childBranches = new List(); + + /// + /// Get/set the model objects that are beneath this branch + /// + public virtual IEnumerable Children { + get { + ArrayList children = new ArrayList(); + foreach (Branch x in this.ChildBranches) + children.Add(x.Model); + return children; + } + set { + this.ChildBranches.Clear(); + + TreeListView treeListView = this.Tree.TreeView; + CheckState? checkedness = null; + if (treeListView != null && treeListView.HierarchicalCheckboxes) + checkedness = treeListView.GetCheckState(this.Model); + foreach (Object x in value) { + this.AddChild(x); + + // If the tree view is showing hierarchical checkboxes, then + // when a child object is first added, it has the same checkedness as this branch + if (checkedness.HasValue && checkedness.Value == CheckState.Checked) + treeListView.SetObjectCheckedness(x, checkedness.Value); + } + } + } + + private void AddChild(object childModel) { + Branch br = this.Tree.GetBranch(childModel); + if (br == null) + br = this.Tree.MakeBranch(this, childModel); + else { + br.ParentBranch = this; + br.Model = childModel; + br.ClearCachedInfo(); + } + this.ChildBranches.Add(br); + } + + /// + /// Gets a list of all the branches that survive filtering + /// + public List FilteredChildBranches { + get { + if (!this.IsExpanded) + return new List(); + + if (!this.Tree.IsFiltering) + return this.ChildBranches; + + List filtered = new List(); + foreach (Branch b in this.ChildBranches) { + if (this.Tree.IncludeModel(b.Model)) + filtered.Add(b); + else { + // Also include this branch if it has any filtered branches (yes, its recursive) + if (b.FilteredChildBranches.Count > 0) + filtered.Add(b); + } + } + return filtered; + } + } + + /// + /// Gets or set whether this branch is expanded + /// + public bool IsExpanded { + get { return this.Tree.IsModelExpanded(this.Model); } + set { this.Tree.SetModelExpanded(this.Model, value); } + } + + /// + /// Return true if this branch is the first branch of the entire tree + /// + public virtual bool IsFirstBranch { + get { + return ((this.flags & Branch.BranchFlags.FirstBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.FirstBranch; + else + this.flags &= ~Branch.BranchFlags.FirstBranch; + } + } + + /// + /// Return true if this branch is the last child of its parent + /// + public virtual bool IsLastChild { + get { + return ((this.flags & Branch.BranchFlags.LastChild) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.LastChild; + else + this.flags &= ~Branch.BranchFlags.LastChild; + } + } + + /// + /// Return true if this branch is the only top level branch + /// + public virtual bool IsOnlyBranch { + get { + return ((this.flags & Branch.BranchFlags.OnlyBranch) != 0); + } + set { + if (value) + this.flags |= Branch.BranchFlags.OnlyBranch; + else + this.flags &= ~Branch.BranchFlags.OnlyBranch; + } + } + + /// + /// Gets the depth level of this branch + /// + public int Level { + get { + if (this.ParentBranch == null) + return 0; + + return this.ParentBranch.Level + 1; + } + } + + /// + /// Gets or sets which model is represented by this branch + /// + public Object Model { + get { return model; } + set { model = value; } + } + private Object model; + + /// + /// Return the number of descendants of this branch that are currently visible + /// + /// + public virtual int NumberVisibleDescendents { + get { + if (!this.IsExpanded) + return 0; + + List filtered = this.FilteredChildBranches; + int count = filtered.Count; + foreach (Branch br in filtered) + count += br.NumberVisibleDescendents; + return count; + } + } + + /// + /// Gets or sets our parent branch + /// + public Branch ParentBranch { + get { return parentBranch; } + set { parentBranch = value; } + } + private Branch parentBranch; + + /// + /// Gets or sets our overall tree + /// + public Tree Tree { + get { return tree; } + set { tree = value; } + } + private Tree tree; + + /// + /// Is this branch currently visible? A branch is visible + /// if it has no parent (i.e. it's a root), or its parent + /// is visible and expanded. + /// + public virtual bool Visible { + get { + if (this.ParentBranch == null) + return true; + + return this.ParentBranch.IsExpanded && this.ParentBranch.Visible; + } + } + + #endregion + + #region Commands + + //------------------------------------------------------------------------------------------ + // Commands + + /// + /// Clear any cached information that this branch is holding + /// + public virtual void ClearCachedInfo() { + this.Children = new ArrayList(); + this.alreadyHasChildren = false; + } + + /// + /// Collapse this branch + /// + public virtual void Collapse() { + this.IsExpanded = false; + } + + /// + /// Expand this branch + /// + public virtual void Expand() { + if (this.CanExpand) { + this.IsExpanded = true; + this.FetchChildren(); + } + } + + /// + /// Expand this branch recursively + /// + public virtual void ExpandAll() { + this.Expand(); + foreach (Branch br in this.ChildBranches) { + if (br.CanExpand) + br.ExpandAll(); + } + } + + /// + /// Collapse all branches in this tree + /// + /// Nothing useful + public virtual void CollapseAll() + { + this.Collapse(); + foreach (Branch br in this.ChildBranches) { + if (br.IsExpanded) + br.CollapseAll(); + } + } + + /// + /// Fetch the children of this branch. + /// + /// This should only be called when CanExpand is true. + public virtual void FetchChildren() { + if (this.alreadyHasChildren) + return; + + this.alreadyHasChildren = true; + + if (this.Tree.ChildrenGetter == null) + return; + + Cursor previous = Cursor.Current; + try { + if (this.Tree.TreeView.UseWaitCursorWhenExpanding) + Cursor.Current = Cursors.WaitCursor; + this.Children = this.Tree.ChildrenGetter(this.Model); + } + finally { + Cursor.Current = previous; + } + } + + /// + /// Collapse the visible descendants of this branch into list of model objects + /// + /// + public virtual IList Flatten() { + ArrayList flatList = new ArrayList(); + if (this.IsExpanded) + this.FlattenOnto(flatList); + return flatList; + } + + /// + /// Flatten this branch's visible descendants onto the given list. + /// + /// + /// The branch itself is not included in the list. + public virtual void FlattenOnto(IList flatList) { + Branch lastBranch = null; + foreach (Branch br in this.FilteredChildBranches) { + lastBranch = br; + br.IsFirstBranch = br.IsOnlyBranch = br.IsLastChild = false; + flatList.Add(br.Model); + if (br.IsExpanded) { + br.FetchChildren(); // make sure we have the branches children + br.FlattenOnto(flatList); + } + } + if (lastBranch != null) + lastBranch.IsLastChild = true; + } + + /// + /// Force a refresh of all children recursively + /// + public virtual void RefreshChildren() { + + // Forget any previous children. We always do this so that if + // IsExpanded or CanExpand have changed, we aren't left with stale information. + this.ClearCachedInfo(); + + if (!this.IsExpanded || !this.CanExpand) + return; + + this.FetchChildren(); + foreach (Branch br in this.ChildBranches) + br.RefreshChildren(); + } + + /// + /// Sort the sub-branches and their descendants so they are ordered according + /// to the given comparer. + /// + /// The comparer that orders the branches + public virtual void Sort(BranchComparer comparer) { + if (this.ChildBranches.Count == 0) + return; + + if (comparer != null) + this.ChildBranches.Sort(comparer); + + foreach (Branch br in this.ChildBranches) + br.Sort(comparer); + } + + #endregion + + + //------------------------------------------------------------------------------------------ + // Private instance variables + + private bool alreadyHasChildren; + private BranchFlags flags; + } + + /// + /// This class sorts branches according to how their respective model objects are sorted + /// + public class BranchComparer : IComparer + { + /// + /// Create a BranchComparer + /// + /// + public BranchComparer(IComparer actualComparer) { + this.actualComparer = actualComparer; + } + + /// + /// Order the two branches + /// + /// + /// + /// + public int Compare(Branch x, Branch y) { + return this.actualComparer.Compare(x.Model, y.Model); + } + + private readonly IComparer actualComparer; + } + + } + + /// + /// This interface should be implemented by model objects that can provide children, + /// but that don't have a parent. This is either because the model objects are always + /// root level, or because they are used in TreeListView that never uses parent + /// calculations. Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithChildren { + /// + /// Get whether this this model can be expanded? If true, an expand glyph will be drawn next to it. + /// + /// This is called often! It must be fast. Dont do a database lookup, calculate pi, or do linear searches just return a property value. + bool TreeCanExpand { get; } + + /// + /// Get the models that will be shown under this model when it is expanded. + /// + /// This is only called when CanExpand returns true. + IEnumerable TreeChildren { get; } + } + + /// + /// This interface should be implemented by model objects that can never have children, + /// but that are used in a TreeListView that uses parent calculations. + /// Parent calculations are only used when HierarchicalCheckBoxes is true. + /// + public interface ITreeModelWithParent { + + /// + /// Get the hierarchical parent of this model. + /// + object TreeParent { get; } + } + + /// + /// ITreeModel allows model objects to provide the required information to TreeListView + /// without using the normal Getter delegates. + /// + public interface ITreeModel: ITreeModelWithChildren, ITreeModelWithParent { + + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs new file mode 100644 index 0000000..e8e520e --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.Designer.cs @@ -0,0 +1,190 @@ +namespace BrightIdeasSoftware +{ + partial class ColumnSelectionForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonMoveUp = new System.Windows.Forms.Button(); + this.buttonMoveDown = new System.Windows.Forms.Button(); + this.buttonShow = new System.Windows.Forms.Button(); + this.buttonHide = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.buttonOK = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.objectListView1 = new BrightIdeasSoftware.ObjectListView(); + this.olvColumn1 = new BrightIdeasSoftware.OLVColumn(); + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit(); + this.SuspendLayout(); + // + // buttonMoveUp + // + this.buttonMoveUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveUp.Location = new System.Drawing.Point(295, 31); + this.buttonMoveUp.Name = "buttonMoveUp"; + this.buttonMoveUp.Size = new System.Drawing.Size(87, 23); + this.buttonMoveUp.TabIndex = 1; + this.buttonMoveUp.Text = "Move &Up"; + this.buttonMoveUp.UseVisualStyleBackColor = true; + this.buttonMoveUp.Click += new System.EventHandler(this.buttonMoveUp_Click); + // + // buttonMoveDown + // + this.buttonMoveDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonMoveDown.Location = new System.Drawing.Point(295, 60); + this.buttonMoveDown.Name = "buttonMoveDown"; + this.buttonMoveDown.Size = new System.Drawing.Size(87, 23); + this.buttonMoveDown.TabIndex = 2; + this.buttonMoveDown.Text = "Move &Down"; + this.buttonMoveDown.UseVisualStyleBackColor = true; + this.buttonMoveDown.Click += new System.EventHandler(this.buttonMoveDown_Click); + // + // buttonShow + // + this.buttonShow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonShow.Location = new System.Drawing.Point(295, 89); + this.buttonShow.Name = "buttonShow"; + this.buttonShow.Size = new System.Drawing.Size(87, 23); + this.buttonShow.TabIndex = 3; + this.buttonShow.Text = "&Show"; + this.buttonShow.UseVisualStyleBackColor = true; + this.buttonShow.Click += new System.EventHandler(this.buttonShow_Click); + // + // buttonHide + // + this.buttonHide.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonHide.Location = new System.Drawing.Point(295, 118); + this.buttonHide.Name = "buttonHide"; + this.buttonHide.Size = new System.Drawing.Size(87, 23); + this.buttonHide.TabIndex = 4; + this.buttonHide.Text = "&Hide"; + this.buttonHide.UseVisualStyleBackColor = true; + this.buttonHide.Click += new System.EventHandler(this.buttonHide_Click); + // + // label1 + // + this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.label1.BackColor = System.Drawing.SystemColors.Control; + this.label1.Location = new System.Drawing.Point(13, 9); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(366, 19); + this.label1.TabIndex = 5; + this.label1.Text = "Choose the columns you want to see in this list. "; + // + // buttonOK + // + this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOK.Location = new System.Drawing.Point(198, 304); + this.buttonOK.Name = "buttonOK"; + this.buttonOK.Size = new System.Drawing.Size(87, 23); + this.buttonOK.TabIndex = 6; + this.buttonOK.Text = "&OK"; + this.buttonOK.UseVisualStyleBackColor = true; + this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(295, 304); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(87, 23); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "&Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // objectListView1 + // + this.objectListView1.AllColumns.Add(this.olvColumn1); + this.objectListView1.AlternateRowBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); + this.objectListView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick; + this.objectListView1.CheckBoxes = true; + this.objectListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.olvColumn1}); + this.objectListView1.FullRowSelect = true; + this.objectListView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; + this.objectListView1.HideSelection = false; + this.objectListView1.Location = new System.Drawing.Point(12, 31); + this.objectListView1.MultiSelect = false; + this.objectListView1.Name = "objectListView1"; + this.objectListView1.ShowGroups = false; + this.objectListView1.ShowSortIndicators = false; + this.objectListView1.Size = new System.Drawing.Size(273, 259); + this.objectListView1.TabIndex = 0; + this.objectListView1.UseCompatibleStateImageBehavior = false; + this.objectListView1.View = System.Windows.Forms.View.Details; + this.objectListView1.SelectionChanged += new System.EventHandler(this.objectListView1_SelectionChanged); + // + // olvColumn1 + // + this.olvColumn1.AspectName = "Text"; + this.olvColumn1.IsVisible = true; + this.olvColumn1.Text = "Column"; + this.olvColumn1.Width = 267; + // + // ColumnSelectionForm + // + this.AcceptButton = this.buttonOK; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(391, 339); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOK); + this.Controls.Add(this.label1); + this.Controls.Add(this.buttonHide); + this.Controls.Add(this.buttonShow); + this.Controls.Add(this.buttonMoveDown); + this.Controls.Add(this.buttonMoveUp); + this.Controls.Add(this.objectListView1); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ColumnSelectionForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.Text = "Column Selection"; + ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private BrightIdeasSoftware.ObjectListView objectListView1; + private System.Windows.Forms.Button buttonMoveUp; + private System.Windows.Forms.Button buttonMoveDown; + private System.Windows.Forms.Button buttonShow; + private System.Windows.Forms.Button buttonHide; + private BrightIdeasSoftware.OLVColumn olvColumn1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button buttonOK; + private System.Windows.Forms.Button buttonCancel; + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/ColumnSelectionForm.cs b/ObjectListView/Utilities/ColumnSelectionForm.cs new file mode 100644 index 0000000..6b8e7e0 --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.cs @@ -0,0 +1,263 @@ +/* + * ColumnSelectionForm - A utility form that allows columns to be rearranged and/or hidden + * + * Author: Phillip Piper + * Date: 1/04/2011 11:15 AM + * + * Change log: + * 2013-04-21 JPP - Fixed obscure bug in column re-ordered. Thanks to Edwin Chen. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// This form is an example of how an application could allows the user to select which columns + /// an ObjectListView will display, as well as select which order the columns are displayed in. + /// + /// + /// In Tile view, ColumnHeader.DisplayIndex does nothing. To reorder the columns you have + /// to change the order of objects in the Columns property. + /// Remember that the first column is special! + /// It has to remain the first column. + /// + public partial class ColumnSelectionForm : Form + { + /// + /// Make a new ColumnSelectionForm + /// + public ColumnSelectionForm() + { + InitializeComponent(); + } + + /// + /// Open this form so it will edit the columns that are available in the listview's current view + /// + /// The ObjectListView whose columns are to be altered + public void OpenOn(ObjectListView olv) + { + this.OpenOn(olv, olv.View); + } + + /// + /// Open this form so it will edit the columns that are available in the given listview + /// when the listview is showing the given type of view. + /// + /// The ObjectListView whose columns are to be altered + /// The view that is to be altered. Must be View.Details or View.Tile + public void OpenOn(ObjectListView olv, View view) + { + if (view != View.Details && view != View.Tile) + return; + + this.InitializeForm(olv, view); + if (this.ShowDialog() == DialogResult.OK) + this.Apply(olv, view); + } + + /// + /// Initialize the form to show the columns of the given view + /// + /// + /// + protected void InitializeForm(ObjectListView olv, View view) + { + this.AllColumns = olv.AllColumns; + this.RearrangableColumns = new List(this.AllColumns); + foreach (OLVColumn col in this.RearrangableColumns) { + if (view == View.Details) + this.MapColumnToVisible[col] = col.IsVisible; + else + this.MapColumnToVisible[col] = col.IsTileViewColumn; + } + this.RearrangableColumns.Sort(new SortByDisplayOrder(this)); + + this.objectListView1.BooleanCheckStateGetter = delegate(Object rowObject) { + return this.MapColumnToVisible[(OLVColumn)rowObject]; + }; + + this.objectListView1.BooleanCheckStatePutter = delegate(Object rowObject, bool newValue) { + // Some columns should always be shown, so ignore attempts to hide them + OLVColumn column = (OLVColumn)rowObject; + if (!column.CanBeHidden) + return true; + + this.MapColumnToVisible[column] = newValue; + EnableControls(); + return newValue; + }; + + this.objectListView1.SetObjects(this.RearrangableColumns); + this.EnableControls(); + } + private List AllColumns = null; + private List RearrangableColumns = new List(); + private Dictionary MapColumnToVisible = new Dictionary(); + + /// + /// The user has pressed OK. Do what's required. + /// + /// + /// + protected void Apply(ObjectListView olv, View view) + { + olv.Freeze(); + + // Update the column definitions to reflect whether they have been hidden + if (view == View.Details) { + foreach (OLVColumn col in olv.AllColumns) + col.IsVisible = this.MapColumnToVisible[col]; + } else { + foreach (OLVColumn col in olv.AllColumns) + col.IsTileViewColumn = this.MapColumnToVisible[col]; + } + + // Collect the columns are still visible + List visibleColumns = this.RearrangableColumns.FindAll( + delegate(OLVColumn x) { return this.MapColumnToVisible[x]; }); + + // Detail view and Tile view have to be handled in different ways. + if (view == View.Details) { + // Of the still visible columns, change DisplayIndex to reflect their position in the rearranged list + olv.ChangeToFilteredColumns(view); + foreach (OLVColumn col in visibleColumns) { + col.DisplayIndex = visibleColumns.IndexOf((OLVColumn)col); + col.LastDisplayIndex = col.DisplayIndex; + } + } else { + // In Tile view, DisplayOrder does nothing. So to change the display order, we have to change the + // order of the columns in the Columns property. + // Remember, the primary column is special and has to remain first! + OLVColumn primaryColumn = this.AllColumns[0]; + visibleColumns.Remove(primaryColumn); + + olv.Columns.Clear(); + olv.Columns.Add(primaryColumn); + olv.Columns.AddRange(visibleColumns.ToArray()); + olv.CalculateReasonableTileSize(); + } + + olv.Unfreeze(); + } + + #region Event handlers + + private void buttonMoveUp_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex-1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonMoveDown_Click(object sender, EventArgs e) + { + int selectedIndex = this.objectListView1.SelectedIndices[0]; + OLVColumn col = this.RearrangableColumns[selectedIndex]; + this.RearrangableColumns.RemoveAt(selectedIndex); + this.RearrangableColumns.Insert(selectedIndex + 1, col); + + this.objectListView1.BuildList(); + + EnableControls(); + } + + private void buttonShow_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = true; + } + + private void buttonHide_Click(object sender, EventArgs e) + { + this.objectListView1.SelectedItem.Checked = false; + } + + private void buttonOK_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.OK; + this.Close(); + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.Cancel; + this.Close(); + } + + private void objectListView1_SelectionChanged(object sender, EventArgs e) + { + EnableControls(); + } + + #endregion + + #region Control enabling + + /// + /// Enable the controls on the dialog to match the current state + /// + protected void EnableControls() + { + if (this.objectListView1.SelectedIndices.Count == 0) { + this.buttonMoveUp.Enabled = false; + this.buttonMoveDown.Enabled = false; + this.buttonShow.Enabled = false; + this.buttonHide.Enabled = false; + } else { + // Can't move the first row up or the last row down + this.buttonMoveUp.Enabled = (this.objectListView1.SelectedIndices[0] != 0); + this.buttonMoveDown.Enabled = (this.objectListView1.SelectedIndices[0] < (this.objectListView1.GetItemCount() - 1)); + + OLVColumn selectedColumn = (OLVColumn)this.objectListView1.SelectedObject; + + // Some columns cannot be hidden (and hence cannot be Shown) + this.buttonShow.Enabled = !this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + this.buttonHide.Enabled = this.MapColumnToVisible[selectedColumn] && selectedColumn.CanBeHidden; + } + } + #endregion + + /// + /// A Comparer that will sort a list of columns so that visible ones come before hidden ones, + /// and that are ordered by their display order. + /// + private class SortByDisplayOrder : IComparer + { + public SortByDisplayOrder(ColumnSelectionForm form) + { + this.Form = form; + } + private ColumnSelectionForm Form; + + #region IComparer Members + + int IComparer.Compare(OLVColumn x, OLVColumn y) + { + if (this.Form.MapColumnToVisible[x] && !this.Form.MapColumnToVisible[y]) + return -1; + + if (!this.Form.MapColumnToVisible[x] && this.Form.MapColumnToVisible[y]) + return 1; + + if (x.DisplayIndex == y.DisplayIndex) + return x.Text.CompareTo(y.Text); + else + return x.DisplayIndex - y.DisplayIndex; + } + + #endregion + } + } +} diff --git a/ObjectListView/Utilities/ColumnSelectionForm.resx b/ObjectListView/Utilities/ColumnSelectionForm.resx new file mode 100644 index 0000000..19dc0dd --- /dev/null +++ b/ObjectListView/Utilities/ColumnSelectionForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ObjectListView/Utilities/Generator.cs b/ObjectListView/Utilities/Generator.cs new file mode 100644 index 0000000..705ed30 --- /dev/null +++ b/ObjectListView/Utilities/Generator.cs @@ -0,0 +1,563 @@ +/* + * Generator - Utility methods that generate columns or methods + * + * Author: Phillip Piper + * Date: 15/08/2009 22:37 + * + * Change log: + * 2015-06-17 JPP - Columns without [OLVColumn] now auto size + * 2012-08-16 JPP - Generator now considers [OLVChildren] and [OLVIgnore] attributes. + * 2012-06-14 JPP - Allow columns to be generated even if they are not marked with [OLVColumn] + * - Converted class from static to instance to allow it to be subclassed. + * Also, added IGenerator to allow it to be completely reimplemented. + * v2.5.1 + * 2010-11-01 JPP - DisplayIndex is now set correctly for columns that lack that attribute + * v2.4.1 + * 2010-08-25 JPP - Generator now also resets sort columns + * v2.4 + * 2010-04-14 JPP - Allow Name property to be set + * - Don't double set the Text property + * v2.3 + * 2009-08-15 JPP - Initial version + * + * To do: + * + * Copyright (C) 2009-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; +using System.Reflection.Emit; +using System.Text.RegularExpressions; +using System.Windows.Forms; + +namespace BrightIdeasSoftware +{ + /// + /// An object that implements the IGenerator interface provides the ability + /// to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + public interface IGenerator { + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties); + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + IList GenerateColumns(Type type, bool allProperties); + } + + /// + /// The Generator class provides methods to dynamically create columns + /// for an ObjectListView based on the characteristics of a given collection + /// of model objects. + /// + /// + /// For a given type, a Generator can create columns to match the public properties + /// of that type. The generator can consider all public properties or only those public properties marked with + /// [OLVColumn] attribute. + /// + public class Generator : IGenerator { + #region Static convenience methods + + /// + /// Gets or sets the actual generator used by the static convenience methods. + /// + /// If you subclass the standard generator or implement IGenerator yourself, + /// you should install an instance of your subclass/implementation here. + public static IGenerator Instance { + get { return Generator.instance ?? (Generator.instance = new Generator()); } + set { Generator.instance = value; } + } + private static IGenerator instance; + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable) { + Generator.GenerateColumns(olv, enumerable, false); + } + + /// + /// Replace all columns of the given ObjectListView with columns generated + /// from the first member of the given enumerable. If the enumerable is + /// empty or null, the ObjectListView will be cleared. + /// + /// The ObjectListView to modify + /// The collection whose first element will be used to generate columns. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, IEnumerable enumerable, bool allProperties) { + // Generate columns based on the type of the first model in the collection and then quit + if (enumerable != null) { + foreach (object model in enumerable) { + Generator.Instance.GenerateAndReplaceColumns(olv, model.GetType(), allProperties); + return; + } + } + + // If we reach here, the collection was empty, so we clear the list + Generator.Instance.GenerateAndReplaceColumns(olv, null, allProperties); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + static public void GenerateColumns(ObjectListView olv, Type type) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, false); + } + + /// + /// Generate columns into the given ObjectListView that come from the public properties of the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + static public void GenerateColumns(ObjectListView olv, Type type, bool allProperties) { + Generator.Instance.GenerateAndReplaceColumns(olv, type, allProperties); + } + + /// + /// Generate a list of OLVColumns based on the public properties of the given type + /// that have a OLVColumn attribute. + /// + /// + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + static public IList GenerateColumns(Type type) { + return Generator.Instance.GenerateColumns(type, false); + } + + #endregion + + #region Public interface + + /// + /// Generate columns into the given ObjectListView that come from the given + /// model object type. + /// + /// The ObjectListView to modify + /// The model type whose attributes will be considered. + /// Will columns be generated for properties that are not marked with [OLVColumn]. + public virtual void GenerateAndReplaceColumns(ObjectListView olv, Type type, bool allProperties) { + IList columns = this.GenerateColumns(type, allProperties); + TreeListView tlv = olv as TreeListView; + if (tlv != null) + this.TryGenerateChildrenDelegates(tlv, type); + this.ReplaceColumns(olv, columns); + } + + /// + /// Generate a list of OLVColumns based on the attributes of the given type + /// If allProperties to true, all public properties will have a matching column generated. + /// If allProperties is false, only properties that have a OLVColumn attribute will have a column generated. + /// + /// + /// Will columns be generated for properties that are not marked with [OLVColumn]. + /// A collection of OLVColumns matching the attributes of Type that have OLVColumnAttributes. + public virtual IList GenerateColumns(Type type, bool allProperties) { + List columns = new List(); + + // Sanity + if (type == null) + return columns; + + // Iterate all public properties in the class and build columns from those that have + // an OLVColumn attribute and that are not ignored. + foreach (PropertyInfo pinfo in type.GetProperties()) { + if (Attribute.GetCustomAttribute(pinfo, typeof(OLVIgnoreAttribute)) != null) + continue; + + OLVColumnAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVColumnAttribute)) as OLVColumnAttribute; + if (attr == null) { + if (allProperties) + columns.Add(this.MakeColumnFromPropertyInfo(pinfo)); + } else { + columns.Add(this.MakeColumnFromAttribute(pinfo, attr)); + } + } + + // How many columns have DisplayIndex specifically set? + int countPositiveDisplayIndex = 0; + foreach (OLVColumn col in columns) { + if (col.DisplayIndex >= 0) + countPositiveDisplayIndex += 1; + } + + // Give columns that don't have a DisplayIndex an incremental index + int columnIndex = countPositiveDisplayIndex; + foreach (OLVColumn col in columns) + if (col.DisplayIndex < 0) + col.DisplayIndex = (columnIndex++); + + columns.Sort(delegate(OLVColumn x, OLVColumn y) { + return x.DisplayIndex.CompareTo(y.DisplayIndex); + }); + + return columns; + } + + #endregion + + #region Implementation + + /// + /// Replace all the columns in the given listview with the given list of columns. + /// + /// + /// + protected virtual void ReplaceColumns(ObjectListView olv, IList columns) { + olv.Reset(); + + // Are there new columns to add? + if (columns == null || columns.Count == 0) + return; + + // Setup the columns + olv.AllColumns.AddRange(columns); + this.PostCreateColumns(olv); + } + + /// + /// Post process columns after creating them and adding them to the AllColumns collection. + /// + /// + public virtual void PostCreateColumns(ObjectListView olv) { + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.CheckBoxes; })) + olv.UseSubItemCheckBoxes = true; + if (olv.AllColumns.Exists(delegate(OLVColumn x) { return x.Index > 0 && (x.ImageGetter != null || !String.IsNullOrEmpty(x.ImageAspectName)); })) + olv.ShowImagesOnSubItems = true; + olv.RebuildColumns(); + olv.AutoSizeColumns(); + } + + /// + /// Create a column from the given PropertyInfo and OLVColumn attribute + /// + /// + /// + /// + protected virtual OLVColumn MakeColumnFromAttribute(PropertyInfo pinfo, OLVColumnAttribute attr) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, attr); + } + + /// + /// Make a column from the given PropertyInfo + /// + /// + /// + protected virtual OLVColumn MakeColumnFromPropertyInfo(PropertyInfo pinfo) { + return MakeColumn(pinfo.Name, DisplayNameToColumnTitle(pinfo.Name), pinfo.CanWrite, pinfo.PropertyType, null); + } + + /// + /// Make a column from the given PropertyDescriptor + /// + /// + /// + public virtual OLVColumn MakeColumnFromPropertyDescriptor(PropertyDescriptor pd) { + OLVColumnAttribute attr = pd.Attributes[typeof(OLVColumnAttribute)] as OLVColumnAttribute; + return MakeColumn(pd.Name, DisplayNameToColumnTitle(pd.DisplayName), !pd.IsReadOnly, pd.PropertyType, attr); + } + + /// + /// Create a column with all the given information + /// + /// + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, bool editable, Type propertyType, OLVColumnAttribute attr) { + + OLVColumn column = this.MakeColumn(aspectName, title, attr); + column.Name = (attr == null || String.IsNullOrEmpty(attr.Name)) ? aspectName : attr.Name; + this.ConfigurePossibleBooleanColumn(column, propertyType); + + if (attr == null) { + column.IsEditable = editable; + column.Width = -1; // Auto size + return column; + } + + column.AspectToStringFormat = attr.AspectToStringFormat; + if (attr.IsCheckBoxesSet) + column.CheckBoxes = attr.CheckBoxes; + column.DisplayIndex = attr.DisplayIndex; + column.FillsFreeSpace = attr.FillsFreeSpace; + if (attr.IsFreeSpaceProportionSet) + column.FreeSpaceProportion = attr.FreeSpaceProportion; + column.GroupWithItemCountFormat = attr.GroupWithItemCountFormat; + column.GroupWithItemCountSingularFormat = attr.GroupWithItemCountSingularFormat; + column.Hyperlink = attr.Hyperlink; + column.ImageAspectName = attr.ImageAspectName; + column.IsEditable = attr.IsEditableSet ? attr.IsEditable : editable; + column.IsTileViewColumn = attr.IsTileViewColumn; + column.IsVisible = attr.IsVisible; + column.MaximumWidth = attr.MaximumWidth; + column.MinimumWidth = attr.MinimumWidth; + column.Tag = attr.Tag; + if (attr.IsTextAlignSet) + column.TextAlign = attr.TextAlign; + column.ToolTipText = attr.ToolTipText; + if (attr.IsTriStateCheckBoxesSet) + column.TriStateCheckBoxes = attr.TriStateCheckBoxes; + column.UseInitialLetterForGroup = attr.UseInitialLetterForGroup; + column.Width = attr.Width; + if (attr.GroupCutoffs != null && attr.GroupDescriptions != null) + column.MakeGroupies(attr.GroupCutoffs, attr.GroupDescriptions); + return column; + } + + /// + /// Create a column. + /// + /// + /// + /// + /// + protected virtual OLVColumn MakeColumn(string aspectName, string title, OLVColumnAttribute attr) { + string columnTitle = (attr == null || String.IsNullOrEmpty(attr.Title)) ? title : attr.Title; + return new OLVColumn(columnTitle, aspectName); + } + + /// + /// Convert a property name to a displayable title. + /// + /// + /// + protected virtual string DisplayNameToColumnTitle(string displayName) { + string title = displayName.Replace("_", " "); + // Put a space between a lower-case letter that is followed immediately by an upper case letter + title = Regex.Replace(title, @"(\p{Ll})(\p{Lu})", @"$1 $2"); + return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title); + } + + /// + /// Configure the given column to show a checkbox if appropriate + /// + /// + /// + protected virtual void ConfigurePossibleBooleanColumn(OLVColumn column, Type propertyType) { + if (propertyType != typeof(bool) && propertyType != typeof(bool?) && propertyType != typeof(CheckState)) + return; + + column.CheckBoxes = true; + column.TextAlign = HorizontalAlignment.Center; + column.Width = 32; + column.TriStateCheckBoxes = (propertyType == typeof(bool?) || propertyType == typeof(CheckState)); + } + + /// + /// If this given type has an property marked with [OLVChildren], make delegates that will + /// traverse that property as the children of an instance of the model + /// + /// + /// + protected virtual void TryGenerateChildrenDelegates(TreeListView tlv, Type type) { + foreach (PropertyInfo pinfo in type.GetProperties()) { + OLVChildrenAttribute attr = Attribute.GetCustomAttribute(pinfo, typeof(OLVChildrenAttribute)) as OLVChildrenAttribute; + if (attr != null) { + this.GenerateChildrenDelegates(tlv, pinfo); + return; + } + } + } + + /// + /// Generate CanExpand and ChildrenGetter delegates from the given property. + /// + /// + /// + protected virtual void GenerateChildrenDelegates(TreeListView tlv, PropertyInfo pinfo) { + Munger childrenGetter = new Munger(pinfo.Name); + tlv.CanExpandGetter = delegate(object x) { + try { + IEnumerable result = childrenGetter.GetValueEx(x) as IEnumerable; + return !ObjectListView.IsEnumerableEmpty(result); + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return false; + } + }; + tlv.ChildrenGetter = delegate(object x) { + try { + return childrenGetter.GetValueEx(x) as IEnumerable; + } + catch (MungerException ex) { + System.Diagnostics.Debug.WriteLine(ex); + return null; + } + }; + } + #endregion + + /* + #region Dynamic methods + + /// + /// Generate methods so that reflection is not needed. + /// + /// + /// + public static void GenerateMethods(ObjectListView olv, Type type) { + foreach (OLVColumn column in olv.Columns) { + GenerateColumnMethods(column, type); + } + } + + public static void GenerateColumnMethods(OLVColumn column, Type type) { + if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) + column.AspectGetter = Generator.GenerateAspectGetter(type, column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + private static AspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, typeof(Object), new Type[] { type }, type, true); + Generator.GenerateIL(type, path, getter.GetILGenerator()); + return (AspectGetterDelegate)getter.CreateDelegate(typeof(AspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private static void GenerateIL(Type modelType, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + OpCodes.Castclass + // Generate the IL to access each part of the dotted chain + Type type = modelType; + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = Generator.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !modelType.IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private static Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + */ + } +} diff --git a/ObjectListView/Utilities/OLVExporter.cs b/ObjectListView/Utilities/OLVExporter.cs new file mode 100644 index 0000000..1400ba1 --- /dev/null +++ b/ObjectListView/Utilities/OLVExporter.cs @@ -0,0 +1,277 @@ +/* + * OLVExporter - Export the contents of an ObjectListView into various text-based formats + * + * Author: Phillip Piper + * Date: 7 August 2012, 10:35pm + * + * Change log: + * 2012-08-07 JPP Initial code + * + * Copyright (C) 2012 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace BrightIdeasSoftware { + /// + /// An OLVExporter converts a collection of rows from an ObjectListView + /// into a variety of textual formats. + /// + public class OLVExporter { + + /// + /// What format will be used for exporting + /// + public enum ExportFormat { + + /// + /// Tab separated values, according to http://www.iana.org/assignments/media-types/text/tab-separated-values + /// + TabSeparated = 1, + + /// + /// Alias for TabSeparated + /// + TSV = 1, + + /// + /// Comma separated values, according to http://www.ietf.org/rfc/rfc4180.txt + /// + CSV, + + /// + /// HTML table, according to me + /// + HTML + } + + #region Life and death + + /// + /// Create an empty exporter + /// + public OLVExporter() {} + + /// + /// Create an exporter that will export all the rows of the given ObjectListView + /// + /// + public OLVExporter(ObjectListView olv) : this(olv, olv.Objects) {} + + /// + /// Create an exporter that will export all the given rows from the given ObjectListView + /// + /// + /// + public OLVExporter(ObjectListView olv, IEnumerable objectsToExport) { + if (olv == null) throw new ArgumentNullException("olv"); + if (objectsToExport == null) throw new ArgumentNullException("objectsToExport"); + + this.ListView = olv; + this.ModelObjects = ObjectListView.EnumerableToArray(objectsToExport, true); + } + + #endregion + + #region Properties + + /// + /// Gets or sets whether hidden columns will also be included in the textual + /// representation. If this is false (the default), only visible columns will + /// be included. + /// + public bool IncludeHiddenColumns { + get { return includeHiddenColumns; } + set { includeHiddenColumns = value; } + } + private bool includeHiddenColumns; + + /// + /// Gets or sets whether column headers will also be included in the text + /// and HTML representation. Default is true. + /// + public bool IncludeColumnHeaders { + get { return includeColumnHeaders; } + set { includeColumnHeaders = value; } + } + private bool includeColumnHeaders = true; + + /// + /// Gets the ObjectListView that is being used as the source of the data + /// to be exported + /// + public ObjectListView ListView { + get { return objectListView; } + set { objectListView = value; } + } + private ObjectListView objectListView; + + /// + /// Gets the model objects that are to be placed in the data object + /// + public IList ModelObjects { + get { return modelObjects; } + set { modelObjects = value; } + } + private IList modelObjects = new ArrayList(); + + #endregion + + #region Commands + + /// + /// Export the nominated rows from the nominated ObjectListView. + /// Returns the result in the expected format. + /// + /// + /// + /// This will perform only one conversion, even if called multiple times with different formats. + public string ExportTo(ExportFormat format) { + if (results == null) + this.Convert(); + + return results[format]; + } + + /// + /// Convert + /// + public void Convert() { + + IList columns = this.IncludeHiddenColumns ? this.ListView.AllColumns : this.ListView.ColumnsInDisplayOrder; + + StringBuilder sbText = new StringBuilder(); + StringBuilder sbCsv = new StringBuilder(); + StringBuilder sbHtml = new StringBuilder(""); + + // Include column headers + if (this.IncludeColumnHeaders) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.Text); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + + foreach (object modelObject in this.ModelObjects) { + List strings = new List(); + foreach (OLVColumn col in columns) + strings.Add(col.GetStringValue(modelObject)); + + WriteOneRow(sbText, strings, "", "\t", "", null); + WriteOneRow(sbHtml, strings, "", HtmlEncode); + WriteOneRow(sbCsv, strings, "", ",", "", CsvEncode); + } + sbHtml.AppendLine("
      ", "", "
      ", "", "
      "); + + results = new Dictionary(); + results[ExportFormat.TabSeparated] = sbText.ToString(); + results[ExportFormat.CSV] = sbCsv.ToString(); + results[ExportFormat.HTML] = sbHtml.ToString(); + } + + private delegate string StringToString(string str); + + private void WriteOneRow(StringBuilder sb, IEnumerable strings, string startRow, string betweenCells, string endRow, StringToString encoder) { + sb.Append(startRow); + bool first = true; + foreach (string s in strings) { + if (!first) + sb.Append(betweenCells); + sb.Append(encoder == null ? s : encoder(s)); + first = false; + } + sb.AppendLine(endRow); + } + + private Dictionary results; + + #endregion + + #region Encoding + + /// + /// Encode a string such that it can be used as a value in a CSV file. + /// This basically means replacing any quote mark with two quote marks, + /// and enclosing the whole string in quotes. + /// + /// + /// + private static string CsvEncode(string text) { + if (text == null) + return null; + + const string DOUBLEQUOTE = @""""; // one double quote + const string TWODOUBEQUOTES = @""""""; // two double quotes + + StringBuilder sb = new StringBuilder(DOUBLEQUOTE); + sb.Append(text.Replace(DOUBLEQUOTE, TWODOUBEQUOTES)); + sb.Append(DOUBLEQUOTE); + + return sb.ToString(); + } + + /// + /// HTML-encodes a string and returns the encoded string. + /// + /// The text string to encode. + /// The HTML-encoded text. + /// Taken from http://www.west-wind.com/weblog/posts/2009/Feb/05/Html-and-Uri-String-Encoding-without-SystemWeb + private static string HtmlEncode(string text) { + if (text == null) + return null; + + StringBuilder sb = new StringBuilder(text.Length); + + int len = text.Length; + for (int i = 0; i < len; i++) { + switch (text[i]) { + case '<': + sb.Append("<"); + break; + case '>': + sb.Append(">"); + break; + case '"': + sb.Append("""); + break; + case '&': + sb.Append("&"); + break; + default: + if (text[i] > 159) { + // decimal numeric entity + sb.Append("&#"); + sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture)); + sb.Append(";"); + } else + sb.Append(text[i]); + break; + } + } + return sb.ToString(); + } + #endregion + } +} \ No newline at end of file diff --git a/ObjectListView/Utilities/TypedObjectListView.cs b/ObjectListView/Utilities/TypedObjectListView.cs new file mode 100644 index 0000000..8eb6bd0 --- /dev/null +++ b/ObjectListView/Utilities/TypedObjectListView.cs @@ -0,0 +1,561 @@ +/* + * TypedObjectListView - A wrapper around an ObjectListView that provides type-safe delegates. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * v2.6 + * 2012-10-26 JPP - Handle rare case where a null model object was passed into aspect getters. + * v2.3 + * 2009-03-31 JPP - Added Objects property + * 2008-11-26 JPP - Added tool tip getting methods + * 2008-11-05 JPP - Added CheckState handling methods + * 2008-10-24 JPP - Generate dynamic methods MkII. This one handles value types + * 2008-10-21 JPP - Generate dynamic methods + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Reflection; +using System.Reflection.Emit; + +namespace BrightIdeasSoftware +{ + /// + /// A TypedObjectListView is a type-safe wrapper around an ObjectListView. + /// + /// + /// VCS does not support generics on controls. It can be faked to some degree, but it + /// cannot be completely overcome. In our case in particular, there is no way to create + /// the custom OLVColumn's that we need to truly be generic. So this wrapper is an + /// experiment in providing some type-safe access in a way that is useful and available today. + /// A TypedObjectListView is not more efficient than a normal ObjectListView. + /// Underneath, the same name of casts are performed. But it is easier to use since you + /// do not have to write the casts yourself. + /// + /// + /// The class of model object that the list will manage + /// + /// To use a TypedObjectListView, you write code like this: + /// + /// TypedObjectListView<Person> tlist = new TypedObjectListView<Person>(this.listView1); + /// tlist.CheckStateGetter = delegate(Person x) { return x.IsActive; }; + /// tlist.GetColumn(0).AspectGetter = delegate(Person x) { return x.Name; }; + /// ... + /// + /// To iterate over the selected objects, you can write something elegant like this: + /// + /// foreach (Person x in tlist.SelectedObjects) { + /// x.GrantSalaryIncrease(); + /// } + /// + /// + public class TypedObjectListView where T : class + { + /// + /// Create a typed wrapper around the given list. + /// + /// The listview to be wrapped + public TypedObjectListView(ObjectListView olv) { + this.olv = olv; + } + + //-------------------------------------------------------------------------------------- + // Properties + + /// + /// Return the model object that is checked, if only one row is checked. + /// If zero rows are checked, or more than one row, null is returned. + /// + public virtual T CheckedObject { + get { return (T)this.olv.CheckedObject; } + } + + /// + /// Return the list of all the checked model objects + /// + public virtual IList CheckedObjects { + get { + IList checkedObjects = this.olv.CheckedObjects; + List objects = new List(checkedObjects.Count); + foreach (object x in checkedObjects) + objects.Add((T)x); + + return objects; + } + set { this.olv.CheckedObjects = (IList)value; } + } + + /// + /// The ObjectListView that is being wrapped + /// + public virtual ObjectListView ListView { + get { return olv; } + set { olv = value; } + } + private ObjectListView olv; + + /// + /// Get or set the list of all model objects + /// + public virtual IList Objects { + get { + List objects = new List(this.olv.GetItemCount()); + for (int i = 0; i < this.olv.GetItemCount(); i++) + objects.Add(this.GetModelObject(i)); + + return objects; + } + set { this.olv.SetObjects(value); } + } + + /// + /// Return the model object that is selected, if only one row is selected. + /// If zero rows are selected, or more than one row, null is returned. + /// + public virtual T SelectedObject { + get { return (T)this.olv.SelectedObject; } + set { this.olv.SelectedObject = value; } + } + + /// + /// The list of model objects that are selected. + /// + public virtual IList SelectedObjects { + get { + List objects = new List(this.olv.SelectedIndices.Count); + foreach (int index in this.olv.SelectedIndices) + objects.Add((T)this.olv.GetModelObject(index)); + + return objects; + } + set { this.olv.SelectedObjects = (IList)value; } + } + + //-------------------------------------------------------------------------------------- + // Accessors + + /// + /// Return a typed wrapper around the column at the given index + /// + /// The index of the column + /// A typed column or null + public virtual TypedColumn GetColumn(int i) { + return new TypedColumn(this.olv.GetColumn(i)); + } + + /// + /// Return a typed wrapper around the column with the given name + /// + /// The name of the column + /// A typed column or null + public virtual TypedColumn GetColumn(string name) { + return new TypedColumn(this.olv.GetColumn(name)); + } + + /// + /// Return the model object at the given index + /// + /// The index of the model object + /// The model object or null + public virtual T GetModelObject(int index) { + return (T)this.olv.GetModelObject(index); + } + + //-------------------------------------------------------------------------------------- + // Delegates + + /// + /// CheckStateGetter + /// + /// + /// + public delegate CheckState TypedCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the check state getter + /// + public virtual TypedCheckStateGetterDelegate CheckStateGetter { + get { return checkStateGetter; } + set { + this.checkStateGetter = value; + if (value == null) + this.olv.CheckStateGetter = null; + else + this.olv.CheckStateGetter = delegate(object x) { + return this.checkStateGetter((T)x); + }; + } + } + private TypedCheckStateGetterDelegate checkStateGetter; + + /// + /// BooleanCheckStateGetter + /// + /// + /// + public delegate bool TypedBooleanCheckStateGetterDelegate(T rowObject); + + /// + /// Gets or sets the boolean check state getter + /// + public virtual TypedBooleanCheckStateGetterDelegate BooleanCheckStateGetter { + set { + if (value == null) + this.olv.BooleanCheckStateGetter = null; + else + this.olv.BooleanCheckStateGetter = delegate(object x) { + return value((T)x); + }; + } + } + + /// + /// CheckStatePutter + /// + /// + /// + /// + public delegate CheckState TypedCheckStatePutterDelegate(T rowObject, CheckState newValue); + + /// + /// Gets or sets the check state putter delegate + /// + public virtual TypedCheckStatePutterDelegate CheckStatePutter { + get { return checkStatePutter; } + set { + this.checkStatePutter = value; + if (value == null) + this.olv.CheckStatePutter = null; + else + this.olv.CheckStatePutter = delegate(object x, CheckState newValue) { + return this.checkStatePutter((T)x, newValue); + }; + } + } + private TypedCheckStatePutterDelegate checkStatePutter; + + /// + /// BooleanCheckStatePutter + /// + /// + /// + /// + public delegate bool TypedBooleanCheckStatePutterDelegate(T rowObject, bool newValue); + + /// + /// Gets or sets the boolean check state putter + /// + public virtual TypedBooleanCheckStatePutterDelegate BooleanCheckStatePutter { + set { + if (value == null) + this.olv.BooleanCheckStatePutter = null; + else + this.olv.BooleanCheckStatePutter = delegate(object x, bool newValue) { + return value((T)x, newValue); + }; + } + } + + /// + /// ToolTipGetter + /// + /// + /// + /// + public delegate String TypedCellToolTipGetterDelegate(OLVColumn column, T modelObject); + + /// + /// Gets or sets the cell tooltip getter + /// + public virtual TypedCellToolTipGetterDelegate CellToolTipGetter { + set { + if (value == null) + this.olv.CellToolTipGetter = null; + else + this.olv.CellToolTipGetter = delegate(OLVColumn col, Object x) { + return value(col, (T)x); + }; + } + } + + /// + /// Gets or sets the header tool tip getter + /// + public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { + get { return this.olv.HeaderToolTipGetter; } + set { this.olv.HeaderToolTipGetter = value; } + } + + //-------------------------------------------------------------------------------------- + // Commands + + /// + /// This method will generate AspectGetters for any column that has an AspectName. + /// + public virtual void GenerateAspectGetters() { + for (int i = 0; i < this.ListView.Columns.Count; i++) + this.GetColumn(i).GenerateAspectGetter(); + } + } + + /// + /// A type-safe wrapper around an OLVColumn + /// + /// + public class TypedColumn where T : class + { + /// + /// Creates a TypedColumn + /// + /// + public TypedColumn(OLVColumn column) { + this.column = column; + } + private OLVColumn column; + + /// + /// + /// + /// + /// + public delegate Object TypedAspectGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate void TypedAspectPutterDelegate(T rowObject, Object newValue); + + /// + /// + /// + /// + /// + public delegate Object TypedGroupKeyGetterDelegate(T rowObject); + + /// + /// + /// + /// + /// + public delegate Object TypedImageGetterDelegate(T rowObject); + + /// + /// + /// + public TypedAspectGetterDelegate AspectGetter { + get { return this.aspectGetter; } + set { + this.aspectGetter = value; + if (value == null) + this.column.AspectGetter = null; + else + this.column.AspectGetter = delegate(object x) { + return x == null ? null : this.aspectGetter((T)x); + }; + } + } + private TypedAspectGetterDelegate aspectGetter; + + /// + /// + /// + public TypedAspectPutterDelegate AspectPutter { + get { return aspectPutter; } + set { + this.aspectPutter = value; + if (value == null) + this.column.AspectPutter = null; + else + this.column.AspectPutter = delegate(object x, object newValue) { + this.aspectPutter((T)x, newValue); + }; + } + } + private TypedAspectPutterDelegate aspectPutter; + + /// + /// + /// + public TypedImageGetterDelegate ImageGetter { + get { return imageGetter; } + set { + this.imageGetter = value; + if (value == null) + this.column.ImageGetter = null; + else + this.column.ImageGetter = delegate(object x) { + return this.imageGetter((T)x); + }; + } + } + private TypedImageGetterDelegate imageGetter; + + /// + /// + /// + public TypedGroupKeyGetterDelegate GroupKeyGetter { + get { return groupKeyGetter; } + set { + this.groupKeyGetter = value; + if (value == null) + this.column.GroupKeyGetter = null; + else + this.column.GroupKeyGetter = delegate(object x) { + return this.groupKeyGetter((T)x); + }; + } + } + private TypedGroupKeyGetterDelegate groupKeyGetter; + + #region Dynamic methods + + /// + /// Generate an aspect getter that does the same thing as the AspectName, + /// except without using reflection. + /// + /// + /// + /// If you have an AspectName of "Owner.Address.Postcode", this will generate + /// the equivalent of: this.AspectGetter = delegate (object x) { + /// return x.Owner.Address.Postcode; + /// } + /// + /// + /// + /// If AspectName is empty, this method will do nothing, otherwise + /// this will replace any existing AspectGetter. + /// + /// + public void GenerateAspectGetter() { + if (!String.IsNullOrEmpty(this.column.AspectName)) + this.AspectGetter = this.GenerateAspectGetter(typeof(T), this.column.AspectName); + } + + /// + /// Generates an aspect getter method dynamically. The method will execute + /// the given dotted chain of selectors against a model object given at runtime. + /// + /// The type of model object to be passed to the generated method + /// A dotted chain of selectors. Each selector can be the name of a + /// field, property or parameter-less method. + /// A typed delegate + private TypedAspectGetterDelegate GenerateAspectGetter(Type type, string path) { + DynamicMethod getter = new DynamicMethod(String.Empty, + typeof(Object), new Type[] { type }, type, true); + this.GenerateIL(type, path, getter.GetILGenerator()); + return (TypedAspectGetterDelegate)getter.CreateDelegate(typeof(TypedAspectGetterDelegate)); + } + + /// + /// This method generates the actual IL for the method. + /// + /// + /// + /// + private void GenerateIL(Type type, string path, ILGenerator il) { + // Push our model object onto the stack + il.Emit(OpCodes.Ldarg_0); + + // Generate the IL to access each part of the dotted chain + string[] parts = path.Split('.'); + for (int i = 0; i < parts.Length; i++) { + type = this.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); + if (type == null) + break; + } + + // If the object to be returned is a value type (e.g. int, bool), it + // must be boxed, since the delegate returns an Object + if (type != null && type.IsValueType && !typeof(T).IsValueType) + il.Emit(OpCodes.Box, type); + + il.Emit(OpCodes.Ret); + } + + private Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { + // TODO: Generate check for null + + // Find the first member with the given name that is a field, property, or parameter-less method + List infos = new List(type.GetMember(pathPart)); + MemberInfo info = infos.Find(delegate(MemberInfo x) { + if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) + return true; + if (x.MemberType == MemberTypes.Method) + return ((MethodInfo)x).GetParameters().Length == 0; + else + return false; + }); + + // If we couldn't find anything with that name, pop the current result and return an error + if (info == null) { + il.Emit(OpCodes.Pop); + if (Munger.IgnoreMissingAspects) + il.Emit(OpCodes.Ldnull); + else + il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); + return null; + } + + // Generate the correct IL to access the member. We remember the type of object that is going to be returned + // so that we can do a method lookup on it at the next iteration + Type resultType = null; + switch (info.MemberType) { + case MemberTypes.Method: + MethodInfo mi = (MethodInfo)info; + if (mi.IsVirtual) + il.Emit(OpCodes.Callvirt, mi); + else + il.Emit(OpCodes.Call, mi); + resultType = mi.ReturnType; + break; + case MemberTypes.Property: + PropertyInfo pi = (PropertyInfo)info; + il.Emit(OpCodes.Call, pi.GetGetMethod()); + resultType = pi.PropertyType; + break; + case MemberTypes.Field: + FieldInfo fi = (FieldInfo)info; + il.Emit(OpCodes.Ldfld, fi); + resultType = fi.FieldType; + break; + } + + // If the method returned a value type, and something is going to call a method on that value, + // we need to load its address onto the stack, rather than the object itself. + if (resultType.IsValueType && !isLastPart) { + LocalBuilder lb = il.DeclareLocal(resultType); + il.Emit(OpCodes.Stloc, lb); + il.Emit(OpCodes.Ldloca, lb); + } + + return resultType; + } + + #endregion + } +} diff --git a/ObjectListView/VirtualObjectListView.cs b/ObjectListView/VirtualObjectListView.cs new file mode 100644 index 0000000..8c3ba28 --- /dev/null +++ b/ObjectListView/VirtualObjectListView.cs @@ -0,0 +1,1255 @@ +/* + * VirtualObjectListView - A virtual listview delays fetching model objects until they are actually displayed. + * + * Author: Phillip Piper + * Date: 27/09/2008 9:15 AM + * + * Change log: + * 2015-06-14 JPP - Moved handling of CheckBoxes on virtual lists into base class (ObjectListView). + * This allows the property to be set correctly, even when set via an upcast reference. + * 2015-03-25 JPP - Subscribe to change notifications when objects are added + * v2.8 + * 2014-09-26 JPP - Correct an incorrect use of checkStateMap when setting CheckedObjects + * and a CheckStateGetter is installed + * v2.6 + * 2012-06-13 JPP - Corrected several bugs related to groups on virtual lists. + * - Added EnsureNthGroupVisible() since EnsureGroupVisible() can't work on virtual lists. + * v2.5.1 + * 2012-05-04 JPP - Avoid bug/feature in ListView.VirtalListSize setter that causes flickering + * when the size of the list changes. + * 2012-04-24 JPP - Fixed bug that occurred when adding/removing item while the view was grouped. + * v2.5 + * 2011-05-31 JPP - Setting CheckedObjects is more efficient on large collections + * 2011-04-05 JPP - CheckedObjects now only returns objects that are currently in the list. + * ClearObjects() now resets all check state info. + * 2011-03-31 JPP - Filtering on grouped virtual lists no longer behaves strangely. + * 2011-03-17 JPP - Virtual lists can (finally) set CheckBoxes back to false if it has been set to true. + * (this is a little hacky and may not work reliably). + * - GetNextItem() and GetPreviousItem() now work on grouped virtual lists. + * 2011-03-08 JPP - BREAKING CHANGE: 'DataSource' was renamed to 'VirtualListDataSource'. This was necessary + * to allow FastDataListView which is both a DataListView AND a VirtualListView -- + * which both used a 'DataSource' property :( + * v2.4 + * 2010-04-01 JPP - Support filtering + * v2.3 + * 2009-08-28 JPP - BIG CHANGE. Virtual lists can now have groups! + * - Objects property now uses "yield return" -- much more efficient for big lists + * 2009-08-07 JPP - Use new scheme for formatting rows/cells + * v2.2.1 + * 2009-07-24 JPP - Added specialised version of RefreshSelectedObjects() which works efficiently with virtual lists + * (thanks to chriss85 for finding this bug) + * 2009-07-03 JPP - Standardized code format + * v2.2 + * 2009-04-06 JPP - ClearObjects() now works again + * v2.1 + * 2009-02-24 JPP - Removed redundant OnMouseDown() since checkbox + * handling is now handled in the base class + * 2009-01-07 JPP - Made all public and protected methods virtual + * 2008-12-07 JPP - Trigger Before/AfterSearching events + * 2008-11-15 JPP - Fixed some caching issues + * 2008-11-05 JPP - Rewrote handling of check boxes + * 2008-10-28 JPP - Handle SetSelectedObjects(null) + * 2008-10-02 JPP - MAJOR CHANGE: Use IVirtualListDataSource + * 2008-09-27 JPP - Separated from ObjectListView.cs + * + * Copyright (C) 2006-2014 Phillip Piper + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * If you wish to use this code in a closed source application, please contact phillip.piper@gmail.com. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using System.Runtime.InteropServices; + +namespace BrightIdeasSoftware +{ + /// + /// A virtual object list view operates in virtual mode, that is, it only gets model objects for + /// a row when it is needed. This gives it the ability to handle very large numbers of rows with + /// minimal resources. + /// + /// A listview is not a great user interface for a large number of items. But if you've + /// ever wanted to have a list with 10 million items, go ahead, knock yourself out. + /// Virtual lists can never iterate their contents. That would defeat the whole purpose. + /// Animated GIFs should not be used in virtual lists. Animated GIFs require some state + /// information to be stored for each animation, but virtual lists specifically do not keep any state information. + /// In any case, you really do not want to keep state information for 10 million animations! + /// + /// Although it isn't documented, .NET virtual lists cannot have checkboxes. This class codes around this limitation, + /// but you must use the functions provided by ObjectListView: CheckedObjects, CheckObject(), UncheckObject() and their friends. + /// If you use the normal check box properties (CheckedItems or CheckedIndicies), they will throw an exception, since the + /// list is in virtual mode, and .NET "knows" it can't handle checkboxes in virtual mode. + /// + /// Due to the limits of the underlying Windows control, virtual lists do not trigger ItemCheck/ItemChecked events. + /// Use a CheckStatePutter instead. + /// To enable grouping, you must provide an implementation of IVirtualGroups interface, via the GroupingStrategy property. + /// Similarly, to enable filtering on the list, your VirtualListDataSource must also implement the IFilterableDataSource interface. + /// + public class VirtualObjectListView : ObjectListView + { + /// + /// Create a VirtualObjectListView + /// + public VirtualObjectListView() + : base() { + this.VirtualMode = true; // Virtual lists have to be virtual -- no prizes for guessing that :) + + this.CacheVirtualItems += new CacheVirtualItemsEventHandler(this.HandleCacheVirtualItems); + this.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(this.HandleRetrieveVirtualItem); + this.SearchForVirtualItem += new SearchForVirtualItemEventHandler(this.HandleSearchForVirtualItem); + + // At the moment, we don't need to handle this event. But we'll keep this comment to remind us about it. + this.VirtualItemsSelectionRangeChanged += new ListViewVirtualItemsSelectionRangeChangedEventHandler(this.HandleVirtualItemsSelectionRangeChanged); + + this.VirtualListDataSource = new VirtualListVersion1DataSource(this); + + // Virtual lists have to manage their own check state, since the normal ListView control + // doesn't even allow checkboxes on virtual lists + this.PersistentCheckBoxes = true; + } + + #region Public Properties + + /// + /// Gets whether or not this listview is capable of showing groups + /// + [Browsable(false)] + public override bool CanShowGroups { + get { + // Virtual lists need Vista and a grouping strategy to show groups + return (ObjectListView.IsVistaOrLater && this.GroupingStrategy != null); + } + } + + /// + /// Get or set the collection of model objects that are checked. + /// When setting this property, any row whose model object isn't + /// in the given collection will be unchecked. Setting to null is + /// equivalent to unchecking all. + /// + /// + /// + /// This property returns a simple collection. Changes made to the returned + /// collection do NOT affect the list. This is different to the behaviour of + /// CheckedIndicies collection. + /// + /// + /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. + /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus + /// the number of objects to be checked. + /// + /// + /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does + /// not remember any check box settings made. + /// + /// + /// This class optimizes the management of CheckStates so that it will work efficiently even on + /// large lists of item. However, those optimizations are impossible if you install a CheckStateGetter. + /// With a CheckStateGetter installed, the performance of this method is O(n) where n is the size + /// of the list. This could be painfully slow. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IList CheckedObjects { + get { + // If we aren't should checkboxes, then no objects can be checked + if (!this.CheckBoxes) + return new ArrayList(); + + // If the data source has somehow vanished, we can't do anything + if (this.VirtualListDataSource == null) + return new ArrayList(); + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) + return base.CheckedObjects; + + // Collect items that are checked AND that still exist in the list. + ArrayList objects = new ArrayList(); + foreach (KeyValuePair kvp in this.CheckStateMap) + { + if (kvp.Value == CheckState.Checked && + (!this.CheckedObjectsMustStillExistInList || + this.VirtualListDataSource.GetObjectIndex(kvp.Key) >= 0)) + objects.Add(kvp.Key); + } + return objects; + } + set { + if (!this.CheckBoxes) + return; + + // If a custom check state getter is install, we can't use our check state management + // We have to use the (slower) base version. + if (this.CheckStateGetter != null) { + base.CheckedObjects = value; + return; + } + + Stopwatch sw = Stopwatch.StartNew(); + + // Set up an efficient way of testing for the presence of a particular model + Hashtable table = new Hashtable(this.GetItemCount()); + if (value != null) { + foreach (object x in value) + table[x] = true; + } + + this.BeginUpdate(); + + // Uncheck anything that is no longer checked + Object[] keys = new Object[this.CheckStateMap.Count]; + this.CheckStateMap.Keys.CopyTo(keys, 0); + foreach (Object key in keys) { + if (!table.Contains(key)) + this.SetObjectCheckedness(key, CheckState.Unchecked); + } + + // Check all the new checked objects + foreach (Object x in table.Keys) + this.SetObjectCheckedness(x, CheckState.Checked); + + this.EndUpdate(); + + // Debug.WriteLine(String.Format("PERF - Setting virtual CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); + } + } + + /// + /// Gets or sets whether or not an object will be included in the CheckedObjects + /// collection, even if it is not present in the control at the moment + /// + /// + /// This property is an implementation detail and should not be altered. + /// + protected internal bool CheckedObjectsMustStillExistInList { + get { return checkedObjectsMustStillExistInList; } + set { checkedObjectsMustStillExistInList = value; } + } + private bool checkedObjectsMustStillExistInList = true; + + /// + /// Gets the collection of objects that survive any filtering that may be in place. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable FilteredObjects { + get { + for (int i = 0; i < this.GetItemCount(); i++) + yield return this.GetModelObject(i); + } + } + + /// + /// Gets or sets the strategy that will be used to create groups + /// + /// + /// This must be provided for a virtual list to show groups. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IVirtualGroups GroupingStrategy { + get { return this.groupingStrategy; } + set { this.groupingStrategy = value; } + } + private IVirtualGroups groupingStrategy; + + /// + /// Gets whether or not the current list is filtering its contents + /// + /// + /// This is only possible if our underlying data source supports filtering. + /// + public override bool IsFiltering { + get { + return base.IsFiltering && (this.VirtualListDataSource is IFilterableDataSource); + } + } + + /// + /// Get/set the collection of objects that this list will show + /// + /// + /// + /// The contents of the control will be updated immediately after setting this property. + /// + /// Setting this property preserves selection, if possible. Use SetObjects() if + /// you do not want to preserve the selection. Preserving selection is the slowest part of this + /// code -- performance is O(n) where n is the number of selected rows. + /// This method is not thread safe. + /// The property DOES work on virtual lists, but if you try to iterate through a list + /// of 10 million objects, it may take some time :) + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override IEnumerable Objects { + get { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + try { + // If we are filtering, we have to temporarily disable filtering so we get + // the whole collection + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(null, null); + return this.FilteredObjects; + } finally { + if (filterable != null && this.UseFiltering) + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + } + } + set { base.Objects = value; } + } + + /// + /// This delegate is used to fetch a rowObject, given it's index within the list + /// + /// Only use this property if you are not using a VirtualListDataSource. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual RowGetterDelegate RowGetter { + get { return ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter; } + set { ((VirtualListVersion1DataSource)this.virtualListDataSource).RowGetter = value; } + } + + /// + /// Should this list show its items in groups? + /// + [Category("Appearance"), + Description("Should the list view show items in groups?"), + DefaultValue(true)] + override public bool ShowGroups { + get { + // Pre-Vista, virtual lists cannot show groups + return ObjectListView.IsVistaOrLater && this.showGroups; + } + set { + this.showGroups = value; + if (this.Created && !value) + this.DisableVirtualGroups(); + } + } + private bool showGroups; + + + /// + /// Get/set the data source that is behind this virtual list + /// + /// Setting this will cause the list to redraw. + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public virtual IVirtualListDataSource VirtualListDataSource { + get { + return this.virtualListDataSource; + } + set { + this.virtualListDataSource = value; + this.CustomSorter = delegate(OLVColumn column, SortOrder sortOrder) { + this.ClearCachedInfo(); + this.virtualListDataSource.Sort(column, sortOrder); + }; + this.BuildList(false); + } + } + private IVirtualListDataSource virtualListDataSource; + + /// + /// Gets or sets the number of rows in this virtual list. + /// + /// + /// There is an annoying feature/bug in the .NET ListView class. + /// When you change the VirtualListSize property, it always scrolls so + /// that the focused item is the top item. This is annoying since it makes + /// the virtual list seem to flicker as the control scrolls to show the focused + /// item and then scrolls back to where ObjectListView wants it to be. + /// + [Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + protected new virtual int VirtualListSize { + get { return base.VirtualListSize; } + set { + if (value == this.VirtualListSize || value < 0) + return; + + // Get around the 'private' marker on 'virtualListSize' field using reflection + if (virtualListSizeFieldInfo == null) { + virtualListSizeFieldInfo = typeof(ListView).GetField("virtualListSize", BindingFlags.NonPublic | BindingFlags.Instance); + System.Diagnostics.Debug.Assert(virtualListSizeFieldInfo != null); + } + + // Set the base class private field so that it keeps on working + virtualListSizeFieldInfo.SetValue(this, value); + + // Send a raw message to change the virtual list size *without* changing the scroll position + if (this.IsHandleCreated && !this.DesignMode) + NativeMethods.SetItemCount(this, value); + } + } + static private FieldInfo virtualListSizeFieldInfo; + + #endregion + + #region OLV accessing + + /// + /// Return the number of items in the list + /// + /// the number of items in the list + public override int GetItemCount() { + return this.VirtualListSize; + } + + /// + /// Return the model object at the given index + /// + /// Index of the model object to be returned + /// A model object + public override object GetModelObject(int index) { + if (this.VirtualListDataSource != null && index >= 0 && index < this.GetItemCount()) + return this.VirtualListDataSource.GetNthObject(index); + else + return null; + } + + /// + /// Find the given model object within the listview and return its index + /// + /// The model object to be found + /// The index of the object. -1 means the object was not present + public override int IndexOf(Object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return -1; + + return this.VirtualListDataSource.GetObjectIndex(modelObject); + } + + /// + /// Return the OLVListItem that displays the given model object + /// + /// The modelObject whose item is to be found + /// The OLVListItem that displays the model, or null + /// This method has O(n) performance. + public override OLVListItem ModelToItem(object modelObject) { + if (this.VirtualListDataSource == null || modelObject == null) + return null; + + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + return index >= 0 ? this.GetItem(index) : null; + } + + #endregion + + #region Object manipulation + + /// + /// Add the given collection of model objects to this control. + /// + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the end of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void AddObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.AddObjects(args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Remove all items from this list + /// + /// This method can safely be called from background threads. + public override void ClearObjects() { + if (this.InvokeRequired) + this.Invoke(new MethodInvoker(this.ClearObjects)); + else { + this.CheckStateMap.Clear(); + this.SetObjects(new ArrayList()); + } + } + + /// + /// Scroll the listview so that the given group is at the top. + /// + /// The index of the group to be revealed + /// + /// If the group is already visible, the list will still be scrolled to move + /// the group to the top, if that is possible. + /// + /// This only works when the list is showing groups (obviously). + /// + public virtual void EnsureNthGroupVisible(int groupIndex) { + if (!this.ShowGroups) + return; + + if (groupIndex <= 0 || groupIndex >= this.OLVGroups.Count) { + // There is no easy way to scroll back to the beginning of the list + int delta = 0 - NativeMethods.GetScrollPosition(this, false); + NativeMethods.Scroll(this, 0, delta); + } else { + // Find the display rectangle of the last item in the previous group + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + int lastItemInGroup = this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1); + Rectangle r = this.GetItemRect(lastItemInGroup); + + // Scroll so that the last item of the previous group is just out of sight, + // which will make the desired group header visible. + int delta = r.Y + r.Height / 2; + NativeMethods.Scroll(this, 0, delta); + } + } + + /// + /// Inserts the given collection of model objects to this control at hte given location + /// + /// The index where the new objects will be inserted + /// A collection of model objects + /// + /// The added objects will appear in their correct sort position, if sorting + /// is active. Otherwise, they will appear at the given position of the list. + /// No check is performed to see if any of the objects are already in the ListView. + /// Null objects are silently ignored. + /// + public override void InsertObjects(int index, ICollection modelObjects) + { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the added objects + ItemsAddingEventArgs args = new ItemsAddingEventArgs(index, modelObjects); + this.OnItemsAdding(args); + if (args.Canceled) + return; + + try + { + this.BeginUpdate(); + this.VirtualListDataSource.InsertObjects(index, args.ObjectsToAdd); + this.BuildList(); + this.SubscribeNotifications(args.ObjectsToAdd); + } + finally + { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are showing the given objects + /// + /// This method does not resort the items. + public override void RefreshObjects(IList modelObjects) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.RefreshObjects(modelObjects); }); + return; + } + + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + try { + this.BeginUpdate(); + this.ClearCachedInfo(); + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0) { + this.VirtualListDataSource.UpdateObject(index, modelObject); + this.RedrawItems(index, index, true); + } + } + } + finally { + this.EndUpdate(); + } + } + + /// + /// Update the rows that are selected + /// + /// This method does not resort or regroup the view. + public override void RefreshSelectedObjects() { + foreach (int index in this.SelectedIndices) + this.RedrawItems(index, index, true); + } + + /// + /// Remove all of the given objects from the control + /// + /// Collection of objects to be removed + /// + /// Nulls and model objects that are not in the ListView are silently ignored. + /// Due to problems in the underlying ListView, if you remove all the objects from + /// the control using this method and the list scroll vertically when you do so, + /// then when you subsequently add more objects to the control, + /// the vertical scroll bar will become confused and the control will draw one or more + /// blank lines at the top of the list. + /// + public override void RemoveObjects(ICollection modelObjects) { + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the removed objects + ItemsRemovingEventArgs args = new ItemsRemovingEventArgs(modelObjects); + this.OnItemsRemoving(args); + if (args.Canceled) + return; + + try { + this.BeginUpdate(); + this.VirtualListDataSource.RemoveObjects(args.ObjectsToRemove); + this.BuildList(); + this.UnsubscribeNotifications(args.ObjectsToRemove); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Select the row that is displaying the given model object. All other rows are deselected. + /// + /// Model object to select + /// Should the object be focused as well? + public override void SelectObject(object modelObject, bool setFocus) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + // Check that the object is in the list (plus not all data sources can locate objects) + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index < 0 || index >= this.VirtualListSize) + return; + + // If the given model is already selected, don't do anything else (prevents an flicker) + if (this.SelectedIndices.Count == 1 && this.SelectedIndices[0] == index) + return; + + // Finally, select the row + this.SelectedIndices.Clear(); + this.SelectedIndices.Add(index); + if (setFocus && this.SelectedItem != null) + this.SelectedItem.Focused = true; + } + + /// + /// Select the rows that is displaying any of the given model object. All other rows are deselected. + /// + /// A collection of model objects + /// This method has O(n) performance where n is the number of model objects passed. + /// Do not use this to select all the rows in the list -- use SelectAll() for that. + public override void SelectObjects(IList modelObjects) { + // Without a data source, we can't do this. + if (this.VirtualListDataSource == null) + return; + + this.SelectedIndices.Clear(); + + if (modelObjects == null) + return; + + foreach (object modelObject in modelObjects) { + int index = this.VirtualListDataSource.GetObjectIndex(modelObject); + if (index >= 0 && index < this.VirtualListSize) + this.SelectedIndices.Add(index); + } + } + + /// + /// Set the collection of objects that this control will show. + /// + /// + /// Should the state of the list be preserved as far as is possible. + public override void SetObjects(IEnumerable collection, bool preserveState) { + if (this.InvokeRequired) { + this.Invoke((MethodInvoker)delegate { this.SetObjects(collection, preserveState); }); + return; + } + + if (this.VirtualListDataSource == null) + return; + + // Give the world a chance to cancel or change the assigned collection + ItemsChangingEventArgs args = new ItemsChangingEventArgs(null, collection); + this.OnItemsChanging(args); + if (args.Canceled) + return; + + this.BeginUpdate(); + try { + this.VirtualListDataSource.SetObjects(args.NewObjects); + this.BuildList(); + this.UpdateNotificationSubscriptions(args.NewObjects); + } + finally { + this.EndUpdate(); + } + } + + #endregion + + #region Check boxes +// +// /// +// /// Check all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void CheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Checked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - CheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// +// } +// +// /// +// /// Uncheck all rows +// /// +// /// The performance of this method is O(n) where n is the number of rows in the control. +// public override void UncheckAll() +// { +// if (!this.CheckBoxes) +// return; +// +// Stopwatch sw = Stopwatch.StartNew(); +// +// this.BeginUpdate(); +// +// foreach (Object x in this.Objects) +// this.SetObjectCheckedness(x, CheckState.Unchecked); +// +// this.EndUpdate(); +// +// Debug.WriteLine(String.Format("PERF - UncheckAll() on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, this.GetItemCount())); +// } + + /// + /// Get the checkedness of an object from the model. Returning null means the + /// model does know and the value from the control will be used. + /// + /// + /// + protected override CheckState? GetCheckState(object modelObject) + { + if (this.CheckStateGetter != null) + return base.GetCheckState(modelObject); + + CheckState state; + if (modelObject != null && this.CheckStateMap.TryGetValue(modelObject, out state)) + return state; + return CheckState.Unchecked; + } + + #endregion + + #region Implementation + + /// + /// Rebuild the list with its current contents. + /// + /// + /// Invalidate any cached information when we rebuild the list. + /// + public override void BuildList(bool shouldPreserveSelection) { + this.UpdateVirtualListSize(); + this.ClearCachedInfo(); + if (this.ShowGroups) + this.BuildGroups(); + else + this.Sort(); + this.Invalidate(); + } + + /// + /// Clear any cached info this list may have been using + /// + public override void ClearCachedInfo() { + this.lastRetrieveVirtualItemIndex = -1; + } + + /// + /// Do the work of creating groups for this control + /// + /// + protected override void CreateGroups(IEnumerable groups) { + + // In a virtual list, we cannot touch the Groups property. + // It was obviously not written for virtual list and often throws exceptions. + + NativeMethods.ClearGroups(this); + + this.EnableVirtualGroups(); + + foreach (OLVGroup group in groups) { + System.Diagnostics.Debug.Assert(group.Items.Count == 0, "Groups in virtual lists cannot set Items. Use VirtualItemCount instead."); + System.Diagnostics.Debug.Assert(group.VirtualItemCount > 0, "VirtualItemCount must be greater than 0."); + + group.InsertGroupNewStyle(this); + } + } + + /// + /// Do the plumbing to disable groups on a virtual list + /// + protected void DisableVirtualGroups() { + NativeMethods.ClearGroups(this); + //System.Diagnostics.Debug.WriteLine(err); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 0, 0); + //System.Diagnostics.Debug.WriteLine(x); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr x2 = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, 0, 0); + //System.Diagnostics.Debug.WriteLine(x2); + } + + /// + /// Do the plumbing to enable groups on a virtual list + /// + protected void EnableVirtualGroups() { + + // We need to implement the IOwnerDataCallback interface + if (this.ownerDataCallbackImpl == null) + this.ownerDataCallbackImpl = new OwnerDataCallbackImpl(this); + + const int LVM_SETOWNERDATACALLBACK = 0x10BB; + IntPtr ptr = Marshal.GetComInterfaceForObject(ownerDataCallbackImpl, typeof(IOwnerDataCallback)); + IntPtr x = NativeMethods.SendMessage(this.Handle, LVM_SETOWNERDATACALLBACK, ptr, 0); + //System.Diagnostics.Debug.WriteLine(x); + Marshal.Release(ptr); + + const int LVM_ENABLEGROUPVIEW = 0x1000 + 157; + x = NativeMethods.SendMessage(this.Handle, LVM_ENABLEGROUPVIEW, 1, 0); + //System.Diagnostics.Debug.WriteLine(x); + } + private OwnerDataCallbackImpl ownerDataCallbackImpl; + + /// + /// Return the position of the given itemIndex in the list as it currently shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override int GetDisplayOrderOfItemIndex(int itemIndex) { + if (!this.ShowGroups) + return itemIndex; + + int groupIndex = this.GroupingStrategy.GetGroup(itemIndex); + int displayIndex = 0; + for (int i = 0; i < groupIndex - 1; i++) + displayIndex += this.OLVGroups[i].VirtualItemCount; + displayIndex += this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemIndex); + + return displayIndex; + } + + /// + /// Return the last item in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + public override OLVListItem GetLastItemInDisplayOrder() { + if (!this.ShowGroups) + return base.GetLastItemInDisplayOrder(); + + if (this.OLVGroups.Count > 0) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + if (lastGroup.VirtualItemCount > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Return the n'th item (0-based) in the order they are shown to the user. + /// If the control is not grouped, the display order is the same as the + /// sorted list order. But if the list is grouped, the display order is different. + /// + /// + /// + public override OLVListItem GetNthItemInDisplayOrder(int n) { + if (!this.ShowGroups || this.OLVGroups == null || this.OLVGroups.Count == 0) + return this.GetItem(n); + + foreach (OLVGroup group in this.OLVGroups) { + if (n < group.VirtualItemCount) + return this.GetItem(this.GroupingStrategy.GetGroupMember(group, n)); + + n -= group.VirtualItemCount; + } + + return null; + } + + /// + /// Return the ListViewItem that appears immediately after the given item. + /// If the given item is null, the first item in the list will be returned. + /// Return null if the given item is the last item. + /// + /// The item that is before the item that is returned, or null + /// A OLVListItem + public override OLVListItem GetNextItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetNextItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given item is null, return the first member of the first group + if (itemToFind == null) { + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[0], 0)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the last member, just return the next member + if (indexWithinGroup < this.OLVGroups[groupIndex].VirtualItemCount - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup + 1)); + + // The item is the last member of its group. Return the first member of the next group + // (unless there isn't a next group) + if (groupIndex < this.OLVGroups.Count - 1) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex + 1], 0)); + + return null; + } + + /// + /// Return the ListViewItem that appears immediately before the given item. + /// If the given item is null, the last item in the list will be returned. + /// Return null if the given item is the first item. + /// + /// The item that is before the item that is returned + /// A ListViewItem + public override OLVListItem GetPreviousItem(OLVListItem itemToFind) { + if (!this.ShowGroups) + return base.GetPreviousItem(itemToFind); + + // Sanity + if (this.OLVGroups == null || this.OLVGroups.Count == 0) + return null; + + // If the given items is null, return the last member of the last group + if (itemToFind == null) { + OLVGroup lastGroup = this.OLVGroups[this.OLVGroups.Count - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(lastGroup, lastGroup.VirtualItemCount - 1)); + } + + // Find where this item occurs (which group and where in that group) + int groupIndex = this.GroupingStrategy.GetGroup(itemToFind.Index); + int indexWithinGroup = this.GroupingStrategy.GetIndexWithinGroup(this.OLVGroups[groupIndex], itemToFind.Index); + + // If it's not the first member of the group, just return the previous member + if (indexWithinGroup > 0) + return this.GetItem(this.GroupingStrategy.GetGroupMember(this.OLVGroups[groupIndex], indexWithinGroup - 1)); + + // The item is the first member of its group. Return the last member of the previous group + // (if there is one) + if (groupIndex > 0) { + OLVGroup previousGroup = this.OLVGroups[groupIndex - 1]; + return this.GetItem(this.GroupingStrategy.GetGroupMember(previousGroup, previousGroup.VirtualItemCount - 1)); + } + + return null; + } + + /// + /// Make a list of groups that should be shown according to the given parameters + /// + /// + /// + protected override IList MakeGroups(GroupingParameters parms) { + if (this.GroupingStrategy == null) + return new List(); + else + return this.GroupingStrategy.GetGroups(parms); + } + + /// + /// Create a OLVListItem for given row index + /// + /// The index of the row that is needed + /// An OLVListItem + public virtual OLVListItem MakeListViewItem(int itemIndex) { + OLVListItem olvi = new OLVListItem(this.GetModelObject(itemIndex)); + this.FillInValues(olvi, olvi.RowObject); + + this.PostProcessOneRow(itemIndex, this.GetDisplayOrderOfItemIndex(itemIndex), olvi); + + if (this.HotRowIndex == itemIndex) + this.UpdateHotRow(olvi); + + return olvi; + } + + /// + /// On virtual lists, this cannot work. + /// + protected override void PostProcessRows() { + } + + /// + /// Record the change of checkstate for the given object in the model. + /// This does not update the UI -- only the model + /// + /// + /// + /// The check state that was recorded and that should be used to update + /// the control. + protected override CheckState PutCheckState(object modelObject, CheckState state) { + state = base.PutCheckState(modelObject, state); + this.CheckStateMap[modelObject] = state; + return state; + } + + /// + /// Refresh the given item in the list + /// + /// The item to refresh + public override void RefreshItem(OLVListItem olvi) { + this.ClearCachedInfo(); + this.RedrawItems(olvi.Index, olvi.Index, true); + } + + /// + /// Change the size of the list + /// + /// + protected virtual void SetVirtualListSize(int newSize) { + if (newSize < 0 || this.VirtualListSize == newSize) + return; + + int oldSize = this.VirtualListSize; + + this.ClearCachedInfo(); + + // There is a bug in .NET when a virtual ListView is cleared + // (i.e. VirtuaListSize set to 0) AND it is scrolled vertically: the scroll position + // is wrong when the list is next populated. To avoid this, before + // clearing a virtual list, we make sure the list is scrolled to the top. + // [6 weeks later] Damn this is a pain! There are cases where this can also throw exceptions! + try { + if (newSize == 0 && this.TopItemIndex > 0) + this.TopItemIndex = 0; + } + catch (Exception) { + // Ignore any failures + } + + // In strange cases, this can throw the exceptions too. The best we can do is ignore them :( + try { + this.VirtualListSize = newSize; + } + catch (ArgumentOutOfRangeException) { + // pass + } + catch (NullReferenceException) { + // pass + } + + // Tell the world that the size of the list has changed + this.OnItemsChanged(new ItemsChangedEventArgs(oldSize, this.VirtualListSize)); + } + + /// + /// Take ownership of the 'objects' collection. This separates our collection from the source. + /// + /// + /// + /// This method + /// separates the 'objects' instance variable from its source, so that any AddObject/RemoveObject + /// calls will modify our collection and not the original collection. + /// + /// + /// VirtualObjectListViews always own their collections, so this is a no-op. + /// + /// + protected override void TakeOwnershipOfObjects() { + } + + /// + /// Change the state of the control to reflect changes in filtering + /// + protected override void UpdateFiltering() { + IFilterableDataSource filterable = this.VirtualListDataSource as IFilterableDataSource; + if (filterable == null) + return; + + this.BeginUpdate(); + try { + int originalSize = this.VirtualListSize; + filterable.ApplyFilters(this.ModelFilter, this.ListFilter); + this.BuildList(); + + //// If the filtering actually did something, rebuild the groups if they are being shown + //if (originalSize != this.VirtualListSize && this.ShowGroups) + // this.BuildGroups(); + } + finally { + this.EndUpdate(); + } + } + + /// + /// Change the size of the virtual list so that it matches its data source + /// + public virtual void UpdateVirtualListSize() { + if (this.VirtualListDataSource != null) + this.SetVirtualListSize(this.VirtualListDataSource.GetObjectCount()); + } + + #endregion + + #region Event handlers + + /// + /// Handle the CacheVirtualItems event + /// + /// + /// + protected virtual void HandleCacheVirtualItems(object sender, CacheVirtualItemsEventArgs e) { + if (this.VirtualListDataSource != null) + this.VirtualListDataSource.PrepareCache(e.StartIndex, e.EndIndex); + } + + /// + /// Handle a RetrieveVirtualItem + /// + /// + /// + protected virtual void HandleRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) { + // .NET 2.0 seems to generate a lot of these events. Before drawing *each* sub-item, + // this event is triggered 4-8 times for the same index. So we save lots of CPU time + // by caching the last result. + //System.Diagnostics.Debug.WriteLine(String.Format("HandleRetrieveVirtualItem({0})", e.ItemIndex)); + + if (this.lastRetrieveVirtualItemIndex != e.ItemIndex) { + this.lastRetrieveVirtualItemIndex = e.ItemIndex; + this.lastRetrieveVirtualItem = this.MakeListViewItem(e.ItemIndex); + } + e.Item = this.lastRetrieveVirtualItem; + } + + /// + /// Handle the SearchForVirtualList event, which is called when the user types into a virtual list + /// + /// + /// + protected virtual void HandleSearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e) { + // The event has e.IsPrefixSearch, but as far as I can tell, this is always false (maybe that's different under Vista) + // So we ignore IsPrefixSearch and IsTextSearch and always to a case insensitive prefix match. + + // We can't do anything if we don't have a data source + if (this.VirtualListDataSource == null) + return; + + // Where should we start searching? If the last row is focused, the SearchForVirtualItemEvent starts searching + // from the next row, which is actually an invalidate index -- so we make sure we never go past the last object. + int start = Math.Min(e.StartIndex, this.VirtualListDataSource.GetObjectCount() - 1); + + // Give the world a chance to fiddle with or completely avoid the searching process + BeforeSearchingEventArgs args = new BeforeSearchingEventArgs(e.Text, start); + this.OnBeforeSearching(args); + if (args.Canceled) + return; + + // Do the search + int i = this.FindMatchingRow(args.StringToFind, args.StartSearchFrom, e.Direction); + + // Tell the world that a search has occurred + AfterSearchingEventArgs args2 = new AfterSearchingEventArgs(args.StringToFind, i); + this.OnAfterSearching(args2); + + // If we found a match, tell the event + if (i != -1) + e.Index = i; + } + + /// + /// Handle the VirtualItemsSelectionRangeChanged event, which is called "when the selection state of a range of items has changed" + /// + /// + /// + /// This method is not called whenever the selection changes on a virtual list. It only seems to be triggered when + /// the user uses Shift-Ctrl-Click to change the selection + protected virtual void HandleVirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e) { + // System.Diagnostics.Debug.WriteLine(string.Format("HandleVirtualItemsSelectionRangeChanged: {0}->{1}, selected: {2}", e.StartIndex, e.EndIndex, e.IsSelected)); + this.TriggerDeferredSelectionChangedEvent(); + } + + /// + /// Find the first row in the given range of rows that prefix matches the string value of the given column. + /// + /// + /// + /// + /// + /// The index of the matched row, or -1 + protected override int FindMatchInRange(string text, int first, int last, OLVColumn column) { + return this.VirtualListDataSource.SearchText(text, first, last, column); + } + + #endregion + + #region Variable declarations + + private OLVListItem lastRetrieveVirtualItem; + private int lastRetrieveVirtualItemIndex = -1; + + #endregion + } +} diff --git a/ObjectListView/olv-keyfile.snk b/ObjectListView/olv-keyfile.snk new file mode 100644 index 0000000000000000000000000000000000000000..2658a0adcf122aaa2a591535b53464d516af3378 GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa500986W$cIN!~W%bg8iKqt=v+03$~e~mJs!s zjxU8c(azlkAM^?lBdSg#@Xo86g5b(px(_u*|NRInNPMa(oZ7FOGX3y+S9*R?1vg*78kM6LjIK||X zWAU4blpG9GP}*;3w5@>NY`@4N-#_U$uE!7hH-#IbZu}s16Lpq{mQ;i43=-|@nVZDs zG|+jdK4Cm@V#c*g=H%5QNh=MIIeg0)t4qN7H3-6RuS70^Bde3q0o`&}OfWbuURm=Y zn5*%bskV-f%^ClA~ zN7~lW00)-QecLE7reqRZ{s)OjgHOfCAWI2#-kPm(z2TWw^;P~&q24T=-IOLtj~kL+ zUJ}~BbjP&wIAX literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 83a0af9..d214231 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,138 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General * Stich991 - Italian translation * tuku473 - Design suggestions, colors, Spanish translation -* Lachesis - French translation -* Delusional Moonlight - Russian translation ### AlphaDream Engine * irdkwia - Finding games that used the engine diff --git a/VG Music Studio - Core/ADPCMDecoder.cs b/VG Music Studio - Core/ADPCMDecoder.cs index 894ea76..f2ee92c 100644 --- a/VG Music Studio - Core/ADPCMDecoder.cs +++ b/VG Music Studio - Core/ADPCMDecoder.cs @@ -1,14 +1,12 @@ -using System; +namespace Kermalis.VGMusicStudio.Core; -namespace Kermalis.VGMusicStudio.Core; - -internal struct ADPCMDecoder +internal sealed class ADPCMDecoder { - private static ReadOnlySpan IndexTable => new short[8] + private static readonly short[] _indexTable = new short[8] { -1, -1, -1, -1, 2, 4, 6, 8, }; - private static ReadOnlySpan StepTable => new short[89] + private static readonly short[] _stepTable = new short[89] { 00007, 00008, 00009, 00010, 00011, 00012, 00013, 00014, 00016, 00017, 00019, 00021, 00023, 00025, 00028, 00031, @@ -24,26 +22,24 @@ internal struct ADPCMDecoder 32767, }; - private byte[] _data; + private readonly byte[] _data; public short LastSample; public short StepIndex; public int DataOffset; public bool OnSecondNibble; - public void Init(byte[] data) + public ADPCMDecoder(byte[] data) { - _data = data; LastSample = (short)(data[0] | (data[1] << 8)); StepIndex = (short)((data[2] | (data[3] << 8)) & 0x7F); DataOffset = 4; - OnSecondNibble = false; + _data = data; } + // TODO: Span? public static short[] ADPCMToPCM16(byte[] data) { - var decoder = new ADPCMDecoder(); - decoder.Init(data); - + var decoder = new ADPCMDecoder(data); short[] buffer = new short[(data.Length - 4) * 2]; for (int i = 0; i < buffer.Length; i++) { @@ -55,7 +51,7 @@ public static short[] ADPCMToPCM16(byte[] data) public short GetSample() { int val = (_data[DataOffset] >> (OnSecondNibble ? 4 : 0)) & 0xF; - short step = StepTable[StepIndex]; + short step = _stepTable[StepIndex]; int diff = (step / 8) + (step / 4 * (val & 1)) + @@ -73,7 +69,7 @@ public short GetSample() } LastSample = (short)a; - a = StepIndex + IndexTable[val & 7]; + a = StepIndex + _indexTable[val & 7]; if (a < 0) { a = 0; diff --git a/VG Music Studio - Core/Assembler.cs b/VG Music Studio - Core/Assembler.cs index f822018..5274414 100644 --- a/VG Music Studio - Core/Assembler.cs +++ b/VG Music Studio - Core/Assembler.cs @@ -9,12 +9,12 @@ namespace Kermalis.VGMusicStudio.Core; internal sealed class Assembler : IDisposable { - private sealed class Pair // Must be a class + private class Pair { public bool Global; public int Offset; } - private struct Pointer + private class Pointer { public string Label; public int BinaryOffset; @@ -51,8 +51,7 @@ public Assembler(string fileName, int baseOffset, Endianness endianness, Diction _stream = new MemoryStream(); _writer = new EndianBinaryWriter(_stream, endianness: endianness); - string status = Read(fileName); - Debug.WriteLine(status); + Debug.WriteLine(Read(fileName)); SetBaseOffset(baseOffset); } @@ -69,7 +68,9 @@ public void SetBaseOffset(int baseOffset) int labelOffset = oldPointer - BaseOffset; // Then labelOffset is 0x1004 (SEQ_STUFF+4) _stream.Position = p.BinaryOffset; - _writer.WriteInt32(baseOffset + labelOffset); // Copy the new pointer to binary offset 0x1DF4 + _writer.WriteInt32(baseOffset + labelOffset); // b will contain {0x04, 0x28, 0x00, 0x00} [0x2804] (SEQ_STUFF+4 + baseOffset) + // Copy the new pointer to binary offset 0x1DF4 + // TODO: UPDATE THESE OLD COMMENTS LOL } BaseOffset = baseOffset; } @@ -114,7 +115,7 @@ private string Read(string fileName) } bool readingCMD = false; // If it's reading the command - string? cmd = null; + string cmd = null; var args = new List(); string str = string.Empty; foreach (char c in line) @@ -123,7 +124,7 @@ private string Read(string fileName) { break; } - if (c == '.' && cmd is null) + else if (c == '.' && cmd == null) { readingCMD = true; } @@ -155,7 +156,7 @@ private string Read(string fileName) str += c; } } - if (cmd is null) + if (cmd == null) { continue; // Commented line } @@ -190,12 +191,11 @@ private string Read(string fileName) } case "global": { - if (!_labels.TryGetValue(args[0], out Pair? pair)) + if (!_labels.ContainsKey(args[0])) { - pair = new Pair(); - _labels.Add(args[0], pair); + _labels.Add(args[0], new Pair()); } - pair.Global = true; + _labels[args[0]].Global = true; break; } case "align": @@ -284,7 +284,7 @@ private int ParseInt(string value) { return def; } - if (_labels.TryGetValue(value, out Pair? pair)) + if (_labels.TryGetValue(value, out Pair pair)) { _lPointers.Add(new Pointer { Label = value, BinaryOffset = BinaryLength }); return pair.Offset; @@ -358,7 +358,7 @@ private int ParseInt(string value) return ret; } - throw new ArgumentOutOfRangeException(nameof(value), value, null); + throw new ArgumentOutOfRangeException(nameof(value)); } public void Dispose() diff --git a/VG Music Studio - Core/Config.cs b/VG Music Studio - Core/Config.cs index 2f26ad5..f3c34b3 100644 --- a/VG Music Studio - Core/Config.cs +++ b/VG Music Studio - Core/Config.cs @@ -1,32 +1,24 @@ -using Kermalis.VGMusicStudio.Core.Properties; -using Kermalis.VGMusicStudio.Core.Util; -using System; +using System; using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core; public abstract class Config : IDisposable { - public readonly struct Song + public sealed class Song { - public readonly int Index; - public readonly string Name; + public long Index; + public string Name; - public Song(int index, string name) + public Song(long index, string name) { Index = index; Name = name; } - public static bool operator ==(Song left, Song right) - { - return left.Equals(right); - } - public static bool operator !=(Song left, Song right) - { - return !(left == right); - } - public override bool Equals(object? obj) { return obj is Song other && other.Index == Index; @@ -45,16 +37,32 @@ public sealed class Playlist public string Name; public List Songs; - public Playlist(string name, List songs) + public Playlist(string name, IEnumerable songs) { Name = name; - Songs = songs; + Songs = songs.ToList(); } public override string ToString() { - int num = Songs.Count; - return string.Format("{0} - ({1:N0} {2})", Name, num, LanguageUtils.HandlePlural(num, Strings.Song_s_)); + int songCount = Songs.Count; + CultureInfo cul = Thread.CurrentThread.CurrentUICulture; + if (cul.TwoLetterISOLanguageName == "it") // Italian + { + // PlaylistName - (1 Canzone) + // PlaylistName - (2 Canzoni) + return $"{Name} - ({songCount} {(songCount == 1 ? "Canzone" : "Canzoni")})"; + } + if (cul.TwoLetterISOLanguageName == "es") // Spanish + { + // PlaylistName - (1 Canción) + // PlaylistName - (2 Canciones) + return $"{Name} - ({songCount} {(songCount == 1 ? "Canción" : "Canciones")})"; + } + // Fallback to en-US + // PlaylistName - (1 Song) + // PlaylistName - (2 Songs) + return $"{Name} - ({songCount} {(songCount == 1 ? "Song" : "Songs")})"; } } @@ -65,7 +73,7 @@ protected Config() Playlists = new List(); } - public bool TryGetFirstSong(int index, out Song song) + public Song? GetFirstSong(long index) { foreach (Playlist p in Playlists) { @@ -73,17 +81,15 @@ public bool TryGetFirstSong(int index, out Song song) { if (s.Index == index) { - song = s; - return true; + return s; } } } - song = default; - return false; + return null; } public abstract string GetGameName(); - public abstract string GetSongName(int index); + public abstract string GetSongName(long index); public virtual void Dispose() { diff --git a/VG Music Studio - Core/Config.yaml b/VG Music Studio - Core/Config.yaml index c7c809c..d4bdf7b 100644 --- a/VG Music Studio - Core/Config.yaml +++ b/VG Music Studio - Core/Config.yaml @@ -6,132 +6,132 @@ PlaylistMode: "Random" # "Random" or "Sequential" PlaylistSongLoops: 0 # Loops >= 0 and Loops <= 9223372036854775807 # How many times a song should loop before fading out PlaylistFadeOutMilliseconds: 10000 # Milliseconds >= 0 and Milliseconds <= 9223372036854775807 # How many milliseconds it should take to fade out of a song MiddleCOctave: 4 # Octave >= --128 and Octave <= 127 # The octave that holds middle C. Used in the visual and track viewer -Colors: # Each color must be a RGB hex code - 0: "CF7FFF" - 1: "BF6CFF" - 2: "A750FF" - 3: "6C00B7" - 4: "5C1FFF" - 5: "7750FF" - 6: "FFF06A" - 7: "FF701C" - 8: "C8AAFF" - 9: "3FFFFF" - 10: "28FFDF" - 11: "6CFFB4" - 12: "98FF6C" - 13: "AAFFB0" - 14: "DD008C" - 15: "FFDFAA" - 16: "FF3F8C" - 17: "DF00FF" - 18: "C900AB" - 19: "FF1394" - 20: "FF7FF5" - 21: "004FD4" - 22: "0075EB" - 23: "0039FF" - 24: "FF7A68" - 25: "FF674C" - 26: "FF965D" - 27: "FF6524" - 28: "FF552A" - 29: "FF0606" - 30: "940028" - 31: "BD0004" - 32: "E9B96A" - 33: "E59A4E" - 34: "E48845" - 35: "FFEE5B" - 36: "E4A845" - 37: "BD7B0C" - 38: "BFBFBF" - 39: "BF00BF" - 40: "B900D4" - 41: "9400C5" - 42: "5F00BF" - 43: "6F3FFF" - 44: "1C00BD" - 45: "FF6AD9" - 46: "FF8AD6" - 47: "CE7F50" - 48: "155BFF" - 49: "3700AA" - 50: "3200C9" - 51: "5500D4" - 52: "FFECC9" - 53: "FFDFBF" - 54: "FFD9D4" - 55: "FF5C3F" - 56: "FF991D" - 57: "FFA715" - 58: "FFFF00" - 59: "FFB304" - 60: "FF6B08" - 61: "FA4400" - 62: "C6FF50" - 63: "9EFF1B" - 64: "FFE79F" - 65: "FFCA83" - 66: "FFDD54" - 67: "FFD015" - 68: "FFEE1F" - 69: "FF7330" - 70: "0075B4" - 71: "0097C9" - 72: "5FFFFF" - 73: "00D8FF" - 74: "00B4D4" - 75: "54BFFF" - 76: "8CFFF9" - 77: "0087D8" - 78: "00D4AF" - 79: "7FFF54" - 80: "19FF24" - 81: "FF90B4" - 82: "2AFFA4" - 83: "AFFF5F" - 84: "FF5F63" - 85: "74F4FF" - 86: "FF35CC" - 87: "ACFF00" - 88: "4AFFD1" - 89: "B4FBFF" - 90: "C90074" - 91: "002F6A" - 92: "00BF5F" - 93: "006DBF" - 94: "AE00F8" - 95: "BFBFFF" - 96: "AAE9FF" - 97: "AA00A1" - 98: "FF5454" - 99: "E9AF00" - 100: "BFEFFF" - 101: "139F00" - 102: "D9B4FF" - 103: "CC9012" - 104: "EED045" - 105: "F5E51E" - 106: "E3FF1F" - 107: "CBFF74" - 108: "8AFFB5" - 109: "DCFF94" - 110: "009FFF" - 111: "E9DE00" - 112: "FF6AB4" - 113: "7FBFBF" - 114: "AFD7E4" - 115: "7F3F3F" - 116: "C6844D" - 117: "A4765A" - 118: "9B4D9B" - 119: "AFBFCF" - 120: "BF2F00" - 121: "25A4AF" - 122: "00A9D4" - 123: "FFFF7F" - 124: "AF0F13" - 125: "A0A3A8" - 126: "C6A28D" - 127: "7F7FBF" \ No newline at end of file +Colors: + 0: {H: 185, S: 240, L: 180} + 1: {H: 183, S: 240, L: 170} + 2: {H: 180, S: 240, L: 157} + 3: {H: 184, S: 240, L: 85} + 4: {H: 171, S: 240, L: 134} + 5: {H: 168, S: 240, L: 159} + 6: {H: 36, S: 240, L: 170} + 7: {H: 15, S: 240, L: 134} + 8: {H: 175, S: 240, L: 200} + 9: {H: 120, S: 240, L: 150} + 10: {H: 114, S: 240, L: 138} + 11: {H: 99, S: 240, L: 171} + 12: {H: 68, S: 240, L: 171} + 13: {H: 83, S: 240, L: 200} + 14: {H: 215, S: 240, L: 104} + 15: {H: 25, S: 240, L: 200} + 16: {H: 224, S: 240, L: 150} + 17: {H: 195, S: 240, L: 120} + 18: {H: 206, S: 240, L: 95} + 19: {H: 218, S: 240, L: 129} + 20: {H: 203, S: 240, L: 180} + 21: {H: 145, S: 240, L: 100} + 22: {H: 140, S: 240, L: 111} + 23: {H: 151, S: 240, L: 120} + 24: {H: 5, S: 240, L: 169} + 25: {H: 6, S: 240, L: 156} + 26: {H: 14, S: 240, L: 164} + 27: {H: 12, S: 240, L: 137} + 28: {H: 8, S: 240, L: 140} + 29: {H: 0, S: 240, L: 123} + 30: {H: 229, S: 240, L: 70} + 31: {H: 239, S: 240, L: 89} + 32: {H: 25, S: 180, L: 160} + 33: {H: 20, S: 180, L: 145} + 34: {H: 17, S: 180, L: 140} + 35: {H: 36, S: 240, L: 163} + 36: {H: 25, S: 180, L: 140} + 37: {H: 25, S: 210, L: 95} + 38: {H: 160, S: 0, L: 180} + 39: {H: 200, S: 240, L: 90} + 40: {H: 195, S: 240, L: 100} + 41: {H: 190, S: 240, L: 93} + 42: {H: 180, S: 240, L: 90} + 43: {H: 170, S: 240, L: 150} + 44: {H: 166, S: 240, L: 89} + 45: {H: 210, S: 240, L: 170} + 46: {H: 214, S: 240, L: 185} + 47: {H: 15, S: 135, L: 135} + 48: {H: 148, S: 240, L: 130} + 49: {H: 173, S: 240, L: 80} + 50: {H: 170, S: 240, L: 95} + 51: {H: 176, S: 240, L: 100} + 52: {H: 26, S: 240, L: 215} + 53: {H: 20, S: 240, L: 210} + 54: {H: 5, S: 240, L: 220} + 55: {H: 6, S: 240, L: 150} + 56: {H: 22, S: 240, L: 134} + 57: {H: 25, S: 240, L: 130} + 58: {H: 40, S: 240, L: 120} + 59: {H: 28, S: 240, L: 122} + 60: {H: 16, S: 240, L: 124} + 61: {H: 11, S: 240, L: 118} + 62: {H: 53, S: 240, L: 158} + 63: {H: 57, S: 240, L: 133} + 64: {H: 30, S: 240, L: 195} + 65: {H: 23, S: 240, L: 182} + 66: {H: 32, S: 240, L: 160} + 67: {H: 32, S: 240, L: 130} + 68: {H: 37, S: 240, L: 135} + 69: {H: 13, S: 240, L: 143} + 70: {H: 134, S: 240, L: 85} + 71: {H: 130, S: 240, L: 95} + 72: {H: 120, S: 240, L: 165} + 73: {H: 126, S: 240, L: 120} + 74: {H: 126, S: 240, L: 100} + 75: {H: 135, S: 240, L: 160} + 76: {H: 118, S: 240, L: 186} + 77: {H: 135, S: 240, L: 102} + 78: {H: 113, S: 240, L: 100} + 79: {H: 70, S: 240, L: 160} + 80: {H: 82, S: 240, L: 132} + 81: {H: 227, S: 240, L: 188} + 82: {H: 103, S: 240, L: 140} + 83: {H: 60, S: 240, L: 165} + 84: {H: 239, S: 240, L: 165} + 85: {H: 123, S: 240, L: 175} + 86: {H: 210, S: 240, L: 145} + 87: {H: 53, S: 240, L: 120} + 88: {H: 110, S: 240, L: 155} + 89: {H: 122, S: 240, L: 205} + 90: {H: 217, S: 240, L: 95} + 91: {H: 142, S: 240, L: 50} + 92: {H: 100, S: 240, L: 90} + 93: {H: 137, S: 240, L: 90} + 94: {H: 188, S: 240, L: 117} + 95: {H: 160, S: 240, L: 210} + 96: {H: 130, S: 240, L: 200} + 97: {H: 202, S: 240, L: 80} + 98: {H: 0, S: 240, L: 160} + 99: {H: 30, S: 240, L: 110} + 100: {H: 130, S: 240, L: 210} + 101: {H: 75, S: 240, L: 75} + 102: {H: 180, S: 240, L: 205} + 103: {H: 27, S: 200, L: 105} + 104: {H: 33, S: 200, L: 145} + 105: {H: 37, S: 220, L: 130} + 106: {H: 45, S: 240, L: 135} + 107: {H: 55, S: 240, L: 175} + 108: {H: 95, S: 240, L: 185} + 109: {H: 53, S: 240, L: 190} + 110: {H: 135, S: 240, L: 120} + 111: {H: 38, S: 240, L: 110} + 112: {H: 220, S: 240, L: 170} + 113: {H: 120, S: 80, L: 150} + 114: {H: 130, S: 120, L: 190} + 115: {H: 0, S: 80, L: 90} + 116: {H: 18, S: 125, L: 130} + 117: {H: 15, S: 70, L: 120} + 118: {H: 200, S: 80, L: 110} + 119: {H: 140, S: 60, L: 180} + 120: {H: 10, S: 240, L: 90} + 121: {H: 123, S: 156, L: 100} + 122: {H: 128, S: 240, L: 100} + 123: {H: 40, S: 240, L: 180} + 124: {H: 239, S: 200, L: 90} + 125: {H: 145, S: 10, L: 155} + 126: {H: 15, S: 80, L: 160} + 127: {H: 160, S: 80, L: 150} \ No newline at end of file diff --git a/VG Music Studio - Core/Dependencies/KMIDI.deps.json b/VG Music Studio - Core/Dependencies/KMIDI.deps.json deleted file mode 100644 index 7feb759..0000000 --- a/VG Music Studio - Core/Dependencies/KMIDI.deps.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "runtimeTarget": { - "name": ".NETCoreApp,Version=v7.0", - "signature": "" - }, - "compilationOptions": {}, - "targets": { - ".NETCoreApp,Version=v7.0": { - "KMIDI/1.0.0": { - "dependencies": { - "EndianBinaryIO": "2.1.0" - }, - "runtime": { - "KMIDI.dll": {} - } - }, - "EndianBinaryIO/2.1.0": { - "runtime": { - "lib/net7.0/EndianBinaryIO.dll": { - "assemblyVersion": "2.1.0.0", - "fileVersion": "2.1.0.0" - } - } - } - } - }, - "libraries": { - "KMIDI/1.0.0": { - "type": "project", - "serviceable": false, - "sha512": "" - }, - "EndianBinaryIO/2.1.0": { - "type": "package", - "serviceable": true, - "sha512": "sha512-OzcYSj5h37lj8PJAcROuYIW+FEO/it3Famh3cduziKQzE2ZKDgirNUJNnDCYkHgBxc2CRc//GV2ChRSqlXhbjQ==", - "path": "endianbinaryio/2.1.0", - "hashPath": "endianbinaryio.2.1.0.nupkg.sha512" - } - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/Dependencies/KMIDI.dll b/VG Music Studio - Core/Dependencies/KMIDI.dll deleted file mode 100644 index 372b9e3267f3ac7910431a340807fa7f02cdc29b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 49664 zcmbq+3t&{$we~va%$#}TITP{%LMA|PBq2f)Bq&ls5+KSWl8B&am?T3oGMR}p69k1C z6e(6zd|YcST70zCYOVHKtJb#oe$-ZLt=D_6ZK2v$TibGb?O)qk{J*vKIr9i$Z7(|C zS$plh*Is+=wby=}8CY@7UNVTtfzL-D5j}z@|5+sX@i2z$!s^Eg=^@V#Y97&+|DdL4 zD3T0}B;tdK&~TtX6pO`Efxd7cF&Ya*VuAKm-GSlwK)9ixz&qU%-PJ*~Tr=pMs)v7X zw|0=G2J*DoM2~@ED(+>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Df+ZKiU}w;ySu z%33!N)lZYQWeeeZEwr{O&-N%~y;MJqTAD6x&stm8wi29j(BIwgdqY!$#HqZvw9cgE zg|A%R%gqE;BUY%qxQy~Z`L+=D-#Jm?gHVB{JiCp2(oM8M_L!>26C5oIxmPKpJiLsL TQ$jCs{NChEmoX16 - - - KMIDI - - - - Includes the end of track event - - - - - - If there are other events at , will be inserted after them. - - - Length 4 - - - Contains a single multi-channel track - - - Contains one or more simultaneous tracks - - - Contains one or more independent single-track patterns - - - Used with - - - Used with - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Not optional - - - Used with - - - Used with - - - Used with - - - How many ticks are between this event and the previous one. If this is the first event in the track, then it is equal to - - - Returns a value in the range [-8_192, 8_191] - - - - - - Middle C - - - diff --git a/VG Music Studio - Core/Engine.cs b/VG Music Studio - Core/Engine.cs index a37f0e0..e58922a 100644 --- a/VG Music Studio - Core/Engine.cs +++ b/VG Music Studio - Core/Engine.cs @@ -8,7 +8,7 @@ public abstract class Engine : IDisposable public abstract Config Config { get; } public abstract Mixer Mixer { get; } - public abstract Player Player { get; } + public abstract IPlayer Player { get; } public virtual void Dispose() { diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs new file mode 100644 index 0000000..f799d45 --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs @@ -0,0 +1,241 @@ +using System; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; + +internal abstract class AlphaDreamChannel +{ + protected readonly AlphaDreamMixer _mixer; + public EnvelopeState State; + public byte Key; + public bool Stopped; + + protected ADSR _adsr; + + protected byte _velocity; + protected int _pos; + protected float _interPos; + protected float _frequency; + protected byte _leftVol; + protected byte _rightVol; + + protected AlphaDreamChannel(AlphaDreamMixer mixer) + { + _mixer = mixer; + } + + public ChannelVolume GetVolume() + { + const float MAX = 1f / 0x10000; + return new ChannelVolume + { + LeftVol = _leftVol * _velocity * MAX, + RightVol = _rightVol * _velocity * MAX, + }; + } + public void SetVolume(byte vol, sbyte pan) + { + _leftVol = (byte)((vol * (-pan + 0x80)) >> 8); + _rightVol = (byte)((vol * (pan + 0x80)) >> 8); + } + public abstract void SetPitch(int pitch); + + public abstract void Process(float[] buffer); +} +internal class PCMChannel : AlphaDreamChannel +{ + private SampleHeader _sampleHeader; + private int _sampleOffset; + private bool _bFixed; + + public PCMChannel(AlphaDreamMixer mixer) : base(mixer) + { + // + } + public void Init(byte key, ADSR adsr, int sampleOffset, bool bFixed) + { + _velocity = adsr.A; + State = EnvelopeState.Attack; + _pos = 0; _interPos = 0; + Key = key; + _adsr = adsr; + + _sampleHeader = MemoryMarshal.Read(_mixer.Config.ROM.AsSpan(sampleOffset)); + _sampleOffset = sampleOffset + 0x10; + _bFixed = bFixed; + Stopped = false; + } + + public override void SetPitch(int pitch) + { + _frequency = (_sampleHeader.SampleRate >> 10) * MathF.Pow(2, ((Key - 60) / 12f) + (pitch / 768f)); + } + + private void StepEnvelope() + { + switch (State) + { + case EnvelopeState.Attack: + { + int nextVel = _velocity + _adsr.A; + if (nextVel >= 0xFF) + { + State = EnvelopeState.Decay; + _velocity = 0xFF; + } + else + { + _velocity = (byte)nextVel; + } + break; + } + case EnvelopeState.Decay: + { + int nextVel = (_velocity * _adsr.D) >> 8; + if (nextVel <= _adsr.S) + { + State = EnvelopeState.Sustain; + _velocity = _adsr.S; + } + else + { + _velocity = (byte)nextVel; + } + break; + } + case EnvelopeState.Release: + { + int next = (_velocity * _adsr.R) >> 8; + if (next < 0) + { + next = 0; + } + _velocity = (byte)next; + break; + } + } + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + + ChannelVolume vol = GetVolume(); + float interStep = (_bFixed ? _sampleHeader.SampleRate >> 10 : _frequency) * _mixer.SampleRateReciprocal; + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = (_mixer.Config.ROM[_pos + _sampleOffset] - 0x80) / (float)0x80; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _sampleHeader.Length) + { + if (_sampleHeader.DoesLoop == 0x40000000) + { + _pos = _sampleHeader.LoopOffset; + } + else + { + Stopped = true; + break; + } + } + } while (--samplesPerBuffer > 0); + } +} +internal class SquareChannel : AlphaDreamChannel +{ + private float[] _pat; + + public SquareChannel(AlphaDreamMixer mixer) : base(mixer) + { + // + } + public void Init(byte key, ADSR env, byte vol, sbyte pan, int pitch) + { + _pat = MP2K.Utils.SquareD50; // TODO: Which square pattern? + Key = key; + _adsr = env; + SetVolume(vol, pan); + SetPitch(pitch); + State = EnvelopeState.Attack; + } + + public override void SetPitch(int pitch) + { + _frequency = 3_520 * MathF.Pow(2, ((Key - 69) / 12f) + (pitch / 768f)); + } + + private void StepEnvelope() + { + switch (State) + { + case EnvelopeState.Attack: + { + int next = _velocity + _adsr.A; + if (next >= 0xF) + { + State = EnvelopeState.Decay; + _velocity = 0xF; + } + else + { + _velocity = (byte)next; + } + break; + } + case EnvelopeState.Decay: + { + int next = (_velocity * _adsr.D) >> 3; + if (next <= _adsr.S) + { + State = EnvelopeState.Sustain; + _velocity = _adsr.S; + } + else + { + _velocity = (byte)next; + } + break; + } + case EnvelopeState.Release: + { + int next = (_velocity * _adsr.R) >> 3; + if (next < 0) + { + next = 0; + } + _velocity = (byte)next; + break; + } + } + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + + ChannelVolume vol = GetVolume(); + float interStep = _frequency * _mixer.SampleRateReciprocal; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _pat[_pos]; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos = (_pos + posDelta) & 0x7; + } while (--samplesPerBuffer > 0); + } +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs index 750ae76..4858291 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamConfig.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using YamlDotNet.Core; using YamlDotNet.RepresentationModel; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -114,7 +113,7 @@ void Load(YamlMappingNode gameToLoad) var songs = new List(); foreach (KeyValuePair song in (YamlMappingNode)kvp.Value) { - int songIndex = (int)ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, int.MaxValue); + long songIndex = ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, long.MaxValue); if (songs.Any(s => s.Index == songIndex)) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorAlphaDreamMP2KSongRepeated, name, songIndex))); @@ -140,7 +139,7 @@ void Load(YamlMappingNode gameToLoad) } AudioEngineVersion = ConfigUtils.ParseEnum(nameof(AudioEngineVersion), audioEngineVersionNode.ToString()); - if (songTableOffsetsNode is null) + if (songTableOffsetsNode == null) { throw new BetterKeyNotFoundException(nameof(SongTableOffsets), null); } @@ -190,7 +189,7 @@ void Load(YamlMappingNode gameToLoad) // The complete playlist if (!Playlists.Any(p => p.Name == "Music")) { - Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index).ToList())); + Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index))); } } catch (BetterKeyNotFoundException ex) @@ -201,7 +200,7 @@ void Load(YamlMappingNode gameToLoad) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + ex.Message)); } - catch (YamlException ex) + catch (YamlDotNet.Core.YamlException ex) { throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + ex.Message)); } @@ -212,13 +211,10 @@ public override string GetGameName() { return Name; } - public override string GetSongName(int index) + public override string GetSongName(long index) { - if (TryGetFirstSong(index, out Song s)) - { - return s.Name; - } - return index.ToString(); + Song? s = GetFirstSong(index); + return s is not null ? s.Name : index.ToString(); } public override void Dispose() diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs index fdee70e..ae021f7 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs @@ -12,9 +12,9 @@ public sealed class AlphaDreamEngine : Engine public AlphaDreamEngine(byte[] rom) { - if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) + if (rom.Length > GBAUtils.CartridgeCapacity) { - throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); + throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CartridgeCapacity:X7} bytes."); } Config = new AlphaDreamConfig(rom); diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs deleted file mode 100644 index 3698f7f..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEnums.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal enum AudioEngineVersion : byte -{ - Hamtaro, - MLSS, -} - -internal enum EnvelopeState : byte -{ - Attack, - Decay, - Sustain, - Release, -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs deleted file mode 100644 index f81833a..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong : ILoadedSong -{ - public List?[] Events { get; } - public long MaxTicks { get; private set; } - public int LongestTrack; - - private readonly AlphaDreamPlayer _player; - - public AlphaDreamLoadedSong(AlphaDreamPlayer player, int songOffset) - { - _player = player; - - Events = new List[AlphaDreamPlayer.NUM_TRACKS]; - songOffset -= GBAUtils.CARTRIDGE_OFFSET; - EndianBinaryReader r = player.Config.Reader; - r.Stream.Position = songOffset; - ushort trackBits = r.ReadUInt16(); - int usedTracks = 0; - for (byte trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - AlphaDreamTrack track = player.Tracks[trackIndex]; - if ((trackBits & (1 << trackIndex)) == 0) - { - track.IsEnabled = false; - track.StartOffset = 0; - continue; - } - - track.IsEnabled = true; - r.Stream.Position = songOffset + 2 + (2 * usedTracks++); - track.StartOffset = songOffset + r.ReadInt16(); - - AddTrackEvents(trackIndex, track.StartOffset); - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs deleted file mode 100644 index 66ae341..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Events.cs +++ /dev/null @@ -1,266 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex]!.Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex]!.Exists(e => e.Offset == cmdOffset); - } - - private void AddTrackEvents(byte trackIndex, int trackStart) - { - Events[trackIndex] = new List(); - AddEvents(trackIndex, trackStart); - } - private void AddEvents(byte trackIndex, int startOffset) - { - EndianBinaryReader r = _player.Config.Reader; - r.Stream.Position = startOffset; - - bool cont = true; - while (cont) - { - long cmdOffset = r.Stream.Position; - byte cmd = r.ReadByte(); - switch (cmd) - { - case 0x00: - { - byte keyArg = r.ReadByte(); - switch (_player.Config.AudioEngineVersion) - { - case AudioEngineVersion.Hamtaro: - { - byte volume = r.ReadByte(); - byte duration = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FreeNoteHamtaroCommand { Note = (byte)(keyArg - 0x80), Volume = volume, Duration = duration }); - } - break; - } - case AudioEngineVersion.MLSS: - { - byte duration = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FreeNoteMLSSCommand { Note = (byte)(keyArg - 0x80), Duration = duration }); - } - break; - } - } - break; - } - case 0xF0: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xF1: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xF2: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x80) }); - } - break; - } - case 0xF4: - { - byte range = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendRangeCommand { Range = range }); - } - break; - } - case 0xF5: - { - sbyte bend = r.ReadSByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = bend }); - } - break; - } - case 0xF6: - { - byte rest = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = rest }); - } - break; - } - case 0xF8: - { - short jumpOffset = r.ReadInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - int off = (int)(r.Stream.Position + jumpOffset); - AddEvent(trackIndex, cmdOffset, new JumpCommand { Offset = off }); - if (!EventExists(trackIndex, off)) - { - AddEvents(trackIndex, off); - } - } - cont = false; - break; - } - case 0xF9: - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackTempoCommand { Tempo = tempoArg }); - } - break; - } - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand()); - } - cont = false; - break; - } - default: - { - if (cmd >= 0xE0) - { - throw new AlphaDreamInvalidCMDException(trackIndex, (int)cmdOffset, cmd); - } - - byte key = r.ReadByte(); - switch (_player.Config.AudioEngineVersion) - { - case AudioEngineVersion.Hamtaro: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteHamtaroCommand { Note = key, Volume = volume, Duration = cmd }); - } - break; - } - case AudioEngineVersion.MLSS: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteMLSSCommand { Note = key, Duration = cmd }); - } - break; - } - } - break; - } - } - } - } - - public void SetTicks() - { - MaxTicks = 0; - bool u = false; - for (int trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - List? evs = Events[trackIndex]; - if (evs is null) - { - continue; - } - - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - AlphaDreamTrack track = _player.Tracks[trackIndex]; - track.Init(); - - long elapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - if (e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(elapsedTicks); - ExecuteNext(track, ref u); - if (track.Stopped) - { - break; - } - - elapsedTicks += track.Rest; - track.Rest = 0; - } - if (elapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = elapsedTicks; - } - track.NoteDuration = 0; - } - } - internal void SetCurTick(long ticks) - { - bool u = false; - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 75) - { - _player.TempoStack -= 75; - for (int trackIndex = 0; trackIndex < AlphaDreamPlayer.NUM_TRACKS; trackIndex++) - { - AlphaDreamTrack track = _player.Tracks[trackIndex]; - if (track.IsEnabled && !track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track, ref u); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) - { - _player.Tracks[i].NoteDuration = 0; - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs deleted file mode 100644 index 5b71b59..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamLoadedSong_Runtime.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed partial class AlphaDreamLoadedSong -{ - private static bool TryGetVoiceEntry(byte[] rom, int voiceTableOffset, byte voice, byte key, out VoiceEntry e) - { - short voiceOffset = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + (voice * 2))); - short nextVoiceOffset = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + ((voice + 1) * 2))); - if (voiceOffset == nextVoiceOffset) - { - e = default; - return false; - } - - int pos = voiceTableOffset + voiceOffset; // Prevent object creation in the last iteration - ref readonly var refE = ref VoiceEntry.Get(rom.AsSpan(pos)); - while (refE.MinKey > key || refE.MaxKey < key) - { - pos += 8; - if (pos == nextVoiceOffset) - { - e = default; - return false; - } - refE = ref VoiceEntry.Get(rom.AsSpan(pos)); - } - e = refE; - return true; - } - private void PlayNote(AlphaDreamTrack track, byte key, byte duration) - { - AlphaDreamConfig cfg = _player.Config; - if (!TryGetVoiceEntry(cfg.ROM, cfg.VoiceTableOffset, track.Voice, key, out VoiceEntry entry)) - { - return; - } - - track.NoteDuration = duration; - if (track.Index >= 8) - { - // TODO: "Sample" byte in VoiceEntry - var sqr = (AlphaDreamSquareChannel)track.Channel; - sqr.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, track.Volume, track.Panpot, track.GetPitch()); - } - else - { - int sto = cfg.SampleTableOffset; - int sampleOffset = ReadInt32LittleEndian(cfg.ROM.AsSpan(sto + (entry.Sample * 4))); // Some entries are 0. If you play them, are they silent, or does it not care if they are 0? - - var pcm = (AlphaDreamPCMChannel)track.Channel; - pcm.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, sto + sampleOffset, entry.IsFixedFrequency == VoiceEntry.FIXED_FREQ_TRUE); - pcm.SetVolume(track.Volume, track.Panpot); - pcm.SetPitch(track.GetPitch()); - } - } - public void ExecuteNext(AlphaDreamTrack track, ref bool update) - { - byte[] rom = _player.Config.ROM; - byte cmd = rom[track.DataOffset++]; - switch (cmd) - { - case 0x00: // Free Note - { - byte note = (byte)(rom[track.DataOffset++] - 0x80); - if (_player.Config.AudioEngineVersion == AudioEngineVersion.Hamtaro) - { - track.Volume = rom[track.DataOffset++]; - update = true; - } - - byte duration = rom[track.DataOffset++]; - track.Rest += duration; - if (track.PrevCommand == 0 && track.Channel.Key == note) - { - track.NoteDuration += duration; - } - else - { - PlayNote(track, note, duration); - } - break; - } - case <= 0xDF: // Note - { - byte key = rom[track.DataOffset++]; - if (_player.Config.AudioEngineVersion == AudioEngineVersion.Hamtaro) - { - track.Volume = rom[track.DataOffset++]; - update = true; - } - - track.Rest += cmd; - if (track.PrevCommand == 0 && track.Channel.Key == key) - { - track.NoteDuration += cmd; - } - else - { - PlayNote(track, key, cmd); - } - break; - } - case 0xF0: // Voice - { - track.Voice = rom[track.DataOffset++]; - break; - } - case 0xF1: // Volume - { - track.Volume = rom[track.DataOffset++]; - update = true; - break; - } - case 0xF2: // Panpot - { - track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x80); - update = true; - break; - } - case 0xF4: // Pitch Bend Range - { - track.PitchBendRange = rom[track.DataOffset++]; - update = true; - break; - } - case 0xF5: // Pitch Bend - { - track.PitchBend = (sbyte)rom[track.DataOffset++]; - update = true; - break; - } - case 0xF6: // Rest - { - track.Rest = rom[track.DataOffset++]; - break; - } - case 0xF8: // Jump - { - track.DataOffset += 2 + ReadInt16LittleEndian(rom.AsSpan(track.DataOffset)); - break; - } - case 0xF9: // Track Tempo - { - _player.Tempo = rom[track.DataOffset++]; // TODO: Implement per track - break; - } - case 0xFF: // Finish - { - track.Stopped = true; - break; - } - default: throw new AlphaDreamInvalidCMDException(track.Index, track.DataOffset - 1, cmd); - } - - track.PrevCommand = cmd; - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs index 1cc823c..05c4afd 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs @@ -19,8 +19,6 @@ public sealed class AlphaDreamMixer : Mixer private readonly float[][] _trackBuffers = new float[AlphaDreamPlayer.NUM_TRACKS][]; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal AlphaDreamMixer(AlphaDreamConfig config) { Config = config; @@ -71,7 +69,17 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } - internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } + internal void Process(Track[] tracks, bool output, bool recording) { _audio.Clear(); float masterStep; @@ -98,8 +106,8 @@ internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) } for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) { - AlphaDreamTrack track = tracks[i]; - if (!track.IsEnabled || track.NoteDuration == 0 || track.Channel.Stopped || Mutes[i]) + Track track = tracks[i]; + if (!track.Enabled || track.NoteDuration == 0 || track.Channel.Stopped || Mutes[i]) { continue; } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs index e202a38..6d8f062 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs @@ -1,167 +1,714 @@ -using System; -using static System.Buffers.Binary.BinaryPrimitives; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; -public sealed class AlphaDreamPlayer : Player +public sealed class AlphaDreamPlayer : IPlayer, ILoadedSong { internal const int NUM_TRACKS = 12; // 8 PCM, 4 PSG - protected override string Name => "AlphaDream Player"; - - internal readonly AlphaDreamTrack[] Tracks; - internal readonly AlphaDreamConfig Config; + private readonly Track[] _tracks = new Track[NUM_TRACKS]; private readonly AlphaDreamMixer _mixer; - private AlphaDreamLoadedSong? _loadedSong; - - internal byte Tempo; - internal int TempoStack; + private readonly AlphaDreamConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private byte _tempo; + private int _tempoStack; private long _elapsedLoops; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => _mixer; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; + + public PlayerState State { get; private set; } + public event Action? SongEnded; internal AlphaDreamPlayer(AlphaDreamConfig config, AlphaDreamMixer mixer) - : base(GBAUtils.AGB_FPS) { - Config = config; + _config = config; _mixer = mixer; - Tracks = new AlphaDreamTrack[NUM_TRACKS]; for (byte i = 0; i < NUM_TRACKS; i++) { - Tracks[i] = new AlphaDreamTrack(i, mixer); + _tracks[i] = new Track(i, mixer); } - } - public override void LoadSong(int index) + _time = new TimeBarrier(GBAUtils.AGB_FPS); + } + private void CreateThread() { - if (_loadedSong is not null) - { - _loadedSong = null; - } - - int songPtr = Config.SongTableOffsets[0] + (index * 4); - int songOffset = ReadInt32LittleEndian(Config.ROM.AsSpan(songPtr)); - if (songOffset == 0) - { - return; - } - - // If there's an exception, this will remain null - _loadedSong = new AlphaDreamLoadedSong(this, songOffset); - _loadedSong.SetTicks(); + _thread = new Thread(Tick) { Name = "AlphaDream Player Tick" }; + _thread.Start(); } - public override void UpdateSongState(SongState info) + private void WaitThread() { - info.Tempo = Tempo; - for (int i = 0; i < NUM_TRACKS; i++) + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) { - AlphaDreamTrack track = Tracks[i]; - if (track.IsEnabled) - { - track.UpdateSongState(info.Tracks[i]); - } + _thread.Join(); } } - internal override void InitEmulation() + + private void InitEmulation() { - Tempo = 120; // Player tempo is set to 75 on init, but I did not separate player and track tempo yet - TempoStack = 0; + _tempo = 120; // Player tempo is set to 75 on init, but I did not separate player and track tempo yet + _tempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; _mixer.ResetFade(); for (int i = 0; i < NUM_TRACKS; i++) { - Tracks[i].Init(); + _tracks[i].Init(); } } - protected override void SetCurTick(long ticks) + private void SetTicks() { - _loadedSong!.SetCurTick(ticks); + MaxTicks = 0; + bool u = false; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + if (Events[trackIndex] == null) + { + continue; + } + + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = _tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + if (e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + ExecuteNext(track, ref u); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.NoteDuration = 0; + } } - protected override void OnStopped() + public void LoadSong(long index) { - // - } + _config.Reader.Stream.Position = _config.SongTableOffsets[0] + (index * 4); + int songOffset = _config.Reader.ReadInt32(); + if (songOffset == 0) + { + Events = null; + return; + } - protected override bool Tick(bool playing, bool recording) + Events = new List[NUM_TRACKS]; + songOffset -= GBAUtils.CartridgeOffset; + _config.Reader.Stream.Position = songOffset; + ushort trackBits = _config.Reader.ReadUInt16(); + for (byte i = 0, usedTracks = 0; i < NUM_TRACKS; i++) + { + Track track = _tracks[i]; + if ((trackBits & (1 << i)) == 0) + { + track.Enabled = false; + track.StartOffset = 0; + continue; + } + + track.Enabled = true; + Events[i] = new List(); + bool EventExists(long offset) + { + return Events[i].Any(e => e.Offset == offset); + } + + _config.Reader.Stream.Position = songOffset + 2 + (2 * usedTracks++); + AddEvents(track.StartOffset = songOffset + _config.Reader.ReadInt16()); + void AddEvents(int startOffset) + { + _config.Reader.Stream.Position = startOffset; + bool cont = true; + while (cont) + { + long offset = _config.Reader.Stream.Position; + void AddEvent(ICommand command) + { + Events[i].Add(new SongEvent(offset, command)); + } + byte cmd = _config.Reader.ReadByte(); + switch (cmd) + { + case 0x00: + { + byte keyArg = _config.Reader.ReadByte(); + switch (_config.AudioEngineVersion) + { + case AudioEngineVersion.Hamtaro: + { + byte volume = _config.Reader.ReadByte(); + byte duration = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new FreeNoteHamtaroCommand { Note = (byte)(keyArg - 0x80), Volume = volume, Duration = duration }); + } + break; + } + case AudioEngineVersion.MLSS: + { + byte duration = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new FreeNoteMLSSCommand { Note = (byte)(keyArg - 0x80), Duration = duration }); + } + break; + } + } + break; + } + case 0xF0: + { + byte voice = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = voice }); + } + break; + } + case 0xF1: + { + byte volume = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VolumeCommand { Volume = volume }); + } + break; + } + case 0xF2: + { + byte panArg = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = (sbyte)(panArg - 0x80) }); + } + break; + } + case 0xF4: + { + byte range = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendRangeCommand { Range = range }); + } + break; + } + case 0xF5: + { + sbyte bend = _config.Reader.ReadSByte(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = bend }); + } + break; + } + case 0xF6: + { + byte rest = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = rest }); + } + break; + } + case 0xF8: + { + short jumpOffset = _config.Reader.ReadInt16(); + if (!EventExists(offset)) + { + int off = (int)(_config.Reader.Stream.Position + jumpOffset); + AddEvent(new JumpCommand { Offset = off }); + if (!EventExists(off)) + { + AddEvents(off); + } + } + cont = false; + break; + } + case 0xF9: + { + byte tempoArg = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new TrackTempoCommand { Tempo = tempoArg }); + } + break; + } + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + cont = false; + break; + } + default: + { + if (cmd >= 0xE0) + { + throw new AlphaDreamInvalidCMDException(i, (int)offset, cmd); + } + + byte key = _config.Reader.ReadByte(); + switch (_config.AudioEngineVersion) + { + case AudioEngineVersion.Hamtaro: + { + byte volume = _config.Reader.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new NoteHamtaroCommand { Note = key, Volume = volume, Duration = cmd }); + } + break; + } + case AudioEngineVersion.MLSS: + { + if (!EventExists(offset)) + { + AddEvent(new NoteMLSSCommand { Note = key, Duration = cmd }); + } + break; + } + } + break; + } + } + } + } + } + SetTicks(); + } + public void SetCurrentPosition(long ticks) { - bool allDone = false; // TODO: Individual track tempo - while (!allDone && TempoStack >= 75) + if (Events == null) { - TempoStack -= 75; - allDone = true; - for (int i = 0; i < NUM_TRACKS; i++) + SongEnded?.Invoke(); + } + else if (State == PlayerState.Playing || State == PlayerState.Paused || State == PlayerState.Stopped) + { + if (State == PlayerState.Playing) { - AlphaDreamTrack track = Tracks[i]; - if (track.IsEnabled) + Pause(); + } + InitEmulation(); + bool u = false; + while (true) + { + if (ElapsedTicks == ticks) + { + goto finish; + } + + while (_tempoStack >= 75) { - TickTrack(track, ref allDone); + _tempoStack -= 75; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref u); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } } + _tempoStack += _tempo; } - if (_mixer.IsFadeDone()) + finish: + for (int i = 0; i < NUM_TRACKS; i++) { - allDone = true; + _tracks[i].NoteDuration = 0; } + Pause(); + } + } + public void Play() + { + if (State is PlayerState.ShutDown or PlayerState.Recording) + { + return; } - if (!allDone) + + if (Events is null) { - TempoStack += Tempo; + SongEnded?.Invoke(); + return; } - _mixer.Process(Tracks, playing, recording); - return allDone; + + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } - private void TickTrack(AlphaDreamTrack track, ref bool allDone) + public void Pause() { - byte prevDuration = track.NoteDuration; - track.Tick(); - bool update = false; - while (track.Rest == 0 && !track.Stopped) + switch (State) { - _loadedSong!.ExecuteNext(track, ref update); + case PlayerState.Playing: + { + State = PlayerState.Paused; + WaitThread(); + break; + } + case PlayerState.Paused: + case PlayerState.Stopped: + { + State = PlayerState.Playing; + CreateThread(); + break; + } } - if (track.Index == _loadedSong!.LongestTrack) + } + public void Stop() + { + if (State is PlayerState.Playing or PlayerState.Paused) { - HandleTicksAndLoop(_loadedSong, track); + State = PlayerState.Stopped; + WaitThread(); } - if (prevDuration == 1 && track.NoteDuration == 0) // Note was not renewed + } + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() + { + if (State != PlayerState.ShutDown) { - track.Channel.State = EnvelopeState.Release; + State = PlayerState.ShutDown; + WaitThread(); } - if (track.NoteDuration != 0) // A note is playing + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int i = 0; i < NUM_TRACKS; i++) { - allDone = false; - if (update) + Track track = _tracks[i]; + if (!track.Enabled) + { + continue; + } + + SongState.Track tin = info.Tracks[i]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.Type = track.Type; + tin.Volume = track.Volume; + tin.PitchBend = track.GetPitch(); + tin.Panpot = track.Panpot; + if (track.NoteDuration != 0 && !track.Channel.Stopped) { - track.Channel.SetVolume(track.Volume, track.Panpot); - track.Channel.SetPitch(track.GetPitch()); + tin.Keys[0] = track.Channel.Key; + ChannelVolume vol = track.Channel.GetVolume(); + tin.LeftVolume = vol.LeftVol; + tin.RightVolume = vol.RightVol; } + else + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + } + } + } + + private bool TryGetVoiceEntry(byte voice, byte key, out VoiceEntry e) + { + int vto = _config.VoiceTableOffset; + byte[] rom = _config.ROM; + short voiceOffset = BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(vto + (voice * 2))); + short nextVoiceOffset = BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(vto + ((voice + 1) * 2))); + if (voiceOffset == nextVoiceOffset) + { + e = default; + return false; } - if (!track.Stopped) + + int pos = vto + voiceOffset; // Prevent object creation in the last iteration + ref VoiceEntry refE = ref MemoryMarshal.AsRef(rom.AsSpan(pos)); + while (refE.MinKey > key || refE.MaxKey < key) { - allDone = false; + pos += 8; + if (pos == nextVoiceOffset) + { + e = default; + return false; + } + refE = ref MemoryMarshal.AsRef(rom.AsSpan(pos)); } + e = refE; + return true; } - private void HandleTicksAndLoop(AlphaDreamLoadedSong s, AlphaDreamTrack track) + private void PlayNote(Track track, byte key, byte duration) { - if (ElapsedTicks != s.MaxTicks) + if (!TryGetVoiceEntry(track.Voice, key, out VoiceEntry entry)) { - ElapsedTicks++; return; } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + track.NoteDuration = duration; + if (track.Index >= 8) { - return; + // TODO: "Sample" byte in VoiceEntry + var sqr = (SquareChannel)track.Channel; + sqr.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, track.Volume, track.Panpot, track.GetPitch()); } + else + { + int sto = _config.SampleTableOffset; + byte[] rom = _config.ROM; + int sampleOffset = BinaryPrimitives.ReadInt32LittleEndian(rom.AsSpan(sto + (entry.Sample * 4))); // Some entries are 0. If you play them, are they silent, or does it not care if they are 0? - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index]!, track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !_mixer.IsFading()) + var pcm = (PCMChannel)track.Channel; + pcm.Init(key, new ADSR { A = 0xFF, D = 0x00, S = 0xFF, R = 0x00 }, sto + sampleOffset, entry.IsFixedFrequency == 0x80); + pcm.SetVolume(track.Volume, track.Panpot); + pcm.SetPitch(track.GetPitch()); + } + } + private void ExecuteNext(Track track, ref bool update) + { + byte[] rom = _config.ROM; + byte cmd = rom[track.DataOffset++]; + switch (cmd) { - _mixer.BeginFadeOut(); + case 0x00: // Free Note + { + byte note = (byte)(rom[track.DataOffset++] - 0x80); + if (_config.AudioEngineVersion == AudioEngineVersion.Hamtaro) + { + track.Volume = rom[track.DataOffset++]; + update = true; + } + + byte duration = rom[track.DataOffset++]; + track.Rest += duration; + if (track.PrevCommand == 0 && track.Channel.Key == note) + { + track.NoteDuration += duration; + } + else + { + PlayNote(track, note, duration); + } + break; + } + case <= 0xDF: // Note + { + byte key = rom[track.DataOffset++]; + if (_config.AudioEngineVersion == AudioEngineVersion.Hamtaro) + { + track.Volume = rom[track.DataOffset++]; + update = true; + } + + track.Rest += cmd; + if (track.PrevCommand == 0 && track.Channel.Key == key) + { + track.NoteDuration += cmd; + } + else + { + PlayNote(track, key, cmd); + } + break; + } + case 0xF0: // Voice + { + track.Voice = rom[track.DataOffset++]; + break; + } + case 0xF1: // Volume + { + track.Volume = rom[track.DataOffset++]; + update = true; + break; + } + case 0xF2: // Panpot + { + track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x80); + update = true; + break; + } + case 0xF4: // Pitch Bend Range + { + track.PitchBendRange = rom[track.DataOffset++]; + update = true; + break; + } + case 0xF5: // Pitch Bend + { + track.PitchBend = (sbyte)rom[track.DataOffset++]; + update = true; + break; + } + case 0xF6: // Rest + { + track.Rest = rom[track.DataOffset++]; + break; + } + case 0xF8: // Jump + { + track.DataOffset += 2 + BinaryPrimitives.ReadInt16LittleEndian(rom.AsSpan(track.DataOffset, 2)); + break; + } + case 0xF9: // Track Tempo + { + _tempo = rom[track.DataOffset++]; + break; + } + case 0xFF: // Finish + { + track.Stopped = true; + break; + } + default: throw new AlphaDreamInvalidCMDException(track.Index, track.DataOffset - 1, cmd); + } + + track.PrevCommand = cmd; + } + + private void Tick() + { + _time.Start(); + while (true) + { + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 75) + { + _tempoStack -= 75; + bool allDone = true; + for (int trackIndex = 0; trackIndex < NUM_TRACKS; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled) + { + byte prevDuration = track.NoteDuration; + track.Tick(); + bool update = false; + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref update); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (prevDuration == 1 && track.NoteDuration == 0) // Note was not renewed + { + track.Channel.State = EnvelopeState.Release; + } + if (!track.Stopped) + { + allDone = false; + } + if (track.NoteDuration != 0) + { + allDone = false; + if (update) + { + track.Channel.SetVolume(track.Volume, track.Panpot); + track.Channel.SetPitch(track.GetPitch()); + } + } + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.Process(_tracks, playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.Process(_tracks, playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs index 606f9b5..f9f351f 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_DLS.cs @@ -4,6 +4,7 @@ using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -54,7 +55,7 @@ private static void AddInfo(AlphaDreamConfig config, DLS dls) } ofs += config.SampleTableOffset; - var sh = new SampleHeader(config.ROM, ofs, out int sampleOffset); + ref SampleHeader sh = ref MemoryMarshal.AsRef(config.ROM.AsSpan(ofs)); // Create format chunk var fmt = new FormatChunk(WaveFormat.PCM); @@ -80,7 +81,7 @@ private static void AddInfo(AlphaDreamConfig config, DLS dls) } // Get PCM sample byte[] pcm = new byte[sh.Length]; - Array.Copy(config.ROM, sampleOffset, pcm, 0, sh.Length); + Array.Copy(config.ROM, ofs + 0x10, pcm, 0, sh.Length); // Add int dlsIndex = waves.Count; @@ -126,7 +127,7 @@ private static void AddInstruments(AlphaDreamConfig config, DLS dls, Dictionary< lins.Add(ins); for (int e = 0; e < numEntries; e++) { - ref readonly var entry = ref VoiceEntry.Get(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); + ref VoiceEntry entry = ref MemoryMarshal.AsRef(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); // Sample if (entry.Sample >= config.SampleTableSize) { @@ -139,7 +140,7 @@ private static void AddInstruments(AlphaDreamConfig config, DLS dls, Dictionary< continue; } - void Add(ushort low, ushort high, ushort baseNote) + void Add(ushort low, ushort high, ushort baseKey) { var rgnh = new RegionHeaderChunk(); rgnh.KeyRange.Low = low; @@ -149,7 +150,7 @@ void Add(ushort low, ushort high, ushort baseNote) rgnh, new WaveSampleChunk { - UnityNote = baseNote, + UnityNote = baseKey, Options = WaveSampleOptions.NoTruncation | WaveSampleOptions.NoCompression, Loop = value.Item1.Loop, }, diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs index 30c0529..6ed9a2c 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamSoundFontSaver_SF2.cs @@ -1,63 +1,57 @@ using Kermalis.SoundFont2; using Kermalis.VGMusicStudio.Core.Util; using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; -using static System.Buffers.Binary.BinaryPrimitives; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; public static class AlphaDreamSoundFontSaver_SF2 { - public static void Save(string path, AlphaDreamConfig cfg) - { - Save(path, cfg.ROM, cfg.Name, cfg.SampleTableOffset, (int)cfg.SampleTableSize, cfg.VoiceTableOffset); - } - private static void Save(string path, - byte[] rom, string romName, - int sampleTableOffset, int sampleTableSize, int voiceTableOffset) + public static void Save(AlphaDreamConfig config, string path) { var sf2 = new SF2(); - AddInfo(romName, sf2.InfoChunk); - Dictionary sampleDict = AddSamples(rom, sampleTableOffset, sampleTableSize, sf2); - AddInstruments(rom, voiceTableOffset, sampleTableSize, sf2, sampleDict); + AddInfo(config, sf2.InfoChunk); + Dictionary sampleDict = AddSamples(config, sf2); + AddInstruments(config, sf2, sampleDict); sf2.Save(path); } - private static void AddInfo(string romName, InfoListChunk chunk) + private static void AddInfo(AlphaDreamConfig config, InfoListChunk chunk) { - chunk.Bank = romName; + chunk.Bank = config.Name; //chunk.Copyright = config.Creator; chunk.Tools = ConfigUtils.PROGRAM_NAME + " by Kermalis"; } - private static Dictionary AddSamples(byte[] rom, int sampleTableOffset, int sampleTableSize, SF2 sf2) + private static Dictionary AddSamples(AlphaDreamConfig config, SF2 sf2) { - var sampleDict = new Dictionary(sampleTableSize); - for (int i = 0; i < sampleTableSize; i++) + var sampleDict = new Dictionary((int)config.SampleTableSize); + for (int i = 0; i < config.SampleTableSize; i++) { - int ofs = ReadInt32LittleEndian(rom.AsSpan(sampleTableOffset + (i * 4))); + int ofs = BinaryPrimitives.ReadInt32LittleEndian(config.ROM.AsSpan(config.SampleTableOffset + (i * 4))); if (ofs == 0) { continue; } - ofs += sampleTableOffset; - var sh = new SampleHeader(rom, ofs, out int sampleOffset); + ofs += config.SampleTableOffset; + ref SampleHeader sh = ref MemoryMarshal.AsRef(config.ROM.AsSpan(ofs)); - short[] pcm16 = new short[sh.Length]; - SampleUtils.PCMU8ToPCM16(rom.AsSpan(sampleOffset), pcm16); + short[] pcm16 = SampleUtils.PCMU8ToPCM16(config.ROM.AsSpan(ofs + 0x10, sh.Length)); int sf2Index = (int)sf2.AddSample(pcm16, $"Sample {i}", sh.DoesLoop == SampleHeader.LOOP_TRUE, (uint)sh.LoopOffset, (uint)sh.SampleRate >> 10, 60, 0); sampleDict.Add(i, (sh, sf2Index)); } return sampleDict; } - private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleTableSize, SF2 sf2, Dictionary sampleDict) + private static void AddInstruments(AlphaDreamConfig config, SF2 sf2, Dictionary sampleDict) { for (ushort v = 0; v < 256; v++) { - short off = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + (v * 2))); - short nextOff = ReadInt16LittleEndian(rom.AsSpan(voiceTableOffset + ((v + 1) * 2))); + short off = BinaryPrimitives.ReadInt16LittleEndian(config.ROM.AsSpan(config.VoiceTableOffset + (v * 2))); + short nextOff = BinaryPrimitives.ReadInt16LittleEndian(config.ROM.AsSpan(config.VoiceTableOffset + ((v + 1) * 2))); int numEntries = (nextOff - off) / 8; // Each entry is 8 bytes if (numEntries == 0) { @@ -70,10 +64,10 @@ private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleT sf2.AddPresetGenerator(SF2Generator.Instrument, new SF2GeneratorAmount { Amount = (short)sf2.AddInstrument(name) }); for (int e = 0; e < numEntries; e++) { - ref readonly var entry = ref VoiceEntry.Get(rom.AsSpan(voiceTableOffset + off + (e * 8))); + ref VoiceEntry entry = ref MemoryMarshal.AsRef(config.ROM.AsSpan(config.VoiceTableOffset + off + (e * 8))); sf2.AddInstrumentBag(); // Key range - if (entry.MinKey != 0 || entry.MaxKey != 0x7F) + if (!(entry.MinKey == 0 && entry.MaxKey == 0x7F)) { sf2.AddInstrumentGenerator(SF2Generator.KeyRange, new SF2GeneratorAmount { LowByte = entry.MinKey, HighByte = entry.MaxKey }); } @@ -83,7 +77,7 @@ private static void AddInstruments(byte[] rom, int voiceTableOffset, int sampleT sf2.AddInstrumentGenerator(SF2Generator.ScaleTuning, new SF2GeneratorAmount { Amount = 0 }); } // Sample - if (entry.Sample < sampleTableSize) + if (entry.Sample < config.SampleTableSize) { if (!sampleDict.TryGetValue(entry.Sample, out (SampleHeader, int) value)) { diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs deleted file mode 100644 index 720c72e..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamStructs.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SampleHeader -{ - public const int SIZE = 16; - public const int LOOP_TRUE = 0x40_000_000; - - /// 0x40_000_000 if True - public readonly int DoesLoop; - /// Right shift 10 for value - public readonly int SampleRate; - public readonly int LoopOffset; - public readonly int Length; - // byte[Length] Sample; - - public SampleHeader(byte[] rom, int offset, out int sampleOffset) - { - ReadOnlySpan data = rom.AsSpan(offset, SIZE); - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(data); - } - else - { - DoesLoop = ReadInt32LittleEndian(data.Slice(0, 4)); - SampleRate = ReadInt32LittleEndian(data.Slice(4, 4)); - LoopOffset = ReadInt32LittleEndian(data.Slice(8, 4)); - Length = ReadInt32LittleEndian(data.Slice(12, 4)); - } - sampleOffset = offset + SIZE; - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct VoiceEntry -{ - public const int SIZE = 8; - public const byte FIXED_FREQ_TRUE = 0x80; - - public readonly byte MinKey; - public readonly byte MaxKey; - public readonly byte Sample; - /// 0x80 if True - public readonly byte IsFixedFrequency; - public readonly byte Unknown1; - public readonly byte Unknown2; - public readonly byte Unknown3; - public readonly byte Unknown4; - - public static ref readonly VoiceEntry Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} - -internal struct ChannelVolume -{ - public float LeftVol, RightVol; -} -internal struct ADSR // TODO -{ - public byte A, D, S, R; -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs deleted file mode 100644 index ded6a34..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed class AlphaDreamTrack -{ - public readonly byte Index; - public readonly string Type; - public readonly AlphaDreamChannel Channel; - - public byte Voice; - public byte PitchBendRange; - public byte Volume; - public byte Rest; - public byte NoteDuration; - public sbyte PitchBend; - public sbyte Panpot; - public bool IsEnabled; - public bool Stopped; - public int StartOffset; - public int DataOffset; - public byte PrevCommand; - - public int GetPitch() - { - return PitchBend * (PitchBendRange / 2); - } - - public AlphaDreamTrack(byte i, AlphaDreamMixer mixer) - { - Index = i; - if (i >= 8) - { - Type = GBAUtils.PSGTypes[i & 3]; - Channel = new AlphaDreamSquareChannel(mixer); // TODO: PSG Channels 3 and 4 - } - else - { - Type = "PCM8"; - Channel = new AlphaDreamPCMChannel(mixer); - } - } - // 0x819B040 - public void Init() - { - Voice = 0; - Rest = 1; // Unsure why Rest starts at 1 - PitchBendRange = 2; - NoteDuration = 0; - PitchBend = 0; - Panpot = 0; // Start centered; ROM sets this to 0x7F since it's unsigned there - DataOffset = StartOffset; - Stopped = false; - Volume = 200; - PrevCommand = 0xFF; - //Tempo = 120; - //TempoStack = 0; - } - public void Tick() - { - if (Rest != 0) - { - Rest--; - } - if (NoteDuration > 0) - { - NoteDuration--; - } - } - - public void UpdateSongState(SongState.Track tin) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.Type = Type; - tin.Volume = Volume; - tin.PitchBend = GetPitch(); - tin.Panpot = Panpot; - if (NoteDuration != 0 && !Channel.Stopped) - { - tin.Keys[0] = Channel.Key; - ChannelVolume vol = Channel.GetVolume(); - tin.LeftVolume = vol.LeftVol; - tin.RightVolume = vol.RightVol; - } - else - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - } -} diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs deleted file mode 100644 index 471fdb4..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal abstract class AlphaDreamChannel -{ - protected readonly AlphaDreamMixer _mixer; - public EnvelopeState State; - public byte Key; - public bool Stopped; - - protected ADSR _adsr; - - protected byte _velocity; - protected int _pos; - protected float _interPos; - protected float _frequency; - protected byte _leftVol; - protected byte _rightVol; - - protected AlphaDreamChannel(AlphaDreamMixer mixer) - { - _mixer = mixer; - } - - public ChannelVolume GetVolume() - { - const float MAX = 1f / 0x10000; - return new ChannelVolume - { - LeftVol = _leftVol * _velocity * MAX, - RightVol = _rightVol * _velocity * MAX, - }; - } - public void SetVolume(byte vol, sbyte pan) - { - _leftVol = (byte)((vol * (-pan + 0x80)) >> 8); - _rightVol = (byte)((vol * (pan + 0x80)) >> 8); - } - public abstract void SetPitch(int pitch); - - public abstract void Process(float[] buffer); -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs deleted file mode 100644 index 455dc77..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed class AlphaDreamPCMChannel : AlphaDreamChannel -{ - private SampleHeader _sampleHeader; - private int _sampleOffset; - private bool _bFixed; - - public AlphaDreamPCMChannel(AlphaDreamMixer mixer) : base(mixer) - { - // - } - public void Init(byte key, ADSR adsr, int sampleOffset, bool bFixed) - { - _velocity = adsr.A; - State = EnvelopeState.Attack; - _pos = 0; _interPos = 0; - Key = key; - _adsr = adsr; - - _sampleHeader = new SampleHeader(_mixer.Config.ROM, sampleOffset, out _sampleOffset); - _bFixed = bFixed; - Stopped = false; - } - - public override void SetPitch(int pitch) - { - _frequency = (_sampleHeader.SampleRate >> 10) * MathF.Pow(2, ((Key - 60) / 12f) + (pitch / 768f)); - } - - private void StepEnvelope() - { - switch (State) - { - case EnvelopeState.Attack: - { - int nextVel = _velocity + _adsr.A; - if (nextVel >= 0xFF) - { - State = EnvelopeState.Decay; - _velocity = 0xFF; - } - else - { - _velocity = (byte)nextVel; - } - break; - } - case EnvelopeState.Decay: - { - int nextVel = (_velocity * _adsr.D) >> 8; - if (nextVel <= _adsr.S) - { - State = EnvelopeState.Sustain; - _velocity = _adsr.S; - } - else - { - _velocity = (byte)nextVel; - } - break; - } - case EnvelopeState.Release: - { - int next = (_velocity * _adsr.R) >> 8; - if (next < 0) - { - next = 0; - } - _velocity = (byte)next; - break; - } - } - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - - ChannelVolume vol = GetVolume(); - float interStep = (_bFixed ? _sampleHeader.SampleRate >> 10 : _frequency) * _mixer.SampleRateReciprocal; - int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = (_mixer.Config.ROM[_pos + _sampleOffset] - 0x80) / (float)0x80; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _sampleHeader.Length) - { - if (_sampleHeader.DoesLoop == 0x40000000) - { - _pos = _sampleHeader.LoopOffset; - } - else - { - Stopped = true; - break; - } - } - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs deleted file mode 100644 index a627bf0..0000000 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Kermalis.VGMusicStudio.Core.GBA.MP2K; -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; - -internal sealed class AlphaDreamSquareChannel : AlphaDreamChannel -{ - private float[] _pat; - - public AlphaDreamSquareChannel(AlphaDreamMixer mixer) - : base(mixer) - { - _pat = null!; - } - public void Init(byte key, ADSR env, byte vol, sbyte pan, int pitch) - { - _pat = MP2KUtils.SquareD50; // TODO: Which square pattern? - Key = key; - _adsr = env; - SetVolume(vol, pan); - SetPitch(pitch); - State = EnvelopeState.Attack; - } - - public override void SetPitch(int pitch) - { - _frequency = 3_520 * MathF.Pow(2, ((Key - 69) / 12f) + (pitch / 768f)); - } - - private void StepEnvelope() - { - switch (State) - { - case EnvelopeState.Attack: - { - int next = _velocity + _adsr.A; - if (next >= 0xF) - { - State = EnvelopeState.Decay; - _velocity = 0xF; - } - else - { - _velocity = (byte)next; - } - break; - } - case EnvelopeState.Decay: - { - int next = (_velocity * _adsr.D) >> 3; - if (next <= _adsr.S) - { - State = EnvelopeState.Sustain; - _velocity = _adsr.S; - } - else - { - _velocity = (byte)next; - } - break; - } - case EnvelopeState.Release: - { - int next = (_velocity * _adsr.R) >> 3; - if (next < 0) - { - next = 0; - } - _velocity = (byte)next; - break; - } - } - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - - ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; - - int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _pat[_pos]; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos = (_pos + posDelta) & 0x7; - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs b/VG Music Studio - Core/GBA/AlphaDream/Commands.cs similarity index 77% rename from VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs rename to VG Music Studio - Core/GBA/AlphaDream/Commands.cs index b27f327..faaee21 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamCommands.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/Commands.cs @@ -3,13 +3,13 @@ namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; public string Arguments => string.Empty; } -internal sealed class FreeNoteHamtaroCommand : ICommand // TODO: When optimization comes, get rid of free note vs note and just have the label differ +internal class FreeNoteHamtaroCommand : ICommand // TODO: When optimization comes, get rid of free note vs note and just have the label differ { public Color Color => Color.SkyBlue; public string Label => "Free Note"; @@ -19,7 +19,7 @@ internal sealed class FreeNoteHamtaroCommand : ICommand // TODO: When optimizati public byte Volume { get; set; } public byte Duration { get; set; } } -internal sealed class FreeNoteMLSSCommand : ICommand +internal class FreeNoteMLSSCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Free Note"; @@ -28,7 +28,7 @@ internal sealed class FreeNoteMLSSCommand : ICommand public byte Note { get; set; } public byte Duration { get; set; } } -internal sealed class JumpCommand : ICommand +internal class JumpCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Jump"; @@ -36,7 +36,7 @@ internal sealed class JumpCommand : ICommand public int Offset { get; set; } } -internal sealed class NoteHamtaroCommand : ICommand +internal class NoteHamtaroCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -46,7 +46,7 @@ internal sealed class NoteHamtaroCommand : ICommand public byte Volume { get; set; } public byte Duration { get; set; } } -internal sealed class NoteMLSSCommand : ICommand +internal class NoteMLSSCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -55,7 +55,7 @@ internal sealed class NoteMLSSCommand : ICommand public byte Note { get; set; } public byte Duration { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -63,7 +63,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -71,7 +71,7 @@ internal sealed class PitchBendCommand : ICommand public sbyte Bend { get; set; } } -internal sealed class PitchBendRangeCommand : ICommand +internal class PitchBendRangeCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend Range"; @@ -79,7 +79,7 @@ internal sealed class PitchBendRangeCommand : ICommand public byte Range { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -87,7 +87,7 @@ internal sealed class RestCommand : ICommand public byte Rest { get; set; } } -internal sealed class TrackTempoCommand : ICommand +internal class TrackTempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => "Track Tempo"; @@ -95,7 +95,7 @@ internal sealed class TrackTempoCommand : ICommand public byte Tempo { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -103,7 +103,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/GBA/AlphaDream/Enums.cs b/VG Music Studio - Core/GBA/AlphaDream/Enums.cs new file mode 100644 index 0000000..bca47c4 --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Enums.cs @@ -0,0 +1,16 @@ +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream +{ + internal enum AudioEngineVersion : byte + { + Hamtaro, + MLSS, + } + + internal enum EnvelopeState : byte + { + Attack, + Decay, + Sustain, + Release, + } +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/Structs.cs b/VG Music Studio - Core/GBA/AlphaDream/Structs.cs new file mode 100644 index 0000000..dcd8832 --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Structs.cs @@ -0,0 +1,40 @@ +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; + +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 16)] +internal struct SampleHeader +{ + public const int LOOP_TRUE = 0x40_000_000; + + /// 0x40_000_000 if True + public int DoesLoop; + /// Right shift 10 for value + public int SampleRate; + public int LoopOffset; + public int Length; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 8)] +internal struct VoiceEntry +{ + public const byte FIXED_FREQ_TRUE = 0x80; + + public byte MinKey; + public byte MaxKey; + public byte Sample; + /// 0x80 if True + public byte IsFixedFrequency; + public byte Unknown1; + public byte Unknown2; + public byte Unknown3; + public byte Unknown4; +} + +internal struct ChannelVolume +{ + public float LeftVol, RightVol; +} +internal class ADSR // TODO +{ + public byte A, D, S, R; +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/Track.cs b/VG Music Studio - Core/GBA/AlphaDream/Track.cs new file mode 100644 index 0000000..d9401fc --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/Track.cs @@ -0,0 +1,69 @@ +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream +{ + internal class Track + { + public readonly byte Index; + public readonly string Type; + public readonly AlphaDreamChannel Channel; + + public byte Voice; + public byte PitchBendRange; + public byte Volume; + public byte Rest; + public byte NoteDuration; + public sbyte PitchBend; + public sbyte Panpot; + public bool Enabled; + public bool Stopped; + public int StartOffset; + public int DataOffset; + public byte PrevCommand; + + public int GetPitch() + { + return PitchBend * (PitchBendRange / 2); + } + + public Track(byte i, AlphaDreamMixer mixer) + { + Index = i; + if (i >= 8) + { + Type = GBAUtils.PSGTypes[i & 3]; + Channel = new SquareChannel(mixer); // TODO: PSG Channels 3 and 4 + } + else + { + Type = "PCM8"; + Channel = new PCMChannel(mixer); + } + } + // 0x819B040 + public void Init() + { + Voice = 0; + Rest = 1; // Unsure why Rest starts at 1 + PitchBendRange = 2; + NoteDuration = 0; + PitchBend = 0; + Panpot = 0; // Start centered; ROM sets this to 0x7F since it's unsigned there + DataOffset = StartOffset; + Stopped = false; + Volume = 200; + PrevCommand = 0xFF; + //Tempo = 120; + //TempoStack = 0; + } + public void Tick() + { + if (Rest != 0) + { + Rest--; + } + if (NoteDuration > 0) + { + NoteDuration--; + } + } + } +} diff --git a/VG Music Studio - Core/GBA/GBAUtils.cs b/VG Music Studio - Core/GBA/GBAUtils.cs index ca4ecf1..5106acf 100644 --- a/VG Music Studio - Core/GBA/GBAUtils.cs +++ b/VG Music Studio - Core/GBA/GBAUtils.cs @@ -1,14 +1,12 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA; +namespace Kermalis.VGMusicStudio.Core.GBA; internal static class GBAUtils { public const double AGB_FPS = 59.7275; - public const int SYSTEM_CLOCK = 16_777_216; // 16.777216 MHz (16*1024*1024 Hz) + public const int SystemClock = 16_777_216; // 16.777216 MHz (16*1024*1024 Hz) - public const int CARTRIDGE_OFFSET = 0x08_000_000; - public const int CARTRIDGE_CAPACITY = 0x02_000_000; + public const int CartridgeOffset = 0x08_000_000; + public const int CartridgeCapacity = 0x02_000_000; - public static ReadOnlySpan PSGTypes => new string[4] { "Square 1", "Square 2", "PCM4", "Noise" }; + public static readonly string[] PSGTypes = new string[4] { "Square 1", "Square 2", "PCM4", "Noise" }; } diff --git a/VG Music Studio - Core/GBA/MP2K/Channel.cs b/VG Music Studio - Core/GBA/MP2K/Channel.cs new file mode 100644 index 0000000..f25482d --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Channel.cs @@ -0,0 +1,787 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +internal abstract class Channel +{ + public EnvelopeState State = EnvelopeState.Dead; + public Track? Owner; + protected readonly MP2KMixer _mixer; + + public NoteInfo Note; // Must be a struct & field + protected ADSR _adsr; + protected int _instPan; + + protected byte _velocity; + protected int _pos; + protected float _interPos; + protected float _frequency; + + protected Channel(MP2KMixer mixer) + { + _mixer = mixer; + } + + public abstract ChannelVolume GetVolume(); + public abstract void SetVolume(byte vol, sbyte pan); + public abstract void SetPitch(int pitch); + public virtual void Release() + { + if (State < EnvelopeState.Releasing) + { + State = EnvelopeState.Releasing; + } + } + + public abstract void Process(float[] buffer); + + // Returns whether the note is active or not + public virtual bool TickNote() + { + if (State < EnvelopeState.Releasing) + { + if (Note.Duration > 0) + { + Note.Duration--; + if (Note.Duration == 0) + { + State = EnvelopeState.Releasing; + return false; + } + return true; + } + else + { + return true; + } + } + else + { + return false; + } + } + public void Stop() + { + State = EnvelopeState.Dead; + if (Owner != null) + { + Owner.Channels.Remove(this); + } + Owner = null; + } +} +internal class PCM8Channel : Channel +{ + private SampleHeader _sampleHeader; + private int _sampleOffset; + private GoldenSunPSG _gsPSG; + private bool _bFixed; + private bool _bGoldenSun; + private bool _bCompressed; + private byte _leftVol; + private byte _rightVol; + private sbyte[]? _decompressedSample; + + public PCM8Channel(MP2KMixer mixer) : base(mixer) { } + public void Init(Track owner, NoteInfo note, ADSR adsr, int sampleOffset, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed) + { + State = EnvelopeState.Initializing; + _pos = 0; _interPos = 0; + if (Owner is not null) + { + Owner.Channels.Remove(this); + } + Owner = owner; + Owner.Channels.Add(this); + Note = note; + _adsr = adsr; + _instPan = instPan; + byte[] rom = _mixer.Config.ROM; + _sampleHeader = MemoryMarshal.Read(rom.AsSpan(sampleOffset)); + _sampleOffset = sampleOffset + 0x10; + _bFixed = bFixed; + _bCompressed = bCompressed; + _decompressedSample = bCompressed ? Utils.Decompress(_sampleOffset, _sampleHeader.Length) : null; + _bGoldenSun = _mixer.Config.HasGoldenSunSynths && _sampleHeader.DoesLoop == 0x40000000 && _sampleHeader.LoopOffset == 0 && _sampleHeader.Length == 0; + if (_bGoldenSun) + { + _gsPSG = MemoryMarshal.Read(rom.AsSpan(_sampleOffset)); + } + SetVolume(vol, pan); + SetPitch(pitch); + } + + public override ChannelVolume GetVolume() + { + const float max = 0x10000; + return new ChannelVolume + { + LeftVol = _leftVol * _velocity / max * _mixer.PCM8MasterVolume, + RightVol = _rightVol * _velocity / max * _mixer.PCM8MasterVolume + }; + } + public override void SetVolume(byte vol, sbyte pan) + { + int combinedPan = pan + _instPan; + if (combinedPan > 63) + { + combinedPan = 63; + } + else if (combinedPan < -64) + { + combinedPan = -64; + } + const int fix = 0x2000; + if (State < EnvelopeState.Releasing) + { + int a = Note.Velocity * vol; + _leftVol = (byte)(a * (-combinedPan + 0x40) / fix); + _rightVol = (byte)(a * (combinedPan + 0x40) / fix); + } + } + public override void SetPitch(int pitch) + { + _frequency = (_sampleHeader.SampleRate >> 10) * MathF.Pow(2, ((Note.Note - 60) / 12f) + (pitch / 768f)); + } + + private void StepEnvelope() + { + switch (State) + { + case EnvelopeState.Initializing: + { + _velocity = _adsr.A; + State = EnvelopeState.Rising; + break; + } + case EnvelopeState.Rising: + { + int nextVel = _velocity + _adsr.A; + if (nextVel >= 0xFF) + { + State = EnvelopeState.Decaying; + _velocity = 0xFF; + } + else + { + _velocity = (byte)nextVel; + } + break; + } + case EnvelopeState.Decaying: + { + int nextVel = (_velocity * _adsr.D) >> 8; + if (nextVel <= _adsr.S) + { + State = EnvelopeState.Playing; + _velocity = _adsr.S; + } + else + { + _velocity = (byte)nextVel; + } + break; + } + case EnvelopeState.Playing: + { + break; + } + case EnvelopeState.Releasing: + { + int nextVel = (_velocity * _adsr.R) >> 8; + if (nextVel <= 0) + { + State = EnvelopeState.Dying; + _velocity = 0; + } + else + { + _velocity = (byte)nextVel; + } + break; + } + case EnvelopeState.Dying: + { + Stop(); + break; + } + } + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + if (State == EnvelopeState.Dead) + { + return; + } + + ChannelVolume vol = GetVolume(); + float interStep = _bFixed && !_bGoldenSun ? _mixer.SampleRate * _mixer.SampleRateReciprocal : _frequency * _mixer.SampleRateReciprocal; + if (_bGoldenSun) // Most Golden Sun processing is thanks to ipatix + { + interStep /= 0x40; + switch (_gsPSG.Type) + { + case GoldenSunPSGType.Square: + { + _pos += _gsPSG.CycleSpeed << 24; + int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; + iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; + iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); + float threshold = iThreshold / (float)0x100000000; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _interPos < threshold ? 0.5f : -0.5f; + samp += 0.5f - threshold; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + } while (--samplesPerBuffer > 0); + break; + } + case GoldenSunPSGType.Saw: + { + const int fix = 0x70; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + int var1 = (int)(_interPos * 0x100) - fix; + int var2 = (int)(_interPos * 0x10000) << 17; + int var3 = var1 - (var2 >> 27); + _pos = var3 + (_pos >> 1); + + float samp = _pos / (float)0x100; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } + case GoldenSunPSGType.Triangle: + { + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } + } + } + else if (_bCompressed) + { + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _decompressedSample![_pos] / (float)0x80; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _decompressedSample.Length) + { + Stop(); + break; + } + } while (--samplesPerBuffer > 0); + } + else + { + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = (sbyte)_mixer.Config.ROM[_pos + _sampleOffset] / (float)0x80; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _sampleHeader.Length) + { + if (_sampleHeader.DoesLoop == 0x40000000) + { + _pos = _sampleHeader.LoopOffset; + } + else + { + Stop(); + break; + } + } + } while (--samplesPerBuffer > 0); + } + } +} +internal abstract class PSGChannel : Channel +{ + protected enum GBPan : byte + { + Left, + Center, + Right + } + + private byte _processStep; + private EnvelopeState _nextState; + private byte _peakVelocity; + private byte _sustainVelocity; + protected GBPan _panpot = GBPan.Center; + + public PSGChannel(MP2KMixer mixer) : base(mixer) { } + protected void Init(Track owner, NoteInfo note, ADSR env, int instPan) + { + State = EnvelopeState.Initializing; + if (Owner != null) + { + Owner.Channels.Remove(this); + } + Owner = owner; + Owner.Channels.Add(this); + Note = note; + _adsr.A = (byte)(env.A & 0x7); + _adsr.D = (byte)(env.D & 0x7); + _adsr.S = (byte)(env.S & 0xF); + _adsr.R = (byte)(env.R & 0x7); + _instPan = instPan; + } + + public override void Release() + { + if (State < EnvelopeState.Releasing) + { + if (_adsr.R == 0) + { + _velocity = 0; + Stop(); + } + else if (_velocity == 0) + { + Stop(); + } + else + { + _nextState = EnvelopeState.Releasing; + } + } + } + public override bool TickNote() + { + if (State < EnvelopeState.Releasing) + { + if (Note.Duration > 0) + { + Note.Duration--; + if (Note.Duration == 0) + { + if (_velocity == 0) + { + Stop(); + } + else + { + State = EnvelopeState.Releasing; + } + return false; + } + return true; + } + else + { + return true; + } + } + else + { + return false; + } + } + + public override ChannelVolume GetVolume() + { + const float max = 0x20; + return new ChannelVolume + { + LeftVol = _panpot == GBPan.Right ? 0 : _velocity / max, + RightVol = _panpot == GBPan.Left ? 0 : _velocity / max + }; + } + public override void SetVolume(byte vol, sbyte pan) + { + int combinedPan = pan + _instPan; + if (combinedPan > 63) + { + combinedPan = 63; + } + else if (combinedPan < -64) + { + combinedPan = -64; + } + if (State < EnvelopeState.Releasing) + { + _panpot = combinedPan < -21 ? GBPan.Left : combinedPan > 20 ? GBPan.Right : GBPan.Center; + _peakVelocity = (byte)((Note.Velocity * vol) >> 10); + _sustainVelocity = (byte)(((_peakVelocity * _adsr.S) + 0xF) >> 4); // TODO + if (State == EnvelopeState.Playing) + { + _velocity = _sustainVelocity; + } + } + } + + protected void StepEnvelope() + { + void dec() + { + _processStep = 0; + if (_velocity - 1 <= _sustainVelocity) + { + _velocity = _sustainVelocity; + _nextState = EnvelopeState.Playing; + } + else if (_velocity != 0) + { + _velocity--; + } + } + void sus() + { + _processStep = 0; + } + void rel() + { + if (_adsr.R == 0) + { + _velocity = 0; + Stop(); + } + else + { + _processStep = 0; + if (_velocity - 1 <= 0) + { + _nextState = EnvelopeState.Dying; + _velocity = 0; + } + else + { + _velocity--; + } + } + } + + switch (State) + { + case EnvelopeState.Initializing: + { + _nextState = EnvelopeState.Rising; + _processStep = 0; + if ((_adsr.A | _adsr.D) == 0 || (_sustainVelocity == 0 && _peakVelocity == 0)) + { + State = EnvelopeState.Playing; + _velocity = _sustainVelocity; + return; + } + else if (_adsr.A == 0 && _adsr.S < 0xF) + { + State = EnvelopeState.Decaying; + int next = _peakVelocity - 1; + if (next < 0) + { + next = 0; + } + _velocity = (byte)next; + if (_velocity < _sustainVelocity) + { + _velocity = _sustainVelocity; + } + return; + } + else if (_adsr.A == 0) + { + State = EnvelopeState.Playing; + _velocity = _sustainVelocity; + return; + } + else + { + State = EnvelopeState.Rising; + _velocity = 1; + return; + } + } + case EnvelopeState.Rising: + { + if (++_processStep >= _adsr.A) + { + if (_nextState == EnvelopeState.Decaying) + { + State = EnvelopeState.Decaying; + dec(); return; + } + if (_nextState == EnvelopeState.Playing) + { + State = EnvelopeState.Playing; + sus(); return; + } + if (_nextState == EnvelopeState.Releasing) + { + State = EnvelopeState.Releasing; + rel(); return; + } + _processStep = 0; + if (++_velocity >= _peakVelocity) + { + if (_adsr.D == 0) + { + _nextState = EnvelopeState.Playing; + } + else if (_peakVelocity == _sustainVelocity) + { + _nextState = EnvelopeState.Playing; + _velocity = _peakVelocity; + } + else + { + _velocity = _peakVelocity; + _nextState = EnvelopeState.Decaying; + } + } + } + break; + } + case EnvelopeState.Decaying: + { + if (++_processStep >= _adsr.D) + { + if (_nextState == EnvelopeState.Playing) + { + State = EnvelopeState.Playing; + sus(); return; + } + if (_nextState == EnvelopeState.Releasing) + { + State = EnvelopeState.Releasing; + rel(); return; + } + dec(); + } + break; + } + case EnvelopeState.Playing: + { + if (++_processStep >= 1) + { + if (_nextState == EnvelopeState.Releasing) + { + State = EnvelopeState.Releasing; + rel(); return; + } + sus(); + } + break; + } + case EnvelopeState.Releasing: + { + if (++_processStep >= _adsr.R) + { + if (_nextState == EnvelopeState.Dying) + { + Stop(); + return; + } + rel(); + } + break; + } + } + } +} +internal class SquareChannel : PSGChannel +{ + private float[] _pat; + + public SquareChannel(MP2KMixer mixer) : base(mixer) + { + // + } + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, SquarePattern pattern) + { + Init(owner, note, env, instPan); + switch (pattern) + { + default: _pat = Utils.SquareD12; break; + case SquarePattern.D25: _pat = Utils.SquareD25; break; + case SquarePattern.D50: _pat = Utils.SquareD50; break; + case SquarePattern.D75: _pat = Utils.SquareD75; break; + } + } + + public override void SetPitch(int pitch) + { + _frequency = 3_520 * MathF.Pow(2, ((Note.Note - 69) / 12f) + (pitch / 768f)); + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + if (State == EnvelopeState.Dead) + { + return; + } + + ChannelVolume vol = GetVolume(); + float interStep = _frequency * _mixer.SampleRateReciprocal; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _pat[_pos]; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos = (_pos + posDelta) & 0x7; + } while (--samplesPerBuffer > 0); + } +} +internal class PCM4Channel : PSGChannel +{ + private float[] _sample; + + public PCM4Channel(MP2KMixer mixer) : base(mixer) + { + // + } + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, int sampleOffset) + { + Init(owner, note, env, instPan); + _sample = Utils.PCM4ToFloat(sampleOffset); + } + + public override void SetPitch(int pitch) + { + _frequency = 7_040 * MathF.Pow(2, ((Note.Note - 69) / 12f) + (pitch / 768f)); + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + if (State == EnvelopeState.Dead) + { + return; + } + + ChannelVolume vol = GetVolume(); + float interStep = _frequency * _mixer.SampleRateReciprocal; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _sample[_pos]; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos = (_pos + posDelta) & 0x1F; + } while (--samplesPerBuffer > 0); + } +} +internal class NoiseChannel : PSGChannel +{ + private BitArray _pat; + + public NoiseChannel(MP2KMixer mixer) : base(mixer) + { + // + } + public void Init(Track owner, NoteInfo note, ADSR env, int instPan, NoisePattern pattern) + { + Init(owner, note, env, instPan); + _pat = pattern == NoisePattern.Fine ? Utils.NoiseFine : Utils.NoiseRough; + } + + public override void SetPitch(int pitch) + { + int key = Note.Note + (int)MathF.Round(pitch / 64f); + if (key <= 20) + { + key = 0; + } + else + { + key -= 21; + if (key > 59) + { + key = 59; + } + } + byte v = Utils.NoiseFrequencyTable[key]; + // The following emulates 0x0400007C - SOUND4CNT_H + int r = v & 7; // Bits 0-2 + int s = v >> 4; // Bits 4-7 + _frequency = 524_288f / (r == 0 ? 0.5f : r) / MathF.Pow(2, s + 1); + } + + public override void Process(float[] buffer) + { + StepEnvelope(); + if (State == EnvelopeState.Dead) + { + return; + } + + ChannelVolume vol = GetVolume(); + float interStep = _frequency * _mixer.SampleRateReciprocal; + + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = _pat[_pos & (_pat.Length - 1)] ? 0.5f : -0.5f; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos = (_pos + posDelta) & (_pat.Length - 1); + } while (--samplesPerBuffer > 0); + } +} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs deleted file mode 100644 index 3d35241..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal abstract class MP2KChannel -{ - public EnvelopeState State; - public MP2KTrack? Owner; - protected readonly MP2KMixer _mixer; - - public NoteInfo Note; - protected ADSR _adsr; - protected int _instPan; - - protected byte _velocity; - protected int _pos; - protected float _interPos; - protected float _frequency; - - protected MP2KChannel(MP2KMixer mixer) - { - _mixer = mixer; - State = EnvelopeState.Dead; - } - - public abstract ChannelVolume GetVolume(); - public abstract void SetVolume(byte vol, sbyte pan); - public abstract void SetPitch(int pitch); - public virtual void Release() - { - if (State < EnvelopeState.Releasing) - { - State = EnvelopeState.Releasing; - } - } - - public abstract void Process(float[] buffer); - - /// Returns whether the note is active or not - public virtual bool TickNote() - { - if (State >= EnvelopeState.Releasing) - { - return false; - } - - if (Note.Duration > 0) - { - Note.Duration--; - if (Note.Duration == 0) - { - State = EnvelopeState.Releasing; - return false; - } - } - return true; - } - public void Stop() - { - State = EnvelopeState.Dead; - Owner?.Channels.Remove(this); - Owner = null; - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs deleted file mode 100644 index 4389352..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KNoiseChannel : MP2KPSGChannel -{ - private BitArray _pat; - - public MP2KNoiseChannel(MP2KMixer mixer) - : base(mixer) - { - _pat = null!; - } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, NoisePattern pattern) - { - Init(owner, note, env, instPan); - _pat = pattern == NoisePattern.Fine ? MP2KUtils.NoiseFine : MP2KUtils.NoiseRough; - } - - public override void SetPitch(int pitch) - { - int key = Note.Note + (int)MathF.Round(pitch / 64f); - if (key <= 20) - { - key = 0; - } - else - { - key -= 21; - if (key > 59) - { - key = 59; - } - } - byte v = MP2KUtils.NoiseFrequencyTable[key]; - // The following emulates 0x0400007C - SOUND4CNT_H - int r = v & 7; // Bits 0-2 - int s = v >> 4; // Bits 4-7 - _frequency = 524_288f / (r == 0 ? 0.5f : r) / MathF.Pow(2, s + 1); - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - if (State == EnvelopeState.Dead) - { - return; - } - - ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _pat[_pos & (_pat.Length - 1)] ? 0.5f : -0.5f; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos = (_pos + posDelta) & (_pat.Length - 1); - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs deleted file mode 100644 index 90ba63b..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KPCM4Channel : MP2KPSGChannel -{ - private readonly float[] _sample; - - public MP2KPCM4Channel(MP2KMixer mixer) - : base(mixer) - { - _sample = new float[0x20]; - } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, int sampleOffset) - { - Init(owner, note, env, instPan); - MP2KUtils.PCM4ToFloat(_mixer.Config.ROM.AsSpan(sampleOffset), _sample); - } - - public override void SetPitch(int pitch) - { - _frequency = 7_040 * MathF.Pow(2, ((Note.Note - 69) / 12f) + (pitch / 768f)); - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - if (State == EnvelopeState.Dead) - { - return; - } - - ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _sample[_pos]; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos = (_pos + posDelta) & 0x1F; - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs deleted file mode 100644 index 552e230..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs +++ /dev/null @@ -1,294 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KPCM8Channel : MP2KChannel -{ - private SampleHeader _sampleHeader; - private int _sampleOffset; - private GoldenSunPSG _gsPSG; - private bool _bFixed; - private bool _bGoldenSun; - private bool _bCompressed; - private byte _leftVol; - private byte _rightVol; - private sbyte[]? _decompressedSample; - - public MP2KPCM8Channel(MP2KMixer mixer) - : base(mixer) - { - // - } - public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed) - { - State = EnvelopeState.Initializing; - _pos = 0; - _interPos = 0; - if (Owner is not null) - { - Owner.Channels.Remove(this); - } - Owner = owner; - Owner.Channels.Add(this); - Note = note; - _adsr = adsr; - _instPan = instPan; - byte[] rom = _mixer.Config.ROM; - _sampleHeader = SampleHeader.Get(rom, sampleOffset, out _sampleOffset); - _bFixed = bFixed; - _bCompressed = bCompressed; - _decompressedSample = bCompressed ? MP2KUtils.Decompress(rom.AsSpan(_sampleOffset), _sampleHeader.Length) : null; - _bGoldenSun = _mixer.Config.HasGoldenSunSynths && _sampleHeader.Length == 0 && _sampleHeader.DoesLoop == SampleHeader.LOOP_TRUE && _sampleHeader.LoopOffset == 0; - if (_bGoldenSun) - { - _gsPSG = GoldenSunPSG.Get(rom.AsSpan(_sampleOffset)); - } - SetVolume(vol, pan); - SetPitch(pitch); - } - - public override ChannelVolume GetVolume() - { - const float MAX = 0x10_000; - return new ChannelVolume - { - LeftVol = _leftVol * _velocity / MAX * _mixer.PCM8MasterVolume, - RightVol = _rightVol * _velocity / MAX * _mixer.PCM8MasterVolume - }; - } - public override void SetVolume(byte vol, sbyte pan) - { - int combinedPan = pan + _instPan; - if (combinedPan > 63) - { - combinedPan = 63; - } - else if (combinedPan < -64) - { - combinedPan = -64; - } - const int fix = 0x2000; - if (State < EnvelopeState.Releasing) - { - int a = Note.Velocity * vol; - _leftVol = (byte)(a * (-combinedPan + 0x40) / fix); - _rightVol = (byte)(a * (combinedPan + 0x40) / fix); - } - } - public override void SetPitch(int pitch) - { - _frequency = (_sampleHeader.SampleRate >> 10) * MathF.Pow(2, ((Note.Note - 60) / 12f) + (pitch / 768f)); - } - - private void StepEnvelope() - { - switch (State) - { - case EnvelopeState.Initializing: - { - _velocity = _adsr.A; - State = EnvelopeState.Rising; - break; - } - case EnvelopeState.Rising: - { - int nextVel = _velocity + _adsr.A; - if (nextVel >= 0xFF) - { - State = EnvelopeState.Decaying; - _velocity = 0xFF; - } - else - { - _velocity = (byte)nextVel; - } - break; - } - case EnvelopeState.Decaying: - { - int nextVel = (_velocity * _adsr.D) >> 8; - if (nextVel <= _adsr.S) - { - State = EnvelopeState.Playing; - _velocity = _adsr.S; - } - else - { - _velocity = (byte)nextVel; - } - break; - } - case EnvelopeState.Playing: - { - break; - } - case EnvelopeState.Releasing: - { - int nextVel = (_velocity * _adsr.R) >> 8; - if (nextVel <= 0) - { - State = EnvelopeState.Dying; - _velocity = 0; - } - else - { - _velocity = (byte)nextVel; - } - break; - } - case EnvelopeState.Dying: - { - Stop(); - break; - } - } - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - if (State == EnvelopeState.Dead) - { - return; - } - - ChannelVolume vol = GetVolume(); - float interStep = _bFixed && !_bGoldenSun ? _mixer.SampleRate * _mixer.SampleRateReciprocal : _frequency * _mixer.SampleRateReciprocal; - if (_bGoldenSun) // Most Golden Sun processing is thanks to ipatix - { - Process_GS(buffer, vol, interStep); - } - else if (_bCompressed) - { - Process_Compressed(buffer, vol, interStep); - } - else - { - Process_Standard(buffer, vol, interStep, _mixer.Config.ROM); - } - } - private void Process_GS(float[] buffer, ChannelVolume vol, float interStep) - { - interStep /= 0x40; - switch (_gsPSG.Type) - { - case GoldenSunPSGType.Square: - { - _pos += _gsPSG.CycleSpeed << 24; - int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; - iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; - iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); - float threshold = iThreshold / (float)0x100_000_000; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _interPos < threshold ? 0.5f : -0.5f; - samp += 0.5f - threshold; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - if (_interPos >= 1) - { - _interPos--; - } - } while (--samplesPerBuffer > 0); - break; - } - case GoldenSunPSGType.Saw: - { - const int FIX = 0x70; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - _interPos += interStep; - if (_interPos >= 1) - { - _interPos--; - } - int var1 = (int)(_interPos * 0x100) - FIX; - int var2 = (int)(_interPos * 0x10000) << 17; - int var3 = var1 - (var2 >> 27); - _pos = var3 + (_pos >> 1); - - float samp = _pos / (float)0x100; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; - } - case GoldenSunPSGType.Triangle: - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - _interPos += interStep; - if (_interPos >= 1) - { - _interPos--; - } - float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; - } - } - } - private void Process_Compressed(float[] buffer, ChannelVolume vol, float interStep) - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _decompressedSample![_pos] / (float)0x80; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _decompressedSample.Length) - { - Stop(); - break; - } - } while (--samplesPerBuffer > 0); - } - private void Process_Standard(float[] buffer, ChannelVolume vol, float interStep, byte[] rom) - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = (sbyte)rom[_pos + _sampleOffset] / (float)0x80; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _sampleHeader.Length) - { - if (_sampleHeader.DoesLoop != SampleHeader.LOOP_TRUE) - { - Stop(); - return; - } - - _pos = _sampleHeader.LoopOffset; - } - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs deleted file mode 100644 index bc795df..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs +++ /dev/null @@ -1,282 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal abstract class MP2KPSGChannel : MP2KChannel -{ - protected enum GBPan : byte - { - Left, - Center, - Right, - } - - private byte _processStep; - private EnvelopeState _nextState; - private byte _peakVelocity; - private byte _sustainVelocity; - protected GBPan _panpot = GBPan.Center; - - public MP2KPSGChannel(MP2KMixer mixer) - : base(mixer) - { - // - } - protected void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan) - { - State = EnvelopeState.Initializing; - Owner?.Channels.Remove(this); - Owner = owner; - Owner.Channels.Add(this); - Note = note; - _adsr.A = (byte)(env.A & 0x7); - _adsr.D = (byte)(env.D & 0x7); - _adsr.S = (byte)(env.S & 0xF); - _adsr.R = (byte)(env.R & 0x7); - _instPan = instPan; - } - - public override void Release() - { - if (State < EnvelopeState.Releasing) - { - if (_adsr.R == 0) - { - _velocity = 0; - Stop(); - } - else if (_velocity == 0) - { - Stop(); - } - else - { - _nextState = EnvelopeState.Releasing; - } - } - } - public override bool TickNote() - { - if (State >= EnvelopeState.Releasing) - { - return false; - } - if (Note.Duration <= 0) - { - return true; - } - - Note.Duration--; - if (Note.Duration == 0) - { - if (_velocity == 0) - { - Stop(); - } - else - { - State = EnvelopeState.Releasing; - } - return false; - } - return true; - } - - public override ChannelVolume GetVolume() - { - const float MAX = 0x20; - return new ChannelVolume - { - LeftVol = _panpot == GBPan.Right ? 0 : _velocity / MAX, - RightVol = _panpot == GBPan.Left ? 0 : _velocity / MAX - }; - } - public override void SetVolume(byte vol, sbyte pan) - { - int combinedPan = pan + _instPan; - if (combinedPan > 63) - { - combinedPan = 63; - } - else if (combinedPan < -64) - { - combinedPan = -64; - } - if (State < EnvelopeState.Releasing) - { - _panpot = combinedPan < -21 ? GBPan.Left : combinedPan > 20 ? GBPan.Right : GBPan.Center; - _peakVelocity = (byte)((Note.Velocity * vol) >> 10); - _sustainVelocity = (byte)(((_peakVelocity * _adsr.S) + 0xF) >> 4); // TODO - if (State == EnvelopeState.Playing) - { - _velocity = _sustainVelocity; - } - } - } - - protected void StepEnvelope() - { - void dec() - { - _processStep = 0; - if (_velocity - 1 <= _sustainVelocity) - { - _velocity = _sustainVelocity; - _nextState = EnvelopeState.Playing; - } - else if (_velocity != 0) - { - _velocity--; - } - } - void sus() - { - _processStep = 0; - } - void rel() - { - if (_adsr.R == 0) - { - _velocity = 0; - Stop(); - } - else - { - _processStep = 0; - if (_velocity - 1 <= 0) - { - _nextState = EnvelopeState.Dying; - _velocity = 0; - } - else - { - _velocity--; - } - } - } - - switch (State) - { - case EnvelopeState.Initializing: - { - _nextState = EnvelopeState.Rising; - _processStep = 0; - if ((_adsr.A | _adsr.D) == 0 || (_sustainVelocity == 0 && _peakVelocity == 0)) - { - State = EnvelopeState.Playing; - _velocity = _sustainVelocity; - return; - } - else if (_adsr.A == 0 && _adsr.S < 0xF) - { - State = EnvelopeState.Decaying; - int next = _peakVelocity - 1; - if (next < 0) - { - next = 0; - } - _velocity = (byte)next; - if (_velocity < _sustainVelocity) - { - _velocity = _sustainVelocity; - } - return; - } - else if (_adsr.A == 0) - { - State = EnvelopeState.Playing; - _velocity = _sustainVelocity; - return; - } - else - { - State = EnvelopeState.Rising; - _velocity = 1; - return; - } - } - case EnvelopeState.Rising: - { - if (++_processStep >= _adsr.A) - { - if (_nextState == EnvelopeState.Decaying) - { - State = EnvelopeState.Decaying; - dec(); return; - } - if (_nextState == EnvelopeState.Playing) - { - State = EnvelopeState.Playing; - sus(); return; - } - if (_nextState == EnvelopeState.Releasing) - { - State = EnvelopeState.Releasing; - rel(); return; - } - _processStep = 0; - if (++_velocity >= _peakVelocity) - { - if (_adsr.D == 0) - { - _nextState = EnvelopeState.Playing; - } - else if (_peakVelocity == _sustainVelocity) - { - _nextState = EnvelopeState.Playing; - _velocity = _peakVelocity; - } - else - { - _velocity = _peakVelocity; - _nextState = EnvelopeState.Decaying; - } - } - } - break; - } - case EnvelopeState.Decaying: - { - if (++_processStep >= _adsr.D) - { - if (_nextState == EnvelopeState.Playing) - { - State = EnvelopeState.Playing; - sus(); return; - } - if (_nextState == EnvelopeState.Releasing) - { - State = EnvelopeState.Releasing; - rel(); return; - } - dec(); - } - break; - } - case EnvelopeState.Playing: - { - if (++_processStep >= 1) - { - if (_nextState == EnvelopeState.Releasing) - { - State = EnvelopeState.Releasing; - rel(); return; - } - sus(); - } - break; - } - case EnvelopeState.Releasing: - { - if (++_processStep >= _adsr.R) - { - if (_nextState == EnvelopeState.Dying) - { - Stop(); - return; - } - rel(); - } - break; - } - } - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs deleted file mode 100644 index 4e655ff..0000000 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KSquareChannel : MP2KPSGChannel -{ - private float[] _pat; - - public MP2KSquareChannel(MP2KMixer mixer) - : base(mixer) - { - _pat = null!; - } - public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, SquarePattern pattern) - { - Init(owner, note, env, instPan); - _pat = pattern switch - { - SquarePattern.D12 => MP2KUtils.SquareD12, - SquarePattern.D25 => MP2KUtils.SquareD25, - SquarePattern.D50 => MP2KUtils.SquareD50, - _ => MP2KUtils.SquareD75, - }; - } - - public override void SetPitch(int pitch) - { - _frequency = 3_520 * MathF.Pow(2, ((Note.Note - 69) / 12f) + (pitch / 768f)); - } - - public override void Process(float[] buffer) - { - StepEnvelope(); - if (State == EnvelopeState.Dead) - { - return; - } - - ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do - { - float samp = _pat[_pos]; - - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos = (_pos + posDelta) & 0x7; - } while (--samplesPerBuffer > 0); - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs b/VG Music Studio - Core/GBA/MP2K/Commands.cs similarity index 79% rename from VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs rename to VG Music Studio - Core/GBA/MP2K/Commands.cs index 4959a5b..5778eec 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KCommands.cs +++ b/VG Music Studio - Core/GBA/MP2K/Commands.cs @@ -3,7 +3,7 @@ namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; -internal sealed class CallCommand : ICommand +internal class CallCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Call"; @@ -11,7 +11,7 @@ internal sealed class CallCommand : ICommand public int Offset { get; set; } } -internal sealed class EndOfTieCommand : ICommand +internal class EndOfTieCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "End Of Tie"; @@ -19,7 +19,7 @@ internal sealed class EndOfTieCommand : ICommand public int Note { get; set; } } -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; @@ -27,7 +27,7 @@ internal sealed class FinishCommand : ICommand public bool Prev { get; set; } } -internal sealed class JumpCommand : ICommand +internal class JumpCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Jump"; @@ -35,7 +35,7 @@ internal sealed class JumpCommand : ICommand public int Offset { get; set; } } -internal sealed class LFODelayCommand : ICommand +internal class LFODelayCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Delay"; @@ -43,7 +43,7 @@ internal sealed class LFODelayCommand : ICommand public byte Delay { get; set; } } -internal sealed class LFODepthCommand : ICommand +internal class LFODepthCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Depth"; @@ -51,7 +51,7 @@ internal sealed class LFODepthCommand : ICommand public byte Depth { get; set; } } -internal sealed class LFOSpeedCommand : ICommand +internal class LFOSpeedCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Speed"; @@ -59,7 +59,7 @@ internal sealed class LFOSpeedCommand : ICommand public byte Speed { get; set; } } -internal sealed class LFOTypeCommand : ICommand +internal class LFOTypeCommand : ICommand { public Color Color => Color.LightSteelBlue; public string Label => "LFO Type"; @@ -67,7 +67,7 @@ internal sealed class LFOTypeCommand : ICommand public LFOType Type { get; set; } } -internal sealed class LibraryCommand : ICommand +internal class LibraryCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Library Call"; @@ -76,7 +76,7 @@ internal sealed class LibraryCommand : ICommand public byte Command { get; set; } public byte Argument { get; set; } } -internal sealed class MemoryAccessCommand : ICommand +internal class MemoryAccessCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Memory Access"; @@ -86,7 +86,7 @@ internal sealed class MemoryAccessCommand : ICommand public byte Address { get; set; } public byte Data { get; set; } } -internal sealed class NoteCommand : ICommand +internal class NoteCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -96,7 +96,7 @@ internal sealed class NoteCommand : ICommand public byte Velocity { get; set; } public int Duration { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -104,7 +104,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -112,7 +112,7 @@ internal sealed class PitchBendCommand : ICommand public sbyte Bend { get; set; } } -internal sealed class PitchBendRangeCommand : ICommand +internal class PitchBendRangeCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend Range"; @@ -120,7 +120,7 @@ internal sealed class PitchBendRangeCommand : ICommand public byte Range { get; set; } } -internal sealed class PriorityCommand : ICommand +internal class PriorityCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Priority"; @@ -128,7 +128,7 @@ internal sealed class PriorityCommand : ICommand public byte Priority { get; set; } } -internal sealed class RepeatCommand : ICommand +internal class RepeatCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Repeat"; @@ -137,7 +137,7 @@ internal sealed class RepeatCommand : ICommand public byte Times { get; set; } public int Offset { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -145,13 +145,13 @@ internal sealed class RestCommand : ICommand public byte Rest { get; set; } } -internal sealed class ReturnCommand : ICommand +internal class ReturnCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Return"; public string Arguments => string.Empty; } -internal sealed class TempoCommand : ICommand +internal class TempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => "Tempo"; @@ -159,7 +159,7 @@ internal sealed class TempoCommand : ICommand public ushort Tempo { get; set; } } -internal sealed class TransposeCommand : ICommand +internal class TransposeCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Transpose"; @@ -167,7 +167,7 @@ internal sealed class TransposeCommand : ICommand public sbyte Transpose { get; set; } } -internal sealed class TuneCommand : ICommand +internal class TuneCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Fine Tune"; @@ -175,7 +175,7 @@ internal sealed class TuneCommand : ICommand public sbyte Tune { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -183,7 +183,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/GBA/MP2K/Enums.cs b/VG Music Studio - Core/GBA/MP2K/Enums.cs new file mode 100644 index 0000000..cb169c6 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Enums.cs @@ -0,0 +1,76 @@ +using System; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal enum EnvelopeState : byte + { + Initializing, + Rising, + Decaying, + Playing, + Releasing, + Dying, + Dead, + } + internal enum ReverbType : byte + { + None, + Normal, + Camelot1, + Camelot2, + MGAT, + } + + internal enum GoldenSunPSGType : byte + { + Square, + Saw, + Triangle, + } + internal enum LFOType : byte + { + Pitch, + Volume, + Panpot, + } + internal enum SquarePattern : byte + { + D12, + D25, + D50, + D75, + } + internal enum NoisePattern : byte + { + Fine, + Rough, + } + internal enum VoiceType : byte + { + PCM8, + Square1, + Square2, + PCM4, + Noise, + Invalid5, + Invalid6, + Invalid7, + } + [Flags] + internal enum VoiceFlags : byte + { + // These are flags that apply to the types + /// PCM8 + Fixed = 0x08, + /// Square1, Square2, PCM4, Noise + OffWithNoise = 0x08, + /// PCM8 + Reversed = 0x10, + /// PCM8 (Only in Pokémon main series games) + Compressed = 0x20, + + // These are flags that cancel out every other bit after them if set so they should only be checked with equality + KeySplit = 0x40, + Drum = 0x80, + } +} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs b/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs index 97eb540..c583a1e 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KConfig.cs @@ -14,6 +14,7 @@ public sealed class MP2KConfig : Config private const string CONFIG_FILE = "MP2K.yaml"; internal readonly byte[] ROM; + internal readonly EndianBinaryReader Reader; // TODO: Need? internal readonly string GameCode; internal readonly byte Version; @@ -30,17 +31,16 @@ public sealed class MP2KConfig : Config internal MP2KConfig(byte[] rom) { using (StreamReader fileStream = File.OpenText(ConfigUtils.CombineWithBaseDirectory(CONFIG_FILE))) - using (var ms = new MemoryStream(rom)) { string gcv = string.Empty; try { ROM = rom; - var r = new EndianBinaryReader(ms, ascii: true); - r.Stream.Position = 0xAC; - GameCode = r.ReadString_Count(4); - r.Stream.Position = 0xBC; - Version = r.ReadByte(); + Reader = new EndianBinaryReader(new MemoryStream(rom), ascii: true); + Reader.Stream.Position = 0xAC; + GameCode = Reader.ReadString_Count(4); + Reader.Stream.Position = 0xBC; + Version = Reader.ReadByte(); gcv = $"{GameCode}_{Version:X2}"; var yaml = new YamlStream(); yaml.Load(fileStream); @@ -125,7 +125,7 @@ void Load(YamlMappingNode gameToLoad) var songs = new List(); foreach (KeyValuePair song in (YamlMappingNode)kvp.Value) { - int songIndex = (int)ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, int.MaxValue); + long songIndex = ConfigUtils.ParseValue(string.Format(Strings.ConfigKeySubkey, nameof(Playlists)), song.Key.ToString(), 0, long.MaxValue); if (songs.Any(s => s.Index == songIndex)) { throw new Exception(string.Format(Strings.ErrorAlphaDreamMP2KParseGameCode, gcv, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorAlphaDreamMP2KSongRepeated, name, songIndex))); @@ -178,7 +178,7 @@ void Load(YamlMappingNode gameToLoad) { throw new BetterKeyNotFoundException(nameof(SampleRate), null); } - SampleRate = (int)ConfigUtils.ParseValue(nameof(SampleRate), sampleRateNode.ToString(), 0, MP2KUtils.FrequencyTable.Length - 1); + SampleRate = (int)ConfigUtils.ParseValue(nameof(SampleRate), sampleRateNode.ToString(), 0, Utils.FrequencyTable.Length - 1); if (reverbTypeNode is null) { @@ -211,7 +211,10 @@ void Load(YamlMappingNode gameToLoad) HasPokemonCompression = ConfigUtils.ParseBoolean(nameof(HasPokemonCompression), hasPokemonCompression.ToString()); // The complete playlist - ConfigUtils.TryCreateMasterPlaylist(Playlists); + if (!Playlists.Any(p => p.Name == "Music")) + { + Playlists.Insert(0, new Playlist(Strings.PlaylistMusic, Playlists.SelectMany(p => p.Songs).Distinct().OrderBy(s => s.Index))); + } } catch (BetterKeyNotFoundException ex) { @@ -232,12 +235,14 @@ public override string GetGameName() { return Name; } - public override string GetSongName(int index) + public override string GetSongName(long index) { - if (TryGetFirstSong(index, out Song s)) - { - return s.Name; - } - return index.ToString(); + Song? s = GetFirstSong(index); + return s is not null ? s.Name : index.ToString(); + } + + public override void Dispose() + { + Reader.Stream.Dispose(); } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs index 43c40ba..43d5264 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs @@ -12,9 +12,9 @@ public sealed class MP2KEngine : Engine public MP2KEngine(byte[] rom) { - if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) + if (rom.Length > GBAUtils.CartridgeCapacity) { - throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); + throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CartridgeCapacity:X7} bytes."); } Config = new MP2KConfig(rom); diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs deleted file mode 100644 index 86029a6..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEnums.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal enum EnvelopeState : byte -{ - Initializing, - Rising, - Decaying, - Playing, - Releasing, - Dying, - Dead, -} -internal enum ReverbType : byte -{ - None, - Normal, - Camelot1, - Camelot2, - MGAT, -} - -internal enum GoldenSunPSGType : byte -{ - Square, - Saw, - Triangle, -} -internal enum LFOType : byte -{ - Pitch, - Volume, - Panpot, -} -internal enum SquarePattern : byte -{ - D12, - D25, - D50, - D75, -} -internal enum NoisePattern : byte -{ - Fine, - Rough, -} -internal enum VoiceType : byte -{ - PCM8, - Square1, - Square2, - PCM4, - Noise, - Invalid5, - Invalid6, - Invalid7, -} -[Flags] -internal enum VoiceFlags : byte -{ - // These are flags that apply to the types - /// PCM8 - Fixed = 0x08, - /// Square1, Square2, PCM4, Noise - OffWithNoise = 0x08, - /// PCM8 - Reversed = 0x10, - /// PCM8 (Only in Pokémon main series games) - Compressed = 0x20, - - // These are flags that cancel out every other bit after them if set so they should only be checked with equality - KeySplit = 0x40, - Drum = 0x80, -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs index b336371..1c8da7c 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong.cs @@ -1,46 +1,535 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; internal sealed partial class MP2KLoadedSong : ILoadedSong { - public List[] Events { get; } + public List[] Events { get; private set; } public long MaxTicks { get; private set; } - public int LongestTrack; + public long ElapsedTicks { get; internal set; } + internal int LongestTrack; private readonly MP2KPlayer _player; - private readonly int _voiceTableOffset; - public readonly MP2KTrack[] Tracks; + public readonly int VoiceTableOffset; + internal readonly Track[] Tracks; - public MP2KLoadedSong(MP2KPlayer player, int index) + public MP2KLoadedSong(long index, MP2KPlayer player, MP2KConfig cfg, int? oldVoiceTableOffset, string?[] voiceTypeCache) { _player = player; - MP2KConfig cfg = player.Config; - var entry = SongEntry.Get(cfg.ROM, cfg.SongTableOffsets[0], index); - int headerOffset = entry.HeaderOffset - GBAUtils.CARTRIDGE_OFFSET; - - var header = SongHeader.Get(cfg.ROM, headerOffset, out int tracksOffset); - _voiceTableOffset = header.VoiceTableOffset - GBAUtils.CARTRIDGE_OFFSET; + ref SongEntry entry = ref MemoryMarshal.AsRef(cfg.ROM.AsSpan(cfg.SongTableOffsets[0] + ((int)index * 8))); + cfg.Reader.Stream.Position = entry.HeaderOffset - GBA.GBAUtils.CartridgeOffset; + SongHeader header = cfg.Reader.ReadObject(); // TODO: Can I RefStruct this? If not, should still ditch reader and use pointer + VoiceTableOffset = header.VoiceTableOffset - GBA.GBAUtils.CartridgeOffset; + if (oldVoiceTableOffset != VoiceTableOffset) + { + Array.Clear(voiceTypeCache); + } - Tracks = new MP2KTrack[header.NumTracks]; + Tracks = new Track[header.NumTracks]; Events = new List[header.NumTracks]; for (byte trackIndex = 0; trackIndex < header.NumTracks; trackIndex++) { - int trackStart = SongHeader.GetTrackOffset(cfg.ROM, tracksOffset, trackIndex) - GBAUtils.CARTRIDGE_OFFSET; - Tracks[trackIndex] = new MP2KTrack(trackIndex, trackStart); + int trackStart = header.TrackOffsets[trackIndex] - GBA.GBAUtils.CartridgeOffset; + Tracks[trackIndex] = new Track(trackIndex, trackStart); + Events[trackIndex] = new List(); - AddTrackEvents(trackIndex, trackStart); + byte runCmd = 0, prevKey = 0, prevVelocity = 0x7F; + int callStackDepth = 0; + AddEvents(trackStart, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); } } - public void CheckVoiceTypeCache(ref int? old, string?[] voiceTypeCache) + private static void AddEvent(List trackEvents, long offset, ICommand command) { - if (old != _voiceTableOffset) + trackEvents.Add(new SongEvent(offset, command)); + } + private static bool EventExists(List trackEvents, long offset) + { + return trackEvents.Any(e => e.Offset == offset); + } + private static void EmulateNote(List trackEvents, long offset, byte key, byte velocity, byte addedDuration, + ref byte runCmd, ref byte prevKey, ref byte prevVelocity) + { + prevKey = key; + prevVelocity = velocity; + if (!EventExists(trackEvents, offset)) { - old = _voiceTableOffset; - Array.Clear(voiceTypeCache); + AddEvent(trackEvents, offset, new NoteCommand + { + Note = key, + Velocity = velocity, + Duration = runCmd == 0xCF ? -1 : (Utils.RestTable[runCmd - 0xCF] + addedDuration), + }); + } + } + private void AddEvents(long startOffset, MP2KConfig cfg, byte trackIndex, + ref byte runCmd, ref byte prevKey, ref byte prevVelocity, ref int callStackDepth) + { + cfg.Reader.Stream.Position = startOffset; + List trackEvents = Events[trackIndex]; + + Span peek = stackalloc byte[3]; + bool cont = true; + while (cont) + { + long offset = cfg.Reader.Stream.Position; + + byte cmd = cfg.Reader.ReadByte(); + if (cmd >= 0xBD) // Commands that work within running status + { + runCmd = cmd; + } + + #region TIE & Notes + + if (runCmd >= 0xCF && cmd <= 0x7F) // Within running status + { + byte velocity, addedDuration; + cfg.Reader.PeekBytes(peek.Slice(0, 2)); + if (peek[0] > 0x7F) + { + velocity = prevVelocity; + addedDuration = 0; + } + else if (peek[1] > 3) + { + velocity = cfg.Reader.ReadByte(); + addedDuration = 0; + } + else + { + velocity = cfg.Reader.ReadByte(); + addedDuration = cfg.Reader.ReadByte(); + } + EmulateNote(trackEvents, offset, cmd, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); + } + else if (cmd >= 0xCF) + { + byte key, velocity, addedDuration; + cfg.Reader.PeekBytes(peek); + if (peek[0] > 0x7F) + { + key = prevKey; + velocity = prevVelocity; + addedDuration = 0; + } + else if (peek[1] > 0x7F) + { + key = cfg.Reader.ReadByte(); + velocity = prevVelocity; + addedDuration = 0; + } + // TIE (0xCF) cannot have an added duration so it needs to stop here + else if (cmd == 0xCF || peek[2] > 3) + { + key = cfg.Reader.ReadByte(); + velocity = cfg.Reader.ReadByte(); + addedDuration = 0; + } + else + { + key = cfg.Reader.ReadByte(); + velocity = cfg.Reader.ReadByte(); + addedDuration = cfg.Reader.ReadByte(); + } + EmulateNote(trackEvents, offset, key, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); + } + + #endregion + + #region Rests + + else if (cmd >= 0x80 && cmd <= 0xB0) + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new RestCommand { Rest = Utils.RestTable[cmd - 0x80] }); + } + } + + #endregion + + #region Commands + + else if (runCmd < 0xCF && cmd <= 0x7F) + { + switch (runCmd) + { + case 0xBD: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VoiceCommand { Voice = cmd }); + } + break; + } + case 0xBE: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VolumeCommand { Volume = cmd }); + } + break; + } + case 0xBF: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PanpotCommand { Panpot = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xC0: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendCommand { Bend = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xC1: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendRangeCommand { Range = cmd }); + } + break; + } + case 0xC2: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOSpeedCommand { Speed = cmd }); + } + break; + } + case 0xC3: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODelayCommand { Delay = cmd }); + } + break; + } + case 0xC4: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODepthCommand { Depth = cmd }); + } + break; + } + case 0xC5: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOTypeCommand { Type = (LFOType)cmd }); + } + break; + } + case 0xC8: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TuneCommand { Tune = (sbyte)(cmd - 0x40) }); + } + break; + } + case 0xCD: + { + byte arg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LibraryCommand { Command = cmd, Argument = arg }); + } + break; + } + case 0xCE: + { + prevKey = cmd; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new EndOfTieCommand { Note = cmd }); + } + break; + } + default: throw new MP2KInvalidRunningStatusCMDException(trackIndex, (int)offset, runCmd); + } + } + else if (cmd > 0xB0 && cmd < 0xCF) + { + switch (cmd) + { + case 0xB1: + case 0xB6: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new FinishCommand { Prev = cmd == 0xB6 }); + } + cont = false; + break; + } + case 0xB2: + { + int jumpOffset = cfg.Reader.ReadInt32() - GBA.GBAUtils.CartridgeOffset; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new JumpCommand { Offset = jumpOffset }); + if (!EventExists(trackEvents, jumpOffset)) + { + AddEvents(jumpOffset, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); + } + } + cont = false; + break; + } + case 0xB3: + { + int callOffset = cfg.Reader.ReadInt32() - GBA.GBAUtils.CartridgeOffset; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new CallCommand { Offset = callOffset }); + } + if (callStackDepth < 3) + { + long backup = cfg.Reader.Stream.Position; + callStackDepth++; + AddEvents(callOffset, cfg, trackIndex, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); + cfg.Reader.Stream.Position = backup; + } + else + { + throw new MP2KTooManyNestedCallsException(trackIndex); + } + break; + } + case 0xB4: + { + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new ReturnCommand()); + } + if (callStackDepth != 0) + { + cont = false; + callStackDepth--; + } + break; + } + /*case 0xB5: // TODO: Logic so this isn't an infinite loop + { + byte times = config.Reader.ReadByte(); + int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; + if (!EventExists(offset, trackEvents)) + { + AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); + } + break; + }*/ + case 0xB9: + { + byte op = cfg.Reader.ReadByte(); + byte address = cfg.Reader.ReadByte(); + byte data = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new MemoryAccessCommand { Operator = op, Address = address, Data = data }); + } + break; + } + case 0xBA: + { + byte priority = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PriorityCommand { Priority = priority }); + } + break; + } + case 0xBB: + { + byte tempoArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TempoCommand { Tempo = (ushort)(tempoArg * 2) }); + } + break; + } + case 0xBC: + { + sbyte transpose = cfg.Reader.ReadSByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TransposeCommand { Transpose = transpose }); + } + break; + } + // Commands that work within running status: + case 0xBD: + { + byte voice = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VoiceCommand { Voice = voice }); + } + break; + } + case 0xBE: + { + byte volume = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new VolumeCommand { Volume = volume }); + } + break; + } + case 0xBF: + { + byte panArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); + } + break; + } + case 0xC0: + { + byte bendArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendCommand { Bend = (sbyte)(bendArg - 0x40) }); + } + break; + } + case 0xC1: + { + byte range = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new PitchBendRangeCommand { Range = range }); + } + break; + } + case 0xC2: + { + byte speed = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOSpeedCommand { Speed = speed }); + } + break; + } + case 0xC3: + { + byte delay = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODelayCommand { Delay = delay }); + } + break; + } + case 0xC4: + { + byte depth = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFODepthCommand { Depth = depth }); + } + break; + } + case 0xC5: + { + byte type = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LFOTypeCommand { Type = (LFOType)type }); + } + break; + } + case 0xC8: + { + byte tuneArg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new TuneCommand { Tune = (sbyte)(tuneArg - 0x40) }); + } + break; + } + case 0xCD: + { + byte command = cfg.Reader.ReadByte(); + byte arg = cfg.Reader.ReadByte(); + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new LibraryCommand { Command = command, Argument = arg }); + } + break; + } + case 0xCE: + { + int key = cfg.Reader.PeekByte() <= 0x7F ? (prevKey = cfg.Reader.ReadByte()) : -1; + if (!EventExists(trackEvents, offset)) + { + AddEvent(trackEvents, offset, new EndOfTieCommand { Note = key }); + } + break; + } + default: throw new MP2KInvalidCMDException(trackIndex, (int)offset, cmd); + } + } + + #endregion + } + } + + internal void SetTicks() + { + MaxTicks = 0; + bool u = false; + for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) + { + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = Tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + if (track.CallStackDepth == 0 && e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + _player.ExecuteNext(track, ref u); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + LongestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.StopAllChannels(); + } + } + + public void Dispose() + { + for (int i = 0; i < Tracks.Length; i++) + { + Tracks[i].StopAllChannels(); } } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs deleted file mode 100644 index ab62db7..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Events.cs +++ /dev/null @@ -1,546 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed partial class MP2KLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex].Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex].Exists(e => e.Offset == cmdOffset); - } - - private void EmulateNote(byte trackIndex, long cmdOffset, byte key, byte velocity, byte addedDuration, ref byte runCmd, ref byte prevKey, ref byte prevVelocity) - { - prevKey = key; - prevVelocity = velocity; - if (EventExists(trackIndex, cmdOffset)) - { - return; - } - - AddEvent(trackIndex, cmdOffset, new NoteCommand - { - Note = key, - Velocity = velocity, - Duration = runCmd == 0xCF ? -1 : (MP2KUtils.RestTable[runCmd - 0xCF] + addedDuration), - }); - } - - private void AddTrackEvents(byte trackIndex, long trackStart) - { - Events[trackIndex] = new List(); - byte runCmd = 0; - byte prevKey = 0; - byte prevVelocity = 0x7F; - int callStackDepth = 0; - AddEvents(trackIndex, trackStart, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - } - private void AddEvents(byte trackIndex, long startOffset, ref byte runCmd, ref byte prevKey, ref byte prevVelocity, ref int callStackDepth) - { - using (var ms = new MemoryStream(_player.Config.ROM)) - { - var r = new EndianBinaryReader(ms, ascii: true); - r.Stream.Position = startOffset; - - Span peek = stackalloc byte[3]; - bool cont = true; - while (cont) - { - long offset = r.Stream.Position; - - byte cmd = r.ReadByte(); - if (cmd >= 0xBD) // Commands that work within running status - { - runCmd = cmd; - } - - #region TIE & Notes - - if (runCmd >= 0xCF && cmd <= 0x7F) // Within running status - { - byte velocity, addedDuration; - r.PeekBytes(peek.Slice(0, 2)); - if (peek[0] > 0x7F) - { - velocity = prevVelocity; - addedDuration = 0; - } - else if (peek[1] > 3) - { - velocity = r.ReadByte(); - addedDuration = 0; - } - else - { - velocity = r.ReadByte(); - addedDuration = r.ReadByte(); - } - EmulateNote(trackIndex, offset, cmd, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); - } - else if (cmd >= 0xCF) - { - byte key, velocity, addedDuration; - r.PeekBytes(peek); - if (peek[0] > 0x7F) - { - key = prevKey; - velocity = prevVelocity; - addedDuration = 0; - } - else if (peek[1] > 0x7F) - { - key = r.ReadByte(); - velocity = prevVelocity; - addedDuration = 0; - } - // TIE (0xCF) cannot have an added duration so it needs to stop here - else if (cmd == 0xCF || peek[2] > 3) - { - key = r.ReadByte(); - velocity = r.ReadByte(); - addedDuration = 0; - } - else - { - key = r.ReadByte(); - velocity = r.ReadByte(); - addedDuration = r.ReadByte(); - } - EmulateNote(trackIndex, offset, key, velocity, addedDuration, ref runCmd, ref prevKey, ref prevVelocity); - } - - #endregion - - #region Rests - - else if (cmd is >= 0x80 and <= 0xB0) - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new RestCommand { Rest = MP2KUtils.RestTable[cmd - 0x80] }); - } - } - - #endregion - - #region Commands - - else if (runCmd < 0xCF && cmd <= 0x7F) - { - switch (runCmd) - { - case 0xBD: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VoiceCommand { Voice = cmd }); - } - break; - } - case 0xBE: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VolumeCommand { Volume = cmd }); - } - break; - } - case 0xBF: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PanpotCommand { Panpot = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xC0: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendCommand { Bend = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xC1: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendRangeCommand { Range = cmd }); - } - break; - } - case 0xC2: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOSpeedCommand { Speed = cmd }); - } - break; - } - case 0xC3: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODelayCommand { Delay = cmd }); - } - break; - } - case 0xC4: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODepthCommand { Depth = cmd }); - } - break; - } - case 0xC5: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOTypeCommand { Type = (LFOType)cmd }); - } - break; - } - case 0xC8: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TuneCommand { Tune = (sbyte)(cmd - 0x40) }); - } - break; - } - case 0xCD: - { - byte arg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LibraryCommand { Command = cmd, Argument = arg }); - } - break; - } - case 0xCE: - { - prevKey = cmd; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new EndOfTieCommand { Note = cmd }); - } - break; - } - default: throw new MP2KInvalidRunningStatusCMDException(trackIndex, (int)offset, runCmd); - } - } - else if (cmd is > 0xB0 and < 0xCF) - { - switch (cmd) - { - case 0xB1: - case 0xB6: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new FinishCommand { Prev = cmd == 0xB6 }); - } - cont = false; - break; - } - case 0xB2: - { - int jumpOffset = r.ReadInt32() - GBAUtils.CARTRIDGE_OFFSET; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new JumpCommand { Offset = jumpOffset }); - if (!EventExists(trackIndex, jumpOffset)) - { - AddEvents(trackIndex, jumpOffset, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - } - } - cont = false; - break; - } - case 0xB3: - { - int callOffset = r.ReadInt32() - GBAUtils.CARTRIDGE_OFFSET; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new CallCommand { Offset = callOffset }); - } - if (callStackDepth < 3) - { - long backup = r.Stream.Position; - callStackDepth++; - AddEvents(trackIndex, callOffset, ref runCmd, ref prevKey, ref prevVelocity, ref callStackDepth); - r.Stream.Position = backup; - } - else - { - throw new MP2KTooManyNestedCallsException(trackIndex); - } - break; - } - case 0xB4: - { - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new ReturnCommand()); - } - if (callStackDepth != 0) - { - cont = false; - callStackDepth--; - } - break; - } - /*case 0xB5: // TODO: Logic so this isn't an infinite loop - { - byte times = config.Reader.ReadByte(); - int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; - if (!EventExists(offset, trackEvents)) - { - AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); - } - break; - }*/ - case 0xB9: - { - byte op = r.ReadByte(); - byte address = r.ReadByte(); - byte data = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new MemoryAccessCommand { Operator = op, Address = address, Data = data }); - } - break; - } - case 0xBA: - { - byte priority = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PriorityCommand { Priority = priority }); - } - break; - } - case 0xBB: - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TempoCommand { Tempo = (ushort)(tempoArg * 2) }); - } - break; - } - case 0xBC: - { - sbyte transpose = r.ReadSByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TransposeCommand { Transpose = transpose }); - } - break; - } - // Commands that work within running status: - case 0xBD: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xBE: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xBF: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); - } - break; - } - case 0xC0: - { - byte bendArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendCommand { Bend = (sbyte)(bendArg - 0x40) }); - } - break; - } - case 0xC1: - { - byte range = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new PitchBendRangeCommand { Range = range }); - } - break; - } - case 0xC2: - { - byte speed = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOSpeedCommand { Speed = speed }); - } - break; - } - case 0xC3: - { - byte delay = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODelayCommand { Delay = delay }); - } - break; - } - case 0xC4: - { - byte depth = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFODepthCommand { Depth = depth }); - } - break; - } - case 0xC5: - { - byte type = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LFOTypeCommand { Type = (LFOType)type }); - } - break; - } - case 0xC8: - { - byte tuneArg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new TuneCommand { Tune = (sbyte)(tuneArg - 0x40) }); - } - break; - } - case 0xCD: - { - byte command = r.ReadByte(); - byte arg = r.ReadByte(); - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new LibraryCommand { Command = command, Argument = arg }); - } - break; - } - case 0xCE: - { - int key = r.PeekByte() <= 0x7F ? (prevKey = r.ReadByte()) : -1; - if (!EventExists(trackIndex, offset)) - { - AddEvent(trackIndex, offset, new EndOfTieCommand { Note = key }); - } - break; - } - default: throw new MP2KInvalidCMDException(trackIndex, (int)offset, cmd); - } - } - - #endregion - } - } - } - - public void SetTicks() - { - MaxTicks = 0; - bool u = false; - for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) - { - List evs = Events[trackIndex]; - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - MP2KTrack track = Tracks[trackIndex]; - track.Init(); - - _player.ElapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - if (track.CallStackDepth == 0 && e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(_player.ElapsedTicks); - ExecuteNext(track, ref u); - if (track.Stopped) - { - break; - } - - _player.ElapsedTicks += track.Rest; - track.Rest = 0; - } - if (_player.ElapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = _player.ElapsedTicks; - } - track.StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - bool u = false; - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - while (_player.TempoStack >= 150) - { - _player.TempoStack -= 150; - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - MP2KTrack track = Tracks[trackIndex]; - if (!track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track, ref u); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < Tracks.Length; i++) - { - Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs index 1d6c4f0..4a9cd2d 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_MIDI.cs @@ -1,8 +1,7 @@ -using Kermalis.MIDI; +using Kermalis.VGMusicStudio.MIDI; using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; @@ -11,14 +10,7 @@ public sealed class MIDISaveArgs { public bool SaveCommandsBeforeTranspose; // TODO: I forgor why I would want this public bool ReverseVolume; - public (int AbsoluteTick, (byte Numerator, byte Denominator))[] TimeSignatures; - - public MIDISaveArgs(bool saveCmdsBeforeTranspose, bool reverseVol, (int, (byte, byte))[] timeSignatures) - { - SaveCommandsBeforeTranspose = saveCmdsBeforeTranspose; - ReverseVolume = reverseVol; - TimeSignatures = timeSignatures; - } + public List<(int AbsoluteTick, (byte Numerator, byte Denominator))> TimeSignatures; } internal sealed partial class MP2KLoadedSong @@ -43,25 +35,22 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } var midi = new MIDIFile(MIDIFormat.Format1, TimeDivisionValue.CreatePPQN(24), Events.Length + 1); - var metaTrack = new MIDITrackChunk(); - midi.AddChunk(metaTrack); + MIDITrackChunk metaTrack = midi.CreateTrack(); foreach ((int AbsoluteTick, (byte Numerator, byte Denominator)) e in args.TimeSignatures) { - metaTrack.InsertMessage(e.AbsoluteTick, MetaMessage.CreateTimeSignatureMessage(e.Item2.Numerator, e.Item2.Denominator)); + metaTrack.Insert(e.AbsoluteTick, MetaMessage.CreateTimeSignatureMessage(e.Item2.Numerator, e.Item2.Denominator)); } for (byte trackIndex = 0; trackIndex < Events.Length; trackIndex++) { - var track = new MIDITrackChunk(); - midi.AddChunk(track); + MIDITrackChunk track = midi.CreateTrack(); bool foundTranspose = false; int endOfPattern = 0; long startOfPatternTicks = 0; long endOfPatternTicks = 0; sbyte transpose = 0; - int? endTicks = null; var playing = new List(); List trackEvents = Events[trackIndex]; for (int i = 0; i < trackEvents.Count; i++) @@ -113,15 +102,14 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) { key = 0x7F; } - track.InsertMessage(ticks, new NoteOnMessage(trackIndex, (MIDINote)key, 0)); - //track.InsertMessage(ticks, new NoteOffMessage(trackIndex, (MIDINote)key, 0)); + track.Insert(ticks, new NoteOnMessage(trackIndex, (MIDINote)key, 0)); playing.Remove(nc); } break; } case FinishCommand _: { - endTicks = ticks; + track.Insert(ticks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); goto endOfTrack; } case JumpCommand c: @@ -129,42 +117,42 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) if (trackIndex == 0) { int jumpCmd = trackEvents.FindIndex(ev => ev.Offset == c.Offset); - metaTrack.InsertMessage((int)trackEvents[jumpCmd].Ticks[0], MetaMessage.CreateTextMessage(MetaMessageType.Marker, "[")); - metaTrack.InsertMessage(ticks, MetaMessage.CreateTextMessage(MetaMessageType.Marker, "]")); + metaTrack.Insert((int)trackEvents[jumpCmd].Ticks[0], new MetaMessage(MetaMessageType.Marker, new byte[] { (byte)'[' })); + metaTrack.Insert(ticks, new MetaMessage(MetaMessageType.Marker, new byte[] { (byte)']' })); } break; } case LFODelayCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)26, c.Delay)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)26, c.Delay)); break; } case LFODepthCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.ModulationWheel, c.Depth)); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.ModulationWheel, c.Depth)); break; } case LFOSpeedCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)21, c.Speed)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)21, c.Speed)); break; } case LFOTypeCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)22, (byte)c.Type)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)22, (byte)c.Type)); break; } case LibraryCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)30, c.Command)); - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)29, c.Argument)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)30, c.Command)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)29, c.Argument)); break; } case MemoryAccessCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.EffectControl2, c.Operator)); - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)14, c.Address)); - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.EffectControl1, c.Data)); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.EffectControl2, c.Operator)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)14, c.Address)); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.EffectControl1, c.Data)); break; } case NoteCommand c: @@ -178,11 +166,10 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) { note = 0x7F; } - track.InsertMessage(ticks, new NoteOnMessage(trackIndex, (MIDINote)note, c.Velocity)); + track.Insert(ticks, new NoteOnMessage(trackIndex, (MIDINote)note, c.Velocity)); if (c.Duration != -1) { - track.InsertMessage(ticks + c.Duration, new NoteOnMessage(trackIndex, (MIDINote)note, 0)); - //track.InsertMessage(ticks + c.Duration, new NoteOffMessage(trackIndex, (MIDINote)note, 0)); + track.Insert(ticks + c.Duration, new NoteOnMessage(trackIndex, (MIDINote)note, 0)); } else { @@ -192,22 +179,22 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } case PanpotCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.Pan, (byte)(c.Panpot + 0x40))); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.Pan, (byte)(c.Panpot + 0x40))); break; } case PitchBendCommand c: { - track.InsertMessage(ticks, new PitchBendMessage(trackIndex, 0, (byte)(c.Bend + 0x40))); + track.Insert(ticks, new PitchBendMessage(trackIndex, 0, (byte)(c.Bend + 0x40))); break; } case PitchBendRangeCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)20, c.Range)); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)20, c.Range)); break; } case PriorityCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.ChannelVolumeLSB, c.Priority)); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.ChannelVolumeLSB, c.Priority)); break; } case ReturnCommand _: @@ -223,7 +210,7 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } case TempoCommand c: { - metaTrack.InsertMessage(ticks, MetaMessage.CreateTempoMessage(c.Tempo)); + metaTrack.Insert(ticks, MetaMessage.CreateTempoMessage(c.Tempo)); break; } case TransposeCommand c: @@ -233,12 +220,12 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } case TuneCommand c: { - track.InsertMessage(ticks, new ControllerMessage(trackIndex, (ControllerType)24, (byte)(c.Tune + 0x40))); + track.Insert(ticks, new ControllerMessage(trackIndex, (ControllerType)24, (byte)(c.Tune + 0x40))); break; } case VoiceCommand c: { - track.InsertMessage(ticks, new ProgramChangeMessage(trackIndex, (MIDIProgram)c.Voice)); + track.Insert(ticks, new ProgramChangeMessage(trackIndex, (MIDIProgram)c.Voice)); break; } case VolumeCommand c: @@ -250,20 +237,17 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) { volume++; } - track.InsertMessage(ticks, new ControllerMessage(trackIndex, ControllerType.ChannelVolume, (byte)volume)); + track.Insert(ticks, new ControllerMessage(trackIndex, ControllerType.ChannelVolume, (byte)volume)); break; } } } endOfTrack: - track.InsertMessage(endTicks ?? track.NumTicks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); + ; } - metaTrack.InsertMessage(metaTrack.NumTicks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); + metaTrack.Insert(metaTrack.NumTicks, new MetaMessage(MetaMessageType.EndOfTrack, Array.Empty())); - using (FileStream fs = File.Create(fileName)) - { - midi.Save(fs); - } + midi.Save(fileName); } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs deleted file mode 100644 index b3c038c..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs +++ /dev/null @@ -1,458 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed partial class MP2KLoadedSong -{ - private void TryPlayNote(MP2KTrack track, byte note, byte velocity, byte addedDuration) - { - int n = note + track.Transpose; - if (n < 0) - { - n = 0; - } - else if (n > 0x7F) - { - n = 0x7F; - } - note = (byte)n; - track.PrevNote = note; - track.PrevVelocity = velocity; - // Tracks do not play unless they have had a voice change event - if (track.Ready) - { - PlayNote(_player.Config.ROM, track, note, velocity, addedDuration); - } - } - private void PlayNote(byte[] rom, MP2KTrack track, byte note, byte velocity, byte addedDuration) - { - bool fromDrum = false; - int offset = _voiceTableOffset + (track.Voice * 12); - while (true) - { - var v = new VoiceEntry(rom.AsSpan(offset)); - if (v.Type == (int)VoiceFlags.KeySplit) - { - fromDrum = false; // In case there is a multi within a drum - byte inst = rom[v.Int8 - GBAUtils.CARTRIDGE_OFFSET + note]; - offset = v.Int4 - GBAUtils.CARTRIDGE_OFFSET + (inst * 12); - } - else if (v.Type == (int)VoiceFlags.Drum) - { - fromDrum = true; - offset = v.Int4 - GBAUtils.CARTRIDGE_OFFSET + (note * 12); - } - else - { - var ni = new NoteInfo - { - Duration = track.RunCmd == 0xCF ? -1 : (MP2KUtils.RestTable[track.RunCmd - 0xCF] + addedDuration), - Velocity = velocity, - OriginalNote = note, - Note = fromDrum ? v.RootNote : note, - }; - var type = (VoiceType)(v.Type & 0x7); - int instPan = v.Pan; - instPan = (instPan & 0x80) != 0 ? instPan - 0xC0 : 0; - switch (type) - { - case VoiceType.PCM8: - { - bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; - bool bCompressed = _player.Config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); - _player.MMixer.AllocPCM8Channel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - bFixed, bCompressed, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } - case VoiceType.Square1: - case VoiceType.Square2: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (SquarePattern)v.Int4); - return; - } - case VoiceType.PCM4: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } - case VoiceType.Noise: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (NoisePattern)v.Int4); - return; - } - } - return; // Prevent infinite loop with invalid instruments - } - } - } - public void ExecuteNext(MP2KTrack track, ref bool update) - { - byte[] rom = _player.Config.ROM; - byte cmd = rom[track.DataOffset++]; - if (cmd >= 0xBD) // Commands that work within running status - { - track.RunCmd = cmd; - } - - if (track.RunCmd >= 0xCF && cmd <= 0x7F) // Within running status - { - byte peek0 = rom[track.DataOffset]; - byte peek1 = rom[track.DataOffset + 1]; - byte velocity, addedDuration; - if (peek0 > 0x7F) - { - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (peek1 > 3) - { - track.DataOffset++; - velocity = peek0; - addedDuration = 0; - } - else - { - track.DataOffset += 2; - velocity = peek0; - addedDuration = peek1; - } - TryPlayNote(track, cmd, velocity, addedDuration); - } - else if (cmd >= 0xCF) - { - byte peek0 = rom[track.DataOffset]; - byte peek1 = rom[track.DataOffset + 1]; - byte peek2 = rom[track.DataOffset + 2]; - byte key, velocity, addedDuration; - if (peek0 > 0x7F) - { - key = track.PrevNote; - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (peek1 > 0x7F) - { - track.DataOffset++; - key = peek0; - velocity = track.PrevVelocity; - addedDuration = 0; - } - else if (cmd == 0xCF || peek2 > 3) - { - track.DataOffset += 2; - key = peek0; - velocity = peek1; - addedDuration = 0; - } - else - { - track.DataOffset += 3; - key = peek0; - velocity = peek1; - addedDuration = peek2; - } - TryPlayNote(track, key, velocity, addedDuration); - } - else if (cmd >= 0x80 && cmd <= 0xB0) - { - track.Rest = MP2KUtils.RestTable[cmd - 0x80]; - } - else if (track.RunCmd < 0xCF && cmd <= 0x7F) - { - switch (track.RunCmd) - { - case 0xBD: - { - track.Voice = cmd; - //track.Ready = true; // This is unnecessary because if we're in running status of a voice command, then Ready was already set - break; - } - case 0xBE: - { - track.Volume = cmd; - update = true; - break; - } - case 0xBF: - { - track.Panpot = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xC0: - { - track.PitchBend = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xC1: - { - track.PitchBendRange = cmd; - update = true; - break; - } - case 0xC2: - { - track.LFOSpeed = cmd; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC3: - { - track.LFODelay = cmd; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC4: - { - track.LFODepth = cmd; - update = true; - break; - } - case 0xC5: - { - track.LFOType = (LFOType)cmd; - update = true; - break; - } - case 0xC8: - { - track.Tune = (sbyte)(cmd - 0x40); - update = true; - break; - } - case 0xCD: - { - track.DataOffset++; - break; - } - case 0xCE: - { - track.PrevNote = cmd; - int k = cmd + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.ReleaseChannels(k); - break; - } - default: throw new MP2KInvalidRunningStatusCMDException(track.Index, track.DataOffset - 1, track.RunCmd); - } - } - else if (cmd > 0xB0 && cmd < 0xCF) - { - switch (cmd) - { - case 0xB1: - case 0xB6: - { - track.Stopped = true; - //track.ReleaseAllTieingChannels(); // Necessary? - break; - } - case 0xB2: - { - track.DataOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBAUtils.CARTRIDGE_OFFSET; - break; - } - case 0xB3: - { - if (track.CallStackDepth >= 3) - { - throw new MP2KTooManyNestedCallsException(track.Index); - } - - int callOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBAUtils.CARTRIDGE_OFFSET; - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackDepth++; - track.DataOffset = callOffset; - break; - } - case 0xB4: - { - if (track.CallStackDepth != 0) - { - track.CallStackDepth--; - track.DataOffset = track.CallStack[track.CallStackDepth]; - } - break; - } - /*case 0xB5: // TODO: Logic so this isn't an infinite loop - { - byte times = config.Reader.ReadByte(); - int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; - if (!EventExists(offset)) - { - AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); - } - break; - }*/ - case 0xB9: - { - track.DataOffset += 3; - break; - } - case 0xBA: - { - track.Priority = rom[track.DataOffset++]; - break; - } - case 0xBB: - { - _player.Tempo = (ushort)(rom[track.DataOffset++] * 2); - break; - } - case 0xBC: - { - track.Transpose = (sbyte)rom[track.DataOffset++]; - break; - } - // Commands that work within running status: - case 0xBD: - { - track.Voice = rom[track.DataOffset++]; - track.Ready = true; - break; - } - case 0xBE: - { - track.Volume = rom[track.DataOffset++]; - update = true; - break; - } - case 0xBF: - { - track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xC0: - { - track.PitchBend = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xC1: - { - track.PitchBendRange = rom[track.DataOffset++]; - update = true; - break; - } - case 0xC2: - { - track.LFOSpeed = rom[track.DataOffset++]; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC3: - { - track.LFODelay = rom[track.DataOffset++]; - track.LFOPhase = 0; - track.LFODelayCount = 0; - update = true; - break; - } - case 0xC4: - { - track.LFODepth = rom[track.DataOffset++]; - update = true; - break; - } - case 0xC5: - { - track.LFOType = (LFOType)rom[track.DataOffset++]; - update = true; - break; - } - case 0xC8: - { - track.Tune = (sbyte)(rom[track.DataOffset++] - 0x40); - update = true; - break; - } - case 0xCD: - { - track.DataOffset += 2; - break; - } - case 0xCE: - { - byte peek = rom[track.DataOffset]; - if (peek > 0x7F) - { - track.ReleaseChannels(track.PrevNote); - } - else - { - track.DataOffset++; - track.PrevNote = peek; - int k = peek + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.ReleaseChannels(k); - } - break; - } - default: throw new MP2KInvalidCMDException(track.Index, track.DataOffset - 1, cmd); - } - } - } - - public void UpdateInstrumentCache(byte voice, out string str) - { - byte t = _player.Config.ROM[_voiceTableOffset + (voice * 12)]; - if (t == (byte)VoiceFlags.KeySplit) - { - str = "Key Split"; - } - else if (t == (byte)VoiceFlags.Drum) - { - str = "Drum"; - } - else - { - switch ((VoiceType)(t & 0x7)) // Disregard the other flags - { - case VoiceType.PCM8: str = "PCM8"; break; - case VoiceType.Square1: str = "Square 1"; break; - case VoiceType.Square2: str = "Square 2"; break; - case VoiceType.PCM4: str = "PCM4"; break; - case VoiceType.Noise: str = "Noise"; break; - case VoiceType.Invalid5: str = "Invalid 5"; break; - case VoiceType.Invalid6: str = "Invalid 6"; break; - default: str = "Invalid 7"; break; // VoiceType.Invalid7 - } - } - } - public void UpdateSongState(SongState info, string?[] voiceTypeCache) - { - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - Tracks[trackIndex].UpdateSongState(info.Tracks[trackIndex], this, voiceTypeCache); - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index 8997f70..638301b 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -2,6 +2,9 @@ using NAudio.Wave; using System; using System.Linq; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.CoreAudioApi; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; @@ -9,6 +12,7 @@ public sealed class MP2KMixer : Mixer { internal readonly int SampleRate; internal readonly int SamplesPerBuffer; + public readonly int BufferLength; internal readonly float SampleRateReciprocal; private readonly float _samplesReciprocal; internal readonly float PCM8MasterVolume; @@ -20,61 +24,59 @@ public sealed class MP2KMixer : Mixer internal readonly MP2KConfig Config; private readonly WaveBuffer _audio; private readonly float[][] _trackBuffers; - private readonly MP2KPCM8Channel[] _pcm8Channels; - private readonly MP2KSquareChannel _sq1; - private readonly MP2KSquareChannel _sq2; - private readonly MP2KPCM4Channel _pcm4; - private readonly MP2KNoiseChannel _noise; - private readonly MP2KPSGChannel[] _psgChannels; + private readonly PCM8Channel[] _pcm8Channels; + private readonly SquareChannel _sq1; + private readonly SquareChannel _sq2; + private readonly PCM4Channel _pcm4; + private readonly NoiseChannel _noise; + private readonly PSGChannel[] _psgChannels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal MP2KMixer(MP2KConfig config) { - Config = config; - (SampleRate, SamplesPerBuffer) = MP2KUtils.FrequencyTable[config.SampleRate]; - SampleRateReciprocal = 1f / SampleRate; - _samplesReciprocal = 1f / SamplesPerBuffer; - PCM8MasterVolume = config.Volume / 15f; + Config = config; + (SampleRate, SamplesPerBuffer) = Utils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; - _pcm8Channels = new MP2KPCM8Channel[24]; - for (int i = 0; i < _pcm8Channels.Length; i++) - { - _pcm8Channels[i] = new MP2KPCM8Channel(this); - } - _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; + _pcm8Channels = new PCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new PCM8Channel(this); + } + _psgChannels = new PSGChannel[4] { _sq1 = new SquareChannel(this), _sq2 = new SquareChannel(this), _pcm4 = new PCM4Channel(this), _noise = new NoiseChannel(this), }; - int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; - _trackBuffers = new float[0x10][]; - for (int i = 0; i < _trackBuffers.Length; i++) - { - _trackBuffers[i] = new float[amt]; - } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) - { - DiscardOnBufferOverflow = true, - BufferLength = SamplesPerBuffer * 64, - }; - Init(_buffer); - } + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + Init(_buffer); + } - internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) + internal PCM8Channel AllocPCM8Channel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) { - MP2KPCM8Channel? nChn = null; - IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner is null ? 0xFF : c.Owner.Index); - foreach (MP2KPCM8Channel i in byOwner) // Find free + PCM8Channel nChn = null; + IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner == null ? 0xFF : c.Owner.Index); + foreach (PCM8Channel i in byOwner) // Find free { - if (i.State == EnvelopeState.Dead || i.Owner is null) + if (i.State == EnvelopeState.Dead || i.Owner == null) { nChn = i; break; } } - if (nChn is null) // Find releasing + if (nChn == null) // Find releasing { - foreach (MP2KPCM8Channel i in byOwner) + foreach (PCM8Channel i in byOwner) { if (i.State == EnvelopeState.Releasing) { @@ -83,40 +85,40 @@ internal MP2KMixer(MP2KConfig config) } } } - if (nChn is null) // Find prioritized + if (nChn == null) // Find prioritized { - foreach (MP2KPCM8Channel i in byOwner) + foreach (PCM8Channel i in byOwner) { - if (owner.Priority > i.Owner!.Priority) + if (owner.Priority > i.Owner.Priority) { nChn = i; break; } } } - if (nChn is null) // None available + if (nChn == null) // None available { - MP2KPCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one - if (lowest.Owner!.Index >= owner.Index) + PCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one + if (lowest.Owner.Index >= owner.Index) { nChn = lowest; } } - if (nChn is not null) // Could still be null from the above if + if (nChn != null) // Could still be null from the above if { nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); } return nChn; } - internal MP2KPSGChannel? AllocPSGChannel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) + internal PSGChannel AllocPSGChannel(Track owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) { - MP2KPSGChannel nChn; + PSGChannel nChn; switch (type) { case VoiceType.Square1: { nChn = _sq1; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -126,7 +128,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.Square2: { nChn = _sq2; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -136,7 +138,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.PCM4: { nChn = _pcm4; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -146,7 +148,7 @@ internal MP2KMixer(MP2KConfig config) case VoiceType.Noise: { nChn = _noise; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + if (nChn.State < EnvelopeState.Releasing && nChn.Owner.Index < owner.Index) { return null; } @@ -157,20 +159,20 @@ internal MP2KMixer(MP2KConfig config) } nChn.SetVolume(vol, pan); nChn.SetPitch(pitch); - return nChn; - } + return nChn; + } - internal void BeginFadeIn() + internal void BeginFadeIn() { _fadePos = 0f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; _isFading = true; } internal void BeginFadeOut() { _fadePos = 1f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBA.GBAUtils.AGB_FPS); _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; _isFading = true; } @@ -188,6 +190,16 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } internal void Process(bool output, bool recording) { for (int i = 0; i < _trackBuffers.Length; i++) @@ -199,8 +211,8 @@ internal void Process(bool output, bool recording) for (int i = 0; i < _pcm8Channels.Length; i++) { - MP2KPCM8Channel c = _pcm8Channels[i]; - if (c.Owner is not null) + PCM8Channel c = _pcm8Channels[i]; + if (c.Owner != null) { c.Process(_trackBuffers[c.Owner.Index]); } @@ -208,8 +220,8 @@ internal void Process(bool output, bool recording) for (int i = 0; i < _psgChannels.Length; i++) { - MP2KPSGChannel c = _psgChannels[i]; - if (c.Owner is not null) + PSGChannel c = _psgChannels[i]; + if (c.Owner != null) { c.Process(_trackBuffers[c.Owner.Index]); } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs index 7ebe510..7bbd6d1 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs @@ -1,155 +1,786 @@ -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; -public sealed partial class MP2KPlayer : Player +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +public sealed partial class MP2KPlayer : IPlayer { - protected override string Name => "MP2K Player"; + private readonly MP2KMixer _mixer; + private readonly MP2KConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private ushort _tempo; + private int _tempoStack; + private long _elapsedLoops; - private readonly string?[] _voiceTypeCache; - internal readonly MP2KConfig Config; - internal readonly MP2KMixer MMixer; private MP2KLoadedSong? _loadedSong; + public ILoadedSong? LoadedSong => _loadedSong; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } - internal ushort Tempo; - internal int TempoStack; - private long _elapsedLoops; - - private int? _prevVoiceTableOffset; + public PlayerState State { get; private set; } + public event Action? SongEnded; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => MMixer; + private readonly string?[] _voiceTypeCache; internal MP2KPlayer(MP2KConfig config, MP2KMixer mixer) - : base(GBAUtils.AGB_FPS) { - Config = config; - MMixer = mixer; + _config = config; + _mixer = mixer; _voiceTypeCache = new string[256]; + + _time = new TimeBarrier(GBA.GBAUtils.AGB_FPS); + } + private void CreateThread() + { + _thread = new Thread(Tick) { Name = "MP2K Player Tick" }; + _thread.Start(); + } + private void WaitThread() + { + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) + { + _thread.Join(); + } } - public override void LoadSong(int index) + private void InitEmulation() { + _tempo = 150; + _tempoStack = 0; + _elapsedLoops = 0; + _loadedSong!.ElapsedTicks = 0; + _mixer.ResetFade(); + for (int trackIndex = 0; trackIndex < _loadedSong.Tracks.Length; trackIndex++) + { + _loadedSong.Tracks[trackIndex].Init(); + } + } + public void LoadSong(long index) + { + int? oldVoiceTableOffset = _loadedSong?.VoiceTableOffset; if (_loadedSong is not null) { + _loadedSong.Dispose(); _loadedSong = null; } // If there's an exception, this will remain null - _loadedSong = new MP2KLoadedSong(this, index); + _loadedSong = new MP2KLoadedSong(index, this, _config, oldVoiceTableOffset, _voiceTypeCache); + _loadedSong.SetTicks(); if (_loadedSong.Events.Length == 0) { + _loadedSong.Dispose(); _loadedSong = null; - return; } - - _loadedSong.CheckVoiceTypeCache(ref _prevVoiceTableOffset, _voiceTypeCache); - _loadedSong.SetTicks(); } - public override void UpdateSongState(SongState info) + public void SetCurrentPosition(long ticks) { - info.Tempo = Tempo; - _loadedSong!.UpdateSongState(info, _voiceTypeCache); + if (_loadedSong is null) + { + SongEnded?.Invoke(); + return; + } + + if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) + { + return; + } + + if (State is PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + MP2KLoadedSong s = _loadedSong; + bool u = false; + while (ticks != s.ElapsedTicks) + { + while (_tempoStack >= 150) + { + _tempoStack -= 150; + for (int trackIndex = 0; trackIndex < s.Tracks.Length; trackIndex++) + { + Track track = s.Tracks[trackIndex]; + if (!track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref u); + } + } + } + s.ElapsedTicks++; + if (s.ElapsedTicks == ticks) + { + break; + } + } + _tempoStack += _tempo; + } + + for (int i = 0; i < s.Tracks.Length; i++) + { + s.Tracks[i].StopAllChannels(); + } + Pause(); } - internal override void InitEmulation() + public void Play() { - Tempo = 150; - TempoStack = 0; - _elapsedLoops = 0; - ElapsedTicks = 0; - MMixer.ResetFade(); - MP2KTrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (_loadedSong is null) + { + SongEnded?.Invoke(); + return; + } + + if (State is not PlayerState.ShutDown) { - tracks[i].Init(); + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } } - protected override void SetCurTick(long ticks) + public void Pause() { - _loadedSong!.SetCurTick(ticks); + switch (State) + { + case PlayerState.Playing: + { + State = PlayerState.Paused; + WaitThread(); + break; + } + case PlayerState.Paused: + case PlayerState.Stopped: + { + State = PlayerState.Playing; + CreateThread(); + break; + } + } } - protected override void OnStopped() + public void Stop() { - MP2KTrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (State is PlayerState.Playing or PlayerState.Paused) { - tracks[i].StopAllChannels(); + State = PlayerState.Stopped; + WaitThread(); } } - - protected override bool Tick(bool playing, bool recording) + public void Record(string fileName) { - MP2KLoadedSong s = _loadedSong!; + _mixer.CreateWaveWriter(fileName); - bool allDone = false; - while (!allDone && TempoStack >= 150) + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + + _mixer.CloseWaveWriter(); + } + + public void SaveAsMIDI(string fileName, MIDISaveArgs args) + { + _loadedSong!.SaveAsMIDI(fileName, args); + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int trackIndex = 0; trackIndex < _loadedSong!.Tracks.Length; trackIndex++) { - TempoStack -= 150; - allDone = true; - for (int i = 0; i < s.Tracks.Length; i++) + Track track = _loadedSong.Tracks[trackIndex]; + SongState.Track tin = info.Tracks[trackIndex]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.LFO = track.LFODepth; + ref string? voiceType = ref _voiceTypeCache[track.Voice]; + if (voiceType is null) + { + byte t = _config.ROM[_loadedSong.VoiceTableOffset + (track.Voice * 12)]; + if (t == (byte)VoiceFlags.KeySplit) + { + voiceType = "Key Split"; + } + else if (t == (byte)VoiceFlags.Drum) + { + voiceType = "Drum"; + } + else + { + switch ((VoiceType)(t & 0x7)) // Disregard the other flags + { + case VoiceType.PCM8: voiceType = "PCM8"; break; + case VoiceType.Square1: voiceType = "Square 1"; break; + case VoiceType.Square2: voiceType = "Square 2"; break; + case VoiceType.PCM4: voiceType = "PCM4"; break; + case VoiceType.Noise: voiceType = "Noise"; break; + case VoiceType.Invalid5: voiceType = "Invalid 5"; break; + case VoiceType.Invalid6: voiceType = "Invalid 6"; break; + default: voiceType = "Invalid 7"; break; // VoiceType.Invalid7 + } + } + } + tin.Type = voiceType; + tin.Volume = track.GetVolume(); + tin.PitchBend = track.GetPitch(); + tin.Panpot = track.GetPanpot(); + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) { - TickTrack(s, s.Tracks[i], ref allDone); + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; } - if (MMixer.IsFadeDone()) + else { - allDone = true; + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (c.State < EnvelopeState.Releasing) + { + tin.Keys[numKeys++] = c.Note.OriginalNote; + } + ChannelVolume vol = c.GetVolume(); + if (vol.LeftVol > left) + { + left = vol.LeftVol; + } + if (vol.RightVol > right) + { + right = vol.RightVol; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; } } - if (!allDone) - { - TempoStack += Tempo; - } - MMixer.Process(playing, recording); - return allDone; } - private void TickTrack(MP2KLoadedSong s, MP2KTrack track, ref bool allDone) + + private void PlayNote(Track track, byte note, byte velocity, byte addedDuration) { - track.Tick(); - bool update = false; - while (track.Rest == 0 && !track.Stopped) + int n = note + track.Transpose; + if (n < 0) { - s.ExecuteNext(track, ref update); + n = 0; } - if (track.Index == s.LongestTrack) + else if (n > 0x7F) { - HandleTicksAndLoop(s, track); + n = 0x7F; } - if (!track.Stopped) + note = (byte)n; + track.PrevNote = note; + track.PrevVelocity = velocity; + if (!track.Ready) { - allDone = false; + return; // Tracks do not play unless they have had a voice change event } - if (track.Channels.Count > 0) + + bool fromDrum = false; + int offset = _loadedSong!.VoiceTableOffset + (track.Voice * 12); + while (true) { - allDone = false; - if (update || track.LFODepth > 0) + ref VoiceEntry v = ref MemoryMarshal.AsRef(_config.ROM.AsSpan(offset)); + if (v.Type == (int)VoiceFlags.KeySplit) + { + fromDrum = false; // In case there is a multi within a drum + byte inst = _config.ROM[v.Int8 - GBAUtils.CartridgeOffset + note]; + offset = v.Int4 - GBAUtils.CartridgeOffset + (inst * 12); + } + else if (v.Type == (int)VoiceFlags.Drum) { - track.UpdateChannels(); + fromDrum = true; + offset = v.Int4 - GBAUtils.CartridgeOffset + (note * 12); + } + else + { + var ni = new NoteInfo + { + Duration = track.RunCmd == 0xCF ? -1 : (Utils.RestTable[track.RunCmd - 0xCF] + addedDuration), + Velocity = velocity, + OriginalNote = note, + Note = fromDrum ? v.RootNote : note, + }; + var type = (VoiceType)(v.Type & 0x7); + int instPan = v.Pan; + instPan = (instPan & 0x80) != 0 ? instPan - 0xC0 : 0; + switch (type) + { + case VoiceType.PCM8: + { + bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; + bool bCompressed = _config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); + _mixer.AllocPCM8Channel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + bFixed, bCompressed, v.Int4 - GBAUtils.CartridgeOffset); + return; + } + case VoiceType.Square1: + case VoiceType.Square2: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (SquarePattern)v.Int4); + return; + } + case VoiceType.PCM4: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, v.Int4 - GBAUtils.CartridgeOffset); + return; + } + case VoiceType.Noise: + { + _mixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (NoisePattern)v.Int4); + return; + } + } + return; // Prevent infinite loop with invalid instruments } } } - private void HandleTicksAndLoop(MP2KLoadedSong s, MP2KTrack track) + internal void ExecuteNext(Track track, ref bool update) { - if (ElapsedTicks != s.MaxTicks) + byte[] rom = _config.ROM; + byte cmd = rom[track.DataOffset++]; + if (cmd >= 0xBD) // Commands that work within running status { - ElapsedTicks++; - return; + track.RunCmd = cmd; } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + if (track.RunCmd >= 0xCF && cmd <= 0x7F) // Within running status { - return; + byte peek0 = rom[track.DataOffset]; + byte peek1 = rom[track.DataOffset + 1]; + byte velocity, addedDuration; + if (peek0 > 0x7F) + { + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (peek1 > 3) + { + track.DataOffset++; + velocity = peek0; + addedDuration = 0; + } + else + { + track.DataOffset += 2; + velocity = peek0; + addedDuration = peek1; + } + PlayNote(track, cmd, velocity, addedDuration); } + else if (cmd >= 0xCF) + { + byte peek0 = rom[track.DataOffset]; + byte peek1 = rom[track.DataOffset + 1]; + byte peek2 = rom[track.DataOffset + 2]; + byte key, velocity, addedDuration; + if (peek0 > 0x7F) + { + key = track.PrevNote; + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (peek1 > 0x7F) + { + track.DataOffset++; + key = peek0; + velocity = track.PrevVelocity; + addedDuration = 0; + } + else if (cmd == 0xCF || peek2 > 3) + { + track.DataOffset += 2; + key = peek0; + velocity = peek1; + addedDuration = 0; + } + else + { + track.DataOffset += 3; + key = peek0; + velocity = peek1; + addedDuration = peek2; + } + PlayNote(track, key, velocity, addedDuration); + } + else if (cmd >= 0x80 && cmd <= 0xB0) + { + track.Rest = Utils.RestTable[cmd - 0x80]; + } + else if (track.RunCmd < 0xCF && cmd <= 0x7F) + { + switch (track.RunCmd) + { + case 0xBD: + { + track.Voice = cmd; + //track.Ready = true; // This is unnecessary because if we're in running status of a voice command, then Ready was already set + break; + } + case 0xBE: + { + track.Volume = cmd; + update = true; + break; + } + case 0xBF: + { + track.Panpot = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xC0: + { + track.PitchBend = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xC1: + { + track.PitchBendRange = cmd; + update = true; + break; + } + case 0xC2: + { + track.LFOSpeed = cmd; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC3: + { + track.LFODelay = cmd; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC4: + { + track.LFODepth = cmd; + update = true; + break; + } + case 0xC5: + { + track.LFOType = (LFOType)cmd; + update = true; + break; + } + case 0xC8: + { + track.Tune = (sbyte)(cmd - 0x40); + update = true; + break; + } + case 0xCD: + { + track.DataOffset++; + break; + } + case 0xCE: + { + track.PrevNote = cmd; + int k = cmd + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.ReleaseChannels(k); + break; + } + default: throw new MP2KInvalidRunningStatusCMDException(track.Index, track.DataOffset - 1, track.RunCmd); + } + } + else if (cmd > 0xB0 && cmd < 0xCF) + { + switch (cmd) + { + case 0xB1: + case 0xB6: + { + track.Stopped = true; + //track.ReleaseAllTieingChannels(); // Necessary? + break; + } + case 0xB2: + { + track.DataOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBA.GBAUtils.CartridgeOffset; + break; + } + case 0xB3: + { + if (track.CallStackDepth >= 3) + { + throw new MP2KTooManyNestedCallsException(track.Index); + } + + int callOffset = (rom[track.DataOffset++] | (rom[track.DataOffset++] << 8) | (rom[track.DataOffset++] << 16) | (rom[track.DataOffset++] << 24)) - GBA.GBAUtils.CartridgeOffset; + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackDepth++; + track.DataOffset = callOffset; + break; + } + case 0xB4: + { + if (track.CallStackDepth != 0) + { + track.CallStackDepth--; + track.DataOffset = track.CallStack[track.CallStackDepth]; + } + break; + } + /*case 0xB5: // TODO: Logic so this isn't an infinite loop + { + byte times = config.Reader.ReadByte(); + int repeatOffset = config.Reader.ReadInt32() - GBA.Utils.CartridgeOffset; + if (!EventExists(offset)) + { + AddEvent(new RepeatCommand { Times = times, Offset = repeatOffset }); + } + break; + }*/ + case 0xB9: + { + track.DataOffset += 3; + break; + } + case 0xBA: + { + track.Priority = rom[track.DataOffset++]; + break; + } + case 0xBB: + { + _tempo = (ushort)(rom[track.DataOffset++] * 2); + break; + } + case 0xBC: + { + track.Transpose = (sbyte)rom[track.DataOffset++]; + break; + } + // Commands that work within running status: + case 0xBD: + { + track.Voice = rom[track.DataOffset++]; + track.Ready = true; + break; + } + case 0xBE: + { + track.Volume = rom[track.DataOffset++]; + update = true; + break; + } + case 0xBF: + { + track.Panpot = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xC0: + { + track.PitchBend = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xC1: + { + track.PitchBendRange = rom[track.DataOffset++]; + update = true; + break; + } + case 0xC2: + { + track.LFOSpeed = rom[track.DataOffset++]; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC3: + { + track.LFODelay = rom[track.DataOffset++]; + track.LFOPhase = 0; + track.LFODelayCount = 0; + update = true; + break; + } + case 0xC4: + { + track.LFODepth = rom[track.DataOffset++]; + update = true; + break; + } + case 0xC5: + { + track.LFOType = (LFOType)rom[track.DataOffset++]; + update = true; + break; + } + case 0xC8: + { + track.Tune = (sbyte)(rom[track.DataOffset++] - 0x40); + update = true; + break; + } + case 0xCD: + { + track.DataOffset += 2; + break; + } + case 0xCE: + { + byte peek = rom[track.DataOffset]; + if (peek > 0x7F) + { + track.ReleaseChannels(track.PrevNote); + } + else + { + track.DataOffset++; + track.PrevNote = peek; + int k = peek + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.ReleaseChannels(k); + } + break; + } + default: throw new MP2KInvalidCMDException(track.Index, track.DataOffset - 1, cmd); + } + } + } - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !MMixer.IsFading()) + private void Tick() + { + MP2KLoadedSong s = _loadedSong!; + _time.Start(); + while (true) { - MMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 150) + { + _tempoStack -= 150; + bool allDone = true; + for (int trackIndex = 0; trackIndex < s.Tracks.Length; trackIndex++) + { + Track track = s.Tracks[trackIndex]; + track.Tick(); + bool update = false; + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track, ref update); + } + if (trackIndex == s.LongestTrack) + { + if (s.ElapsedTicks == s.MaxTicks) + { + if (!track.Stopped) + { + List evs = s.Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + s.ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + s.ElapsedTicks++; + } + } + if (!track.Stopped) + { + allDone = false; + } + if (track.Channels.Count > 0) + { + allDone = false; + if (update || track.LFODepth > 0) + { + track.UpdateChannels(); + } + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.Process(playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.Process(playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } - public void SaveAsMIDI(string fileName, MIDISaveArgs args) + public void Dispose() { - _loadedSong!.SaveAsMIDI(fileName, args); + if (State is not PlayerState.ShutDown) + { + State = PlayerState.ShutDown; + WaitThread(); + } } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs b/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs deleted file mode 100644 index 5b33542..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KStructs.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SongEntry -{ - public const int SIZE = 8; - - public readonly int HeaderOffset; - public readonly short Player; - public readonly byte Unknown1; - public readonly byte Unknown2; - - public SongEntry(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - HeaderOffset = ReadInt32LittleEndian(src.Slice(0)); - Player = ReadInt16LittleEndian(src.Slice(4)); - Unknown1 = src[6]; - Unknown2 = src[7]; - } - } - - public static SongEntry Get(byte[] rom, int songTableOffset, int songNum) - { - return new SongEntry(rom.AsSpan(songTableOffset + (songNum * SIZE))); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct SongHeader -{ - public const int SIZE = 8; - - public readonly byte NumTracks; - public readonly byte NumBlocks; - public readonly byte Priority; - public readonly byte Reverb; - public readonly int VoiceTableOffset; - // int[NumTracks] TrackOffset; - - public SongHeader(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - NumTracks = src[0]; - NumBlocks = src[1]; - Priority = src[2]; - Reverb = src[3]; - VoiceTableOffset = ReadInt32LittleEndian(src.Slice(4)); - } - } - - public static SongHeader Get(byte[] rom, int offset, out int tracksOffset) - { - tracksOffset = offset + SIZE; - return new SongHeader(rom.AsSpan(offset)); - } - public static int GetTrackOffset(byte[] rom, int tracksOffset, int trackIndex) - { - return ReadInt32LittleEndian(rom.AsSpan(tracksOffset + (trackIndex * 4))); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct VoiceEntry -{ - public const int SIZE = 12; - - public readonly byte Type; // 0 - public readonly byte RootNote; // 1 - public readonly byte Unknown; // 2 - public readonly byte Pan; // 3 - /// SquarePattern for Square1/Square2, NoisePattern for Noise, Address for PCM8/PCM4/KeySplit/Drum - public readonly int Int4; // 4 - /// ADSR for PCM8/Square1/Square2/PCM4/Noise, KeysAddress for KeySplit - public readonly ADSR ADSR; // 8 - - public int Int8 => (ADSR.R << 24) | (ADSR.S << 16) | (ADSR.D << 8) | (ADSR.A); - - public VoiceEntry(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - Type = src[0]; - RootNote = src[1]; - Unknown = src[2]; - Pan = src[3]; - Int4 = ReadInt32LittleEndian(src.Slice(4)); - ADSR = ADSR.Get(src.Slice(8)); - } - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal struct ADSR -{ - public const int SIZE = 4; - - public byte A; - public byte D; - public byte S; - public byte R; - - public static ref readonly ADSR Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal readonly struct GoldenSunPSG -{ - public const int SIZE = 6; - - /// Always 0x80 - public readonly byte Unknown; - public readonly GoldenSunPSGType Type; - public readonly byte InitialCycle; - public readonly byte CycleSpeed; - public readonly byte CycleAmplitude; - public readonly byte MinimumCycle; - - public static ref readonly GoldenSunPSG Get(ReadOnlySpan src) - { - return ref MemoryMarshal.AsRef(src); - } -} -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = SIZE)] -internal struct SampleHeader -{ - public const int SIZE = 16; - public const int LOOP_TRUE = 0x40_000_000; - - /// 0x40_000_000 if True - public int DoesLoop; - /// Right shift 10 for value - public int SampleRate; - public int LoopOffset; - public int Length; - // byte[Length] Sample; - - public SampleHeader(ReadOnlySpan src) - { - if (BitConverter.IsLittleEndian) - { - this = MemoryMarshal.AsRef(src); - } - else - { - DoesLoop = ReadInt32LittleEndian(src.Slice(0, 4)); - SampleRate = ReadInt32LittleEndian(src.Slice(4, 4)); - LoopOffset = ReadInt32LittleEndian(src.Slice(8, 4)); - Length = ReadInt32LittleEndian(src.Slice(12, 4)); - } - } - - public static SampleHeader Get(byte[] rom, int offset, out int sampleOffset) - { - sampleOffset = offset + SIZE; - return new SampleHeader(rom.AsSpan(offset)); - } -} - -internal struct ChannelVolume -{ - public float LeftVol, RightVol; -} -internal struct NoteInfo -{ - public byte Note, OriginalNote; - public byte Velocity; - /// -1 if forever - public int Duration; -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs b/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs deleted file mode 100644 index e612465..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal sealed class MP2KTrack -{ - public readonly byte Index; - private readonly int _startOffset; - public byte Voice; - public byte PitchBendRange; - public byte Priority; - public byte Volume; - public byte Rest; - public byte LFOPhase; - public byte LFODelayCount; - public byte LFOSpeed; - public byte LFODelay; - public byte LFODepth; - public LFOType LFOType; - public sbyte PitchBend; - public sbyte Tune; - public sbyte Panpot; - public sbyte Transpose; - public bool Ready; - public bool Stopped; - public int DataOffset; - public int[] CallStack = new int[3]; - public byte CallStackDepth; - public byte RunCmd; - public byte PrevNote; - public byte PrevVelocity; - - public readonly List Channels = new(); - - public int GetPitch() - { - int lfo = LFOType == LFOType.Pitch ? (MP2KUtils.Tri(LFOPhase) * LFODepth) >> 8 : 0; - return (PitchBend * PitchBendRange) + Tune + lfo; - } - public byte GetVolume() - { - int lfo = LFOType == LFOType.Volume ? (MP2KUtils.Tri(LFOPhase) * LFODepth * 3 * Volume) >> 19 : 0; - int v = Volume + lfo; - if (v < 0) - { - v = 0; - } - else if (v > 0x7F) - { - v = 0x7F; - } - return (byte)v; - } - public sbyte GetPanpot() - { - int lfo = LFOType == LFOType.Panpot ? (MP2KUtils.Tri(LFOPhase) * LFODepth * 3) >> 12 : 0; - int p = Panpot + lfo; - if (p < -0x40) - { - p = -0x40; - } - else if (p > 0x3F) - { - p = 0x3F; - } - return (sbyte)p; - } - - public MP2KTrack(byte i, int startOffset) - { - Index = i; - _startOffset = startOffset; - } - public void Init() - { - Voice = 0; - Priority = 0; - Rest = 0; - LFODelay = 0; - LFODelayCount = 0; - LFOPhase = 0; - LFODepth = 0; - CallStackDepth = 0; - PitchBend = 0; - Tune = 0; - Panpot = 0; - Transpose = 0; - DataOffset = _startOffset; - RunCmd = 0; - PrevNote = 0; - PrevVelocity = 0x7F; - PitchBendRange = 2; - LFOType = LFOType.Pitch; - Ready = false; - Stopped = false; - LFOSpeed = 22; - Volume = 100; - StopAllChannels(); - } - public void Tick() - { - if (Rest != 0) - { - Rest--; - } - if (LFODepth > 0) - { - LFOPhase += LFOSpeed; - } - else - { - LFOPhase = 0; - } - int active = 0; - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - if (chans[i].TickNote()) - { - active++; - } - } - if (active != 0) - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - } - else - { - LFODelayCount = LFODelay; - } - if ((LFODelay == LFODelayCount && LFODelay != 0) || LFOSpeed == 0) - { - LFOPhase = 0; - } - } - - public void ReleaseChannels(int key) - { - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - MP2KChannel c = chans[i]; - if (c.Note.OriginalNote == key && c.Note.Duration == -1) - { - c.Release(); - } - } - } - public void StopAllChannels() - { - MP2KChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - public void UpdateChannels() - { - byte vol = GetVolume(); - sbyte pan = GetPanpot(); - int pitch = GetPitch(); - for (int i = 0; i < Channels.Count; i++) - { - MP2KChannel c = Channels[i]; - c.SetVolume(vol, pan); - c.SetPitch(pitch); - } - } - - public void UpdateSongState(SongState.Track tin, MP2KLoadedSong loadedSong, string?[] voiceTypeCache) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.LFO = LFODepth; - ref string? cache = ref voiceTypeCache[Voice]; - if (cache is null) - { - loadedSong.UpdateInstrumentCache(Voice, out cache); - } - tin.Type = cache; - tin.Volume = GetVolume(); - tin.PitchBend = GetPitch(); - tin.Panpot = GetPanpot(); - - MP2KChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - MP2KChannel c = channels[j]; - if (c.State < EnvelopeState.Releasing) - { - tin.Keys[numKeys++] = c.Note.OriginalNote; - } - ChannelVolume vol = c.GetVolume(); - if (vol.LeftVol > left) - { - left = vol.LeftVol; - } - if (vol.RightVol > right) - { - right = vol.RightVol; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - } - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs b/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs deleted file mode 100644 index 6b3b0f6..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KUtils.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.Collections; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -internal static partial class MP2KUtils -{ - public static ReadOnlySpan RestTable => new byte[49] - { - 00, 01, 02, 03, 04, 05, 06, 07, - 08, 09, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 28, 30, 32, 36, 40, 42, 44, - 48, 52, 54, 56, 60, 64, 66, 68, - 72, 76, 78, 80, 84, 88, 90, 92, - 96, - }; - public static ReadOnlySpan<(int sampleRate, int samplesPerBuffer)> FrequencyTable => new (int, int)[12] - { - (05734, 096), // 59.72916666666667 - (07884, 132), // 59.72727272727273 - (10512, 176), // 59.72727272727273 - (13379, 224), // 59.72767857142857 - (15768, 264), // 59.72727272727273 - (18157, 304), // 59.72697368421053 - (21024, 352), // 59.72727272727273 - (26758, 448), // 59.72767857142857 - (31536, 528), // 59.72727272727273 - (36314, 608), // 59.72697368421053 - (40137, 672), // 59.72767857142857 - (42048, 704), // 59.72727272727273 - }; - - // Squares (Use arrays since they are stored as references in MP2KSquareChannel) - public static readonly float[] SquareD12 = new float[8] { 0.875f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, }; - public static readonly float[] SquareD25 = new float[8] { 0.750f, 0.750f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, }; - public static readonly float[] SquareD50 = new float[8] { 0.500f, 0.500f, 0.500f, 0.500f, -0.500f, -0.500f, -0.500f, -0.500f, }; - public static readonly float[] SquareD75 = new float[8] { 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, -0.750f, -0.750f, }; - - // Noises - public static readonly BitArray NoiseFine; - public static readonly BitArray NoiseRough; - public static ReadOnlySpan NoiseFrequencyTable => new byte[60] - { - 0xD7, 0xD6, 0xD5, 0xD4, - 0xC7, 0xC6, 0xC5, 0xC4, - 0xB7, 0xB6, 0xB5, 0xB4, - 0xA7, 0xA6, 0xA5, 0xA4, - 0x97, 0x96, 0x95, 0x94, - 0x87, 0x86, 0x85, 0x84, - 0x77, 0x76, 0x75, 0x74, - 0x67, 0x66, 0x65, 0x64, - 0x57, 0x56, 0x55, 0x54, - 0x47, 0x46, 0x45, 0x44, - 0x37, 0x36, 0x35, 0x34, - 0x27, 0x26, 0x25, 0x24, - 0x17, 0x16, 0x15, 0x14, - 0x07, 0x06, 0x05, 0x04, - 0x03, 0x02, 0x01, 0x00, - }; - - // PCM4 - /// dest must be 0x20 bytes - public static void PCM4ToFloat(ReadOnlySpan src, Span dest) - { - float sum = 0; - for (int i = 0; i < 0x10; i++) - { - byte b = src[i]; - float first = (b >> 4) / 16f; - float second = (b & 0xF) / 16f; - sum += dest[i * 2] = first; - sum += dest[(i * 2) + 1] = second; - } - float dcCorrection = sum / 0x20; - for (int i = 0; i < 0x20; i++) - { - dest[i] -= dcCorrection; - } - } - - static MP2KUtils() - { - NoiseFine = new BitArray(0x8_000); - int reg = 0x4_000; - for (int i = 0; i < NoiseFine.Length; i++) - { - if ((reg & 1) == 1) - { - reg >>= 1; - reg ^= 0x6_000; - NoiseFine[i] = true; - } - else - { - reg >>= 1; - NoiseFine[i] = false; - } - } - NoiseRough = new BitArray(0x80); - reg = 0x40; - for (int i = 0; i < NoiseRough.Length; i++) - { - if ((reg & 1) == 1) - { - reg >>= 1; - reg ^= 0x60; - NoiseRough[i] = true; - } - else - { - reg >>= 1; - NoiseRough[i] = false; - } - } - } - public static int Tri(int index) - { - index = (index - 64) & 0xFF; - return (index < 128) ? (index * 12) - 768 : 2_304 - (index * 12); - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KUtils_PkmnCompress.cs b/VG Music Studio - Core/GBA/MP2K/MP2KUtils_PkmnCompress.cs deleted file mode 100644 index ae25958..0000000 --- a/VG Music Studio - Core/GBA/MP2K/MP2KUtils_PkmnCompress.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; - -partial class MP2KUtils -{ - private static ReadOnlySpan CompressionLookup => new sbyte[16] - { - 0, 1, 4, 9, 16, 25, 36, 49, -64, -49, -36, -25, -16, -9, -4, -1, - }; - - // TODO: Do runtime - // TODO: How large is the decompress buffer in-game? - public static sbyte[] Decompress(ReadOnlySpan src, int sampleLength) - { - var samples = new List(); - sbyte compressionLevel = 0; - int compressionByte = 0, compressionIdx = 0; - - for (int i = 0; true; i++) - { - byte b = src[i]; - if (compressionByte == 0) - { - compressionByte = 0x20; - compressionLevel = (sbyte)b; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - else - { - if (compressionByte < 0x20) - { - compressionLevel += CompressionLookup[b >> 4]; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - // Potential for 2 samples to be added here at the same time - compressionByte--; - compressionLevel += CompressionLookup[b & 0xF]; - samples.Add(compressionLevel); - if (++compressionIdx >= sampleLength) - { - break; - } - } - } - - return samples.ToArray(); - } -} diff --git a/VG Music Studio - Core/GBA/MP2K/Structs.cs b/VG Music Studio - Core/GBA/MP2K/Structs.cs new file mode 100644 index 0000000..fe06998 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Structs.cs @@ -0,0 +1,80 @@ +using Kermalis.EndianBinaryIO; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 8)] +internal struct SongEntry +{ + public int HeaderOffset; + public short Player; + public byte Unknown1; + public byte Unknown2; +} +internal class SongHeader +{ + public byte NumTracks { get; set; } + public byte NumBlocks { get; set; } + public byte Priority { get; set; } + public byte Reverb { get; set; } + public int VoiceTableOffset { get; set; } + [BinaryArrayVariableLength(nameof(NumTracks))] + public int[] TrackOffsets { get; set; } +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 12)] +internal struct VoiceEntry +{ + public byte Type; // 0 + public byte RootNote; // 1 + public byte Unknown; // 2 + public byte Pan; // 3 + /// SquarePattern for Square1/Square2, NoisePattern for Noise, Address for PCM8/PCM4/KeySplit/Drum + public int Int4; // 4 + /// ADSR for PCM8/Square1/Square2/PCM4/Noise, KeysAddress for KeySplit + public ADSR ADSR; // 8 + + public int Int8 => (ADSR.R << 24) | (ADSR.S << 16) | (ADSR.D << 8) | (ADSR.A); +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4)] +internal struct ADSR +{ + public byte A; + public byte D; + public byte S; + public byte R; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 6)] +internal struct GoldenSunPSG +{ + /// Always 0x80 + public byte Unknown; + public GoldenSunPSGType Type; + public byte InitialCycle; + public byte CycleSpeed; + public byte CycleAmplitude; + public byte MinimumCycle; +} +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 16)] +internal struct SampleHeader +{ + public const int LOOP_TRUE = 0x40_000_000; + + /// 0x40_000_000 if True + public int DoesLoop; + /// Right shift 10 for value + public int SampleRate; + public int LoopOffset; + public int Length; +} + +internal struct ChannelVolume +{ + public float LeftVol, RightVol; +} +internal struct NoteInfo +{ + public byte Note, OriginalNote; + public byte Velocity; + /// -1 if forever + public int Duration; +} diff --git a/VG Music Studio - Core/GBA/MP2K/Track.cs b/VG Music Studio - Core/GBA/MP2K/Track.cs new file mode 100644 index 0000000..7b047ff --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Track.cs @@ -0,0 +1,174 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal class Track + { + public readonly byte Index; + private readonly int _startOffset; + public byte Voice; + public byte PitchBendRange; + public byte Priority; + public byte Volume; + public byte Rest; + public byte LFOPhase; + public byte LFODelayCount; + public byte LFOSpeed; + public byte LFODelay; + public byte LFODepth; + public LFOType LFOType; + public sbyte PitchBend; + public sbyte Tune; + public sbyte Panpot; + public sbyte Transpose; + public bool Ready; + public bool Stopped; + public int DataOffset; + public int[] CallStack = new int[3]; + public byte CallStackDepth; + public byte RunCmd; + public byte PrevNote; + public byte PrevVelocity; + + public readonly List Channels = new List(); + + public int GetPitch() + { + int lfo = LFOType == LFOType.Pitch ? (Utils.Tri(LFOPhase) * LFODepth) >> 8 : 0; + return (PitchBend * PitchBendRange) + Tune + lfo; + } + public byte GetVolume() + { + int lfo = LFOType == LFOType.Volume ? (Utils.Tri(LFOPhase) * LFODepth * 3 * Volume) >> 19 : 0; + int v = Volume + lfo; + if (v < 0) + { + v = 0; + } + else if (v > 0x7F) + { + v = 0x7F; + } + return (byte)v; + } + public sbyte GetPanpot() + { + int lfo = LFOType == LFOType.Panpot ? (Utils.Tri(LFOPhase) * LFODepth * 3) >> 12 : 0; + int p = Panpot + lfo; + if (p < -0x40) + { + p = -0x40; + } + else if (p > 0x3F) + { + p = 0x3F; + } + return (sbyte)p; + } + + public Track(byte i, int startOffset) + { + Index = i; + _startOffset = startOffset; + } + public void Init() + { + Voice = 0; + Priority = 0; + Rest = 0; + LFODelay = 0; + LFODelayCount = 0; + LFOPhase = 0; + LFODepth = 0; + CallStackDepth = 0; + PitchBend = 0; + Tune = 0; + Panpot = 0; + Transpose = 0; + DataOffset = _startOffset; + RunCmd = 0; + PrevNote = 0; + PrevVelocity = 0x7F; + PitchBendRange = 2; + LFOType = LFOType.Pitch; + Ready = false; + Stopped = false; + LFOSpeed = 22; + Volume = 100; + StopAllChannels(); + } + public void Tick() + { + if (Rest != 0) + { + Rest--; + } + if (LFODepth > 0) + { + LFOPhase += LFOSpeed; + } + else + { + LFOPhase = 0; + } + int active = 0; + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + if (chans[i].TickNote()) + { + active++; + } + } + if (active != 0) + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + } + else + { + LFODelayCount = LFODelay; + } + if ((LFODelay == LFODelayCount && LFODelay != 0) || LFOSpeed == 0) + { + LFOPhase = 0; + } + } + + public void ReleaseChannels(int key) + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + Channel c = chans[i]; + if (c.Note.OriginalNote == key && c.Note.Duration == -1) + { + c.Release(); + } + } + } + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } + public void UpdateChannels() + { + byte vol = GetVolume(); + sbyte pan = GetPanpot(); + int pitch = GetPitch(); + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + c.SetVolume(vol, pan); + c.SetPitch(pitch); + } + } + } +} diff --git a/VG Music Studio - Core/GBA/MP2K/Utils.cs b/VG Music Studio - Core/GBA/MP2K/Utils.cs new file mode 100644 index 0000000..223bb43 --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/Utils.cs @@ -0,0 +1,175 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K +{ + internal static class Utils + { + public static readonly byte[] RestTable = new byte[49] + { + 00, 01, 02, 03, 04, 05, 06, 07, + 08, 09, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 28, 30, 32, 36, 40, 42, 44, + 48, 52, 54, 56, 60, 64, 66, 68, + 72, 76, 78, 80, 84, 88, 90, 92, + 96, + }; + public static readonly (int sampleRate, int samplesPerBuffer)[] FrequencyTable = new (int, int)[12] + { + (05734, 096), // 59.72916666666667 + (07884, 132), // 59.72727272727273 + (10512, 176), // 59.72727272727273 + (13379, 224), // 59.72767857142857 + (15768, 264), // 59.72727272727273 + (18157, 304), // 59.72697368421053 + (21024, 352), // 59.72727272727273 + (26758, 448), // 59.72767857142857 + (31536, 528), // 59.72727272727273 + (36314, 608), // 59.72697368421053 + (40137, 672), // 59.72767857142857 + (42048, 704), // 59.72727272727273 + }; + + // Squares + public static readonly float[] SquareD12 = new float[8] { 0.875f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, }; + public static readonly float[] SquareD25 = new float[8] { 0.750f, 0.750f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, -0.250f, }; + public static readonly float[] SquareD50 = new float[8] { 0.500f, 0.500f, 0.500f, 0.500f, -0.500f, -0.500f, -0.500f, -0.500f, }; + public static readonly float[] SquareD75 = new float[8] { 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, 0.250f, -0.750f, -0.750f, }; + + // Noises + public static readonly BitArray NoiseFine; + public static readonly BitArray NoiseRough; + public static readonly byte[] NoiseFrequencyTable = new byte[60] + { + 0xD7, 0xD6, 0xD5, 0xD4, + 0xC7, 0xC6, 0xC5, 0xC4, + 0xB7, 0xB6, 0xB5, 0xB4, + 0xA7, 0xA6, 0xA5, 0xA4, + 0x97, 0x96, 0x95, 0x94, + 0x87, 0x86, 0x85, 0x84, + 0x77, 0x76, 0x75, 0x74, + 0x67, 0x66, 0x65, 0x64, + 0x57, 0x56, 0x55, 0x54, + 0x47, 0x46, 0x45, 0x44, + 0x37, 0x36, 0x35, 0x34, + 0x27, 0x26, 0x25, 0x24, + 0x17, 0x16, 0x15, 0x14, + 0x07, 0x06, 0x05, 0x04, + 0x03, 0x02, 0x01, 0x00, + }; + + // PCM4 + // TODO: Do runtime instead of make arrays + public static float[] PCM4ToFloat(int sampleOffset) + { + var config = (MP2KConfig)Engine.Instance.Config; + float[] sample = new float[0x20]; + float sum = 0; + for (int i = 0; i < 0x10; i++) + { + byte b = config.ROM[sampleOffset + i]; + float first = (b >> 4) / 16f; + float second = (b & 0xF) / 16f; + sum += sample[i * 2] = first; + sum += sample[(i * 2) + 1] = second; + } + float dcCorrection = sum / 0x20; + for (int i = 0; i < 0x20; i++) + { + sample[i] -= dcCorrection; + } + return sample; + } + + // Pokémon Only + private static readonly sbyte[] _compressionLookup = new sbyte[16] + { + 0, 1, 4, 9, 16, 25, 36, 49, -64, -49, -36, -25, -16, -9, -4, -1, + }; + public static sbyte[] Decompress(int sampleOffset, int sampleLength) + { + var config = (MP2KConfig)Engine.Instance.Config; + var samples = new List(); + sbyte compressionLevel = 0; + int compressionByte = 0, compressionIdx = 0; + + for (int i = 0; true; i++) + { + byte b = config.ROM[sampleOffset + i]; + if (compressionByte == 0) + { + compressionByte = 0x20; + compressionLevel = (sbyte)b; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + else + { + if (compressionByte < 0x20) + { + compressionLevel += _compressionLookup[b >> 4]; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + compressionByte--; + compressionLevel += _compressionLookup[b & 0xF]; + samples.Add(compressionLevel); + if (++compressionIdx >= sampleLength) + { + break; + } + } + } + + return samples.ToArray(); + } + + static Utils() + { + NoiseFine = new BitArray(0x8_000); + int reg = 0x4_000; + for (int i = 0; i < NoiseFine.Length; i++) + { + if ((reg & 1) == 1) + { + reg >>= 1; + reg ^= 0x6_000; + NoiseFine[i] = true; + } + else + { + reg >>= 1; + NoiseFine[i] = false; + } + } + NoiseRough = new BitArray(0x80); + reg = 0x40; + for (int i = 0; i < NoiseRough.Length; i++) + { + if ((reg & 1) == 1) + { + reg >>= 1; + reg ^= 0x60; + NoiseRough[i] = true; + } + else + { + reg >>= 1; + NoiseRough[i] = false; + } + } + } + public static int Tri(int index) + { + index = (index - 64) & 0xFF; + return (index < 128) ? (index * 12) - 768 : 2_304 - (index * 12); + } + } +} diff --git a/VG Music Studio - Core/MP2K.yaml b/VG Music Studio - Core/MP2K.yaml index 7235295..1347ea8 100644 --- a/VG Music Studio - Core/MP2K.yaml +++ b/VG Music Studio - Core/MP2K.yaml @@ -223,20 +223,6 @@ AFXP_00: Name: "Final Fantasy Tactics Advance (Europe)" SongTableOffsets: 0x14F540 Copy: "AFXE_00" -AFZE_00: - Name: "F-Zero: Maximum Velocity (USA)" - SongTableOffsets: 0x54BF8 - SongTableSizes: 72 - SampleRate: 2 - ReverbType: "Normal" - Reverb: 0 - Volume: 10 - HasGoldenSunSynths: False - HasPokemonCompression: False -AFZJ_00: - Name: "F-Zero: Maximum Velocity (Japan)" - SongTableOffsets: 0x58324 - Copy: "AFZE_00" AGFD_00: Name: "Golden Sun: The Lost Age (Germany)" Copy: "AGFE_00" @@ -975,24 +961,6 @@ B24J_00: B24P_00: Name: "Pokémon Mystery Dungeon: Red Rescue Team (Europe)" Copy: "B24E_00" -B8KE_00: - Name: "Kirby & The Amazing Mirror (USA)" - SongTableOffsets: 0xB59ED0 - SongTableSizes: 620 - SampleRate: 4 - ReverbType: "Normal" - Reverb: 0 - Volume: 15 - HasGoldenSunSynths: False - HasPokemonCompression: False -B8KJ_01: - Name: "Kirby & The Amazing Mirror (Japan)" - SongTableOffsets: 0xB253E0 - Copy: "B8KE_00" -B8KP_00: - Name: "Kirby & The Amazing Mirror (Europe/Australia)" - SongTableOffsets: 0xB64334 - Copy: "B8KE_00" BE8E_00: Name: "Fire Emblem: The Sacred Stones (USA)" SongTableOffsets: 0x224470 @@ -1011,52 +979,6 @@ BE8P_00: Name: "Fire Emblem: The Sacred Stones (Europe)" SongTableOffsets: 0x42FFB0 Copy: "BE8E_00" -BFFE_00: - Name: "Final Fantasy I & II - Dawn of Souls (USA)" - SongTableOffsets: 0x8D3058 - SongTableSizes: 717 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 15 - HasGoldenSunSynths: False - HasPokemonCompression: False -BFFJ_01: - Name: "Final Fantasy I & II Advance (Japan)" - SongTableOffsets: 0x8F7BA8 - Copy: "BFFE_00" -BFFP_00: - Name: "Final Fantasy I & II - Dawn of Souls (Europe)" - SongTableOffsets: 0x974660 - Copy: "BFFE_00" -BFTJ_00: - Name: "F-Zero Climax (Japan)" - SongTableOffsets: 0x9EE84 - SongTableSizes: 439 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 14 - HasGoldenSunSynths: False - HasPokemonCompression: False -BFZE_00: - Name: "F-Zero: GP Legend (USA)" - SongTableOffsets: 0x97B44 - SongTableSizes: 352 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 14 - HasGoldenSunSynths: False - HasPokemonCompression: False -BFZJ_00: - Name: "F-Zero: GP Legend (Japan)" - SongTableOffsets: 0xA3BEC - Copy: "BFZE_00" -BFZP_00: - Name: "F-Zero: GP Legend (Europe)" - SongTableOffsets: 0xA21D4 - Copy: "BFZE_00" BMXC_00: Name: "Metroid: Zero Mission (China)" SongTableOffsets: 0xA8AAC @@ -1596,63 +1518,6 @@ BPRS_00: Name: "Pokémon Fire Red Version (Spain)" SongTableOffsets: 0x499BC8 Copy: "BPRE_00" -BZ4E_00: - Name: "Final Fantasy IV Advance (USA)" - SongTableOffsets: 0x3DC894 - SongTableSizes: 221 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 15 - HasGoldenSunSynths: False - HasPokemonCompression: False -BZ4J_00: - Name: "Final Fantasy IV Advance (Japan)" - SongTableOffsets: 0x416D0C - Copy: "BZ4E_00" -BZ4J_01: - SongTableOffsets: 0x3FA87C - Copy: "BZ4J_00" -BZ4P_00: - Name: "Final Fantasy IV Advance (Europe)" - SongTableOffsets: 0x4F5A5C - Copy: "BZ4E_00" -BZ5E_00: - Name: "Final Fantasy V Advance (USA)" - SongTableOffsets: 0x3F2CB4 - SongTableSizes: 290 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 15 - HasGoldenSunSynths: False - HasPokemonCompression: False -BZ5J_00: - Name: "Final Fantasy V Advance (Japan)" - SongTableOffsets: 0x41524C - Copy: "BZ5E_00" -BZ5P_00: - Name: "Final Fantasy V Advance (Europe)" - SongTableOffsets: 0x540620 - Copy: "BZ5E_00" -BZ6E_00: - Name: "Final Fantasy VI Advance (USA)" - SongTableOffsets: 0x1C6A94 - SongTableSizes: 371 - SampleRate: 5 - ReverbType: "Normal" - Reverb: 0 - Volume: 15 - HasGoldenSunSynths: False - HasPokemonCompression: False -BZ6J_00: - Name: "Final Fantasy VI Advance (Japan)" - SongTableOffsets: 0x1EA5DC - Copy: "BZ6E_00" -BZ6P_00: - Name: "Final Fantasy VI Advance (Europe)" - SongTableOffsets: 0x16F41C - Copy: "BZ6E_00" BZME_00: Name: "The Legend of Zelda: The Minish Cap (USA)" SongTableOffsets: 0xA11DBC @@ -1671,24 +1536,6 @@ BZMP_00: Name: "The Legend of Zelda: The Minish Cap (Europe)" SongTableOffsets: 0xB1D414 Copy: "BZME_00" -KYGE_00: - Name: "Yoshi Topsy-Turvy (USA)" - SongTableOffsets: 0x4A5E94 - SongTableSizes: 347 - SampleRate: 2 - ReverbType: "Normal" - Reverb: 0 - Volume: 10 - HasGoldenSunSynths: False - HasPokemonCompression: False -KYGJ_00: - Name: "Yoshi Topsy-Turvy (Japan)" - SongTableOffsets: 0x4A79D8 - Copy: "KYGE_00" -KYGP_00: - Name: "Yoshi Topsy-Turvy (Europe)" - SongTableOffsets: 0x619658 - Copy: "KYGE_00" U32E_00: Name: "Boktai 2 - Solar Boy Django (USA)" SongTableOffsets: 0x25EEA8 diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 7b8d4c5..a33fd80 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -1,28 +1,26 @@ -using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi; using NAudio.CoreAudioApi.Interfaces; using NAudio.Wave; using System; +using System.Diagnostics; +using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.Core; public abstract class Mixer : IAudioSessionEventsHandler, IDisposable { - public static event Action? VolumeChanged; + public static event Action? MixerVolumeChanged; public readonly bool[] Mutes; private IWavePlayer _out; private AudioSessionControl _appVolume; + private Process _appVol; private bool _shouldSendVolUpdateEvent = true; - protected WaveFileWriter? _waveWriter; - protected abstract WaveFormat WaveFormat { get; } - - protected Mixer() + protected Mixer() { Mutes = new bool[SongState.MAX_TRACKS]; - _out = null!; - _appVolume = null!; } protected void Init(IWaveProvider waveProvider) @@ -47,21 +45,34 @@ protected void Init(IWaveProvider waveProvider) _out.Play(); } - public void CreateWaveWriter(string fileName) - { - _waveWriter = new WaveFileWriter(fileName, WaveFormat); - } - public void CloseWaveWriter() - { - _waveWriter!.Dispose(); - _waveWriter = null; - } + // protected void Init(PortAudioOutputStream waveProvider) + // { + // _outStream = waveProvider; + //var dev = Configuration.DefaultOutputDevice; + // { + // var sessions = dev; + // int id = Environment.ProcessId; + // for (int i = 0; i < sessions; i++) + // { + // var sessionID = new int[i]; + // sessionID[i] = sessions; + // var session = Process.GetProcessById(sessionID[i]); + // if (session.SessionId == id) + // { + // _appVol = session; + // _appVolume.RegisterEventClient(this); + // break; + // } + // } + // } + // _outStream.StartStream(); + // } - public void OnVolumeChanged(float volume, bool isMuted) + public void OnVolumeChanged(float volume, bool isMuted) { if (_shouldSendVolUpdateEvent) { - VolumeChanged?.Invoke(volume); + MixerVolumeChanged?.Invoke(volume); } _shouldSendVolUpdateEvent = true; } @@ -101,9 +112,8 @@ public void SetVolume(float volume) public virtual void Dispose() { - GC.SuppressFinalize(this); _out.Stop(); _out.Dispose(); _appVolume.Dispose(); } -} +} \ No newline at end of file diff --git a/VG Music Studio - Core/NDS/DSE/Channel.cs b/VG Music Studio - Core/NDS/DSE/Channel.cs new file mode 100644 index 0000000..e97da44 --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Channel.cs @@ -0,0 +1,368 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal class Channel + { + public readonly byte Index; + + public Track? Owner; + public EnvelopeState State; + public byte RootKey; + public byte Key; + public byte NoteVelocity; + public sbyte Panpot; // Not necessary + public ushort BaseTimer; + public ushort Timer; + public uint NoteLength; + public byte Volume; + + private int _pos; + private short _prevLeft; + private short _prevRight; + + private int _envelopeTimeLeft; + private int _volumeIncrement; + private int _velocity; // From 0-0x3FFFFFFF ((128 << 23) - 1) + private byte _targetVolume; + + private byte _attackVolume; + private byte _attack; + private byte _decay; + private byte _sustain; + private byte _hold; + private byte _decay2; + private byte _release; + + // PCM8, PCM16, ADPCM + private SWD.SampleBlock _sample; + // PCM8, PCM16 + private int _dataOffset; + // ADPCM + private ADPCMDecoder _adpcmDecoder; + private short _adpcmLoopLastSample; + private short _adpcmLoopStepIndex; + + public Channel(byte i) + { + Index = i; + } + + public bool StartPCM(SWD localswd, SWD masterswd, byte voice, int key, uint noteLength) + { + SWD.IProgramInfo programInfo = localswd.Programs.ProgramInfos[voice]; + if (programInfo != null) + { + for (int i = 0; i < programInfo.SplitEntries.Length; i++) + { + SWD.ISplitEntry split = programInfo.SplitEntries[i]; + if (key >= split.LowKey && key <= split.HighKey) + { + _sample = masterswd.Samples[split.SampleId]; + Key = (byte)key; + RootKey = split.SampleRootKey; + BaseTimer = (ushort)(NDS.Utils.ARM7_CLOCK / _sample.WavInfo.SampleRate); + if (_sample.WavInfo.SampleFormat == SampleFormat.ADPCM) + { + _adpcmDecoder = new ADPCMDecoder(_sample.Data); + } + //attackVolume = sample.WavInfo.AttackVolume == 0 ? split.AttackVolume : sample.WavInfo.AttackVolume; + //attack = sample.WavInfo.Attack == 0 ? split.Attack : sample.WavInfo.Attack; + //decay = sample.WavInfo.Decay == 0 ? split.Decay : sample.WavInfo.Decay; + //sustain = sample.WavInfo.Sustain == 0 ? split.Sustain : sample.WavInfo.Sustain; + //hold = sample.WavInfo.Hold == 0 ? split.Hold : sample.WavInfo.Hold; + //decay2 = sample.WavInfo.Decay2 == 0 ? split.Decay2 : sample.WavInfo.Decay2; + //release = sample.WavInfo.Release == 0 ? split.Release : sample.WavInfo.Release; + //attackVolume = split.AttackVolume == 0 ? sample.WavInfo.AttackVolume : split.AttackVolume; + //attack = split.Attack == 0 ? sample.WavInfo.Attack : split.Attack; + //decay = split.Decay == 0 ? sample.WavInfo.Decay : split.Decay; + //sustain = split.Sustain == 0 ? sample.WavInfo.Sustain : split.Sustain; + //hold = split.Hold == 0 ? sample.WavInfo.Hold : split.Hold; + //decay2 = split.Decay2 == 0 ? sample.WavInfo.Decay2 : split.Decay2; + //release = split.Release == 0 ? sample.WavInfo.Release : split.Release; + _attackVolume = split.AttackVolume == 0 ? _sample.WavInfo.AttackVolume == 0 ? (byte)0x7F : _sample.WavInfo.AttackVolume : split.AttackVolume; + _attack = split.Attack == 0 ? _sample.WavInfo.Attack == 0 ? (byte)0x7F : _sample.WavInfo.Attack : split.Attack; + _decay = split.Decay == 0 ? _sample.WavInfo.Decay == 0 ? (byte)0x7F : _sample.WavInfo.Decay : split.Decay; + _sustain = split.Sustain == 0 ? _sample.WavInfo.Sustain == 0 ? (byte)0x7F : _sample.WavInfo.Sustain : split.Sustain; + _hold = split.Hold == 0 ? _sample.WavInfo.Hold == 0 ? (byte)0x7F : _sample.WavInfo.Hold : split.Hold; + _decay2 = split.Decay2 == 0 ? _sample.WavInfo.Decay2 == 0 ? (byte)0x7F : _sample.WavInfo.Decay2 : split.Decay2; + _release = split.Release == 0 ? _sample.WavInfo.Release == 0 ? (byte)0x7F : _sample.WavInfo.Release : split.Release; + DetermineEnvelopeStartingPoint(); + _pos = 0; + _prevLeft = _prevRight = 0; + NoteLength = noteLength; + return true; + } + } + } + return false; + } + + public void Stop() + { + if (Owner is not null) + { + Owner.Channels.Remove(this); + } + Owner = null; + Volume = 0; + } + + private bool CMDB1___sub_2074CA0() + { + bool b = true; + bool ge = _sample.WavInfo.EnvMult >= 0x7F; + bool ee = _sample.WavInfo.EnvMult == 0x7F; + if (_sample.WavInfo.EnvMult > 0x7F) + { + ge = _attackVolume >= 0x7F; + ee = _attackVolume == 0x7F; + } + if (!ee & ge + && _attack > 0x7F + && _decay > 0x7F + && _sustain > 0x7F + && _hold > 0x7F + && _decay2 > 0x7F + && _release > 0x7F) + { + b = false; + } + return b; + } + private void DetermineEnvelopeStartingPoint() + { + State = EnvelopeState.Two; // This isn't actually placed in this func + bool atLeastOneThingIsValid = CMDB1___sub_2074CA0(); // Neither is this + if (atLeastOneThingIsValid) + { + if (_attack != 0) + { + _velocity = _attackVolume << 23; + State = EnvelopeState.Hold; + UpdateEnvelopePlan(0x7F, _attack); + } + else + { + _velocity = 0x7F << 23; + if (_hold != 0) + { + UpdateEnvelopePlan(0x7F, _hold); + State = EnvelopeState.Decay; + } + else if (_decay != 0) + { + UpdateEnvelopePlan(_sustain, _decay); + State = EnvelopeState.Decay2; + } + else + { + UpdateEnvelopePlan(0, _release); + State = EnvelopeState.Six; + } + } + // Unk1E = 1 + } + else if (State != EnvelopeState.One) // What should it be? + { + State = EnvelopeState.Zero; + _velocity = 0x7F << 23; + } + } + public void SetEnvelopePhase7_2074ED8() + { + if (State != EnvelopeState.Zero) + { + UpdateEnvelopePlan(0, _release); + State = EnvelopeState.Seven; + } + } + public int StepEnvelope() + { + if (State > EnvelopeState.Two) + { + if (_envelopeTimeLeft != 0) + { + _envelopeTimeLeft--; + _velocity += _volumeIncrement; + if (_velocity < 0) + { + _velocity = 0; + } + else if (_velocity > 0x3FFFFFFF) + { + _velocity = 0x3FFFFFFF; + } + } + else + { + _velocity = _targetVolume << 23; + switch (State) + { + default: return _velocity >> 23; // case 8 + case EnvelopeState.Hold: + { + if (_hold == 0) + { + goto LABEL_6; + } + else + { + UpdateEnvelopePlan(0x7F, _hold); + State = EnvelopeState.Decay; + } + break; + } + case EnvelopeState.Decay: + LABEL_6: + { + if (_decay == 0) + { + _velocity = _sustain << 23; + goto LABEL_9; + } + else + { + UpdateEnvelopePlan(_sustain, _decay); + State = EnvelopeState.Decay2; + } + break; + } + case EnvelopeState.Decay2: + LABEL_9: + { + if (_decay2 == 0) + { + goto LABEL_11; + } + else + { + UpdateEnvelopePlan(0, _decay2); + State = EnvelopeState.Six; + } + break; + } + case EnvelopeState.Six: + LABEL_11: + { + UpdateEnvelopePlan(0, 0); + State = EnvelopeState.Two; + break; + } + case EnvelopeState.Seven: + { + State = EnvelopeState.Eight; + _velocity = 0; + _envelopeTimeLeft = 0; + break; + } + } + } + } + return _velocity >> 23; + } + private void UpdateEnvelopePlan(byte targetVolume, int envelopeParam) + { + if (envelopeParam == 0x7F) + { + _volumeIncrement = 0; + _envelopeTimeLeft = int.MaxValue; + } + else + { + _targetVolume = targetVolume; + _envelopeTimeLeft = _sample.WavInfo.EnvMult == 0 + ? Utils.Duration32[envelopeParam] * 1000 / 10000 + : Utils.Duration16[envelopeParam] * _sample.WavInfo.EnvMult * 1000 / 10000; + _volumeIncrement = _envelopeTimeLeft == 0 ? 0 : ((targetVolume << 23) - _velocity) / _envelopeTimeLeft; + } + } + + public void Process(out short left, out short right) + { + if (Timer != 0) + { + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + // prevLeft and prevRight are stored because numSamples can be 0. + for (int i = 0; i < numSamples; i++) + { + short samp; + switch (_sample.WavInfo.SampleFormat) + { + case SampleFormat.PCM8: + { + // If hit end + if (_dataOffset >= _sample.Data.Length) + { + if (_sample.WavInfo.Loop) + { + _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)((sbyte)_sample.Data[_dataOffset++] << 8); + break; + } + case SampleFormat.PCM16: + { + // If hit end + if (_dataOffset >= _sample.Data.Length) + { + if (_sample.WavInfo.Loop) + { + _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)(_sample.Data[_dataOffset++] | (_sample.Data[_dataOffset++] << 8)); + break; + } + case SampleFormat.ADPCM: + { + // If just looped + if (_adpcmDecoder.DataOffset == _sample.WavInfo.LoopStart * 4 && !_adpcmDecoder.OnSecondNibble) + { + _adpcmLoopLastSample = _adpcmDecoder.LastSample; + _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; + } + // If hit end + if (_adpcmDecoder.DataOffset >= _sample.Data.Length && !_adpcmDecoder.OnSecondNibble) + { + if (_sample.WavInfo.Loop) + { + _adpcmDecoder.DataOffset = (int)(_sample.WavInfo.LoopStart * 4); + _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; + _adpcmDecoder.LastSample = _adpcmLoopLastSample; + _adpcmDecoder.OnSecondNibble = false; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = _adpcmDecoder.GetSample(); + break; + } + default: samp = 0; break; + } + samp = (short)(samp * Volume / 0x7F); + _prevLeft = (short)(samp * (-Panpot + 0x40) / 0x80); + _prevRight = (short)(samp * (Panpot + 0x40) / 0x80); + } + } + left = _prevLeft; + right = _prevRight; + } + } +} diff --git a/VG Music Studio - Core/NDS/DSE/DSECommands.cs b/VG Music Studio - Core/NDS/DSE/Commands.cs similarity index 78% rename from VG Music Studio - Core/NDS/DSE/DSECommands.cs rename to VG Music Studio - Core/NDS/DSE/Commands.cs index 76e8e5b..cc8ac62 100644 --- a/VG Music Studio - Core/NDS/DSE/DSECommands.cs +++ b/VG Music Studio - Core/NDS/DSE/Commands.cs @@ -4,7 +4,7 @@ namespace Kermalis.VGMusicStudio.Core.NDS.DSE; -internal sealed class ExpressionCommand : ICommand +internal class ExpressionCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Expression"; @@ -12,13 +12,13 @@ internal sealed class ExpressionCommand : ICommand public byte Expression { get; set; } } -internal sealed class FinishCommand : ICommand +internal class FinishCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Finish"; public string Arguments => string.Empty; } -internal sealed class InvalidCommand : ICommand +internal class InvalidCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Invalid 0x{Command:X}"; @@ -26,7 +26,7 @@ internal sealed class InvalidCommand : ICommand public byte Command { get; set; } } -internal sealed class LoopStartCommand : ICommand +internal class LoopStartCommand : ICommand { public Color Color => Color.MediumSpringGreen; public string Label => "Loop Start"; @@ -34,7 +34,7 @@ internal sealed class LoopStartCommand : ICommand public long Offset { get; set; } } -internal sealed class NoteCommand : ICommand +internal class NoteCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Note"; @@ -45,7 +45,7 @@ internal sealed class NoteCommand : ICommand public byte Velocity { get; set; } public uint Duration { get; set; } } -internal sealed class OctaveAddCommand : ICommand +internal class OctaveAddCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Add To Octave"; @@ -53,7 +53,7 @@ internal sealed class OctaveAddCommand : ICommand public sbyte OctaveChange { get; set; } } -internal sealed class OctaveSetCommand : ICommand +internal class OctaveSetCommand : ICommand { public Color Color => Color.SkyBlue; public string Label => "Set Octave"; @@ -61,7 +61,7 @@ internal sealed class OctaveSetCommand : ICommand public byte Octave { get; set; } } -internal sealed class PanpotCommand : ICommand +internal class PanpotCommand : ICommand { public Color Color => Color.GreenYellow; public string Label => "Panpot"; @@ -69,7 +69,7 @@ internal sealed class PanpotCommand : ICommand public sbyte Panpot { get; set; } } -internal sealed class PitchBendCommand : ICommand +internal class PitchBendCommand : ICommand { public Color Color => Color.MediumPurple; public string Label => "Pitch Bend"; @@ -77,7 +77,7 @@ internal sealed class PitchBendCommand : ICommand public ushort Bend { get; set; } } -internal sealed class RestCommand : ICommand +internal class RestCommand : ICommand { public Color Color => Color.PaleVioletRed; public string Label => "Rest"; @@ -85,16 +85,16 @@ internal sealed class RestCommand : ICommand public uint Rest { get; set; } } -internal sealed class SkipBytesCommand : ICommand +internal class SkipBytesCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Skip 0x{Command:X}"; public string Arguments => string.Join(", ", SkippedBytes.Select(b => $"0x{b:X}")); public byte Command { get; set; } - public byte[] SkippedBytes { get; set; } = null!; + public byte[] SkippedBytes { get; set; } } -internal sealed class TempoCommand : ICommand +internal class TempoCommand : ICommand { public Color Color => Color.DeepSkyBlue; public string Label => $"Tempo {Command - 0xA3}"; // The two possible tempo commands are 0xA4 and 0xA5 @@ -103,16 +103,16 @@ internal sealed class TempoCommand : ICommand public byte Command { get; set; } public byte Tempo { get; set; } } -internal sealed class UnknownCommand : ICommand +internal class UnknownCommand : ICommand { public Color Color => Color.MediumVioletRed; public string Label => $"Unknown 0x{Command:X}"; public string Arguments => string.Join(", ", Args.Select(b => $"0x{b:X}")); public byte Command { get; set; } - public byte[] Args { get; set; } = null!; + public byte[] Args { get; set; } } -internal sealed class VoiceCommand : ICommand +internal class VoiceCommand : ICommand { public Color Color => Color.DarkSalmon; public string Label => "Voice"; @@ -120,7 +120,7 @@ internal sealed class VoiceCommand : ICommand public byte Voice { get; set; } } -internal sealed class VolumeCommand : ICommand +internal class VolumeCommand : ICommand { public Color Color => Color.SteelBlue; public string Label => "Volume"; diff --git a/VG Music Studio - Core/NDS/DSE/DSEChannel.cs b/VG Music Studio - Core/NDS/DSE/DSEChannel.cs deleted file mode 100644 index 11670ce..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEChannel.cs +++ /dev/null @@ -1,373 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class DSEChannel -{ - public readonly byte Index; - - public DSETrack? Owner; - public EnvelopeState State; - public byte RootKey; - public byte Key; - public byte NoteVelocity; - public sbyte Panpot; // Not necessary - public ushort BaseTimer; - public ushort Timer; - public uint NoteLength; - public byte Volume; - - private int _pos; - private short _prevLeft; - private short _prevRight; - - private int _envelopeTimeLeft; - private int _volumeIncrement; - private int _velocity; // From 0-0x3FFFFFFF ((128 << 23) - 1) - private byte _targetVolume; - - private byte _attackVolume; - private byte _attack; - private byte _decay; - private byte _sustain; - private byte _hold; - private byte _decay2; - private byte _release; - - // PCM8, PCM16, ADPCM - private SWD.SampleBlock _sample; - // PCM8, PCM16 - private int _dataOffset; - // ADPCM - private ADPCMDecoder _adpcmDecoder; - private short _adpcmLoopLastSample; - private short _adpcmLoopStepIndex; - - public DSEChannel(byte i) - { - _sample = null!; - Index = i; - } - - public bool StartPCM(SWD localswd, SWD masterswd, byte voice, int key, uint noteLength) - { - SWD.IProgramInfo? programInfo = localswd.Programs?.ProgramInfos[voice]; - if (programInfo is null) - { - return false; - } - - for (int i = 0; i < programInfo.SplitEntries.Length; i++) - { - SWD.ISplitEntry split = programInfo.SplitEntries[i]; - if (key < split.LowKey || key > split.HighKey) - { - continue; - } - - _sample = masterswd.Samples![split.SampleId]; - Key = (byte)key; - RootKey = split.SampleRootKey; - BaseTimer = (ushort)(NDSUtils.ARM7_CLOCK / _sample.WavInfo.SampleRate); - if (_sample.WavInfo.SampleFormat == SampleFormat.ADPCM) - { - _adpcmDecoder.Init(_sample.Data); - } - //attackVolume = sample.WavInfo.AttackVolume == 0 ? split.AttackVolume : sample.WavInfo.AttackVolume; - //attack = sample.WavInfo.Attack == 0 ? split.Attack : sample.WavInfo.Attack; - //decay = sample.WavInfo.Decay == 0 ? split.Decay : sample.WavInfo.Decay; - //sustain = sample.WavInfo.Sustain == 0 ? split.Sustain : sample.WavInfo.Sustain; - //hold = sample.WavInfo.Hold == 0 ? split.Hold : sample.WavInfo.Hold; - //decay2 = sample.WavInfo.Decay2 == 0 ? split.Decay2 : sample.WavInfo.Decay2; - //release = sample.WavInfo.Release == 0 ? split.Release : sample.WavInfo.Release; - //attackVolume = split.AttackVolume == 0 ? sample.WavInfo.AttackVolume : split.AttackVolume; - //attack = split.Attack == 0 ? sample.WavInfo.Attack : split.Attack; - //decay = split.Decay == 0 ? sample.WavInfo.Decay : split.Decay; - //sustain = split.Sustain == 0 ? sample.WavInfo.Sustain : split.Sustain; - //hold = split.Hold == 0 ? sample.WavInfo.Hold : split.Hold; - //decay2 = split.Decay2 == 0 ? sample.WavInfo.Decay2 : split.Decay2; - //release = split.Release == 0 ? sample.WavInfo.Release : split.Release; - _attackVolume = split.AttackVolume == 0 ? _sample.WavInfo.AttackVolume == 0 ? (byte)0x7F : _sample.WavInfo.AttackVolume : split.AttackVolume; - _attack = split.Attack == 0 ? _sample.WavInfo.Attack == 0 ? (byte)0x7F : _sample.WavInfo.Attack : split.Attack; - _decay = split.Decay == 0 ? _sample.WavInfo.Decay == 0 ? (byte)0x7F : _sample.WavInfo.Decay : split.Decay; - _sustain = split.Sustain == 0 ? _sample.WavInfo.Sustain == 0 ? (byte)0x7F : _sample.WavInfo.Sustain : split.Sustain; - _hold = split.Hold == 0 ? _sample.WavInfo.Hold == 0 ? (byte)0x7F : _sample.WavInfo.Hold : split.Hold; - _decay2 = split.Decay2 == 0 ? _sample.WavInfo.Decay2 == 0 ? (byte)0x7F : _sample.WavInfo.Decay2 : split.Decay2; - _release = split.Release == 0 ? _sample.WavInfo.Release == 0 ? (byte)0x7F : _sample.WavInfo.Release : split.Release; - DetermineEnvelopeStartingPoint(); - _pos = 0; - _prevLeft = _prevRight = 0; - NoteLength = noteLength; - return true; - } - return false; - } - - public void Stop() - { - Owner?.Channels.Remove(this); - Owner = null; - Volume = 0; - } - - private bool CMDB1___sub_2074CA0() - { - bool b = true; - bool ge = _sample.WavInfo.EnvMult >= 0x7F; - bool ee = _sample.WavInfo.EnvMult == 0x7F; - if (_sample.WavInfo.EnvMult > 0x7F) - { - ge = _attackVolume >= 0x7F; - ee = _attackVolume == 0x7F; - } - if (!ee & ge - && _attack > 0x7F - && _decay > 0x7F - && _sustain > 0x7F - && _hold > 0x7F - && _decay2 > 0x7F - && _release > 0x7F) - { - b = false; - } - return b; - } - private void DetermineEnvelopeStartingPoint() - { - State = EnvelopeState.Two; // This isn't actually placed in this func - bool atLeastOneThingIsValid = CMDB1___sub_2074CA0(); // Neither is this - if (atLeastOneThingIsValid) - { - if (_attack != 0) - { - _velocity = _attackVolume << 23; - State = EnvelopeState.Hold; - UpdateEnvelopePlan(0x7F, _attack); - } - else - { - _velocity = 0x7F << 23; - if (_hold != 0) - { - UpdateEnvelopePlan(0x7F, _hold); - State = EnvelopeState.Decay; - } - else if (_decay != 0) - { - UpdateEnvelopePlan(_sustain, _decay); - State = EnvelopeState.Decay2; - } - else - { - UpdateEnvelopePlan(0, _release); - State = EnvelopeState.Six; - } - } - // Unk1E = 1 - } - else if (State != EnvelopeState.One) // What should it be? - { - State = EnvelopeState.Zero; - _velocity = 0x7F << 23; - } - } - public void SetEnvelopePhase7_2074ED8() - { - if (State != EnvelopeState.Zero) - { - UpdateEnvelopePlan(0, _release); - State = EnvelopeState.Seven; - } - } - public int StepEnvelope() - { - if (State > EnvelopeState.Two) - { - if (_envelopeTimeLeft != 0) - { - _envelopeTimeLeft--; - _velocity += _volumeIncrement; - if (_velocity < 0) - { - _velocity = 0; - } - else if (_velocity > 0x3FFFFFFF) - { - _velocity = 0x3FFFFFFF; - } - } - else - { - _velocity = _targetVolume << 23; - switch (State) - { - default: return _velocity >> 23; // case 8 - case EnvelopeState.Hold: - { - if (_hold == 0) - { - goto LABEL_6; - } - else - { - UpdateEnvelopePlan(0x7F, _hold); - State = EnvelopeState.Decay; - } - break; - } - case EnvelopeState.Decay: - LABEL_6: - { - if (_decay == 0) - { - _velocity = _sustain << 23; - goto LABEL_9; - } - else - { - UpdateEnvelopePlan(_sustain, _decay); - State = EnvelopeState.Decay2; - } - break; - } - case EnvelopeState.Decay2: - LABEL_9: - { - if (_decay2 == 0) - { - goto LABEL_11; - } - else - { - UpdateEnvelopePlan(0, _decay2); - State = EnvelopeState.Six; - } - break; - } - case EnvelopeState.Six: - LABEL_11: - { - UpdateEnvelopePlan(0, 0); - State = EnvelopeState.Two; - break; - } - case EnvelopeState.Seven: - { - State = EnvelopeState.Eight; - _velocity = 0; - _envelopeTimeLeft = 0; - break; - } - } - } - } - return _velocity >> 23; - } - private void UpdateEnvelopePlan(byte targetVolume, int envelopeParam) - { - if (envelopeParam == 0x7F) - { - _volumeIncrement = 0; - _envelopeTimeLeft = int.MaxValue; - } - else - { - _targetVolume = targetVolume; - _envelopeTimeLeft = _sample.WavInfo.EnvMult == 0 - ? DSEUtils.Duration32[envelopeParam] * 1_000 / 10_000 - : DSEUtils.Duration16[envelopeParam] * _sample.WavInfo.EnvMult * 1_000 / 10_000; - _volumeIncrement = _envelopeTimeLeft == 0 ? 0 : ((targetVolume << 23) - _velocity) / _envelopeTimeLeft; - } - } - - public void Process(out short left, out short right) - { - if (Timer == 0) - { - left = _prevLeft; - right = _prevRight; - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - // prevLeft and prevRight are stored because numSamples can be 0. - for (int i = 0; i < numSamples; i++) - { - short samp; - switch (_sample.WavInfo.SampleFormat) - { - case SampleFormat.PCM8: - { - // If hit end - if (_dataOffset >= _sample.Data.Length) - { - if (_sample.WavInfo.Loop) - { - _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)((sbyte)_sample.Data[_dataOffset++] << 8); - break; - } - case SampleFormat.PCM16: - { - // If hit end - if (_dataOffset >= _sample.Data.Length) - { - if (_sample.WavInfo.Loop) - { - _dataOffset = (int)(_sample.WavInfo.LoopStart * 4); - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)(_sample.Data[_dataOffset++] | (_sample.Data[_dataOffset++] << 8)); - break; - } - case SampleFormat.ADPCM: - { - // If just looped - if (_adpcmDecoder.DataOffset == _sample.WavInfo.LoopStart * 4 && !_adpcmDecoder.OnSecondNibble) - { - _adpcmLoopLastSample = _adpcmDecoder.LastSample; - _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; - } - // If hit end - if (_adpcmDecoder.DataOffset >= _sample.Data.Length && !_adpcmDecoder.OnSecondNibble) - { - if (_sample.WavInfo.Loop) - { - _adpcmDecoder.DataOffset = (int)(_sample.WavInfo.LoopStart * 4); - _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; - _adpcmDecoder.LastSample = _adpcmLoopLastSample; - _adpcmDecoder.OnSecondNibble = false; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = _adpcmDecoder.GetSample(); - break; - } - default: samp = 0; break; - } - samp = (short)(samp * Volume / 0x7F); - _prevLeft = (short)(samp * (-Panpot + 0x40) / 0x80); - _prevRight = (short)(samp * (Panpot + 0x40) / 0x80); - } - left = _prevLeft; - right = _prevRight; - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEConfig.cs b/VG Music Studio - Core/NDS/DSE/DSEConfig.cs index 6a68eed..69edd6c 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEConfig.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEConfig.cs @@ -1,7 +1,7 @@ using Kermalis.EndianBinaryIO; using Kermalis.VGMusicStudio.Core.Properties; -using System.Collections.Generic; using System.IO; +using System.Linq; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; @@ -19,17 +19,14 @@ internal DSEConfig(string bgmPath) throw new DSENoSequencesException(bgmPath); } - // TODO: Big endian files - var songs = new List(BGMFiles.Length); + var songs = new Song[BGMFiles.Length]; for (int i = 0; i < BGMFiles.Length; i++) { using (FileStream stream = File.OpenRead(BGMFiles[i])) { var r = new EndianBinaryReader(stream, ascii: true); SMD.Header header = r.ReadObject(); - char[] chars = header.Label.ToCharArray(); - EndianBinaryPrimitives.TrimNullTerminators(ref chars); - songs.Add(new Song(i, $"{Path.GetFileNameWithoutExtension(BGMFiles[i])} - {new string(chars)}")); + songs[i] = new Song(i, $"{Path.GetFileNameWithoutExtension(BGMFiles[i])} - {new string(header.Label.TakeWhile(c => c != '\0').ToArray())}"); } } Playlists.Add(new Playlist(Strings.PlaylistMusic, songs)); @@ -39,7 +36,7 @@ public override string GetGameName() { return "DSE"; } - public override string GetSongName(int index) + public override string GetSongName(long index) { return index < 0 || index >= BGMFiles.Length ? index.ToString() diff --git a/VG Music Studio - Core/NDS/DSE/DSEEnums.cs b/VG Music Studio - Core/NDS/DSE/DSEEnums.cs deleted file mode 100644 index 911c5f0..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEEnums.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal enum EnvelopeState : byte -{ - Zero = 0, - One = 1, - Two = 2, - Hold = 3, - Decay = 4, - Decay2 = 5, - Six = 6, - Seven = 7, - Eight = 8, -} - -internal enum SampleFormat : ushort -{ - PCM8 = 0x000, - PCM16 = 0x100, - ADPCM = 0x200, -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs deleted file mode 100644 index 2cee106..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Kermalis.EndianBinaryIO; -using Kermalis.VGMusicStudio.Core.Util; -using System.Collections.Generic; -using System.IO; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong : ILoadedSong -{ - public List[] Events { get; } - public long MaxTicks { get; private set; } - public int LongestTrack; - - private readonly DSEPlayer _player; - private readonly SWD LocalSWD; - private readonly byte[] SMDFile; - public readonly DSETrack[] Tracks; - - public DSELoadedSong(DSEPlayer player, string bgm) - { - _player = player; - - LocalSWD = new SWD(Path.ChangeExtension(bgm, "swd")); - SMDFile = File.ReadAllBytes(bgm); - using (var stream = new MemoryStream(SMDFile)) - { - var r = new EndianBinaryReader(stream, ascii: true); - SMD.Header header = r.ReadObject(); - SMD.ISongChunk songChunk; - switch (header.Version) - { - case 0x402: - { - songChunk = r.ReadObject(); - break; - } - case 0x415: - { - songChunk = r.ReadObject(); - break; - } - default: throw new DSEInvalidHeaderVersionException(header.Version); - } - - Tracks = new DSETrack[songChunk.NumTracks]; - Events = new List[songChunk.NumTracks]; - for (byte trackIndex = 0; trackIndex < songChunk.NumTracks; trackIndex++) - { - long chunkStart = r.Stream.Position; - r.Stream.Position += 0x14; // Skip header - Tracks[trackIndex] = new DSETrack(trackIndex, (int)r.Stream.Position); - - AddTrackEvents(trackIndex, r); - - r.Stream.Position = chunkStart + 0xC; - uint chunkLength = r.ReadUInt32(); - r.Stream.Position += chunkLength; - r.Stream.Align(16); - } - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs deleted file mode 100644 index b37dde9..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Events.cs +++ /dev/null @@ -1,461 +0,0 @@ -using Kermalis.EndianBinaryIO; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, ICommand command) - { - Events[trackIndex].Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex].Exists(e => e.Offset == cmdOffset); - } - - private void AddTrackEvents(byte trackIndex, EndianBinaryReader r) - { - Events[trackIndex] = new List(); - - uint lastNoteDuration = 0; - uint lastRest = 0; - bool cont = true; - while (cont) - { - long cmdOffset = r.Stream.Position; - byte cmd = r.ReadByte(); - if (cmd <= 0x7F) - { - byte arg = r.ReadByte(); - int numParams = (arg & 0xC0) >> 6; - int oct = ((arg & 0x30) >> 4) - 2; - int n = arg & 0xF; - if (n >= 12) - { - throw new DSEInvalidNoteException(trackIndex, (int)cmdOffset, n); - } - - uint duration; - if (numParams == 0) - { - duration = lastNoteDuration; - } - else // Big Endian reading of 8, 16, or 24 bits - { - duration = 0; - for (int b = 0; b < numParams; b++) - { - duration = (duration << 8) | r.ReadByte(); - } - lastNoteDuration = duration; - } - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteCommand { Note = (byte)n, OctaveChange = (sbyte)oct, Velocity = cmd, Duration = duration }); - } - } - else if (cmd >= 0x80 && cmd <= 0x8F) - { - lastRest = DSEUtils.FixedRests[cmd - 0x80]; - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - } - else // 0x90-0xFF - { - // TODO: 0x95 - a rest that may or may not repeat depending on some condition within channels - // TODO: 0x9E - may or may not jump somewhere else depending on an unknown structure - switch (cmd) - { - case 0x90: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x91: - { - lastRest = (uint)(lastRest + r.ReadSByte()); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x92: - { - lastRest = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x93: - { - lastRest = r.ReadUInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x94: - { - lastRest = (uint)(r.ReadByte() | (r.ReadByte() << 8) | (r.ReadByte() << 16)); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = lastRest }); - } - break; - } - case 0x96: - case 0x97: - case 0x9A: - case 0x9B: - case 0x9F: - case 0xA2: - case 0xA3: - case 0xA6: - case 0xA7: - case 0xAD: - case 0xAE: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBD: - case 0xC1: - case 0xC2: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD9: - case 0xDA: - case 0xDE: - case 0xE6: - case 0xEB: - case 0xEE: - case 0xF4: - case 0xF5: - case 0xF7: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new InvalidCommand { Command = cmd }); - } - break; - } - case 0x98: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand()); - } - cont = false; - break; - } - case 0x99: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopStartCommand { Offset = r.Stream.Position }); - } - break; - } - case 0xA0: - { - byte octave = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OctaveSetCommand { Octave = octave }); - } - break; - } - case 0xA1: - { - sbyte change = r.ReadSByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OctaveAddCommand { OctaveChange = change }); - } - break; - } - case 0xA4: - case 0xA5: // The code for these two is identical - { - byte tempoArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TempoCommand { Command = cmd, Tempo = tempoArg }); - } - break; - } - case 0xAB: - { - byte[] bytes = new byte[1]; - r.ReadBytes(bytes); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); - } - break; - } - case 0xAC: - { - byte voice = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = voice }); - } - break; - } - case 0xCB: - case 0xF8: - { - byte[] bytes = new byte[2]; - r.ReadBytes(bytes); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); - } - break; - } - case 0xD7: - { - ushort bend = r.ReadUInt16(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = bend }); - } - break; - } - case 0xE0: - { - byte volume = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VolumeCommand { Volume = volume }); - } - break; - } - case 0xE3: - { - byte expression = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ExpressionCommand { Expression = expression }); - } - break; - } - case 0xE8: - { - byte panArg = r.ReadByte(); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); - } - break; - } - case 0x9D: - case 0xB0: - case 0xC0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = Array.Empty() }); - } - break; - } - case 0x9C: - case 0xA9: - case 0xAA: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB5: - case 0xB6: - case 0xBC: - case 0xBE: - case 0xBF: - case 0xC3: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xDB: - case 0xDF: - case 0xE1: - case 0xE7: - case 0xE9: - case 0xEF: - case 0xF6: - { - byte[] args = new byte[1]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xA8: - case 0xB4: - case 0xD3: - case 0xD5: - case 0xD6: - case 0xD8: - case 0xF2: - { - byte[] args = new byte[2]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xAF: - case 0xD4: - case 0xE2: - case 0xEA: - case 0xF3: - { - byte[] args = new byte[3]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xDD: - case 0xE5: - case 0xED: - case 0xF1: - { - byte[] args = new byte[4]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - case 0xDC: - case 0xE4: - case 0xEC: - case 0xF0: - { - byte[] args = new byte[5]; - r.ReadBytes(args); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new UnknownCommand { Command = cmd, Args = args }); - } - break; - } - default: throw new DSEInvalidCMDException(trackIndex, (int)cmdOffset, cmd); - } - } - } - } - - public void SetTicks() - { - MaxTicks = 0; - for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) - { - List evs = Events[trackIndex]; - evs.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - - DSETrack track = Tracks[trackIndex]; - track.Init(); - - long elapsedTicks = 0; - while (true) - { - SongEvent e = evs.Single(ev => ev.Offset == track.CurOffset); - if (e.Ticks.Count > 0) - { - break; - } - - e.Ticks.Add(elapsedTicks); - ExecuteNext(track); - if (track.Stopped) - { - break; - } - - elapsedTicks += track.Rest; - track.Rest = 0; - } - if (elapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = elapsedTicks; - } - track.StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - DSETrack track = Tracks[trackIndex]; - if (!track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) - { - ExecuteNext(track); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - } - finish: - for (int i = 0; i < Tracks.Length; i++) - { - Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs b/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs deleted file mode 100644 index 90e30e4..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSELoadedSong_Runtime.cs +++ /dev/null @@ -1,285 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed partial class DSELoadedSong -{ - public void UpdateSongState(SongState info) - { - for (int trackIndex = 0; trackIndex < Tracks.Length; trackIndex++) - { - Tracks[trackIndex].UpdateSongState(info.Tracks[trackIndex]); - } - } - - public void ExecuteNext(DSETrack track) - { - byte cmd = SMDFile[track.CurOffset++]; - if (cmd <= 0x7F) - { - byte arg = SMDFile[track.CurOffset++]; - int numParams = (arg & 0xC0) >> 6; - int oct = ((arg & 0x30) >> 4) - 2; - int n = arg & 0xF; - if (n >= 12) - { - throw new DSEInvalidNoteException(track.Index, track.CurOffset - 2, n); - } - - uint duration; - if (numParams == 0) - { - duration = track.LastNoteDuration; - } - else - { - duration = 0; - for (int b = 0; b < numParams; b++) - { - duration = (duration << 8) | SMDFile[track.CurOffset++]; - } - track.LastNoteDuration = duration; - } - DSEChannel channel = _player.DMixer.AllocateChannel() - ?? throw new Exception("Not enough channels"); - - channel.Stop(); - track.Octave = (byte)(track.Octave + oct); - if (channel.StartPCM(LocalSWD, _player.MasterSWD, track.Voice, n + (12 * track.Octave), duration)) - { - channel.NoteVelocity = cmd; - channel.Owner = track; - track.Channels.Add(channel); - } - } - else if (cmd is >= 0x80 and <= 0x8F) - { - track.LastRest = DSEUtils.FixedRests[cmd - 0x80]; - track.Rest = track.LastRest; - } - else // 0x90-0xFF - { - // TODO: 0x95, 0x9E - switch (cmd) - { - case 0x90: - { - track.Rest = track.LastRest; - break; - } - case 0x91: - { - track.LastRest = (uint)(track.LastRest + (sbyte)SMDFile[track.CurOffset++]); - track.Rest = track.LastRest; - break; - } - case 0x92: - { - track.LastRest = SMDFile[track.CurOffset++]; - track.Rest = track.LastRest; - break; - } - case 0x93: - { - track.LastRest = (uint)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8)); - track.Rest = track.LastRest; - break; - } - case 0x94: - { - track.LastRest = (uint)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8) | (SMDFile[track.CurOffset++] << 16)); - track.Rest = track.LastRest; - break; - } - case 0x96: - case 0x97: - case 0x9A: - case 0x9B: - case 0x9F: - case 0xA2: - case 0xA3: - case 0xA6: - case 0xA7: - case 0xAD: - case 0xAE: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBD: - case 0xC1: - case 0xC2: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD9: - case 0xDA: - case 0xDE: - case 0xE6: - case 0xEB: - case 0xEE: - case 0xF4: - case 0xF5: - case 0xF7: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - { - track.Stopped = true; - break; - } - case 0x98: - { - if (track.LoopOffset == -1) - { - track.Stopped = true; - } - else - { - track.CurOffset = track.LoopOffset; - } - break; - } - case 0x99: - { - track.LoopOffset = track.CurOffset; - break; - } - case 0xA0: - { - track.Octave = SMDFile[track.CurOffset++]; - break; - } - case 0xA1: - { - track.Octave = (byte)(track.Octave + (sbyte)SMDFile[track.CurOffset++]); - break; - } - case 0xA4: - case 0xA5: - { - _player.Tempo = SMDFile[track.CurOffset++]; - break; - } - case 0xAB: - { - track.CurOffset++; - break; - } - case 0xAC: - { - track.Voice = SMDFile[track.CurOffset++]; - break; - } - case 0xCB: - case 0xF8: - { - track.CurOffset += 2; - break; - } - case 0xD7: - { - track.PitchBend = (ushort)(SMDFile[track.CurOffset++] | (SMDFile[track.CurOffset++] << 8)); - break; - } - case 0xE0: - { - track.Volume = SMDFile[track.CurOffset++]; - break; - } - case 0xE3: - { - track.Expression = SMDFile[track.CurOffset++]; - break; - } - case 0xE8: - { - track.Panpot = (sbyte)(SMDFile[track.CurOffset++] - 0x40); - break; - } - case 0x9D: - case 0xB0: - case 0xC0: - { - break; - } - case 0x9C: - case 0xA9: - case 0xAA: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB5: - case 0xB6: - case 0xBC: - case 0xBE: - case 0xBF: - case 0xC3: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xDB: - case 0xDF: - case 0xE1: - case 0xE7: - case 0xE9: - case 0xEF: - case 0xF6: - { - track.CurOffset++; - break; - } - case 0xA8: - case 0xB4: - case 0xD3: - case 0xD5: - case 0xD6: - case 0xD8: - case 0xF2: - { - track.CurOffset += 2; - break; - } - case 0xAF: - case 0xD4: - case 0xE2: - case 0xEA: - case 0xF3: - { - track.CurOffset += 3; - break; - } - case 0xDD: - case 0xE5: - case 0xED: - case 0xF1: - { - track.CurOffset += 4; - break; - } - case 0xDC: - case 0xE4: - case 0xEC: - case 0xF0: - { - track.CurOffset += 5; - break; - } - default: throw new DSEInvalidCMDException(track.Index, track.CurOffset - 1, cmd); - } - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs index 89f6c52..cbcf840 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs @@ -1,5 +1,4 @@ -using Kermalis.VGMusicStudio.Core.NDS.SDAT; -using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.Core.Util; using NAudio.Wave; using System; @@ -16,11 +15,9 @@ public sealed class DSEMixer : Mixer private float _fadePos; private float _fadeStepPerMicroframe; - private readonly DSEChannel[] _channels; + private readonly Channel[] _channels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - public DSEMixer() { // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. @@ -30,10 +27,10 @@ public DSEMixer() _samplesPerBuffer = 341; // TODO _samplesReciprocal = 1f / _samplesPerBuffer; - _channels = new DSEChannel[NUM_CHANNELS]; + _channels = new Channel[NUM_CHANNELS]; for (byte i = 0; i < NUM_CHANNELS; i++) { - _channels[i] = new DSEChannel(i); + _channels[i] = new Channel(i); } _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) @@ -44,17 +41,17 @@ public DSEMixer() Init(_buffer); } - internal DSEChannel? AllocateChannel() + internal Channel? AllocateChannel() { - static int GetScore(DSEChannel c) + static int GetScore(Channel c) { // Free channels should be used before releasing channels - return c.Owner is null ? -2 : DSEUtils.IsStateRemovable(c.State) ? -1 : 0; + return c.Owner is null ? -2 : Utils.IsStateRemovable(c.State) ? -1 : 0; } - DSEChannel? nChan = null; + Channel? nChan = null; for (int i = 0; i < NUM_CHANNELS; i++) { - DSEChannel c = _channels[i]; + Channel c = _channels[i]; if (nChan is null) { nChan = c; @@ -76,29 +73,29 @@ internal void ChannelTick() { for (int i = 0; i < NUM_CHANNELS; i++) { - DSEChannel chan = _channels[i]; + Channel chan = _channels[i]; if (chan.Owner is null) { continue; } chan.Volume = (byte)chan.StepEnvelope(); - if (chan.NoteLength == 0 && !DSEUtils.IsStateRemovable(chan.State)) + if (chan.NoteLength == 0 && !Utils.IsStateRemovable(chan.State)) { chan.SetEnvelopePhase7_2074ED8(); } - int vol = SDATUtils.SustainTable[chan.NoteVelocity] + SDATUtils.SustainTable[chan.Volume] + SDATUtils.SustainTable[chan.Owner.Volume] + SDATUtils.SustainTable[chan.Owner.Expression]; + int vol = SDAT.SDATUtils.SustainTable[chan.NoteVelocity] + SDAT.SDATUtils.SustainTable[chan.Volume] + SDAT.SDATUtils.SustainTable[chan.Owner.Volume] + SDAT.SDATUtils.SustainTable[chan.Owner.Expression]; //int pitch = ((chan.Key - chan.BaseKey) << 6) + chan.SweepMain() + chan.Owner.GetPitch(); // "<< 6" is "* 0x40" int pitch = (chan.Key - chan.RootKey) << 6; // "<< 6" is "* 0x40" - if (DSEUtils.IsStateRemovable(chan.State) && vol <= -92544) + if (Utils.IsStateRemovable(chan.State) && vol <= -92544) { chan.Stop(); } else { - chan.Volume = SDATUtils.GetChannelVolume(vol); + chan.Volume = SDAT.SDATUtils.GetChannelVolume(vol); chan.Panpot = chan.Owner.Panpot; - chan.Timer = SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); + chan.Timer = SDAT.SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); } } } @@ -131,6 +128,16 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } private readonly byte[] _b = new byte[4]; internal void Process(bool output, bool recording) { @@ -162,7 +169,7 @@ internal void Process(bool output, bool recording) right = 0; for (int j = 0; j < NUM_CHANNELS; j++) { - DSEChannel chan = _channels[j]; + Channel chan = _channels[j]; if (chan.Owner is null) { continue; diff --git a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs index bfdcda2..3eb9b59 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs @@ -1,135 +1,1046 @@ -using System.IO; +using Kermalis.EndianBinaryIO; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; -public sealed class DSEPlayer : Player +public sealed class DSEPlayer : IPlayer, ILoadedSong { - protected override string Name => "DSE Player"; - + private readonly DSEMixer _mixer; private readonly DSEConfig _config; - internal readonly DSEMixer DMixer; - internal readonly SWD MasterSWD; - private DSELoadedSong? _loadedSong; - - internal byte Tempo; - internal int TempoStack; + private readonly TimeBarrier _time; + private Thread? _thread; + private readonly SWD _masterSWD; + private SWD _localSWD; + private byte[] _smdFile; + private Track[] _tracks; + private byte _tempo; + private int _tempoStack; private long _elapsedLoops; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => DMixer; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; + + public PlayerState State { get; private set; } + public event Action? SongEnded; public DSEPlayer(DSEConfig config, DSEMixer mixer) - : base(192) { - DMixer = mixer; + _mixer = mixer; _config = config; + _masterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); - MasterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); + _time = new TimeBarrier(192); } - - public override void LoadSong(int index) + private void CreateThread() { - if (_loadedSong is not null) - { - _loadedSong = null; - } - - // If there's an exception, this will remain null - _loadedSong = new DSELoadedSong(this, _config.BGMFiles[index]); - _loadedSong.SetTicks(); + _thread = new Thread(Tick) { Name = "DSE Player Tick" }; + _thread.Start(); } - public override void UpdateSongState(SongState info) + private void WaitThread() { - info.Tempo = Tempo; - _loadedSong!.UpdateSongState(info); + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) + { + _thread.Join(); + } } - internal override void InitEmulation() + + private void InitEmulation() { - Tempo = 120; - TempoStack = 0; + _tempo = 120; + _tempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - DMixer.ResetFade(); - DSETrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + _mixer.ResetFade(); + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) { - tracks[i].Init(); + _tracks[trackIndex].Init(); } } - protected override void SetCurTick(long ticks) + private void SetTicks() { - _loadedSong!.SetCurTick(ticks); + MaxTicks = 0; + for (int trackIndex = 0; trackIndex < Events.Length; trackIndex++) + { + Events[trackIndex] = Events[trackIndex].OrderBy(e => e.Offset).ToList(); + List evs = Events[trackIndex]; + Track track = _tracks[trackIndex]; + track.Init(); + ElapsedTicks = 0; + while (true) + { + SongEvent e = evs.Single(ev => ev.Offset == track.CurOffset); + if (e.Ticks.Count > 0) + { + break; + } + + e.Ticks.Add(ElapsedTicks); + ExecuteNext(track); + if (track.Stopped) + { + break; + } + + ElapsedTicks += track.Rest; + track.Rest = 0; + } + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + track.StopAllChannels(); + } } - protected override void OnStopped() + public void LoadSong(long index) { - DSETrack[] tracks = _loadedSong!.Tracks; - for (int i = 0; i < tracks.Length; i++) + if (_tracks != null) { - tracks[i].StopAllChannels(); + for (int i = 0; i < _tracks.Length; i++) + { + _tracks[i].StopAllChannels(); + } + _tracks = null; } - } - protected override bool Tick(bool playing, bool recording) + string bgm = _config.BGMFiles[index]; + _localSWD = new SWD(Path.ChangeExtension(bgm, "swd")); + _smdFile = File.ReadAllBytes(bgm); + using (var stream = new MemoryStream(_smdFile)) + { + var r = new EndianBinaryReader(stream, ascii: true); + SMD.Header header = r.ReadObject(); + SMD.ISongChunk songChunk; + switch (header.Version) + { + case 0x402: + { + songChunk = r.ReadObject(); + break; + } + case 0x415: + { + songChunk = r.ReadObject(); + break; + } + default: throw new DSEInvalidHeaderVersionException(header.Version); + } + + _tracks = new Track[songChunk.NumTracks]; + Events = new List[songChunk.NumTracks]; + for (byte trackIndex = 0; trackIndex < songChunk.NumTracks; trackIndex++) + { + Events[trackIndex] = new List(); + bool EventExists(long offset) + { + return Events[trackIndex].Any(e => e.Offset == offset); + } + + long chunkStart = r.Stream.Position; + r.Stream.Position += 0x14; // Skip header + _tracks[trackIndex] = new Track(trackIndex, (int)r.Stream.Position); + + uint lastNoteDuration = 0, lastRest = 0; + bool cont = true; + while (cont) + { + long offset = r.Stream.Position; + void AddEvent(ICommand command) + { + Events[trackIndex].Add(new SongEvent(offset, command)); + } + byte cmd = r.ReadByte(); + if (cmd <= 0x7F) + { + byte arg = r.ReadByte(); + int numParams = (arg & 0xC0) >> 6; + int oct = ((arg & 0x30) >> 4) - 2; + int n = arg & 0xF; + if (n >= 12) + { + throw new DSEInvalidNoteException(trackIndex, (int)offset, n); + } + + uint duration; + if (numParams == 0) + { + duration = lastNoteDuration; + } + else // Big Endian reading of 8, 16, or 24 bits + { + duration = 0; + for (int b = 0; b < numParams; b++) + { + duration = (duration << 8) | r.ReadByte(); + } + lastNoteDuration = duration; + } + if (!EventExists(offset)) + { + AddEvent(new NoteCommand { Note = (byte)n, OctaveChange = (sbyte)oct, Velocity = cmd, Duration = duration }); + } + } + else if (cmd >= 0x80 && cmd <= 0x8F) + { + lastRest = Utils.FixedRests[cmd - 0x80]; + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + } + else // 0x90-0xFF + { + // TODO: 0x95 - a rest that may or may not repeat depending on some condition within channels + // TODO: 0x9E - may or may not jump somewhere else depending on an unknown structure + switch (cmd) + { + case 0x90: + { + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x91: + { + lastRest = (uint)(lastRest + r.ReadSByte()); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x92: + { + lastRest = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x93: + { + lastRest = r.ReadUInt16(); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x94: + { + lastRest = (uint)(r.ReadByte() | (r.ReadByte() << 8) | (r.ReadByte() << 16)); + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = lastRest }); + } + break; + } + case 0x96: + case 0x97: + case 0x9A: + case 0x9B: + case 0x9F: + case 0xA2: + case 0xA3: + case 0xA6: + case 0xA7: + case 0xAD: + case 0xAE: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBD: + case 0xC1: + case 0xC2: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD9: + case 0xDA: + case 0xDE: + case 0xE6: + case 0xEB: + case 0xEE: + case 0xF4: + case 0xF5: + case 0xF7: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new InvalidCommand { Command = cmd }); + } + break; + } + case 0x98: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + cont = false; + break; + } + case 0x99: + { + if (!EventExists(offset)) + { + AddEvent(new LoopStartCommand { Offset = r.Stream.Position }); + } + break; + } + case 0xA0: + { + byte octave = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new OctaveSetCommand { Octave = octave }); + } + break; + } + case 0xA1: + { + sbyte change = r.ReadSByte(); + if (!EventExists(offset)) + { + AddEvent(new OctaveAddCommand { OctaveChange = change }); + } + break; + } + case 0xA4: + case 0xA5: // The code for these two is identical + { + byte tempoArg = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new TempoCommand { Command = cmd, Tempo = tempoArg }); + } + break; + } + case 0xAB: + { + byte[] bytes = new byte[1]; + r.ReadBytes(bytes); + if (!EventExists(offset)) + { + AddEvent(new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); + } + break; + } + case 0xAC: + { + byte voice = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = voice }); + } + break; + } + case 0xCB: + case 0xF8: + { + byte[] bytes = new byte[2]; + r.ReadBytes(bytes); + if (!EventExists(offset)) + { + AddEvent(new SkipBytesCommand { Command = cmd, SkippedBytes = bytes }); + } + break; + } + case 0xD7: + { + ushort bend = r.ReadUInt16(); + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = bend }); + } + break; + } + case 0xE0: + { + byte volume = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new VolumeCommand { Volume = volume }); + } + break; + } + case 0xE3: + { + byte expression = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new ExpressionCommand { Expression = expression }); + } + break; + } + case 0xE8: + { + byte panArg = r.ReadByte(); + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = (sbyte)(panArg - 0x40) }); + } + break; + } + case 0x9D: + case 0xB0: + case 0xC0: + { + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = Array.Empty() }); + } + break; + } + case 0x9C: + case 0xA9: + case 0xAA: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB5: + case 0xB6: + case 0xBC: + case 0xBE: + case 0xBF: + case 0xC3: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xDB: + case 0xDF: + case 0xE1: + case 0xE7: + case 0xE9: + case 0xEF: + case 0xF6: + { + byte[] args = new byte[1]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xA8: + case 0xB4: + case 0xD3: + case 0xD5: + case 0xD6: + case 0xD8: + case 0xF2: + { + byte[] args = new byte[2]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xAF: + case 0xD4: + case 0xE2: + case 0xEA: + case 0xF3: + { + byte[] args = new byte[3]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xDD: + case 0xE5: + case 0xED: + case 0xF1: + { + byte[] args = new byte[4]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + case 0xDC: + case 0xE4: + case 0xEC: + case 0xF0: + { + byte[] args = new byte[5]; + r.ReadBytes(args); + if (!EventExists(offset)) + { + AddEvent(new UnknownCommand { Command = cmd, Args = args }); + } + break; + } + default: throw new DSEInvalidCMDException(trackIndex, (int)offset, cmd); + } + } + } + r.Stream.Position = chunkStart + 0xC; + uint chunkLength = r.ReadUInt32(); + r.Stream.Position += chunkLength; + // Align 4 + while (r.Stream.Position % 4 != 0) + { + r.Stream.Position++; + } + } + SetTicks(); + } + } + public void SetCurrentPosition(long ticks) { - DSELoadedSong s = _loadedSong!; + if (_tracks is null) + { + SongEnded?.Invoke(); + return; + } - bool allDone = false; - while (!allDone && TempoStack >= 240) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - TempoStack -= 240; - allDone = true; - for (int i = 0; i < s.Tracks.Length; i++) + if (State == PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + while (true) { - TickTrack(s, s.Tracks[i], ref allDone); + if (ElapsedTicks == ticks) + { + goto finish; + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (!track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } + } + _tempoStack += _tempo; } - if (DMixer.IsFadeDone()) + finish: + for (int i = 0; i < _tracks.Length; i++) { - allDone = true; + _tracks[i].StopAllChannels(); } + Pause(); } - if (!allDone) + } + public void Play() + { + if (_tracks == null) { - TempoStack += Tempo; + SongEnded?.Invoke(); + return; + } + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) + { + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } - DMixer.ChannelTick(); - DMixer.Process(playing, recording); - return allDone; } - private void TickTrack(DSELoadedSong s, DSETrack track, ref bool allDone) + public void Pause() { - track.Tick(); - while (track.Rest == 0 && !track.Stopped) + if (State == PlayerState.Playing) { - s.ExecuteNext(track); + State = PlayerState.Paused; + WaitThread(); } - if (track.Index == s.LongestTrack) + else if (State is PlayerState.Paused or PlayerState.Stopped) { - HandleTicksAndLoop(s, track); + State = PlayerState.Playing; + CreateThread(); } - if (!track.Stopped || track.Channels.Count != 0) + } + public void Stop() + { + if (State is PlayerState.Playing or PlayerState.Paused) { - allDone = false; + State = PlayerState.Stopped; + WaitThread(); } } - private void HandleTicksAndLoop(DSELoadedSong s, DSETrack track) + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() { - if (ElapsedTicks != s.MaxTicks) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - ElapsedTicks++; - return; + State = PlayerState.ShutDown; + WaitThread(); + } + } + public void UpdateSongState(SongState info) + { + info.Tempo = _tempo; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + SongState.Track tin = info.Tracks[trackIndex]; + tin.Position = track.CurOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.Type = "PCM"; + tin.Volume = track.Volume; + tin.PitchBend = track.PitchBend; + tin.Extra = track.Octave; + tin.Panpot = track.Panpot; + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + //tin.Type = string.Empty; + } + else + { + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (!Utils.IsStateRemovable(c.State)) + { + tin.Keys[numKeys++] = c.Key; + } + float a = (float)(-c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > left) + { + left = a; + } + a = (float)(c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > right) + { + right = a; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; + //tin.Type = string.Join(", ", channels.Select(c => c.State.ToString())); + } } + } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + private void ExecuteNext(Track track) + { + byte cmd = _smdFile[track.CurOffset++]; + if (cmd <= 0x7F) { - return; + byte arg = _smdFile[track.CurOffset++]; + int numParams = (arg & 0xC0) >> 6; + int oct = ((arg & 0x30) >> 4) - 2; + int n = arg & 0xF; + if (n >= 12) + { + throw new DSEInvalidNoteException(track.Index, track.CurOffset - 2, n); + } + + uint duration; + if (numParams == 0) + { + duration = track.LastNoteDuration; + } + else + { + duration = 0; + for (int b = 0; b < numParams; b++) + { + duration = (duration << 8) | _smdFile[track.CurOffset++]; + } + track.LastNoteDuration = duration; + } + Channel? channel = _mixer.AllocateChannel(); + if (channel is null) + { + throw new Exception("Not enough channels"); + } + + channel.Stop(); + track.Octave = (byte)(track.Octave + oct); + if (channel.StartPCM(_localSWD, _masterSWD, track.Voice, n + (12 * track.Octave), duration)) + { + channel.NoteVelocity = cmd; + channel.Owner = track; + track.Channels.Add(channel); + } } + else if (cmd >= 0x80 && cmd <= 0x8F) + { + track.LastRest = Utils.FixedRests[cmd - 0x80]; + track.Rest = track.LastRest; + } + else // 0x90-0xFF + { + // TODO: 0x95, 0x9E + switch (cmd) + { + case 0x90: + { + track.Rest = track.LastRest; + break; + } + case 0x91: + { + track.LastRest = (uint)(track.LastRest + (sbyte)_smdFile[track.CurOffset++]); + track.Rest = track.LastRest; + break; + } + case 0x92: + { + track.LastRest = _smdFile[track.CurOffset++]; + track.Rest = track.LastRest; + break; + } + case 0x93: + { + track.LastRest = (uint)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8)); + track.Rest = track.LastRest; + break; + } + case 0x94: + { + track.LastRest = (uint)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8) | (_smdFile[track.CurOffset++] << 16)); + track.Rest = track.LastRest; + break; + } + case 0x96: + case 0x97: + case 0x9A: + case 0x9B: + case 0x9F: + case 0xA2: + case 0xA3: + case 0xA6: + case 0xA7: + case 0xAD: + case 0xAE: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBD: + case 0xC1: + case 0xC2: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD9: + case 0xDA: + case 0xDE: + case 0xE6: + case 0xEB: + case 0xEE: + case 0xF4: + case 0xF5: + case 0xF7: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + { + track.Stopped = true; + break; + } + case 0x98: + { + if (track.LoopOffset == -1) + { + track.Stopped = true; + } + else + { + track.CurOffset = track.LoopOffset; + } + break; + } + case 0x99: + { + track.LoopOffset = track.CurOffset; + break; + } + case 0xA0: + { + track.Octave = _smdFile[track.CurOffset++]; + break; + } + case 0xA1: + { + track.Octave = (byte)(track.Octave + (sbyte)_smdFile[track.CurOffset++]); + break; + } + case 0xA4: + case 0xA5: + { + _tempo = _smdFile[track.CurOffset++]; + break; + } + case 0xAB: + { + track.CurOffset++; + break; + } + case 0xAC: + { + track.Voice = _smdFile[track.CurOffset++]; + break; + } + case 0xCB: + case 0xF8: + { + track.CurOffset += 2; + break; + } + case 0xD7: + { + track.PitchBend = (ushort)(_smdFile[track.CurOffset++] | (_smdFile[track.CurOffset++] << 8)); + break; + } + case 0xE0: + { + track.Volume = _smdFile[track.CurOffset++]; + break; + } + case 0xE3: + { + track.Expression = _smdFile[track.CurOffset++]; + break; + } + case 0xE8: + { + track.Panpot = (sbyte)(_smdFile[track.CurOffset++] - 0x40); + break; + } + case 0x9D: + case 0xB0: + case 0xC0: + { + break; + } + case 0x9C: + case 0xA9: + case 0xAA: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB5: + case 0xB6: + case 0xBC: + case 0xBE: + case 0xBF: + case 0xC3: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xDB: + case 0xDF: + case 0xE1: + case 0xE7: + case 0xE9: + case 0xEF: + case 0xF6: + { + track.CurOffset++; + break; + } + case 0xA8: + case 0xB4: + case 0xD3: + case 0xD5: + case 0xD6: + case 0xD8: + case 0xF2: + { + track.CurOffset += 2; + break; + } + case 0xAF: + case 0xD4: + case 0xE2: + case 0xEA: + case 0xF3: + { + track.CurOffset += 3; + break; + } + case 0xDD: + case 0xE5: + case 0xED: + case 0xF1: + { + track.CurOffset += 4; + break; + } + case 0xDC: + case 0xE4: + case 0xEC: + case 0xF0: + { + track.CurOffset += 5; + break; + } + default: throw new DSEInvalidCMDException(track.Index, track.CurOffset - 1, cmd); + } + } + } - _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.CurOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !DMixer.IsFading()) + private void Tick() + { + _time.Start(); + while (true) { - DMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + bool allDone = true; + for (int trackIndex = 0; trackIndex < _tracks.Length; trackIndex++) + { + Track track = _tracks[trackIndex]; + track.Tick(); + while (track.Rest == 0 && !track.Stopped) + { + ExecuteNext(track); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.CurOffset) + { + ElapsedTicks = ev.Ticks[0] - track.Rest; + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (!track.Stopped || track.Channels.Count != 0) + { + allDone = false; + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/NDS/DSE/DSETrack.cs b/VG Music Studio - Core/NDS/DSE/DSETrack.cs deleted file mode 100644 index a15e380..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSETrack.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class DSETrack -{ - public readonly byte Index; - private readonly int _startOffset; - public byte Octave; - public byte Voice; - public byte Expression; - public byte Volume; - public sbyte Panpot; - public uint Rest; - public ushort PitchBend; - public int CurOffset; - public int LoopOffset; - public bool Stopped; - public uint LastNoteDuration; - public uint LastRest; - - public readonly List Channels = new(0x10); - - public DSETrack(byte i, int startOffset) - { - Index = i; - _startOffset = startOffset; - } - - public void Init() - { - Expression = 0; - Voice = 0; - Volume = 0; - Octave = 4; - Panpot = 0; - Rest = 0; - PitchBend = 0; - CurOffset = _startOffset; - LoopOffset = -1; - Stopped = false; - LastNoteDuration = 0; - LastRest = 0; - StopAllChannels(); - } - - public void Tick() - { - if (Rest > 0) - { - Rest--; - } - for (int i = 0; i < Channels.Count; i++) - { - DSEChannel c = Channels[i]; - if (c.NoteLength > 0) - { - c.NoteLength--; - } - } - } - - public void StopAllChannels() - { - DSEChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - - public void UpdateSongState(SongState.Track tin) - { - tin.Position = CurOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.Type = "PCM"; - tin.Volume = Volume; - tin.PitchBend = PitchBend; - tin.Extra = Octave; - tin.Panpot = Panpot; - - DSEChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - //tin.Type = string.Empty; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - DSEChannel c = channels[j]; - if (!DSEUtils.IsStateRemovable(c.State)) - { - tin.Keys[numKeys++] = c.Key; - } - float a = (float)(-c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > left) - { - left = a; - } - a = (float)(c.Panpot + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > right) - { - right = a; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - //tin.Type = string.Join(", ", channels.Select(c => c.State.ToString())); - } - } -} diff --git a/VG Music Studio - Core/NDS/DSE/DSEUtils.cs b/VG Music Studio - Core/NDS/DSE/DSEUtils.cs deleted file mode 100644 index 8264b31..0000000 --- a/VG Music Studio - Core/NDS/DSE/DSEUtils.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal static class DSEUtils -{ - public static ReadOnlySpan Duration16 => new short[128] - { - 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, - 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, - 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, - 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, - 0x0020, 0x0023, 0x0028, 0x002D, 0x0033, 0x0039, 0x0040, 0x0048, - 0x0050, 0x0058, 0x0062, 0x006D, 0x0078, 0x0083, 0x0090, 0x009E, - 0x00AC, 0x00BC, 0x00CC, 0x00DE, 0x00F0, 0x0104, 0x0119, 0x012F, - 0x0147, 0x0160, 0x017A, 0x0196, 0x01B3, 0x01D2, 0x01F2, 0x0214, - 0x0238, 0x025E, 0x0285, 0x02AE, 0x02D9, 0x0307, 0x0336, 0x0367, - 0x039B, 0x03D1, 0x0406, 0x0442, 0x047E, 0x04C4, 0x0500, 0x0546, - 0x058C, 0x0622, 0x0672, 0x06CC, 0x071C, 0x0776, 0x07DA, 0x0834, - 0x0898, 0x0906, 0x096A, 0x09D8, 0x0A50, 0x0ABE, 0x0B40, 0x0BB8, - 0x0C3A, 0x0CBC, 0x0D48, 0x0DDE, 0x0E6A, 0x0F00, 0x0FA0, 0x1040, - 0x10EA, 0x1194, 0x123E, 0x12F2, 0x13B0, 0x146E, 0x1536, 0x15FE, - 0x16D0, 0x17A2, 0x187E, 0x195A, 0x1A40, 0x1B30, 0x1C20, 0x1D1A, - 0x1E1E, 0x1F22, 0x2030, 0x2148, 0x2260, 0x2382, 0x2710, 0x7FFF, - }; - public static ReadOnlySpan Duration32 => new int[128] - { - 0x00000000, 0x00000004, 0x00000007, 0x0000000A, 0x0000000F, 0x00000015, 0x0000001C, 0x00000024, - 0x0000002E, 0x0000003A, 0x00000048, 0x00000057, 0x00000068, 0x0000007B, 0x00000091, 0x000000A8, - 0x00000185, 0x000001BE, 0x000001FC, 0x0000023F, 0x00000288, 0x000002D6, 0x0000032A, 0x00000385, - 0x000003E5, 0x0000044C, 0x000004BA, 0x0000052E, 0x000005A9, 0x0000062C, 0x000006B5, 0x00000746, - 0x00000BCF, 0x00000CC0, 0x00000DBD, 0x00000EC6, 0x00000FDC, 0x000010FF, 0x0000122F, 0x0000136C, - 0x000014B6, 0x0000160F, 0x00001775, 0x000018EA, 0x00001A6D, 0x00001BFF, 0x00001DA0, 0x00001F51, - 0x00002C16, 0x00002E80, 0x00003100, 0x00003395, 0x00003641, 0x00003902, 0x00003BDB, 0x00003ECA, - 0x000041D0, 0x000044EE, 0x00004824, 0x00004B73, 0x00004ED9, 0x00005259, 0x000055F2, 0x000059A4, - 0x000074CC, 0x000079AB, 0x00007EAC, 0x000083CE, 0x00008911, 0x00008E77, 0x000093FF, 0x000099AA, - 0x00009F78, 0x0000A56A, 0x0000AB80, 0x0000B1BB, 0x0000B81A, 0x0000BE9E, 0x0000C547, 0x0000CC17, - 0x0000FD42, 0x000105CB, 0x00010E82, 0x00011768, 0x0001207E, 0x000129C4, 0x0001333B, 0x00013CE2, - 0x000146BB, 0x000150C5, 0x00015B02, 0x00016572, 0x00017015, 0x00017AEB, 0x000185F5, 0x00019133, - 0x0001E16D, 0x0001EF07, 0x0001FCE0, 0x00020AF7, 0x0002194F, 0x000227E6, 0x000236BE, 0x000245D7, - 0x00025532, 0x000264CF, 0x000274AE, 0x000284D0, 0x00029536, 0x0002A5E0, 0x0002B6CE, 0x0002C802, - 0x000341B0, 0x000355F8, 0x00036A90, 0x00037F79, 0x000394B4, 0x0003AA41, 0x0003C021, 0x0003D654, - 0x0003ECDA, 0x000403B5, 0x00041AE5, 0x0004326A, 0x00044A45, 0x00046277, 0x00047B00, 0x7FFFFFFF, - }; - public static ReadOnlySpan FixedRests => new byte[0x10] - { - 96, 72, 64, 48, 36, 32, 24, 18, 16, 12, 9, 8, 6, 4, 3, 2, - }; - - public static bool IsStateRemovable(EnvelopeState state) - { - return state is EnvelopeState.Two or >= EnvelopeState.Seven; - } -} diff --git a/VG Music Studio - Core/NDS/DSE/Enums.cs b/VG Music Studio - Core/NDS/DSE/Enums.cs new file mode 100644 index 0000000..6cec60d --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Enums.cs @@ -0,0 +1,22 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal enum EnvelopeState : byte + { + Zero = 0, + One = 1, + Two = 2, + Hold = 3, + Decay = 4, + Decay2 = 5, + Six = 6, + Seven = 7, + Eight = 8 + } + + internal enum SampleFormat : ushort + { + PCM8 = 0x000, + PCM16 = 0x100, + ADPCM = 0x200 + } +} diff --git a/VG Music Studio - Core/NDS/DSE/SMD.cs b/VG Music Studio - Core/NDS/DSE/SMD.cs index e9a9083..5383c4d 100644 --- a/VG Music Studio - Core/NDS/DSE/SMD.cs +++ b/VG Music Studio - Core/NDS/DSE/SMD.cs @@ -1,60 +1,61 @@ using Kermalis.EndianBinaryIO; -namespace Kermalis.VGMusicStudio.Core.NDS.DSE; - -internal sealed class SMD +namespace Kermalis.VGMusicStudio.Core.NDS.DSE { - public sealed class Header // Size 0x40 + internal sealed class SMD { - [BinaryStringFixedLength(4)] - public string Type { get; set; } = null!; // "smdb" or "smdl" - [BinaryArrayFixedLength(4)] - public byte[] Unknown1 { get; set; } = null!; - public uint Length { get; set; } - public ushort Version { get; set; } - [BinaryArrayFixedLength(10)] - public byte[] Unknown2 { get; set; } = null!; - public ushort Year { get; set; } - public byte Month { get; set; } - public byte Day { get; set; } - public byte Hour { get; set; } - public byte Minute { get; set; } - public byte Second { get; set; } - public byte Centisecond { get; set; } - [BinaryStringFixedLength(16)] - public string Label { get; set; } = null!; - [BinaryArrayFixedLength(16)] - public byte[] Unknown3 { get; set; } = null!; - } + public sealed class Header + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } // "smdb" or "smdl" + [BinaryArrayFixedLength(4)] + public byte[] Unknown1 { get; set; } + public uint Length { get; set; } + public ushort Version { get; set; } + [BinaryArrayFixedLength(10)] + public byte[] Unknown2 { get; set; } + public ushort Year { get; set; } + public byte Month { get; set; } + public byte Day { get; set; } + public byte Hour { get; set; } + public byte Minute { get; set; } + public byte Second { get; set; } + public byte Centisecond { get; set; } + [BinaryStringFixedLength(16)] + public string Label { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown3 { get; set; } + } - public interface ISongChunk - { - byte NumTracks { get; } - } - public sealed class SongChunk_V402 : ISongChunk // Size 0x20 - { - [BinaryStringFixedLength(4)] - public string Type { get; set; } = null!; - [BinaryArrayFixedLength(16)] - public byte[] Unknown1 { get; set; } = null!; - public byte NumTracks { get; set; } - public byte NumChannels { get; set; } - [BinaryArrayFixedLength(4)] - public byte[] Unknown2 { get; set; } = null!; - public sbyte MasterVolume { get; set; } - public sbyte MasterPanpot { get; set; } - [BinaryArrayFixedLength(4)] - public byte[] Unknown3 { get; set; } = null!; - } - public sealed class SongChunk_V415 : ISongChunk // Size 0x40 - { - [BinaryStringFixedLength(4)] - public string Type { get; set; } = null!; - [BinaryArrayFixedLength(18)] - public byte[] Unknown1 { get; set; } = null!; - public byte NumTracks { get; set; } - public byte NumChannels { get; set; } - [BinaryArrayFixedLength(40)] - public byte[] Unknown2 { get; set; } = null!; + public interface ISongChunk + { + byte NumTracks { get; } + } + public sealed class SongChunk_V402 : ISongChunk + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown1 { get; set; } + public byte NumTracks { get; set; } + public byte NumChannels { get; set; } + [BinaryArrayFixedLength(4)] + public byte[] Unknown2 { get; set; } + public sbyte MasterVolume { get; set; } + public sbyte MasterPanpot { get; set; } + [BinaryArrayFixedLength(4)] + public byte[] Unknown3 { get; set; } + } + public sealed class SongChunk_V415 : ISongChunk + { + [BinaryStringFixedLength(4)] + public string Type { get; set; } + [BinaryArrayFixedLength(18)] + public byte[] Unknown1 { get; set; } + public byte NumTracks { get; set; } + public byte NumChannels { get; set; } + [BinaryArrayFixedLength(40)] + public byte[] Unknown2 { get; set; } + } } } diff --git a/VG Music Studio - Core/NDS/DSE/SWD.cs b/VG Music Studio - Core/NDS/DSE/SWD.cs index 90c28ad..17c08ef 100644 --- a/VG Music Studio - Core/NDS/DSE/SWD.cs +++ b/VG Music Studio - Core/NDS/DSE/SWD.cs @@ -1,7 +1,5 @@ using Kermalis.EndianBinaryIO; -using Kermalis.VGMusicStudio.Core.Util; using System; -using System.Diagnostics; using System.IO; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; @@ -10,12 +8,12 @@ internal sealed class SWD { public interface IHeader { - // + } - private sealed class Header_V402 : IHeader // Size 0x40 + private class Header_V402 : IHeader { - [BinaryArrayFixedLength(8)] - public byte[] Unknown1 { get; set; } = null!; + [BinaryArrayFixedLength(10)] + public byte[] Unknown1 { get; set; } public ushort Year { get; set; } public byte Month { get; set; } public byte Day { get; set; } @@ -24,19 +22,19 @@ private sealed class Header_V402 : IHeader // Size 0x40 public byte Second { get; set; } public byte Centisecond { get; set; } [BinaryStringFixedLength(16)] - public string Label { get; set; } = null!; + public string Label { get; set; } [BinaryArrayFixedLength(22)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } public byte NumWAVISlots { get; set; } public byte NumPRGISlots { get; set; } public byte NumKeyGroups { get; set; } [BinaryArrayFixedLength(7)] - public byte[] Padding { get; set; } = null!; + public byte[] Padding { get; set; } } - private sealed class Header_V415 : IHeader // Size 0x40 + private class Header_V415 : IHeader { - [BinaryArrayFixedLength(8)] - public byte[] Unknown1 { get; set; } = null!; + [BinaryArrayFixedLength(10)] + public byte[] Unknown1 { get; set; } public ushort Year { get; set; } public byte Month { get; set; } public byte Day { get; set; } @@ -45,16 +43,16 @@ private sealed class Header_V415 : IHeader // Size 0x40 public byte Second { get; set; } public byte Centisecond { get; set; } [BinaryStringFixedLength(16)] - public string Label { get; set; } = null!; + public string Label { get; set; } [BinaryArrayFixedLength(16)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } public uint PCMDLength { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } public ushort NumWAVISlots { get; set; } public ushort NumPRGISlots { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown4 { get; set; } = null!; + public byte[] Unknown4 { get; set; } public uint WAVILength { get; set; } } @@ -73,11 +71,11 @@ public interface ISplitEntry byte Decay2 { get; set; } byte Release { get; set; } } - public sealed class SplitEntry_V402 : ISplitEntry // Size 0x30 + public class SplitEntry_V402 : ISplitEntry { public ushort Id { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown1 { get; set; } = null!; + public byte[] Unknown1 { get; set; } public byte LowKey { get; set; } public byte HighKey { get; set; } public byte LowKey2 { get; set; } @@ -87,17 +85,17 @@ public sealed class SplitEntry_V402 : ISplitEntry // Size 0x30 public byte LowVelocity2 { get; set; } public byte HighVelocity2 { get; set; } [BinaryArrayFixedLength(5)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } public byte SampleId { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } public byte SampleRootKey { get; set; } public sbyte SampleTranspose { get; set; } public byte SampleVolume { get; set; } public sbyte SamplePanpot { get; set; } public byte KeyGroupId { get; set; } [BinaryArrayFixedLength(15)] - public byte[] Unknown4 { get; set; } = null!; + public byte[] Unknown4 { get; set; } public byte AttackVolume { get; set; } public byte Attack { get; set; } public byte Decay { get; set; } @@ -107,14 +105,13 @@ public sealed class SplitEntry_V402 : ISplitEntry // Size 0x30 public byte Release { get; set; } public byte Unknown5 { get; set; } - [BinaryIgnore] int ISplitEntry.SampleId => SampleId; } - public sealed class SplitEntry_V415 : ISplitEntry // 0x30 + public class SplitEntry_V415 : ISplitEntry { public ushort Id { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown1 { get; set; } = null!; + public byte[] Unknown1 { get; set; } public byte LowKey { get; set; } public byte HighKey { get; set; } public byte LowKey2 { get; set; } @@ -124,17 +121,17 @@ public sealed class SplitEntry_V415 : ISplitEntry // 0x30 public byte LowVelocity2 { get; set; } public byte HighVelocity2 { get; set; } [BinaryArrayFixedLength(6)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } public ushort SampleId { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } public byte SampleRootKey { get; set; } public sbyte SampleTranspose { get; set; } public byte SampleVolume { get; set; } public sbyte SamplePanpot { get; set; } public byte KeyGroupId { get; set; } [BinaryArrayFixedLength(13)] - public byte[] Unknown4 { get; set; } = null!; + public byte[] Unknown4 { get; set; } public byte AttackVolume { get; set; } public byte Attack { get; set; } public byte Decay { get; set; } @@ -144,7 +141,6 @@ public sealed class SplitEntry_V415 : ISplitEntry // 0x30 public byte Release { get; set; } public byte Unknown5 { get; set; } - [BinaryIgnore] int ISplitEntry.SampleId => SampleId; } @@ -152,46 +148,46 @@ public interface IProgramInfo { ISplitEntry[] SplitEntries { get; } } - public sealed class ProgramInfo_V402 : IProgramInfo + public class ProgramInfo_V402 : IProgramInfo { public byte Id { get; set; } public byte NumSplits { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown1 { get; set; } = null!; + public byte[] Unknown1 { get; set; } public byte Volume { get; set; } public byte Panpot { get; set; } [BinaryArrayFixedLength(5)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } public byte NumLFOs { get; set; } [BinaryArrayFixedLength(4)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } [BinaryArrayFixedLength(16)] - public KeyGroup[] KeyGroups { get; set; } = null!; + public KeyGroup[] KeyGroups { get; set; } [BinaryArrayVariableLength(nameof(NumLFOs))] - public LFOInfo LFOInfos { get; set; } = null!; + public LFOInfo LFOInfos { get; set; } [BinaryArrayVariableLength(nameof(NumSplits))] - public SplitEntry_V402[] SplitEntries { get; set; } = null!; + public SplitEntry_V402[] SplitEntries { get; set; } [BinaryIgnore] ISplitEntry[] IProgramInfo.SplitEntries => SplitEntries; } - public sealed class ProgramInfo_V415 : IProgramInfo + public class ProgramInfo_V415 : IProgramInfo { public ushort Id { get; set; } public ushort NumSplits { get; set; } public byte Volume { get; set; } public byte Panpot { get; set; } [BinaryArrayFixedLength(5)] - public byte[] Unknown1 { get; set; } = null!; + public byte[] Unknown1 { get; set; } public byte NumLFOs { get; set; } [BinaryArrayFixedLength(4)] - public byte[] Unknown2 { get; set; } = null!; + public byte[] Unknown2 { get; set; } [BinaryArrayVariableLength(nameof(NumLFOs))] - public LFOInfo[] LFOInfos { get; set; } = null!; + public LFOInfo[] LFOInfos { get; set; } [BinaryArrayFixedLength(16)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } [BinaryArrayVariableLength(nameof(NumSplits))] - public SplitEntry_V415[] SplitEntries { get; set; } = null!; + public SplitEntry_V415[] SplitEntries { get; set; } [BinaryIgnore] ISplitEntry[] IProgramInfo.SplitEntries => SplitEntries; @@ -199,7 +195,7 @@ public sealed class ProgramInfo_V415 : IProgramInfo public interface IWavInfo { - byte RootNote { get; } + byte RootKey { get; } sbyte Transpose { get; } SampleFormat SampleFormat { get; } bool Loop { get; } @@ -216,30 +212,30 @@ public interface IWavInfo byte Decay2 { get; } byte Release { get; } } - public sealed class WavInfo_V402 : IWavInfo // Size 0x40 + public class WavInfo_V402 : IWavInfo { public byte Unknown1 { get; set; } public byte Id { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown2 { get; set; } = null!; - public byte RootNote { get; set; } + public byte[] Unknown2 { get; set; } + public byte RootKey { get; set; } public sbyte Transpose { get; set; } public byte Volume { get; set; } public sbyte Panpot { get; set; } public SampleFormat SampleFormat { get; set; } [BinaryArrayFixedLength(7)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } public bool Loop { get; set; } public uint SampleRate { get; set; } public uint SampleOffset { get; set; } public uint LoopStart { get; set; } public uint LoopEnd { get; set; } [BinaryArrayFixedLength(16)] - public byte[] Unknown4 { get; set; } = null!; + public byte[] Unknown4 { get; set; } public byte EnvOn { get; set; } public byte EnvMult { get; set; } [BinaryArrayFixedLength(6)] - public byte[] Unknown5 { get; set; } = null!; + public byte[] Unknown5 { get; set; } public byte AttackVolume { get; set; } public byte Attack { get; set; } public byte Decay { get; set; } @@ -249,19 +245,19 @@ public sealed class WavInfo_V402 : IWavInfo // Size 0x40 public byte Release { get; set; } public byte Unknown6 { get; set; } } - public sealed class WavInfo_V415 : IWavInfo // 0x40 + public class WavInfo_V415 : IWavInfo { [BinaryArrayFixedLength(2)] - public byte[] Unknown1 { get; set; } = null!; + public byte[] Unknown1 { get; set; } public ushort Id { get; set; } [BinaryArrayFixedLength(2)] - public byte[] Unknown2 { get; set; } = null!; - public byte RootNote { get; set; } + public byte[] Unknown2 { get; set; } + public byte RootKey { get; set; } public sbyte Transpose { get; set; } public byte Volume { get; set; } public sbyte Panpot { get; set; } [BinaryArrayFixedLength(6)] - public byte[] Unknown3 { get; set; } = null!; + public byte[] Unknown3 { get; set; } public ushort Version { get; set; } public SampleFormat SampleFormat { get; set; } public byte Unknown4 { get; set; } @@ -271,7 +267,7 @@ public sealed class WavInfo_V415 : IWavInfo // 0x40 public byte Unknown6 { get; set; } public byte BitDepth { get; set; } [BinaryArrayFixedLength(6)] - public byte[] Unknown7 { get; set; } = null!; + public byte[] Unknown7 { get; set; } public uint SampleRate { get; set; } public uint SampleOffset { get; set; } public uint LoopStart { get; set; } @@ -279,7 +275,7 @@ public sealed class WavInfo_V415 : IWavInfo // 0x40 public byte EnvOn { get; set; } public byte EnvMult { get; set; } [BinaryArrayFixedLength(6)] - public byte[] Unknown8 { get; set; } = null!; + public byte[] Unknown8 { get; set; } public byte AttackVolume { get; set; } public byte Attack { get; set; } public byte Decay { get; set; } @@ -292,61 +288,49 @@ public sealed class WavInfo_V415 : IWavInfo // 0x40 public class SampleBlock { - public IWavInfo WavInfo = null!; - public byte[] Data = null!; + public IWavInfo WavInfo; + public byte[] Data; } public class ProgramBank { - public IProgramInfo?[] ProgramInfos = null!; - public KeyGroup[] KeyGroups = null!; + public IProgramInfo[] ProgramInfos; + public KeyGroup[] KeyGroups; } - public class KeyGroup // Size 0x8 + public class KeyGroup { public ushort Id { get; set; } public byte Poly { get; set; } public byte Priority { get; set; } - public byte LowNote { get; set; } - public byte HighNote { get; set; } - public ushort Unknown { get; set; } + public byte Low { get; set; } + public byte High { get; set; } + [BinaryArrayFixedLength(2)] + public byte[] Unknown { get; set; } } - public sealed class LFOInfo + public class LFOInfo { - public byte Unknown1 { get; set; } - public byte HasData { get; set; } - public byte Type { get; set; } // LFOType enum - public byte CallbackType { get; set; } - public uint Unknown4 { get; set; } - public ushort Unknown8 { get; set; } - public ushort UnknownA { get; set; } - public ushort UnknownC { get; set; } - public byte UnknownE { get; set; } - public byte UnknownF { get; set; } + [BinaryArrayFixedLength(16)] + public byte[] Unknown { get; set; } } public string Type; // "swdb" or "swdl" - public byte[] Unknown1; + public byte[] Unknown; public uint Length; public ushort Version; public IHeader Header; - public byte[] Unknown2; - public ProgramBank? Programs; - public SampleBlock[]? Samples; + public ProgramBank Programs; + public SampleBlock[] Samples; public SWD(string path) { - using (FileStream stream = File.OpenRead(path)) + using (var stream = new MemoryStream(File.ReadAllBytes(path))) { var r = new EndianBinaryReader(stream, ascii: true); - Type = r.ReadString_Count(4); - Unknown1 = new byte[4]; - r.ReadBytes(Unknown1); + Unknown = new byte[4]; + r.ReadBytes(Unknown); Length = r.ReadUInt32(); Version = r.ReadUInt16(); - Unknown2 = new byte[2]; - r.ReadBytes(Unknown2); - switch (Version) { case 0x402: @@ -378,7 +362,6 @@ private static long FindChunk(EndianBinaryReader r, string chunk) long pos = -1; long oldPosition = r.Stream.Position; r.Stream.Position = 0; - while (r.Stream.Position < r.Stream.Length) { string str = r.ReadString_Count(4); @@ -387,7 +370,6 @@ private static long FindChunk(EndianBinaryReader r, string chunk) pos = r.Stream.Position - 4; break; } - switch (str) { case "swdb": @@ -398,22 +380,23 @@ private static long FindChunk(EndianBinaryReader r, string chunk) } default: { - Debug.WriteLine($"Ignoring {str} chunk"); r.Stream.Position += 0x8; uint length = r.ReadUInt32(); r.Stream.Position += length; - r.Stream.Align(16); + // Align 4 + while (r.Stream.Position % 4 != 0) + { + r.Stream.Position++; + } break; } } } - r.Stream.Position = oldPosition; return pos; } - private static SampleBlock[] ReadSamples(EndianBinaryReader r, int numWAVISlots) - where T : IWavInfo, new() + private static SampleBlock[] ReadSamples(EndianBinaryReader r, int numWAVISlots) where T : IWavInfo, new() { long waviChunkOffset = FindChunk(r, "wavi"); long pcmdChunkOffset = FindChunk(r, "pcmd"); @@ -446,8 +429,7 @@ private static SampleBlock[] ReadSamples(EndianBinaryReader r, int numWAVISlo return samples; } } - private static ProgramBank? ReadPrograms(EndianBinaryReader r, int numPRGISlots) - where T : IProgramInfo, new() + private static ProgramBank? ReadPrograms(EndianBinaryReader r, int numPRGISlots) where T : IProgramInfo, new() { long chunkOffset = FindChunk(r, "prgi"); if (chunkOffset == -1) @@ -456,7 +438,7 @@ private static SampleBlock[] ReadSamples(EndianBinaryReader r, int numWAVISlo } chunkOffset += 0x10; - var programInfos = new IProgramInfo?[numPRGISlots]; + var programInfos = new IProgramInfo[numPRGISlots]; for (int i = 0; i < programInfos.Length; i++) { r.Stream.Position = chunkOffset + (2 * i); @@ -480,14 +462,16 @@ private static KeyGroup[] ReadKeyGroups(EndianBinaryReader r) { return Array.Empty(); } - - r.Stream.Position = chunkOffset + 0xC; - uint chunkLength = r.ReadUInt32(); - var keyGroups = new KeyGroup[chunkLength / 8]; // 8 is the size of a KeyGroup - for (int i = 0; i < keyGroups.Length; i++) + else { - keyGroups[i] = r.ReadObject(); + r.Stream.Position = chunkOffset + 0xC; + uint chunkLength = r.ReadUInt32(); + var keyGroups = new KeyGroup[chunkLength / 8]; // 8 is the size of a KeyGroup + for (int i = 0; i < keyGroups.Length; i++) + { + keyGroups[i] = r.ReadObject(); + } + return keyGroups; } - return keyGroups; } } diff --git a/VG Music Studio - Core/NDS/DSE/Track.cs b/VG Music Studio - Core/NDS/DSE/Track.cs new file mode 100644 index 0000000..ba0a7c6 --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Track.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.NDS.DSE; + +internal sealed class Track +{ + public readonly byte Index; + private readonly int _startOffset; + public byte Octave; + public byte Voice; + public byte Expression; + public byte Volume; + public sbyte Panpot; + public uint Rest; + public ushort PitchBend; + public int CurOffset; + public int LoopOffset; + public bool Stopped; + public uint LastNoteDuration; + public uint LastRest; + + public readonly List Channels = new(0x10); + + public Track(byte i, int startOffset) + { + Index = i; + _startOffset = startOffset; + } + + public void Init() + { + Expression = 0; + Voice = 0; + Volume = 0; + Octave = 4; + Panpot = 0; + Rest = 0; + PitchBend = 0; + CurOffset = _startOffset; + LoopOffset = -1; + Stopped = false; + LastNoteDuration = 0; + LastRest = 0; + StopAllChannels(); + } + + public void Tick() + { + if (Rest > 0) + { + Rest--; + } + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + if (c.NoteLength > 0) + { + c.NoteLength--; + } + } + } + + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } +} diff --git a/VG Music Studio - Core/NDS/DSE/Utils.cs b/VG Music Studio - Core/NDS/DSE/Utils.cs new file mode 100644 index 0000000..1f16b1a --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/Utils.cs @@ -0,0 +1,53 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.DSE +{ + internal static class Utils + { + public static short[] Duration16 = new short[128] + { + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, + 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, + 0x0020, 0x0023, 0x0028, 0x002D, 0x0033, 0x0039, 0x0040, 0x0048, + 0x0050, 0x0058, 0x0062, 0x006D, 0x0078, 0x0083, 0x0090, 0x009E, + 0x00AC, 0x00BC, 0x00CC, 0x00DE, 0x00F0, 0x0104, 0x0119, 0x012F, + 0x0147, 0x0160, 0x017A, 0x0196, 0x01B3, 0x01D2, 0x01F2, 0x0214, + 0x0238, 0x025E, 0x0285, 0x02AE, 0x02D9, 0x0307, 0x0336, 0x0367, + 0x039B, 0x03D1, 0x0406, 0x0442, 0x047E, 0x04C4, 0x0500, 0x0546, + 0x058C, 0x0622, 0x0672, 0x06CC, 0x071C, 0x0776, 0x07DA, 0x0834, + 0x0898, 0x0906, 0x096A, 0x09D8, 0x0A50, 0x0ABE, 0x0B40, 0x0BB8, + 0x0C3A, 0x0CBC, 0x0D48, 0x0DDE, 0x0E6A, 0x0F00, 0x0FA0, 0x1040, + 0x10EA, 0x1194, 0x123E, 0x12F2, 0x13B0, 0x146E, 0x1536, 0x15FE, + 0x16D0, 0x17A2, 0x187E, 0x195A, 0x1A40, 0x1B30, 0x1C20, 0x1D1A, + 0x1E1E, 0x1F22, 0x2030, 0x2148, 0x2260, 0x2382, 0x2710, 0x7FFF + }; + public static int[] Duration32 = new int[128] + { + 0x00000000, 0x00000004, 0x00000007, 0x0000000A, 0x0000000F, 0x00000015, 0x0000001C, 0x00000024, + 0x0000002E, 0x0000003A, 0x00000048, 0x00000057, 0x00000068, 0x0000007B, 0x00000091, 0x000000A8, + 0x00000185, 0x000001BE, 0x000001FC, 0x0000023F, 0x00000288, 0x000002D6, 0x0000032A, 0x00000385, + 0x000003E5, 0x0000044C, 0x000004BA, 0x0000052E, 0x000005A9, 0x0000062C, 0x000006B5, 0x00000746, + 0x00000BCF, 0x00000CC0, 0x00000DBD, 0x00000EC6, 0x00000FDC, 0x000010FF, 0x0000122F, 0x0000136C, + 0x000014B6, 0x0000160F, 0x00001775, 0x000018EA, 0x00001A6D, 0x00001BFF, 0x00001DA0, 0x00001F51, + 0x00002C16, 0x00002E80, 0x00003100, 0x00003395, 0x00003641, 0x00003902, 0x00003BDB, 0x00003ECA, + 0x000041D0, 0x000044EE, 0x00004824, 0x00004B73, 0x00004ED9, 0x00005259, 0x000055F2, 0x000059A4, + 0x000074CC, 0x000079AB, 0x00007EAC, 0x000083CE, 0x00008911, 0x00008E77, 0x000093FF, 0x000099AA, + 0x00009F78, 0x0000A56A, 0x0000AB80, 0x0000B1BB, 0x0000B81A, 0x0000BE9E, 0x0000C547, 0x0000CC17, + 0x0000FD42, 0x000105CB, 0x00010E82, 0x00011768, 0x0001207E, 0x000129C4, 0x0001333B, 0x00013CE2, + 0x000146BB, 0x000150C5, 0x00015B02, 0x00016572, 0x00017015, 0x00017AEB, 0x000185F5, 0x00019133, + 0x0001E16D, 0x0001EF07, 0x0001FCE0, 0x00020AF7, 0x0002194F, 0x000227E6, 0x000236BE, 0x000245D7, + 0x00025532, 0x000264CF, 0x000274AE, 0x000284D0, 0x00029536, 0x0002A5E0, 0x0002B6CE, 0x0002C802, + 0x000341B0, 0x000355F8, 0x00036A90, 0x00037F79, 0x000394B4, 0x0003AA41, 0x0003C021, 0x0003D654, + 0x0003ECDA, 0x000403B5, 0x00041AE5, 0x0004326A, 0x00044A45, 0x00046277, 0x00047B00, 0x7FFFFFFF + }; + public static readonly byte[] FixedRests = new byte[0x10] + { + 96, 72, 64, 48, 36, 32, 24, 18, 16, 12, 9, 8, 6, 4, 3, 2 + }; + + public static bool IsStateRemovable(EnvelopeState state) + { + return state == EnvelopeState.Two || state >= EnvelopeState.Seven; + } + } +} diff --git a/VG Music Studio - Core/NDS/NDSUtils.cs b/VG Music Studio - Core/NDS/NDSUtils.cs deleted file mode 100644 index 2bfd9b5..0000000 --- a/VG Music Studio - Core/NDS/NDSUtils.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS; - -internal static class NDSUtils -{ - public const int ARM7_CLOCK = 16_756_991; // (33.513982 MHz / 2) == 16.756991 MHz == 16,756,991 Hz -} diff --git a/VG Music Studio - Core/NDS/SDAT/Channel.cs b/VG Music Studio - Core/NDS/SDAT/Channel.cs new file mode 100644 index 0000000..742a839 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Channel.cs @@ -0,0 +1,391 @@ +using System; + +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal sealed class Channel + { + public readonly byte Index; + + public Track? Owner; + public InstrumentType Type; + public EnvelopeState State; + public bool AutoSweep; + public byte BaseNote; + public byte Note; + public byte NoteVelocity; + public sbyte StartingPan; + public sbyte Pan; + public int SweepCounter; + public int SweepLength; + public short SweepPitch; + public int Velocity; // The SEQ Player treats 0 as the 100% amplitude value and -92544 (-723*128) as the 0% amplitude value. The starting ampltitude is 0% (-92544). + public byte Volume; // From 0x00-0x7F (Calculated from Utils) + public ushort BaseTimer; + public ushort Timer; + public int NoteDuration; + + private byte _attack; + private int _sustain; + private ushort _decay; + private ushort _release; + public byte LFORange; + public byte LFOSpeed; + public byte LFODepth; + public ushort LFODelay; + public ushort LFOPhase; + public int LFOParam; + public ushort LFODelayCount; + public LFOType LFOType; + public byte Priority; + + private int _pos; + private short _prevLeft; + private short _prevRight; + + // PCM8, PCM16, ADPCM + private SWAR.SWAV _swav; + // PCM8, PCM16 + private int _dataOffset; + // ADPCM + private ADPCMDecoder _adpcmDecoder; + private short _adpcmLoopLastSample; + private short _adpcmLoopStepIndex; + // PSG + private byte _psgDuty; + private int _psgCounter; + // Noise + private ushort _noiseCounter; + + public Channel(byte i) + { + Index = i; + } + + public void StartPCM(SWAR.SWAV swav, int noteDuration) + { + Type = InstrumentType.PCM; + _dataOffset = 0; + _swav = swav; + if (swav.Format == SWAVFormat.ADPCM) + { + _adpcmDecoder = new ADPCMDecoder(swav.Samples); + } + BaseTimer = swav.Timer; + Start(noteDuration); + } + public void StartPSG(byte duty, int noteDuration) + { + Type = InstrumentType.PSG; + _psgCounter = 0; + _psgDuty = duty; + BaseTimer = 8006; + Start(noteDuration); + } + public void StartNoise(int noteLength) + { + Type = InstrumentType.Noise; + _noiseCounter = 0x7FFF; + BaseTimer = 8006; + Start(noteLength); + } + + private void Start(int noteDuration) + { + State = EnvelopeState.Attack; + Velocity = -92544; + _pos = 0; + _prevLeft = _prevRight = 0; + NoteDuration = noteDuration; + } + + public void Stop() + { + if (Owner is not null) + { + Owner.Channels.Remove(this); + } + Owner = null; + Volume = 0; + Priority = 0; + } + + public int SweepMain() + { + if (SweepPitch == 0 || SweepCounter >= SweepLength) + { + return 0; + } + + int sweep = (int)(Math.BigMul(SweepPitch, SweepLength - SweepCounter) / SweepLength); + if (AutoSweep) + { + SweepCounter++; + } + return sweep; + } + public void LFOTick() + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + else + { + int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; + if (LFOType == LFOType.Volume) + { + param = (param * 60) >> 14; + } + else + { + param >>= 8; + } + LFOParam = param; + int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" + while (counter >= 0x8000) + { + counter -= 0x8000; + } + LFOPhase = (ushort)counter; + } + } + + public void SetAttack(int a) + { + _attack = SDATUtils.AttackTable[a]; + } + public void SetDecay(int d) + { + _decay = SDATUtils.DecayTable[d]; + } + public void SetSustain(byte s) + { + _sustain = SDATUtils.SustainTable[s]; + } + public void SetRelease(int r) + { + _release = SDATUtils.DecayTable[r]; + } + public void StepEnvelope() + { + switch (State) + { + case EnvelopeState.Attack: + { + Velocity = _attack * Velocity / 0xFF; + if (Velocity == 0) + { + State = EnvelopeState.Decay; + } + break; + } + case EnvelopeState.Decay: + { + Velocity -= _decay; + if (Velocity <= _sustain) + { + State = EnvelopeState.Sustain; + Velocity = _sustain; + } + break; + } + case EnvelopeState.Release: + { + Velocity -= _release; + if (Velocity < -92544) + { + Velocity = -92544; + } + break; + } + } + } + + /// EmulateProcess doesn't care about samples that loop; it only cares about ones that force the track to wait for them to end + public void EmulateProcess() + { + if (Timer == 0) + { + return; + } + + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + for (int i = 0; i < numSamples; i++) + { + if (Type == InstrumentType.PCM && !_swav.DoesLoop) + { + switch (_swav.Format) + { + case SWAVFormat.PCM8: + { + if (_dataOffset >= _swav.Samples.Length) + { + Stop(); + } + else + { + _dataOffset++; + } + return; + } + case SWAVFormat.PCM16: + { + if (_dataOffset >= _swav.Samples.Length) + { + Stop(); + } + else + { + _dataOffset += 2; + } + return; + } + case SWAVFormat.ADPCM: + { + if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) + { + Stop(); + } + else + { + // This is a faster emulation of adpcmDecoder.GetSample() without caring about the sample + if (_adpcmDecoder.OnSecondNibble) + { + _adpcmDecoder.DataOffset++; + } + _adpcmDecoder.OnSecondNibble = !_adpcmDecoder.OnSecondNibble; + } + return; + } + } + } + } + } + public void Process(out short left, out short right) + { + if (Timer == 0) + { + left = _prevLeft; + right = _prevRight; + return; + } + + int numSamples = (_pos + 0x100) / Timer; + _pos = (_pos + 0x100) % Timer; + // numSamples can be 0 + for (int i = 0; i < numSamples; i++) + { + short samp; + switch (Type) + { + case InstrumentType.PCM: + { + switch (_swav.Format) + { + case SWAVFormat.PCM8: + { + // If hit end + if (_dataOffset >= _swav.Samples.Length) + { + if (_swav.DoesLoop) + { + _dataOffset = _swav.LoopOffset * 4; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)((sbyte)_swav.Samples[_dataOffset++] << 8); + break; + } + case SWAVFormat.PCM16: + { + // If hit end + if (_dataOffset >= _swav.Samples.Length) + { + if (_swav.DoesLoop) + { + _dataOffset = _swav.LoopOffset * 4; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = (short)(_swav.Samples[_dataOffset++] | (_swav.Samples[_dataOffset++] << 8)); + break; + } + case SWAVFormat.ADPCM: + { + // If just looped + if (_swav.DoesLoop && _adpcmDecoder.DataOffset == _swav.LoopOffset * 4 && !_adpcmDecoder.OnSecondNibble) + { + _adpcmLoopLastSample = _adpcmDecoder.LastSample; + _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; + } + // If hit end + if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) + { + if (_swav.DoesLoop) + { + _adpcmDecoder.DataOffset = _swav.LoopOffset * 4; + _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; + _adpcmDecoder.LastSample = _adpcmLoopLastSample; + _adpcmDecoder.OnSecondNibble = false; + } + else + { + left = right = _prevLeft = _prevRight = 0; + Stop(); + return; + } + } + samp = _adpcmDecoder.GetSample(); + break; + } + default: samp = 0; break; + } + break; + } + case InstrumentType.PSG: + { + samp = _psgCounter <= _psgDuty ? short.MinValue : short.MaxValue; + _psgCounter++; + if (_psgCounter >= 8) + { + _psgCounter = 0; + } + break; + } + case InstrumentType.Noise: + { + if ((_noiseCounter & 1) != 0) + { + _noiseCounter = (ushort)((_noiseCounter >> 1) ^ 0x6000); + samp = -0x7FFF; + } + else + { + _noiseCounter = (ushort)(_noiseCounter >> 1); + samp = 0x7FFF; + } + break; + } + default: samp = 0; break; + } + samp = (short)(samp * Volume / 0x7F); + _prevLeft = (short)(samp * (-Pan + 0x40) / 0x80); + _prevRight = (short)(samp * (Pan + 0x40) / 0x80); + } + left = _prevLeft; + right = _prevRight; + } + } +} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATCommands.cs b/VG Music Studio - Core/NDS/SDAT/Commands.cs similarity index 100% rename from VG Music Studio - Core/NDS/SDAT/SDATCommands.cs rename to VG Music Studio - Core/NDS/SDAT/Commands.cs diff --git a/VG Music Studio - Core/NDS/SDAT/Enums.cs b/VG Music Studio - Core/NDS/SDAT/Enums.cs new file mode 100644 index 0000000..9f4aa42 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Enums.cs @@ -0,0 +1,40 @@ +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal enum EnvelopeState : byte + { + Attack, + Decay, + Sustain, + Release + } + internal enum ArgType : byte + { + None, + Byte, + Short, + VarLen, + Rand, + PlayerVar + } + + internal enum LFOType : byte + { + Pitch, + Volume, + Panpot + } + internal enum InstrumentType : byte + { + PCM = 0x1, + PSG = 0x2, + Noise = 0x3, + Drum = 0x10, + KeySplit = 0x11 + } + internal enum SWAVFormat : byte + { + PCM8, + PCM16, + ADPCM + } +} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs b/VG Music Studio - Core/NDS/SDAT/FileHeader.cs similarity index 87% rename from VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs rename to VG Music Studio - Core/NDS/SDAT/FileHeader.cs index dc742dc..638b4fd 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATFileHeader.cs +++ b/VG Music Studio - Core/NDS/SDAT/FileHeader.cs @@ -2,7 +2,7 @@ namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; -public sealed class SDATFileHeader +public sealed class FileHeader { public string FileType; public ushort FileEndianness; @@ -11,7 +11,7 @@ public sealed class SDATFileHeader public ushort HeaderSize; // 16 public ushort NumBlocks; - public SDATFileHeader(EndianBinaryReader er) + public FileHeader(EndianBinaryReader er) { FileType = er.ReadString_Count(4); er.Endianness = Endianness.BigEndian; diff --git a/VG Music Studio - Core/NDS/SDAT/SBNK.cs b/VG Music Studio - Core/NDS/SDAT/SBNK.cs index 953f065..2acd3a4 100644 --- a/VG Music Studio - Core/NDS/SDAT/SBNK.cs +++ b/VG Music Studio - Core/NDS/SDAT/SBNK.cs @@ -119,7 +119,7 @@ public Instrument(EndianBinaryReader er) } } - public SDATFileHeader FileHeader; // "SBNK" + public FileHeader FileHeader; // "SBNK" public string BlockType; // "DATA" public int BlockSize; public byte[] Padding; @@ -133,7 +133,7 @@ public SBNK(byte[] bytes) using (var stream = new MemoryStream(bytes)) { var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); + FileHeader = new FileHeader(er); BlockType = er.ReadString_Count(4); BlockSize = er.ReadInt32(); Padding = new byte[32]; diff --git a/VG Music Studio - Core/NDS/SDAT/SDAT.cs b/VG Music Studio - Core/NDS/SDAT/SDAT.cs index 2b31cf4..85e4ff3 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDAT.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDAT.cs @@ -111,24 +111,6 @@ public sealed class SequenceInfo public byte PlayerNum { get; set; } public byte Unknown3 { get; set; } public byte Unknown4 { get; set; } - - internal SSEQ GetSSEQ(SDAT sdat) - { - return new SSEQ(sdat.FATBlock.Entries[FileId].Data); - } - internal SBNK GetSBNK(SDAT sdat) - { - BankInfo bankInfo = sdat.INFOBlock.BankInfos.Entries[Bank]!; - var sbnk = new SBNK(sdat.FATBlock.Entries[bankInfo.FileId].Data); - for (int i = 0; i < 4; i++) - { - if (bankInfo.SWARs[i] != 0xFFFF) - { - sbnk.SWARs[i] = new SWAR(sdat.FATBlock.Entries[sdat.INFOBlock.WaveArchiveInfos.Entries[bankInfo.SWARs[i]]!.FileId].Data); - } - } - return sbnk; - } } public sealed class BankInfo { @@ -136,7 +118,7 @@ public sealed class BankInfo public byte Unknown1 { get; set; } public byte Unknown2 { get; set; } [BinaryArrayFixedLength(4)] - public ushort[] SWARs { get; set; } = null!; + public ushort[] SWARs { get; set; } } public sealed class WaveArchiveInfo { @@ -224,7 +206,7 @@ public FAT(EndianBinaryReader er) } } - public SDATFileHeader FileHeader; // "SDAT" + public FileHeader FileHeader; // "SDAT" public int SYMBOffset; public int SYMBLength; public int INFOOffset; @@ -240,27 +222,30 @@ public FAT(EndianBinaryReader er) public FAT FATBlock; //FILEBlock - public SDAT(Stream stream) + public SDAT(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - SYMBOffset = er.ReadInt32(); - SYMBLength = er.ReadInt32(); - INFOOffset = er.ReadInt32(); - INFOLength = er.ReadInt32(); - FATOffset = er.ReadInt32(); - FATLength = er.ReadInt32(); - FILEOffset = er.ReadInt32(); - FILELength = er.ReadInt32(); - Padding = new byte[16]; - er.ReadBytes(Padding); - - if (SYMBOffset != 0 && SYMBLength != 0) + using (var stream = new MemoryStream(bytes)) { - SYMBBlock = new SYMB(er, SYMBOffset); + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + SYMBOffset = er.ReadInt32(); + SYMBLength = er.ReadInt32(); + INFOOffset = er.ReadInt32(); + INFOLength = er.ReadInt32(); + FATOffset = er.ReadInt32(); + FATLength = er.ReadInt32(); + FILEOffset = er.ReadInt32(); + FILELength = er.ReadInt32(); + Padding = new byte[16]; + er.ReadBytes(Padding); + + if (SYMBOffset != 0 && SYMBLength != 0) + { + SYMBBlock = new SYMB(er, SYMBOffset); + } + INFOBlock = new INFO(er, INFOOffset); + stream.Position = FATOffset; + FATBlock = new FAT(er); } - INFOBlock = new INFO(er, INFOOffset); - stream.Position = FATOffset; - FATBlock = new FAT(er); } } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs b/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs deleted file mode 100644 index a925176..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATChannel.cs +++ /dev/null @@ -1,391 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SDATChannel -{ - public readonly byte Index; - - public SDATTrack? Owner; - public InstrumentType Type; - public EnvelopeState State; - public bool AutoSweep; - public byte BaseNote; - public byte Note; - public byte NoteVelocity; - public sbyte StartingPan; - public sbyte Pan; - public int SweepCounter; - public int SweepLength; - public short SweepPitch; - /// The SEQ Player treats 0 as the 100% amplitude value and -92544 (-723*128) as the 0% amplitude value. The starting ampltitude is 0% (-92544) - public int Velocity; - /// From 0x00-0x7F (Calculated from Utils) - public byte Volume; - public ushort BaseTimer; - public ushort Timer; - public int NoteDuration; - - private byte _attack; - private int _sustain; - private ushort _decay; - private ushort _release; - public byte LFORange; - public byte LFOSpeed; - public byte LFODepth; - public ushort LFODelay; - public ushort LFOPhase; - public int LFOParam; - public ushort LFODelayCount; - public LFOType LFOType; - public byte Priority; - - private int _pos; - private short _prevLeft; - private short _prevRight; - - // PCM8, PCM16, ADPCM - private SWAR.SWAV? _swav; - // PCM8, PCM16 - private int _dataOffset; - // ADPCM - private ADPCMDecoder _adpcmDecoder; - private short _adpcmLoopLastSample; - private short _adpcmLoopStepIndex; - // PSG - private byte _psgDuty; - private int _psgCounter; - // Noise - private ushort _noiseCounter; - - public SDATChannel(byte i) - { - Index = i; - } - - public void StartPCM(SWAR.SWAV swav, int noteDuration) - { - Type = InstrumentType.PCM; - _dataOffset = 0; - _swav = swav; - if (swav.Format == SWAVFormat.ADPCM) - { - _adpcmDecoder.Init(swav.Samples); - } - BaseTimer = swav.Timer; - Start(noteDuration); - } - public void StartPSG(byte duty, int noteDuration) - { - Type = InstrumentType.PSG; - _psgCounter = 0; - _psgDuty = duty; - BaseTimer = 8006; // NDSUtils.ARM7_CLOCK / 2093 - Start(noteDuration); - } - public void StartNoise(int noteLength) - { - Type = InstrumentType.Noise; - _noiseCounter = 0x7FFF; - BaseTimer = 8006; // NDSUtils.ARM7_CLOCK / 2093 - Start(noteLength); - } - - private void Start(int noteDuration) - { - State = EnvelopeState.Attack; - Velocity = -92544; - _pos = 0; - _prevLeft = _prevRight = 0; - NoteDuration = noteDuration; - } - - public void Stop() - { - Owner?.Channels.Remove(this); - Owner = null; - Volume = 0; - Priority = 0; - } - - public int SweepMain() - { - if (SweepPitch == 0 || SweepCounter >= SweepLength) - { - return 0; - } - - int sweep = (int)(Math.BigMul(SweepPitch, SweepLength - SweepCounter) / SweepLength); - if (AutoSweep) - { - SweepCounter++; - } - return sweep; - } - public void LFOTick() - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - else - { - int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; - if (LFOType == LFOType.Volume) - { - param = (param * 60) >> 14; - } - else - { - param >>= 8; - } - LFOParam = param; - int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" - while (counter >= 0x8000) - { - counter -= 0x8000; - } - LFOPhase = (ushort)counter; - } - } - - public void SetAttack(int a) - { - _attack = SDATUtils.AttackTable[a]; - } - public void SetDecay(int d) - { - _decay = SDATUtils.DecayTable[d]; - } - public void SetSustain(byte s) - { - _sustain = SDATUtils.SustainTable[s]; - } - public void SetRelease(int r) - { - _release = SDATUtils.DecayTable[r]; - } - public void StepEnvelope() - { - switch (State) - { - case EnvelopeState.Attack: - { - Velocity = _attack * Velocity / 0xFF; - if (Velocity == 0) - { - State = EnvelopeState.Decay; - } - break; - } - case EnvelopeState.Decay: - { - Velocity -= _decay; - if (Velocity <= _sustain) - { - State = EnvelopeState.Sustain; - Velocity = _sustain; - } - break; - } - case EnvelopeState.Release: - { - Velocity -= _release; - if (Velocity < -92544) - { - Velocity = -92544; - } - break; - } - } - } - - /// EmulateProcess doesn't care about samples that loop; it only cares about ones that force the track to wait for them to end - public void EmulateProcess() - { - if (Timer == 0) - { - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - for (int i = 0; i < numSamples; i++) - { - if (Type != InstrumentType.PCM || _swav!.DoesLoop) - { - continue; - } - - switch (_swav.Format) - { - case SWAVFormat.PCM8: - { - if (_dataOffset >= _swav.Samples.Length) - { - Stop(); - } - else - { - _dataOffset++; - } - return; - } - case SWAVFormat.PCM16: - { - if (_dataOffset >= _swav.Samples.Length) - { - Stop(); - } - else - { - _dataOffset += 2; - } - return; - } - case SWAVFormat.ADPCM: - { - if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) - { - Stop(); - } - else - { - // This is a faster emulation of adpcmDecoder.GetSample() without caring about the sample - if (_adpcmDecoder.OnSecondNibble) - { - _adpcmDecoder.DataOffset++; - } - _adpcmDecoder.OnSecondNibble = !_adpcmDecoder.OnSecondNibble; - } - return; - } - } - } - } - public void Process(out short left, out short right) - { - if (Timer == 0) - { - left = _prevLeft; - right = _prevRight; - return; - } - - int numSamples = (_pos + 0x100) / Timer; - _pos = (_pos + 0x100) % Timer; - // numSamples can be 0 - for (int i = 0; i < numSamples; i++) - { - short samp; - switch (Type) - { - case InstrumentType.PCM: - { - switch (_swav!.Format) - { - case SWAVFormat.PCM8: - { - // If hit end - if (_dataOffset >= _swav.Samples.Length) - { - if (_swav.DoesLoop) - { - _dataOffset = _swav.LoopOffset * 4; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)((sbyte)_swav.Samples[_dataOffset++] << 8); - break; - } - case SWAVFormat.PCM16: - { - // If hit end - if (_dataOffset >= _swav.Samples.Length) - { - if (_swav.DoesLoop) - { - _dataOffset = _swav.LoopOffset * 4; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = (short)(_swav.Samples[_dataOffset++] | (_swav.Samples[_dataOffset++] << 8)); - break; - } - case SWAVFormat.ADPCM: - { - // If just looped - if (_swav.DoesLoop && _adpcmDecoder.DataOffset == _swav.LoopOffset * 4 && !_adpcmDecoder.OnSecondNibble) - { - _adpcmLoopLastSample = _adpcmDecoder.LastSample; - _adpcmLoopStepIndex = _adpcmDecoder.StepIndex; - } - // If hit end - if (_adpcmDecoder.DataOffset >= _swav.Samples.Length && !_adpcmDecoder.OnSecondNibble) - { - if (_swav.DoesLoop) - { - _adpcmDecoder.DataOffset = _swav.LoopOffset * 4; - _adpcmDecoder.StepIndex = _adpcmLoopStepIndex; - _adpcmDecoder.LastSample = _adpcmLoopLastSample; - _adpcmDecoder.OnSecondNibble = false; - } - else - { - left = right = _prevLeft = _prevRight = 0; - Stop(); - return; - } - } - samp = _adpcmDecoder.GetSample(); - break; - } - default: samp = 0; break; - } - break; - } - case InstrumentType.PSG: - { - samp = _psgCounter <= _psgDuty ? short.MinValue : short.MaxValue; - _psgCounter++; - if (_psgCounter >= 8) - { - _psgCounter = 0; - } - break; - } - case InstrumentType.Noise: - { - if ((_noiseCounter & 1) != 0) - { - _noiseCounter = (ushort)((_noiseCounter >> 1) ^ 0x6000); - samp = -0x7FFF; - } - else - { - _noiseCounter = (ushort)(_noiseCounter >> 1); - samp = 0x7FFF; - } - break; - } - default: samp = 0; break; - } - samp = (short)(samp * Volume / 0x7F); - _prevLeft = (short)(samp * (-Pan + 0x40) / 0x80); - _prevRight = (short)(samp * (Pan + 0x40) / 0x80); - } - left = _prevLeft; - right = _prevRight; - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs b/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs index ce0c21c..c35a95a 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATConfig.cs @@ -31,7 +31,7 @@ public override string GetGameName() { return "SDAT"; } - public override string GetSongName(int index) + public override string GetSongName(long index) { return SDAT.SYMBBlock is null || index < 0 || index >= SDAT.SYMBBlock.SequenceSymbols.NumEntries ? index.ToString() diff --git a/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs b/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs deleted file mode 100644 index 62f10b9..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATEnums.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal enum EnvelopeState : byte -{ - Attack, - Decay, - Sustain, - Release, -} -internal enum ArgType : byte -{ - None, - Byte, - Short, - VarLen, - Rand, - PlayerVar, -} - -internal enum LFOType : byte -{ - Pitch, - Volume, - Panpot, -} -internal enum InstrumentType : byte -{ - PCM = 0x1, - PSG = 0x2, - Noise = 0x3, - Drum = 0x10, - KeySplit = 0x11, -} -internal enum SWAVFormat : byte -{ - PCM8, - PCM16, - ADPCM, -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs deleted file mode 100644 index ff00ed2..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong : ILoadedSong -{ - public List?[] Events { get; } - public long MaxTicks { get; internal set; } - public int LongestTrack; - - private readonly SDATPlayer _player; - private readonly int _randSeed; - private Random? _rand; - public readonly SDAT.INFO.SequenceInfo SEQInfo; // TODO: Not public - private readonly SSEQ _sseq; - private readonly SBNK _sbnk; - - public SDATLoadedSong(SDATPlayer player, SDAT.INFO.SequenceInfo seqInfo) - { - _player = player; - SEQInfo = seqInfo; - - SDAT sdat = player.Config.SDAT; - _sseq = seqInfo.GetSSEQ(sdat); - _sbnk = seqInfo.GetSBNK(sdat); - _randSeed = Random.Shared.Next(); - // Cannot set random seed without creating a new object which is dumb - - Events = new List[0x10]; - AddTrackEvents(0, 0); - } - - private static SDATInvalidCMDException Invalid(byte trackIndex, int cmdOffset, byte cmd) - { - return new SDATInvalidCMDException(trackIndex, cmdOffset, cmd); - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs deleted file mode 100644 index 6d69009..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs +++ /dev/null @@ -1,744 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using static System.Buffers.Binary.BinaryPrimitives; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong -{ - private void AddEvent(byte trackIndex, long cmdOffset, T command, ArgType argOverrideType) - where T : SDATCommand, ICommand - { - command.RandMod = argOverrideType == ArgType.Rand; - command.VarMod = argOverrideType == ArgType.PlayerVar; - Events[trackIndex]!.Add(new SongEvent(cmdOffset, command)); - } - private bool EventExists(byte trackIndex, long cmdOffset) - { - return Events[trackIndex]!.Exists(e => e.Offset == cmdOffset); - } - - private int ReadArg(ref int dataOffset, ArgType type) - { - switch (type) - { - case ArgType.Byte: - { - return _sseq.Data[dataOffset++]; - } - case ArgType.Short: - { - short s = ReadInt16LittleEndian(_sseq.Data.AsSpan(dataOffset)); - dataOffset += 2; - return s; - } - case ArgType.VarLen: - { - int numRead = 0; - int value = 0; - byte b; - do - { - b = _sseq.Data[dataOffset++]; - value = (value << 7) | (b & 0x7F); - numRead++; - } - while (numRead < 4 && (b & 0x80) != 0); - return value; - } - case ArgType.Rand: - { - // Combine min and max into one int - int minMax = ReadInt32LittleEndian(_sseq.Data.AsSpan(dataOffset)); - dataOffset += 4; - return minMax; - } - case ArgType.PlayerVar: - { - return _sseq.Data[dataOffset++]; // Return var index - } - default: throw new Exception(); - } - } - - private void AddTrackEvents(byte trackIndex, int trackStartOffset) - { - ref List? trackEvents = ref Events[trackIndex]; - trackEvents ??= new List(); - - int callStackDepth = 0; - AddEvents(trackIndex, trackStartOffset, ref callStackDepth); - } - private void AddEvents(byte trackIndex, int startOffset, ref int callStackDepth) - { - int dataOffset = startOffset; - bool cont = true; - while (cont) - { - bool @if = false; - int cmdOffset = dataOffset; - ArgType argOverrideType = ArgType.None; - again: - byte cmd = _sseq.Data[dataOffset++]; - - if (cmd <= 0x7F) - { - HandleNoteEvent(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); - } - else - { - switch (cmd & 0xF0) - { - case 0x80: HandleCmdGroup0x80(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0x90: HandleCmdGroup0x90(trackIndex, ref dataOffset, ref callStackDepth, cmdOffset, cmd, argOverrideType, ref @if, ref cont); break; - case 0xA0: - { - if (HandleCmdGroup0xA0(trackIndex, ref cmdOffset, cmd, ref argOverrideType, ref @if)) - { - goto again; - } - break; - } - case 0xB0: HandleCmdGroup0xB0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xC0: HandleCmdGroup0xC0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xD0: HandleCmdGroup0xD0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - case 0xE0: HandleCmdGroup0xE0(trackIndex, ref dataOffset, cmdOffset, cmd, argOverrideType); break; - default: HandleCmdGroup0xF0(trackIndex, ref dataOffset, ref callStackDepth, cmdOffset, cmd, argOverrideType, ref @if, ref cont); break; - } - } - } - } - - private void HandleNoteEvent(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - byte velocity = _sseq.Data[dataOffset++]; - int duration = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new NoteComand { Note = cmd, Velocity = velocity, Duration = duration }, argOverrideType); - } - } - private void HandleCmdGroup0x80(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); - switch (cmd) - { - case 0x80: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new RestCommand { Rest = arg }, argOverrideType); - } - break; - } - case 0x81: // RAND PROGRAM: [BW2 (2249)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VoiceCommand { Voice = arg }, argOverrideType); // TODO: Bank change - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0x90(byte trackIndex, ref int dataOffset, ref int callStackDepth, int cmdOffset, byte cmd, ArgType argOverrideType, ref bool @if, ref bool cont) - { - switch (cmd) - { - case 0x93: - { - byte openTrackIndex = _sseq.Data[dataOffset++]; - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new OpenTrackCommand { Track = openTrackIndex, Offset = offset24bit }, argOverrideType); - AddTrackEvents(openTrackIndex, offset24bit); - } - break; - } - case 0x94: - { - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new JumpCommand { Offset = offset24bit }, argOverrideType); - if (!EventExists(trackIndex, offset24bit)) - { - AddEvents(trackIndex, offset24bit, ref callStackDepth); - } - } - if (!@if) - { - cont = false; - } - break; - } - case 0x95: - { - int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new CallCommand { Offset = offset24bit }, argOverrideType); - } - if (callStackDepth < 3) - { - if (!EventExists(trackIndex, offset24bit)) - { - callStackDepth++; - AddEvents(trackIndex, offset24bit, ref callStackDepth); - } - } - else - { - throw new SDATTooManyNestedCallsException(trackIndex); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private bool HandleCmdGroup0xA0(byte trackIndex, ref int cmdOffset, byte cmd, ref ArgType argOverrideType, ref bool @if) - { - switch (cmd) - { - case 0xA0: // [New Super Mario Bros (BGM_AMB_CHIKA)] [BW2 (1917, 1918)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModRandCommand(), argOverrideType); - } - argOverrideType = ArgType.Rand; - cmdOffset++; - return true; - } - case 0xA1: // [New Super Mario Bros (BGM_AMB_SABAKU)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModVarCommand(), argOverrideType); - } - argOverrideType = ArgType.PlayerVar; - cmdOffset++; - return true; - } - case 0xA2: // [Mario Kart DS (75)] [BW2 (1917, 1918)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ModIfCommand(), argOverrideType); - } - @if = true; - cmdOffset++; - return true; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xB0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - byte varIndex = _sseq.Data[dataOffset++]; - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); - switch (cmd) - { - case 0xB0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarSetCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarAddCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarSubCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarMulCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarDivCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarShiftCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB6: // [Mario Kart DS (75)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarRandCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB8: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpEECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xB9: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpGECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBA: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpGGCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBB: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpLECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBC: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpLLCommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - case 0xBD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarCmpNECommand { Variable = varIndex, Argument = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xC0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); - switch (cmd) - { - case 0xC0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PanpotCommand { Panpot = arg }, argOverrideType); - } - break; - } - case 0xC1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackVolumeCommand { Volume = arg }, argOverrideType); - } - break; - } - case 0xC2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PlayerVolumeCommand { Volume = arg }, argOverrideType); - } - break; - } - case 0xC3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TransposeCommand { Transpose = arg }, argOverrideType); - } - break; - } - case 0xC4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendCommand { Bend = arg }, argOverrideType); - } - break; - } - case 0xC5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PitchBendRangeCommand { Range = arg }, argOverrideType); - } - break; - } - case 0xC6: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PriorityCommand { Priority = arg }, argOverrideType); - } - break; - } - case 0xC7: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new MonophonyCommand { Mono = arg }, argOverrideType); - } - break; - } - case 0xC8: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TieCommand { Tie = arg }, argOverrideType); - } - break; - } - case 0xC9: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoControlCommand { Portamento = arg }, argOverrideType); - } - break; - } - case 0xCA: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFODepthCommand { Depth = arg }, argOverrideType); - } - break; - } - case 0xCB: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFOSpeedCommand { Speed = arg }, argOverrideType); - } - break; - } - case 0xCC: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFOTypeCommand { Type = arg }, argOverrideType); - } - break; - } - case 0xCD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFORangeCommand { Range = arg }, argOverrideType); - } - break; - } - case 0xCE: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoToggleCommand { Portamento = arg }, argOverrideType); - } - break; - } - case 0xCF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new PortamentoTimeCommand { Time = arg }, argOverrideType); - } - break; - } - } - } - private void HandleCmdGroup0xD0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); - switch (cmd) - { - case 0xD0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceAttackCommand { Attack = arg }, argOverrideType); - } - break; - } - case 0xD1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceDecayCommand { Decay = arg }, argOverrideType); - } - break; - } - case 0xD2: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceSustainCommand { Sustain = arg }, argOverrideType); - } - break; - } - case 0xD3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ForceReleaseCommand { Release = arg }, argOverrideType); - } - break; - } - case 0xD4: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopStartCommand { NumLoops = arg }, argOverrideType); - } - break; - } - case 0xD5: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TrackExpressionCommand { Expression = arg }, argOverrideType); - } - break; - } - case 0xD6: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new VarPrintCommand { Variable = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xE0(byte trackIndex, ref int dataOffset, int cmdOffset, byte cmd, ArgType argOverrideType) - { - int arg = ReadArg(ref dataOffset, argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); - switch (cmd) - { - case 0xE0: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LFODelayCommand { Delay = arg }, argOverrideType); - } - break; - } - case 0xE1: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new TempoCommand { Tempo = arg }, argOverrideType); - } - break; - } - case 0xE3: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new SweepPitchCommand { Pitch = arg }, argOverrideType); - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - private void HandleCmdGroup0xF0(byte trackIndex, ref int dataOffset, ref int callStackDepth, int cmdOffset, byte cmd, ArgType argOverrideType, ref bool @if, ref bool cont) - { - switch (cmd) - { - case 0xFC: // [HGSS(1353)] - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new LoopEndCommand(), argOverrideType); - } - break; - } - case 0xFD: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new ReturnCommand(), argOverrideType); - } - if (!@if && callStackDepth != 0) - { - cont = false; - callStackDepth--; - } - break; - } - case 0xFE: - { - ushort bits = (ushort)ReadArg(ref dataOffset, ArgType.Short); - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new AllocTracksCommand { Tracks = bits }, argOverrideType); - } - break; - } - case 0xFF: - { - if (!EventExists(trackIndex, cmdOffset)) - { - AddEvent(trackIndex, cmdOffset, new FinishCommand(), argOverrideType); - } - if (!@if) - { - cont = false; - } - break; - } - default: throw Invalid(trackIndex, cmdOffset, cmd); - } - } - - public void SetTicks() - { - // TODO: (NSMB 81) (Spirit Tracks 18) does not count all ticks because the songs keep jumping backwards while changing vars and then using ModIfCommand to change events - // Should evaluate all branches if possible - MaxTicks = 0; - for (int i = 0; i < 0x10; i++) - { - ref List? evs = ref Events[i]; - evs?.Sort((e1, e2) => e1.Offset.CompareTo(e2.Offset)); - } - _player.InitEmulation(); - - bool[] done = new bool[0x10]; // We use this instead of track.Stopped just to be certain that emulating Monophony works as intended - while (Array.Exists(_player.Tracks, t => t.Allocated && t.Enabled && !done[t.Index])) - { - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - SDATTrack track = _player.Tracks[trackIndex]; - List evs = Events[trackIndex]!; - if (!track.Enabled || track.Stopped) - { - continue; - } - - track.Tick(); - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) - { - SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); - ExecuteNext(track); - if (done[trackIndex]) - { - continue; - } - - e.Ticks.Add(_player.ElapsedTicks); - bool b; - if (track.Stopped) - { - b = true; - } - else - { - SongEvent newE = evs.Single(ev => ev.Offset == track.DataOffset); - b = (track.CallStackDepth == 0 && newE.Ticks.Count > 0) // If we already counted the tick of this event and we're not looping/calling - || (track.CallStackDepth != 0 && track.CallStackLoops.All(l => l == 0) && newE.Ticks.Count > 0); // If we have "LoopStart (0)" and already counted the tick of this event - } - if (b) - { - done[trackIndex] = true; - if (_player.ElapsedTicks > MaxTicks) - { - LongestTrack = trackIndex; - MaxTicks = _player.ElapsedTicks; - } - } - } - } - _player.ElapsedTicks++; - } - _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); - } - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - _player.Tracks[trackIndex].StopAllChannels(); - } - } - internal void SetCurTick(long ticks) - { - while (true) - { - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - - while (_player.TempoStack >= 240) - { - _player.TempoStack -= 240; - for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) - { - SDATTrack track = _player.Tracks[trackIndex]; - if (track.Enabled && !track.Stopped) - { - track.Tick(); - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) - { - ExecuteNext(track); - } - } - } - _player.ElapsedTicks++; - if (_player.ElapsedTicks == ticks) - { - goto finish; - } - } - _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); - } - finish: - for (int i = 0; i < 0x10; i++) - { - _player.Tracks[i].StopAllChannels(); - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs deleted file mode 100644 index c9a87d0..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs +++ /dev/null @@ -1,787 +0,0 @@ -using System; -using System.Linq; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed partial class SDATLoadedSong -{ - public void InitEmulation() - { - _player.Volume = SEQInfo.Volume; - _rand = new Random(_randSeed); - } - - public void UpdateInstrumentCache(byte voice, out string str) - { - if (_sbnk.NumInstruments <= voice) - { - str = "Empty"; - } - else - { - InstrumentType t = _sbnk.Instruments[voice].Type; - switch (t) - { - case InstrumentType.PCM: str = "PCM"; break; - case InstrumentType.PSG: str = "PSG"; break; - case InstrumentType.Noise: str = "Noise"; break; - case InstrumentType.Drum: str = "Drum"; break; - case InstrumentType.KeySplit: str = "Key Split"; break; - default: str = "Invalid " + (byte)t; break; - } - } - } - - private int ReadArg(SDATTrack track, ArgType type) - { - if (track.ArgOverrideType != ArgType.None) - { - type = track.ArgOverrideType; - } - switch (type) - { - case ArgType.Byte: - { - return _sseq.Data[track.DataOffset++]; - } - case ArgType.Short: - { - return _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); - } - case ArgType.VarLen: - { - int read = 0, value = 0; - byte b; - do - { - b = _sseq.Data[track.DataOffset++]; - value = (value << 7) | (b & 0x7F); - read++; - } - while (read < 4 && (b & 0x80) != 0); - return value; - } - case ArgType.Rand: - { - short min = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); - short max = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); - return _rand!.Next(min, max + 1); - } - case ArgType.PlayerVar: - { - byte varIndex = _sseq.Data[track.DataOffset++]; - return _player.Vars[varIndex]; - } - default: throw new Exception(); - } - } - private void TryStartChannel(SBNK.InstrumentData inst, SDATTrack track, byte note, byte velocity, int duration, out SDATChannel? channel) - { - InstrumentType type = inst.Type; - channel = _player.SMixer.AllocateChannel(type, track); - if (channel is null) - { - return; - } - - if (track.Tie) - { - duration = -1; - } - SBNK.InstrumentData.DataParam param = inst.Param; - byte release = param.Release; - if (release == 0xFF) - { - duration = -1; - release = 0; - } - bool started = false; - switch (type) - { - case InstrumentType.PCM: - { - ushort[] info = param.Info; - SWAR.SWAV? swav = _sbnk.GetSWAV(info[1], info[0]); - if (swav is not null) - { - channel.StartPCM(swav, duration); - started = true; - } - break; - } - case InstrumentType.PSG: - { - channel.StartPSG((byte)param.Info[0], duration); - started = true; - break; - } - case InstrumentType.Noise: - { - channel.StartNoise(duration); - started = true; - break; - } - } - channel.Stop(); - if (!started) - { - return; - } - - channel.Note = note; - byte baseNote = param.BaseNote; - channel.BaseNote = type != InstrumentType.PCM && baseNote == 0x7F ? (byte)60 : baseNote; - channel.NoteVelocity = velocity; - channel.SetAttack(param.Attack); - channel.SetDecay(param.Decay); - channel.SetSustain(param.Sustain); - channel.SetRelease(release); - channel.StartingPan = (sbyte)(param.Pan - 0x40); - channel.Owner = track; - channel.Priority = track.Priority; - track.Channels.Add(channel); - } - private void PlayNote(SDATTrack track, byte note, byte velocity, int duration) - { - SDATChannel? channel = null; - if (track.Tie && track.Channels.Count != 0) - { - channel = track.Channels.Last(); - channel.Note = note; - channel.NoteVelocity = velocity; - } - else - { - SBNK.InstrumentData? inst = _sbnk.GetInstrumentData(track.Voice, note); - if (inst is not null) - { - TryStartChannel(inst, track, note, velocity, duration, out channel); - } - - if (channel is null) - { - return; - } - } - - if (track.Attack != 0xFF) - { - channel.SetAttack(track.Attack); - } - if (track.Decay != 0xFF) - { - channel.SetDecay(track.Decay); - } - if (track.Sustain != 0xFF) - { - channel.SetSustain(track.Sustain); - } - if (track.Release != 0xFF) - { - channel.SetRelease(track.Release); - } - channel.SweepPitch = track.SweepPitch; - if (track.Portamento) - { - channel.SweepPitch += (short)((track.PortamentoNote - note) << 6); // "<< 6" is "* 0x40" - } - if (track.PortamentoTime != 0) - { - channel.SweepLength = (track.PortamentoTime * track.PortamentoTime * Math.Abs(channel.SweepPitch)) >> 11; // ">> 11" is "/ 0x800" - channel.AutoSweep = true; - } - else - { - channel.SweepLength = duration; - channel.AutoSweep = false; - } - channel.SweepCounter = 0; - } - - internal void ExecuteNext(SDATTrack track) - { - bool resetOverride = true; - bool resetCmdWork = true; - byte cmd = _sseq.Data[track.DataOffset++]; - if (cmd < 0x80) - { - ExecuteNoteEvent(track, cmd); - } - else - { - switch (cmd & 0xF0) - { - case 0x80: ExecuteCmdGroup0x80(track, cmd); break; - case 0x90: ExecuteCmdGroup0x90(track, cmd); break; - case 0xA0: ExecuteCmdGroup0xA0(track, cmd, ref resetOverride, ref resetCmdWork); break; - case 0xB0: ExecuteCmdGroup0xB0(track, cmd); break; - case 0xC0: ExecuteCmdGroup0xC0(track, cmd); break; - case 0xD0: ExecuteCmdGroup0xD0(track, cmd); break; - case 0xE0: ExecuteCmdGroup0xE0(track, cmd); break; - default: ExecuteCmdGroup0xF0(track, cmd); break; - } - } - if (resetOverride) - { - track.ArgOverrideType = ArgType.None; - } - if (resetCmdWork) - { - track.DoCommandWork = true; - } - } - - private void ExecuteNoteEvent(SDATTrack track, byte cmd) - { - byte velocity = _sseq.Data[track.DataOffset++]; - int duration = ReadArg(track, ArgType.VarLen); - if (!track.DoCommandWork) - { - return; - } - - int n = cmd + track.Transpose; - if (n < 0) - { - n = 0; - } - else if (n > 0x7F) - { - n = 0x7F; - } - byte note = (byte)n; - PlayNote(track, note, velocity, duration); - track.PortamentoNote = note; - if (track.Mono) - { - track.Rest = duration; - if (duration == 0) - { - track.WaitingForNoteToFinishBeforeContinuingXD = true; - } - } - } - private void ExecuteCmdGroup0x80(SDATTrack track, byte cmd) - { - int arg = ReadArg(track, ArgType.VarLen); - - switch (cmd) - { - case 0x80: // Rest - { - if (track.DoCommandWork) - { - track.Rest = arg; - } - break; - } - case 0x81: // Program Change - { - if (track.DoCommandWork && arg <= byte.MaxValue) - { - track.Voice = (byte)arg; - } - break; - } - throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0x90(SDATTrack track, byte cmd) - { - switch (cmd) - { - case 0x93: // Open Track - { - int index = _sseq.Data[track.DataOffset++]; - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork && track.Index == 0) - { - SDATTrack other = _player.Tracks[index]; - if (other.Allocated && !other.Enabled) - { - other.Enabled = true; - other.DataOffset = offset24bit; - } - } - break; - } - case 0x94: // Jump - { - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork) - { - track.DataOffset = offset24bit; - } - break; - } - case 0x95: // Call - { - int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); - if (track.DoCommandWork && track.CallStackDepth < 3) - { - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackLoops[track.CallStackDepth] = byte.MaxValue; // This is only necessary for SetTicks() to deal with LoopStart (0) - track.CallStackDepth++; - track.DataOffset = offset24bit; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private static void ExecuteCmdGroup0xA0(SDATTrack track, byte cmd, ref bool resetOverride, ref bool resetCmdWork) - { - switch (cmd) - { - case 0xA0: // Rand Mod - { - if (track.DoCommandWork) - { - track.ArgOverrideType = ArgType.Rand; - resetOverride = false; - } - break; - } - case 0xA1: // Var Mod - { - if (track.DoCommandWork) - { - track.ArgOverrideType = ArgType.PlayerVar; - resetOverride = false; - } - break; - } - case 0xA2: // If Mod - { - if (track.DoCommandWork) - { - track.DoCommandWork = track.VariableFlag; - resetCmdWork = false; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xB0(SDATTrack track, byte cmd) - { - byte varIndex = _sseq.Data[track.DataOffset++]; - short mathArg = (short)ReadArg(track, ArgType.Short); - switch (cmd) - { - case 0xB0: // VarSet - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] = mathArg; - } - break; - } - case 0xB1: // VarAdd - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] += mathArg; - } - break; - } - case 0xB2: // VarSub - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] -= mathArg; - } - break; - } - case 0xB3: // VarMul - { - if (track.DoCommandWork) - { - _player.Vars[varIndex] *= mathArg; - } - break; - } - case 0xB4: // VarDiv - { - if (track.DoCommandWork && mathArg != 0) - { - _player.Vars[varIndex] /= mathArg; - } - break; - } - case 0xB5: // VarShift - { - if (track.DoCommandWork) - { - ref short v = ref _player.Vars[varIndex]; - v = mathArg < 0 ? (short)(v >> -mathArg) : (short)(v << mathArg); - } - break; - } - case 0xB6: // VarRand - { - if (track.DoCommandWork) - { - bool negate = false; - if (mathArg < 0) - { - negate = true; - mathArg = (short)-mathArg; - } - short val = (short)_rand!.Next(mathArg + 1); - if (negate) - { - val = (short)-val; - } - _player.Vars[varIndex] = val; - } - break; - } - case 0xB8: // VarCmpEE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] == mathArg; - } - break; - } - case 0xB9: // VarCmpGE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] >= mathArg; - } - break; - } - case 0xBA: // VarCmpGG - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] > mathArg; - } - break; - } - case 0xBB: // VarCmpLE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] <= mathArg; - } - break; - } - case 0xBC: // VarCmpLL - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] < mathArg; - } - break; - } - case 0xBD: // VarCmpNE - { - if (track.DoCommandWork) - { - track.VariableFlag = _player.Vars[varIndex] != mathArg; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xC0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Byte); - switch (cmd) - { - case 0xC0: // Panpot - { - if (track.DoCommandWork) - { - track.Panpot = (sbyte)(cmdArg - 0x40); - } - break; - } - case 0xC1: // Track Volume - { - if (track.DoCommandWork) - { - track.Volume = (byte)cmdArg; - } - break; - } - case 0xC2: // Player Volume - { - if (track.DoCommandWork) - { - _player.Volume = (byte)cmdArg; - } - break; - } - case 0xC3: // Transpose - { - if (track.DoCommandWork) - { - track.Transpose = (sbyte)cmdArg; - } - break; - } - case 0xC4: // Pitch Bend - { - if (track.DoCommandWork) - { - track.PitchBend = (sbyte)cmdArg; - } - break; - } - case 0xC5: // Pitch Bend Range - { - if (track.DoCommandWork) - { - track.PitchBendRange = (byte)cmdArg; - } - break; - } - case 0xC6: // Priority - { - if (track.DoCommandWork) - { - track.Priority = (byte)(_player.Priority + (byte)cmdArg); - } - break; - } - case 0xC7: // Mono - { - if (track.DoCommandWork) - { - track.Mono = cmdArg == 1; - } - break; - } - case 0xC8: // Tie - { - if (track.DoCommandWork) - { - track.Tie = cmdArg == 1; - track.StopAllChannels(); - } - break; - } - case 0xC9: // Portamento Control - { - if (track.DoCommandWork) - { - int k = cmdArg + track.Transpose; - if (k < 0) - { - k = 0; - } - else if (k > 0x7F) - { - k = 0x7F; - } - track.PortamentoNote = (byte)k; - track.Portamento = true; - } - break; - } - case 0xCA: // LFO Depth - { - if (track.DoCommandWork) - { - track.LFODepth = (byte)cmdArg; - } - break; - } - case 0xCB: // LFO Speed - { - if (track.DoCommandWork) - { - track.LFOSpeed = (byte)cmdArg; - } - break; - } - case 0xCC: // LFO Type - { - if (track.DoCommandWork) - { - track.LFOType = (LFOType)cmdArg; - } - break; - } - case 0xCD: // LFO Range - { - if (track.DoCommandWork) - { - track.LFORange = (byte)cmdArg; - } - break; - } - case 0xCE: // Portamento Toggle - { - if (track.DoCommandWork) - { - track.Portamento = cmdArg == 1; - } - break; - } - case 0xCF: // Portamento Time - { - if (track.DoCommandWork) - { - track.PortamentoTime = (byte)cmdArg; - } - break; - } - } - } - private void ExecuteCmdGroup0xD0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Byte); - switch (cmd) - { - case 0xD0: // Forced Attack - { - if (track.DoCommandWork) - { - track.Attack = (byte)cmdArg; - } - break; - } - case 0xD1: // Forced Decay - { - if (track.DoCommandWork) - { - track.Decay = (byte)cmdArg; - } - break; - } - case 0xD2: // Forced Sustain - { - if (track.DoCommandWork) - { - track.Sustain = (byte)cmdArg; - } - break; - } - case 0xD3: // Forced Release - { - if (track.DoCommandWork) - { - track.Release = (byte)cmdArg; - } - break; - } - case 0xD4: // Loop Start - { - if (track.DoCommandWork && track.CallStackDepth < 3) - { - track.CallStack[track.CallStackDepth] = track.DataOffset; - track.CallStackLoops[track.CallStackDepth] = (byte)cmdArg; - track.CallStackDepth++; - } - break; - } - case 0xD5: // Track Expression - { - if (track.DoCommandWork) - { - track.Expression = (byte)cmdArg; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } - private void ExecuteCmdGroup0xE0(SDATTrack track, byte cmd) - { - int cmdArg = ReadArg(track, ArgType.Short); - switch (cmd) - { - case 0xE0: // LFO Delay - { - if (track.DoCommandWork) - { - track.LFODelay = (ushort)cmdArg; - } - break; - } - case 0xE1: // Tempo - { - if (track.DoCommandWork) - { - _player.Tempo = (ushort)cmdArg; - } - break; - } - case 0xE3: // Sweep Pitch - { - if (track.DoCommandWork) - { - track.SweepPitch = (short)cmdArg; - } - break; - } - } - } - private void ExecuteCmdGroup0xF0(SDATTrack track, byte cmd) - { - switch (cmd) - { - case 0xFC: // Loop End - { - if (track.DoCommandWork && track.CallStackDepth != 0) - { - byte count = track.CallStackLoops[track.CallStackDepth - 1]; - if (count != 0) - { - count--; - track.CallStackLoops[track.CallStackDepth - 1] = count; - if (count == 0) - { - track.CallStackDepth--; - break; - } - } - track.DataOffset = track.CallStack[track.CallStackDepth - 1]; - } - break; - } - case 0xFD: // Return - { - if (track.DoCommandWork && track.CallStackDepth != 0) - { - track.CallStackDepth--; - track.DataOffset = track.CallStack[track.CallStackDepth]; - track.CallStackLoops[track.CallStackDepth] = 0; // This is only necessary for SetTicks() to deal with LoopStart (0) - } - break; - } - case 0xFE: // Alloc Tracks - { - // Must be in the beginning of the first track to work - if (track.DoCommandWork && track.Index == 0 && track.DataOffset == 1) // == 1 because we read cmd already - { - // Track 1 enabled = bit 1 set, Track 4 enabled = bit 4 set, etc - int trackBits = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); - for (int i = 0; i < 0x10; i++) - { - if ((trackBits & (1 << i)) != 0) - { - _player.Tracks[i].Allocated = true; - } - } - } - break; - } - case 0xFF: // Finish - { - if (track.DoCommandWork) - { - track.Stopped = true; - } - break; - } - default: throw Invalid(track.Index, track.DataOffset - 1, cmd); - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs index e516e15..9cbf17b 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs @@ -13,11 +13,9 @@ public sealed class SDATMixer : Mixer private float _fadePos; private float _fadeStepPerMicroframe; - internal SDATChannel[] Channels; + internal Channel[] Channels; private readonly BufferedWaveProvider _buffer; - protected override WaveFormat WaveFormat => _buffer.WaveFormat; - internal SDATMixer() { // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. @@ -27,10 +25,10 @@ internal SDATMixer() _samplesPerBuffer = 341; // TODO _samplesReciprocal = 1f / _samplesPerBuffer; - Channels = new SDATChannel[0x10]; + Channels = new Channel[0x10]; for (byte i = 0; i < 0x10; i++) { - Channels[i] = new SDATChannel(i); + Channels[i] = new Channel(i); } _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) @@ -44,7 +42,7 @@ internal SDATMixer() private static readonly int[] _pcmChanOrder = new int[] { 4, 5, 6, 7, 2, 0, 3, 1, 8, 9, 10, 11, 14, 12, 15, 13 }; private static readonly int[] _psgChanOrder = new int[] { 8, 9, 10, 11, 12, 13 }; private static readonly int[] _noiseChanOrder = new int[] { 14, 15 }; - internal SDATChannel? AllocateChannel(InstrumentType type, SDATTrack track) + internal Channel? AllocateChannel(InstrumentType type, Track track) { int[] allowedChannels; switch (type) @@ -54,10 +52,10 @@ internal SDATMixer() case InstrumentType.Noise: allowedChannels = _noiseChanOrder; break; default: return null; } - SDATChannel? nChan = null; + Channel? nChan = null; for (int i = 0; i < allowedChannels.Length; i++) { - SDATChannel c = Channels[allowedChannels[i]]; + Channel c = Channels[allowedChannels[i]]; if (nChan is not null && c.Priority >= nChan.Priority && (c.Priority != nChan.Priority || nChan.Volume <= c.Volume)) { continue; @@ -75,7 +73,7 @@ internal void ChannelTick() { for (int i = 0; i < 0x10; i++) { - SDATChannel chan = Channels[i]; + Channel chan = Channels[i]; if (chan.Owner is null) { continue; @@ -147,13 +145,23 @@ internal void ResetFade() _fadeMicroFramesLeft = 0; } + private WaveFileWriter? _waveWriter; + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, _buffer.WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } internal void EmulateProcess() { for (int i = 0; i < _samplesPerBuffer; i++) { for (int j = 0; j < 0x10; j++) { - SDATChannel chan = Channels[j]; + Channel chan = Channels[j]; if (chan.Owner is not null) { chan.EmulateProcess(); @@ -192,7 +200,7 @@ internal void Process(bool output, bool recording) right = 0; for (int j = 0; j < 0x10; j++) { - SDATChannel chan = Channels[j]; + Channel chan = Channels[j]; if (chan.Owner is null) { continue; diff --git a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs index 97fb6ae..3699cc9 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs @@ -1,195 +1,1694 @@ +using Kermalis.VGMusicStudio.Core.Util; using System; using System.Collections.Generic; +using System.Linq; +using System.Threading; namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; -public sealed class SDATPlayer : Player +public sealed class SDATPlayer : IPlayer, ILoadedSong { - protected override string Name => "SDAT Player"; - internal readonly byte Priority = 0x40; - internal readonly short[] Vars = new short[0x20]; // 16 player variables, then 16 global variables - internal readonly SDATTrack[] Tracks = new SDATTrack[0x10]; - private readonly string?[] _voiceTypeCache = new string?[256]; - internal readonly SDATConfig Config; - internal readonly SDATMixer SMixer; - private SDATLoadedSong? _loadedSong; - + private readonly short[] _vars = new short[0x20]; // 16 player variables, then 16 global variables + private readonly Track[] _tracks = new Track[0x10]; + private readonly SDATMixer _mixer; + private readonly SDATConfig _config; + private readonly TimeBarrier _time; + private Thread? _thread; + private int _randSeed; + private Random _rand; + private SDAT.INFO.SequenceInfo _seqInfo; + private SSEQ _sseq; + private SBNK _sbnk; internal byte Volume; - internal ushort Tempo; - internal int TempoStack; + private ushort _tempo; + private int _tempoStack; private long _elapsedLoops; - private ushort? _prevBank; + public List[] Events { get; private set; } + public long MaxTicks { get; private set; } + public long ElapsedTicks { get; private set; } + public ILoadedSong LoadedSong => this; + public bool ShouldFadeOut { get; set; } + public long NumLoops { get; set; } + private int _longestTrack; - public override ILoadedSong? LoadedSong => _loadedSong; - protected override Mixer Mixer => SMixer; + public PlayerState State { get; private set; } + public event Action? SongEnded; internal SDATPlayer(SDATConfig config, SDATMixer mixer) - : base(192) { - Config = config; - SMixer = mixer; + _config = config; + _mixer = mixer; for (byte i = 0; i < 0x10; i++) { - Tracks[i] = new SDATTrack(i, this); + _tracks[i] = new Track(i, this); } - } - public override void LoadSong(int index) + _time = new TimeBarrier(192); + } + private void CreateThread() { - if (_loadedSong is not null) + _thread = new Thread(Tick) { Name = "SDAT Player Tick" }; + _thread.Start(); + } + private void WaitThread() + { + if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) { - _loadedSong = null; + _thread.Join(); } + } - SDAT.INFO.SequenceInfo? seqInfo = Config.SDAT.INFOBlock.SequenceInfos.Entries[index]; - if (seqInfo is null) + private void InitEmulation() + { + _tempo = 120; // Confirmed: default tempo is 120 (MKDS 75) + _tempoStack = 0; + _elapsedLoops = 0; + ElapsedTicks = 0; + _mixer.ResetFade(); + Volume = _seqInfo.Volume; + _rand = new Random(_randSeed); + for (int i = 0; i < 0x10; i++) + { + _tracks[i].Init(); + } + // Initialize player and global variables. Global variables should not have a global effect in this program. + for (int i = 0; i < 0x20; i++) { + _vars[i] = i % 8 == 0 ? short.MaxValue : (short)0; + } + } + private void SetTicks() + { + // TODO: (NSMB 81) (Spirit Tracks 18) does not count all ticks because the songs keep jumping backwards while changing vars and then using ModIfCommand to change events + // Should evaluate all branches if possible + MaxTicks = 0; + for (int i = 0; i < 0x10; i++) + { + if (Events[i] != null) + { + Events[i] = Events[i].OrderBy(e => e.Offset).ToList(); + } + } + InitEmulation(); + bool[] done = new bool[0x10]; // We use this instead of track.Stopped just to be certain that emulating Monophony works as intended + while (_tracks.Any(t => t.Allocated && t.Enabled && !done[t.Index])) + { + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + List evs = Events[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + SongEvent e = evs.Single(ev => ev.Offset == track.DataOffset); + ExecuteNext(track); + if (!done[trackIndex]) + { + e.Ticks.Add(ElapsedTicks); + bool b; + if (track.Stopped) + { + b = true; + } + else + { + SongEvent newE = evs.Single(ev => ev.Offset == track.DataOffset); + b = (track.CallStackDepth == 0 && newE.Ticks.Count > 0) // If we already counted the tick of this event and we're not looping/calling + || (track.CallStackDepth != 0 && track.CallStackLoops.All(l => l == 0) && newE.Ticks.Count > 0); // If we have "LoopStart (0)" and already counted the tick of this event + } + if (b) + { + done[trackIndex] = true; + if (ElapsedTicks > MaxTicks) + { + _longestTrack = trackIndex; + MaxTicks = ElapsedTicks; + } + } + } + } + } + } + ElapsedTicks++; + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.EmulateProcess(); + } + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + _tracks[trackIndex].StopAllChannels(); + } + } + public void LoadSong(long index) + { + Stop(); + SDAT.INFO.SequenceInfo oldSeqInfo = _seqInfo; + _seqInfo = _config.SDAT.INFOBlock.SequenceInfos.Entries[index]; + if (_seqInfo == null) + { + _sseq = null; + _sbnk = null; + Events = null; return; } - // If there's an exception, this will remain null - _loadedSong = new SDATLoadedSong(this, seqInfo); - _loadedSong.SetTicks(); - - ushort? old = _prevBank; - ushort nu = _loadedSong.SEQInfo.Bank; - if (old != nu) + if (oldSeqInfo == null || _seqInfo.Bank != oldSeqInfo.Bank) { - _prevBank = nu; Array.Clear(_voiceTypeCache); } + _sseq = new SSEQ(_config.SDAT.FATBlock.Entries[_seqInfo.FileId].Data); + SDAT.INFO.BankInfo bankInfo = _config.SDAT.INFOBlock.BankInfos.Entries[_seqInfo.Bank]; + _sbnk = new SBNK(_config.SDAT.FATBlock.Entries[bankInfo.FileId].Data); + for (int i = 0; i < 4; i++) + { + if (bankInfo.SWARs[i] != 0xFFFF) + { + _sbnk.SWARs[i] = new SWAR(_config.SDAT.FATBlock.Entries[_config.SDAT.INFOBlock.WaveArchiveInfos.Entries[bankInfo.SWARs[i]].FileId].Data); + } + } + _randSeed = new Random().Next(); + + // RECURSION INCOMING + Events = new List[0x10]; + AddTrackEvents(0, 0); + void AddTrackEvents(byte i, int trackStartOffset) + { + if (Events[i] == null) + { + Events[i] = new List(); + } + int callStackDepth = 0; + AddEvents(trackStartOffset); + bool EventExists(long offset) + { + return Events[i].Any(e => e.Offset == offset); + } + void AddEvents(int startOffset) + { + int dataOffset = startOffset; + int ReadArg(ArgType type) + { + switch (type) + { + case ArgType.Byte: + { + return _sseq.Data[dataOffset++]; + } + case ArgType.Short: + { + return _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8); + } + case ArgType.VarLen: + { + int read = 0, value = 0; + byte b; + do + { + b = _sseq.Data[dataOffset++]; + value = (value << 7) | (b & 0x7F); + read++; + } + while (read < 4 && (b & 0x80) != 0); + return value; + } + case ArgType.Rand: + { + // Combine min and max into one int + return _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16) | (_sseq.Data[dataOffset++] << 24); + } + case ArgType.PlayerVar: + { + // Return var index + return _sseq.Data[dataOffset++]; + } + default: throw new Exception(); + } + } + bool cont = true; + while (cont) + { + bool @if = false; + int offset = dataOffset; + ArgType argOverrideType = ArgType.None; + again: + byte cmd = _sseq.Data[dataOffset++]; + void AddEvent(T command) where T : SDATCommand, ICommand + { + command.RandMod = argOverrideType == ArgType.Rand; + command.VarMod = argOverrideType == ArgType.PlayerVar; + Events[i].Add(new SongEvent(offset, command)); + } + void Invalid() + { + throw new SDATInvalidCMDException(i, offset, cmd); + } + + if (cmd <= 0x7F) + { + byte velocity = _sseq.Data[dataOffset++]; + int duration = ReadArg(argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); + if (!EventExists(offset)) + { + AddEvent(new NoteComand { Note = cmd, Velocity = velocity, Duration = duration }); + } + } + else + { + int cmdGroup = cmd & 0xF0; + if (cmdGroup == 0x80) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.VarLen : argOverrideType); + switch (cmd) + { + case 0x80: + { + if (!EventExists(offset)) + { + AddEvent(new RestCommand { Rest = arg }); + } + break; + } + case 0x81: // RAND PROGRAM: [BW2 (2249)] + { + if (!EventExists(offset)) + { + AddEvent(new VoiceCommand { Voice = arg }); // TODO: Bank change + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0x90) + { + switch (cmd) + { + case 0x93: + { + byte trackIndex = _sseq.Data[dataOffset++]; + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new OpenTrackCommand { Track = trackIndex, Offset = offset24bit }); + AddTrackEvents(trackIndex, offset24bit); + } + break; + } + case 0x94: + { + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new JumpCommand { Offset = offset24bit }); + if (!EventExists(offset24bit)) + { + AddEvents(offset24bit); + } + } + if (!@if) + { + cont = false; + } + break; + } + case 0x95: + { + int offset24bit = _sseq.Data[dataOffset++] | (_sseq.Data[dataOffset++] << 8) | (_sseq.Data[dataOffset++] << 16); + if (!EventExists(offset)) + { + AddEvent(new CallCommand { Offset = offset24bit }); + } + if (callStackDepth < 3) + { + if (!EventExists(offset24bit)) + { + callStackDepth++; + AddEvents(offset24bit); + } + } + else + { + throw new SDATTooManyNestedCallsException(i); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xA0) + { + switch (cmd) + { + case 0xA0: // [New Super Mario Bros (BGM_AMB_CHIKA)] [BW2 (1917, 1918)] + { + if (!EventExists(offset)) + { + AddEvent(new ModRandCommand()); + } + argOverrideType = ArgType.Rand; + offset++; + goto again; + } + case 0xA1: // [New Super Mario Bros (BGM_AMB_SABAKU)] + { + if (!EventExists(offset)) + { + AddEvent(new ModVarCommand()); + } + argOverrideType = ArgType.PlayerVar; + offset++; + goto again; + } + case 0xA2: // [Mario Kart DS (75)] [BW2 (1917, 1918)] + { + if (!EventExists(offset)) + { + AddEvent(new ModIfCommand()); + } + @if = true; + offset++; + goto again; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xB0) + { + byte varIndex = _sseq.Data[dataOffset++]; + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); + switch (cmd) + { + case 0xB0: + { + if (!EventExists(offset)) + { + AddEvent(new VarSetCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB1: + { + if (!EventExists(offset)) + { + AddEvent(new VarAddCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB2: + { + if (!EventExists(offset)) + { + AddEvent(new VarSubCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB3: + { + if (!EventExists(offset)) + { + AddEvent(new VarMulCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB4: + { + if (!EventExists(offset)) + { + AddEvent(new VarDivCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB5: + { + if (!EventExists(offset)) + { + AddEvent(new VarShiftCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB6: // [Mario Kart DS (75)] + { + if (!EventExists(offset)) + { + AddEvent(new VarRandCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB8: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpEECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xB9: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpGECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBA: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpGGCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBB: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpLECommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBC: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpLLCommand { Variable = varIndex, Argument = arg }); + } + break; + } + case 0xBD: + { + if (!EventExists(offset)) + { + AddEvent(new VarCmpNECommand { Variable = varIndex, Argument = arg }); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xC0 || cmdGroup == 0xD0) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Byte : argOverrideType); + switch (cmd) + { + case 0xC0: + { + if (!EventExists(offset)) + { + AddEvent(new PanpotCommand { Panpot = arg }); + } + break; + } + case 0xC1: + { + if (!EventExists(offset)) + { + AddEvent(new TrackVolumeCommand { Volume = arg }); + } + break; + } + case 0xC2: + { + if (!EventExists(offset)) + { + AddEvent(new PlayerVolumeCommand { Volume = arg }); + } + break; + } + case 0xC3: + { + if (!EventExists(offset)) + { + AddEvent(new TransposeCommand { Transpose = arg }); + } + break; + } + case 0xC4: + { + if (!EventExists(offset)) + { + AddEvent(new PitchBendCommand { Bend = arg }); + } + break; + } + case 0xC5: + { + if (!EventExists(offset)) + { + AddEvent(new PitchBendRangeCommand { Range = arg }); + } + break; + } + case 0xC6: + { + if (!EventExists(offset)) + { + AddEvent(new PriorityCommand { Priority = arg }); + } + break; + } + case 0xC7: + { + if (!EventExists(offset)) + { + AddEvent(new MonophonyCommand { Mono = arg }); + } + break; + } + case 0xC8: + { + if (!EventExists(offset)) + { + AddEvent(new TieCommand { Tie = arg }); + } + break; + } + case 0xC9: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoControlCommand { Portamento = arg }); + } + break; + } + case 0xCA: + { + if (!EventExists(offset)) + { + AddEvent(new LFODepthCommand { Depth = arg }); + } + break; + } + case 0xCB: + { + if (!EventExists(offset)) + { + AddEvent(new LFOSpeedCommand { Speed = arg }); + } + break; + } + case 0xCC: + { + if (!EventExists(offset)) + { + AddEvent(new LFOTypeCommand { Type = arg }); + } + break; + } + case 0xCD: + { + if (!EventExists(offset)) + { + AddEvent(new LFORangeCommand { Range = arg }); + } + break; + } + case 0xCE: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoToggleCommand { Portamento = arg }); + } + break; + } + case 0xCF: + { + if (!EventExists(offset)) + { + AddEvent(new PortamentoTimeCommand { Time = arg }); + } + break; + } + case 0xD0: + { + if (!EventExists(offset)) + { + AddEvent(new ForceAttackCommand { Attack = arg }); + } + break; + } + case 0xD1: + { + if (!EventExists(offset)) + { + AddEvent(new ForceDecayCommand { Decay = arg }); + } + break; + } + case 0xD2: + { + if (!EventExists(offset)) + { + AddEvent(new ForceSustainCommand { Sustain = arg }); + } + break; + } + case 0xD3: + { + if (!EventExists(offset)) + { + AddEvent(new ForceReleaseCommand { Release = arg }); + } + break; + } + case 0xD4: + { + if (!EventExists(offset)) + { + AddEvent(new LoopStartCommand { NumLoops = arg }); + } + break; + } + case 0xD5: + { + if (!EventExists(offset)) + { + AddEvent(new TrackExpressionCommand { Expression = arg }); + } + break; + } + case 0xD6: + { + if (!EventExists(offset)) + { + AddEvent(new VarPrintCommand { Variable = arg }); + } + break; + } + default: Invalid(); break; + } + } + else if (cmdGroup == 0xE0) + { + int arg = ReadArg(argOverrideType == ArgType.None ? ArgType.Short : argOverrideType); + switch (cmd) + { + case 0xE0: + { + if (!EventExists(offset)) + { + AddEvent(new LFODelayCommand { Delay = arg }); + } + break; + } + case 0xE1: + { + if (!EventExists(offset)) + { + AddEvent(new TempoCommand { Tempo = arg }); + } + break; + } + case 0xE3: + { + if (!EventExists(offset)) + { + AddEvent(new SweepPitchCommand { Pitch = arg }); + } + break; + } + default: Invalid(); break; + } + } + else // if (cmdGroup == 0xF0) + { + switch (cmd) + { + case 0xFC: // [HGSS(1353)] + { + if (!EventExists(offset)) + { + AddEvent(new LoopEndCommand()); + } + break; + } + case 0xFD: + { + if (!EventExists(offset)) + { + AddEvent(new ReturnCommand()); + } + if (!@if && callStackDepth != 0) + { + cont = false; + callStackDepth--; + } + break; + } + case 0xFE: + { + ushort bits = (ushort)ReadArg(ArgType.Short); + if (!EventExists(offset)) + { + AddEvent(new AllocTracksCommand { Tracks = bits }); + } + break; + } + case 0xFF: + { + if (!EventExists(offset)) + { + AddEvent(new FinishCommand()); + } + if (!@if) + { + cont = false; + } + break; + } + default: Invalid(); break; + } + } + } + } + } + } + SetTicks(); } - public override void UpdateSongState(SongState info) + + public void SetCurrentPosition(long ticks) { - info.Tempo = Tempo; - for (int i = 0; i < 0x10; i++) + if (_seqInfo is null) + { + SongEnded?.Invoke(); + return; + } + if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) + { + return; + } + + if (State is PlayerState.Playing) + { + Pause(); + } + InitEmulation(); + while (true) { - SDATTrack track = Tracks[i]; - if (track.Enabled) + if (ElapsedTicks == ticks) { - track.UpdateSongState(info.Tracks[i], _loadedSong!, _voiceTypeCache); + goto finish; } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (track.Enabled && !track.Stopped) + { + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + ExecuteNext(track); + } + } + } + ElapsedTicks++; + if (ElapsedTicks == ticks) + { + goto finish; + } + } + _tempoStack += _tempo; + _mixer.ChannelTick(); + _mixer.EmulateProcess(); + } + finish: + for (int i = 0; i < 0x10; i++) + { + _tracks[i].StopAllChannels(); } + Pause(); } - internal override void InitEmulation() + public void Play() { - Tempo = 120; // Confirmed: default tempo is 120 (MKDS 75) - TempoStack = 0; - _elapsedLoops = 0; - ElapsedTicks = 0; - SMixer.ResetFade(); - _loadedSong!.InitEmulation(); - for (int i = 0; i < 0x10; i++) + if (_seqInfo == null) { - Tracks[i].Init(); + SongEnded?.Invoke(); + return; } - // Initialize player and global variables. Global variables should not have a global effect in this program. - for (int i = 0; i < 0x20; i++) + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) { - Vars[i] = i % 8 == 0 ? short.MaxValue : (short)0; + Stop(); + InitEmulation(); + State = PlayerState.Playing; + CreateThread(); } } - protected override void SetCurTick(long ticks) + public void Pause() { - _loadedSong!.SetCurTick(ticks); + if (State == PlayerState.Playing) + { + State = PlayerState.Paused; + WaitThread(); + } + else if (State == PlayerState.Paused || State == PlayerState.Stopped) + { + State = PlayerState.Playing; + CreateThread(); + } } - protected override void OnStopped() + public void Stop() { - for (int i = 0; i < 0x10; i++) + if (State == PlayerState.Playing || State == PlayerState.Paused) { - Tracks[i].StopAllChannels(); + State = PlayerState.Stopped; + WaitThread(); } } - - protected override bool Tick(bool playing, bool recording) + public void Record(string fileName) + { + _mixer.CreateWaveWriter(fileName); + InitEmulation(); + State = PlayerState.Recording; + CreateThread(); + WaitThread(); + _mixer.CloseWaveWriter(); + } + public void Dispose() + { + if (State is PlayerState.Playing or PlayerState.Paused or PlayerState.Stopped) + { + State = PlayerState.ShutDown; + WaitThread(); + } + } + private readonly string?[] _voiceTypeCache = new string?[256]; + public void UpdateSongState(SongState info) { - bool allDone = false; - while (!allDone && TempoStack >= 240) + info.Tempo = _tempo; + for (int i = 0; i < 0x10; i++) { - TempoStack -= 240; - allDone = true; - for (int i = 0; i < 0x10; i++) + Track track = _tracks[i]; + if (!track.Enabled) + { + continue; + } + + SongState.Track tin = info.Tracks[i]; + tin.Position = track.DataOffset; + tin.Rest = track.Rest; + tin.Voice = track.Voice; + tin.LFO = track.LFODepth * track.LFORange; + ref string? cache = ref _voiceTypeCache[track.Voice]; + if (cache is null) { - TickTrack(i, ref allDone); + if (_sbnk.NumInstruments <= track.Voice) + { + cache = "Empty"; + } + else + { + InstrumentType t = _sbnk.Instruments[track.Voice].Type; + switch (t) + { + case InstrumentType.PCM: cache = "PCM"; break; + case InstrumentType.PSG: cache = "PSG"; break; + case InstrumentType.Noise: cache = "Noise"; break; + case InstrumentType.Drum: cache = "Drum"; break; + case InstrumentType.KeySplit: cache = "Key Split"; break; + default: cache = "Invalid {0}" + (byte)t; break; + } + } } - if (SMixer.IsFadeDone()) + tin.Type = cache; + tin.Volume = track.Volume; + tin.PitchBend = track.GetPitch(); + tin.Extra = track.Portamento ? track.PortamentoTime : (byte)0; + tin.Panpot = track.GetPan(); + + Channel[] channels = track.Channels.ToArray(); + if (channels.Length == 0) + { + tin.Keys[0] = byte.MaxValue; + tin.LeftVolume = 0f; + tin.RightVolume = 0f; + } + else { - allDone = true; + int numKeys = 0; + float left = 0f; + float right = 0f; + for (int j = 0; j < channels.Length; j++) + { + Channel c = channels[j]; + if (c.State != EnvelopeState.Release) + { + tin.Keys[numKeys++] = c.Note; + } + float a = (float)(-c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > left) + { + left = a; + } + a = (float)(c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; + if (a > right) + { + right = a; + } + } + tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array + tin.LeftVolume = left; + tin.RightVolume = right; } } - if (!allDone) + } + + private void TryStartChannel(SBNK.InstrumentData inst, Track track, byte note, byte velocity, int duration, out Channel? channel) + { + InstrumentType type = inst.Type; + channel = _mixer.AllocateChannel(type, track); + if (channel is null) { - TempoStack += Tempo; + return; } - for (int i = 0; i < 0x10; i++) + + if (track.Tie) { - SDATTrack track = Tracks[i]; - if (track.Enabled) + duration = -1; + } + SBNK.InstrumentData.DataParam param = inst.Param; + byte release = param.Release; + if (release == 0xFF) + { + duration = -1; + release = 0; + } + bool started = false; + switch (type) + { + case InstrumentType.PCM: + { + ushort[] info = param.Info; + SWAR.SWAV? swav = _sbnk.GetSWAV(info[1], info[0]); + if (swav is not null) + { + channel.StartPCM(swav, duration); + started = true; + } + break; + } + case InstrumentType.PSG: { - track.UpdateChannels(); + channel.StartPSG((byte)param.Info[0], duration); + started = true; + break; + } + case InstrumentType.Noise: + { + channel.StartNoise(duration); + started = true; + break; } } - SMixer.ChannelTick(); - SMixer.Process(playing, recording); - return allDone; + channel.Stop(); + if (!started) + { + return; + } + + channel.Note = note; + byte baseNote = param.BaseNote; + channel.BaseNote = type != InstrumentType.PCM && baseNote == 0x7F ? (byte)60 : baseNote; + channel.NoteVelocity = velocity; + channel.SetAttack(param.Attack); + channel.SetDecay(param.Decay); + channel.SetSustain(param.Sustain); + channel.SetRelease(release); + channel.StartingPan = (sbyte)(param.Pan - 0x40); + channel.Owner = track; + channel.Priority = track.Priority; + track.Channels.Add(channel); } - private void TickTrack(int trackIndex, ref bool allDone) + internal void PlayNote(Track track, byte note, byte velocity, int duration) { - SDATTrack track = Tracks[trackIndex]; - if (!track.Enabled) + Channel? channel = null; + if (track.Tie && track.Channels.Count != 0) { - return; + channel = track.Channels.Last(); + channel.Note = note; + channel.NoteVelocity = velocity; + } + else + { + SBNK.InstrumentData? inst = _sbnk.GetInstrumentData(track.Voice, note); + if (inst is not null) + { + TryStartChannel(inst, track, note, velocity, duration, out channel); + } + + if (channel is null) + { + return; + } } - track.Tick(); - SDATLoadedSong s = _loadedSong!; - while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + if (track.Attack != 0xFF) + { + channel.SetAttack(track.Attack); + } + if (track.Decay != 0xFF) + { + channel.SetDecay(track.Decay); + } + if (track.Sustain != 0xFF) + { + channel.SetSustain(track.Sustain); + } + if (track.Release != 0xFF) + { + channel.SetRelease(track.Release); + } + channel.SweepPitch = track.SweepPitch; + if (track.Portamento) { - s.ExecuteNext(track); + channel.SweepPitch += (short)((track.PortamentoKey - note) << 6); // "<< 6" is "* 0x40" } - if (trackIndex == s.LongestTrack) + if (track.PortamentoTime != 0) { - HandleTicksAndLoop(s, track); + channel.SweepLength = (track.PortamentoTime * track.PortamentoTime * Math.Abs(channel.SweepPitch)) >> 11; // ">> 11" is "/ 0x800" + channel.AutoSweep = true; } - if (!track.Stopped || track.Channels.Count != 0) + else { - allDone = false; + channel.SweepLength = duration; + channel.AutoSweep = false; } + channel.SweepCounter = 0; } - private void HandleTicksAndLoop(SDATLoadedSong s, SDATTrack track) + private void ExecuteNext(Track track) { - if (ElapsedTicks != s.MaxTicks) + int ReadArg(ArgType type) { - ElapsedTicks++; - return; + if (track.ArgOverrideType != ArgType.None) + { + type = track.ArgOverrideType; + } + switch (type) + { + case ArgType.Byte: + { + return _sseq.Data[track.DataOffset++]; + } + case ArgType.Short: + { + return _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); + } + case ArgType.VarLen: + { + int read = 0, value = 0; + byte b; + do + { + b = _sseq.Data[track.DataOffset++]; + value = (value << 7) | (b & 0x7F); + read++; + } + while (read < 4 && (b & 0x80) != 0); + return value; + } + case ArgType.Rand: + { + short min = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); + short max = (short)(_sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8)); + return _rand.Next(min, max + 1); + } + case ArgType.PlayerVar: + { + byte varIndex = _sseq.Data[track.DataOffset++]; + return _vars[varIndex]; + } + default: throw new Exception(); + } } - // Track reached the detected end, update loops/ticks accordingly - if (track.Stopped) + bool resetOverride = true; + bool resetCmdWork = true; + byte cmd = _sseq.Data[track.DataOffset++]; + if (cmd < 0x80) // Notes { - return; + byte velocity = _sseq.Data[track.DataOffset++]; + int duration = ReadArg(ArgType.VarLen); + if (track.DoCommandWork) + { + int k = cmd + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + byte key = (byte)k; + PlayNote(track, key, velocity, duration); + track.PortamentoKey = key; + if (track.Mono) + { + track.Rest = duration; + if (duration == 0) + { + track.WaitingForNoteToFinishBeforeContinuingXD = true; + } + } + } } - - _elapsedLoops++; - //UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.DataOffset, track.Rest); // TODO - // Prevent crashes with songs that don't load all ticks yet (See SetTicks()) - List evs = s.Events[track.Index]!; - for (int i = 0; i < evs.Count; i++) + else { - SongEvent ev = evs[i]; - if (ev.Offset == track.DataOffset) + int cmdGroup = cmd & 0xF0; + switch (cmdGroup) { - //ElapsedTicks = ev.Ticks[0] - track.Rest; - ElapsedTicks = ev.Ticks.Count == 0 ? 0 : ev.Ticks[0] - track.Rest; - break; + case 0x80: + { + int arg = ReadArg(ArgType.VarLen); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0x80: // Rest + { + track.Rest = arg; + break; + } + case 0x81: // Program Change + { + if (arg <= byte.MaxValue) + { + track.Voice = (byte)arg; + } + break; + } + } + } + break; + } + case 0x90: + { + switch (cmd) + { + case 0x93: // Open Track + { + int index = _sseq.Data[track.DataOffset++]; + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork && track.Index == 0) + { + Track other = _tracks[index]; + if (other.Allocated && !other.Enabled) + { + other.Enabled = true; + other.DataOffset = offset24bit; + } + } + break; + } + case 0x94: // Jump + { + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork) + { + track.DataOffset = offset24bit; + } + break; + } + case 0x95: // Call + { + int offset24bit = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8) | (_sseq.Data[track.DataOffset++] << 16); + if (track.DoCommandWork && track.CallStackDepth < 3) + { + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackLoops[track.CallStackDepth] = byte.MaxValue; // This is only necessary for SetTicks() to deal with LoopStart (0) + track.CallStackDepth++; + track.DataOffset = offset24bit; + } + break; + } + } + break; + } + case 0xA0: + { + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xA0: // Rand Mod + { + track.ArgOverrideType = ArgType.Rand; + resetOverride = false; + break; + } + case 0xA1: // Var Mod + { + track.ArgOverrideType = ArgType.PlayerVar; + resetOverride = false; + break; + } + case 0xA2: // If Mod + { + track.DoCommandWork = track.VariableFlag; + resetCmdWork = false; + break; + } + } + } + break; + } + case 0xB0: + { + byte varIndex = _sseq.Data[track.DataOffset++]; + short mathArg = (short)ReadArg(ArgType.Short); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xB0: // VarSet + { + _vars[varIndex] = mathArg; + break; + } + case 0xB1: // VarAdd + { + _vars[varIndex] += mathArg; + break; + } + case 0xB2: // VarSub + { + _vars[varIndex] -= mathArg; + break; + } + case 0xB3: // VarMul + { + _vars[varIndex] *= mathArg; + break; + } + case 0xB4: // VarDiv + { + if (mathArg != 0) + { + _vars[varIndex] /= mathArg; + } + break; + } + case 0xB5: // VarShift + { + _vars[varIndex] = mathArg < 0 ? (short)(_vars[varIndex] >> -mathArg) : (short)(_vars[varIndex] << mathArg); + break; + } + case 0xB6: // VarRand + { + bool negate = false; + if (mathArg < 0) + { + negate = true; + mathArg = (short)-mathArg; + } + short val = (short)_rand.Next(mathArg + 1); + if (negate) + { + val = (short)-val; + } + _vars[varIndex] = val; + break; + } + case 0xB8: // VarCmpEE + { + track.VariableFlag = _vars[varIndex] == mathArg; + break; + } + case 0xB9: // VarCmpGE + { + track.VariableFlag = _vars[varIndex] >= mathArg; + break; + } + case 0xBA: // VarCmpGG + { + track.VariableFlag = _vars[varIndex] > mathArg; + break; + } + case 0xBB: // VarCmpLE + { + track.VariableFlag = _vars[varIndex] <= mathArg; + break; + } + case 0xBC: // VarCmpLL + { + track.VariableFlag = _vars[varIndex] < mathArg; + break; + } + case 0xBD: // VarCmpNE + { + track.VariableFlag = _vars[varIndex] != mathArg; + break; + } + } + } + break; + } + case 0xC0: + case 0xD0: + { + int cmdArg = ReadArg(ArgType.Byte); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xC0: // Panpot + { + track.Panpot = (sbyte)(cmdArg - 0x40); + break; + } + case 0xC1: // Track Volume + { + track.Volume = (byte)cmdArg; + break; + } + case 0xC2: // Player Volume + { + Volume = (byte)cmdArg; + break; + } + case 0xC3: // Transpose + { + track.Transpose = (sbyte)cmdArg; + break; + } + case 0xC4: // Pitch Bend + { + track.PitchBend = (sbyte)cmdArg; + break; + } + case 0xC5: // Pitch Bend Range + { + track.PitchBendRange = (byte)cmdArg; + break; + } + case 0xC6: // Priority + { + track.Priority = (byte)(Priority + (byte)cmdArg); + break; + } + case 0xC7: // Mono + { + track.Mono = cmdArg == 1; + break; + } + case 0xC8: // Tie + { + track.Tie = cmdArg == 1; + track.StopAllChannels(); + break; + } + case 0xC9: // Portamento Control + { + int k = cmdArg + track.Transpose; + if (k < 0) + { + k = 0; + } + else if (k > 0x7F) + { + k = 0x7F; + } + track.PortamentoKey = (byte)k; + track.Portamento = true; + break; + } + case 0xCA: // LFO Depth + { + track.LFODepth = (byte)cmdArg; + break; + } + case 0xCB: // LFO Speed + { + track.LFOSpeed = (byte)cmdArg; + break; + } + case 0xCC: // LFO Type + { + track.LFOType = (LFOType)cmdArg; + break; + } + case 0xCD: // LFO Range + { + track.LFORange = (byte)cmdArg; + break; + } + case 0xCE: // Portamento Toggle + { + track.Portamento = cmdArg == 1; + break; + } + case 0xCF: // Portamento Time + { + track.PortamentoTime = (byte)cmdArg; + break; + } + case 0xD0: // Forced Attack + { + track.Attack = (byte)cmdArg; + break; + } + case 0xD1: // Forced Decay + { + track.Decay = (byte)cmdArg; + break; + } + case 0xD2: // Forced Sustain + { + track.Sustain = (byte)cmdArg; + break; + } + case 0xD3: // Forced Release + { + track.Release = (byte)cmdArg; + break; + } + case 0xD4: // Loop Start + { + if (track.CallStackDepth < 3) + { + track.CallStack[track.CallStackDepth] = track.DataOffset; + track.CallStackLoops[track.CallStackDepth] = (byte)cmdArg; + track.CallStackDepth++; + } + break; + } + case 0xD5: // Track Expression + { + track.Expression = (byte)cmdArg; + break; + } + } + } + break; + } + case 0xE0: + { + int cmdArg = ReadArg(ArgType.Short); + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xE0: // LFO Delay + { + track.LFODelay = (ushort)cmdArg; + break; + } + case 0xE1: // Tempo + { + _tempo = (ushort)cmdArg; + break; + } + case 0xE3: // Sweep Pitch + { + track.SweepPitch = (short)cmdArg; + break; + } + } + } + break; + } + case 0xF0: + { + if (track.DoCommandWork) + { + switch (cmd) + { + case 0xFC: // Loop End + { + if (track.CallStackDepth != 0) + { + byte count = track.CallStackLoops[track.CallStackDepth - 1]; + if (count != 0) + { + count--; + track.CallStackLoops[track.CallStackDepth - 1] = count; + if (count == 0) + { + track.CallStackDepth--; + break; + } + } + track.DataOffset = track.CallStack[track.CallStackDepth - 1]; + } + break; + } + case 0xFD: // Return + { + if (track.CallStackDepth != 0) + { + track.CallStackDepth--; + track.DataOffset = track.CallStack[track.CallStackDepth]; + track.CallStackLoops[track.CallStackDepth] = 0; // This is only necessary for SetTicks() to deal with LoopStart (0) + } + break; + } + case 0xFE: // Alloc Tracks + { + // Must be in the beginning of the first track to work + if (track.Index == 0 && track.DataOffset == 1) // == 1 because we read cmd already + { + // Track 1 enabled = bit 1 set, Track 4 enabled = bit 4 set, etc + int trackBits = _sseq.Data[track.DataOffset++] | (_sseq.Data[track.DataOffset++] << 8); + for (int i = 0; i < 0x10; i++) + { + if ((trackBits & (1 << i)) != 0) + { + _tracks[i].Allocated = true; + } + } + } + break; + } + case 0xFF: // Finish + { + track.Stopped = true; + break; + } + } + } + break; + } } } - if (ShouldFadeOut && _elapsedLoops > NumLoops && !SMixer.IsFading()) + if (resetOverride) + { + track.ArgOverrideType = ArgType.None; + } + if (resetCmdWork) + { + track.DoCommandWork = true; + } + } + + private void Tick() + { + _time.Start(); + while (true) { - SMixer.BeginFadeOut(); + PlayerState state = State; + bool playing = state == PlayerState.Playing; + bool recording = state == PlayerState.Recording; + if (!playing && !recording) + { + break; + } + + void MixerProcess() + { + for (int i = 0; i < 0x10; i++) + { + Track track = _tracks[i]; + if (track.Enabled) + { + track.UpdateChannels(); + } + } + _mixer.ChannelTick(); + _mixer.Process(playing, recording); + } + + while (_tempoStack >= 240) + { + _tempoStack -= 240; + bool allDone = true; + for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) + { + Track track = _tracks[trackIndex]; + if (!track.Enabled) + { + continue; + } + track.Tick(); + while (track.Rest == 0 && !track.WaitingForNoteToFinishBeforeContinuingXD && !track.Stopped) + { + ExecuteNext(track); + } + if (trackIndex == _longestTrack) + { + if (ElapsedTicks == MaxTicks) + { + if (!track.Stopped) + { + List evs = Events[trackIndex]; + for (int i = 0; i < evs.Count; i++) + { + SongEvent ev = evs[i]; + if (ev.Offset == track.DataOffset) + { + //ElapsedTicks = ev.Ticks[0] - track.Rest; + ElapsedTicks = ev.Ticks.Count == 0 ? 0 : ev.Ticks[0] - track.Rest; // Prevent crashes with songs that don't load all ticks yet (See SetTicks()) + break; + } + } + _elapsedLoops++; + if (ShouldFadeOut && !_mixer.IsFading() && _elapsedLoops > NumLoops) + { + _mixer.BeginFadeOut(); + } + } + } + else + { + ElapsedTicks++; + } + } + if (!track.Stopped || track.Channels.Count != 0) + { + allDone = false; + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; + } + if (allDone) + { + // TODO: lock state + MixerProcess(); + _time.Stop(); + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return; + } + } + _tempoStack += _tempo; + MixerProcess(); + if (playing) + { + _time.Wait(); + } } + _time.Stop(); } } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs b/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs deleted file mode 100644 index 87be5b5..0000000 --- a/VG Music Studio - Core/NDS/SDAT/SDATTrack.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System.Collections.Generic; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SDATTrack -{ - public readonly byte Index; - private readonly SDATPlayer _player; - - public bool Allocated; - public bool Enabled; - public bool Stopped; - public bool Tie; - public bool Mono; - public bool Portamento; - public bool WaitingForNoteToFinishBeforeContinuingXD; // TODO: Is this necessary? - public byte Voice; - public byte Priority; - public byte Volume; - public byte Expression; - public byte PitchBendRange; - public byte LFORange; - public byte LFOSpeed; - public byte LFODepth; - public ushort LFODelay; - public ushort LFOPhase; - public int LFOParam; - public ushort LFODelayCount; - public LFOType LFOType; - public sbyte PitchBend; - public sbyte Panpot; - public sbyte Transpose; - public byte Attack; - public byte Decay; - public byte Sustain; - public byte Release; - public byte PortamentoNote; - public byte PortamentoTime; - public short SweepPitch; - public int Rest; - public readonly int[] CallStack; - public readonly byte[] CallStackLoops; - public byte CallStackDepth; - public int DataOffset; - public bool VariableFlag; // Set by variable commands (0xB0 - 0xBD) - public bool DoCommandWork; - public ArgType ArgOverrideType; - - public readonly List Channels = new(0x10); - - public SDATTrack(byte i, SDATPlayer player) - { - Index = i; - _player = player; - - CallStack = new int[3]; - CallStackLoops = new byte[3]; - } - public void Init() - { - Stopped = Tie = WaitingForNoteToFinishBeforeContinuingXD = Portamento = false; - Allocated = Enabled = Index == 0; - DataOffset = 0; - ArgOverrideType = ArgType.None; - Mono = VariableFlag = DoCommandWork = true; - CallStackDepth = 0; - Voice = LFODepth = 0; - PitchBend = Panpot = Transpose = 0; - LFOPhase = LFODelay = LFODelayCount = 0; - LFORange = 1; - LFOSpeed = 0x10; - Priority = (byte)(_player.Priority + 0x40); - Volume = Expression = 0x7F; - Attack = Decay = Sustain = Release = 0xFF; - PitchBendRange = 2; - PortamentoNote = 60; - PortamentoTime = 0; - SweepPitch = 0; - LFOType = LFOType.Pitch; - Rest = 0; - StopAllChannels(); - } - public void LFOTick() - { - if (Channels.Count == 0) - { - LFOPhase = 0; - LFOParam = 0; - LFODelayCount = LFODelay; - } - else - { - if (LFODelayCount > 0) - { - LFODelayCount--; - LFOPhase = 0; - } - else - { - int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; - if (LFOType == LFOType.Volume) - { - param = (int)(((long)param * 60) >> 14); - } - else - { - param >>= 8; - } - LFOParam = param; - int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" - while (counter >= 0x8000) - { - counter -= 0x8000; - } - LFOPhase = (ushort)counter; - } - } - } - public void Tick() - { - if (Rest > 0) - { - Rest--; - } - if (Channels.Count != 0) - { - // TickNotes: - for (int i = 0; i < Channels.Count; i++) - { - SDATChannel c = Channels[i]; - if (c.NoteDuration > 0) - { - c.NoteDuration--; - } - if (!c.AutoSweep && c.SweepCounter < c.SweepLength) - { - c.SweepCounter++; - } - } - } - else - { - WaitingForNoteToFinishBeforeContinuingXD = false; - } - } - public void UpdateChannels() - { - for (int i = 0; i < Channels.Count; i++) - { - SDATChannel c = Channels[i]; - c.LFOType = LFOType; - c.LFOSpeed = LFOSpeed; - c.LFODepth = LFODepth; - c.LFORange = LFORange; - c.LFODelay = LFODelay; - } - } - - public void StopAllChannels() - { - SDATChannel[] chans = Channels.ToArray(); - for (int i = 0; i < chans.Length; i++) - { - chans[i].Stop(); - } - } - - public int GetPitch() - { - //int lfo = LFOType == LFOType.Pitch ? LFOParam : 0; - int lfo = 0; - return (PitchBend * PitchBendRange / 2) + lfo; - } - public int GetVolume() - { - //int lfo = LFOType == LFOType.Volume ? LFOParam : 0; - int lfo = 0; - return SDATUtils.SustainTable[_player.Volume] + SDATUtils.SustainTable[Volume] + SDATUtils.SustainTable[Expression] + lfo; - } - public sbyte GetPan() - { - //int lfo = LFOType == LFOType.Panpot ? LFOParam : 0; - int lfo = 0; - int p = Panpot + lfo; - if (p < -0x40) - { - p = -0x40; - } - else if (p > 0x3F) - { - p = 0x3F; - } - return (sbyte)p; - } - - public void UpdateSongState(SongState.Track tin, SDATLoadedSong loadedSong, string?[] voiceTypeCache) - { - tin.Position = DataOffset; - tin.Rest = Rest; - tin.Voice = Voice; - tin.LFO = LFODepth * LFORange; - ref string? cache = ref voiceTypeCache[Voice]; - if (cache is null) - { - loadedSong.UpdateInstrumentCache(Voice, out cache); - } - tin.Type = cache; - tin.Volume = Volume; - tin.PitchBend = GetPitch(); - tin.Extra = Portamento ? PortamentoTime : (byte)0; - tin.Panpot = GetPan(); - - SDATChannel[] channels = Channels.ToArray(); - if (channels.Length == 0) - { - tin.Keys[0] = byte.MaxValue; - tin.LeftVolume = 0f; - tin.RightVolume = 0f; - } - else - { - int numKeys = 0; - float left = 0f; - float right = 0f; - for (int j = 0; j < channels.Length; j++) - { - SDATChannel c = channels[j]; - if (c.State != EnvelopeState.Release) - { - tin.Keys[numKeys++] = c.Note; - } - float a = (float)(-c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > left) - { - left = a; - } - a = (float)(c.Pan + 0x40) / 0x80 * c.Volume / 0x7F; - if (a > right) - { - right = a; - } - } - tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array - tin.LeftVolume = left; - tin.RightVolume = right; - } - } -} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATUtils.cs b/VG Music Studio - Core/NDS/SDAT/SDATUtils.cs index e86d328..675d657 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATUtils.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATUtils.cs @@ -1,10 +1,8 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; internal static class SDATUtils { - public static ReadOnlySpan AttackTable => new byte[128] + public static readonly byte[] AttackTable = new byte[128] { 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, @@ -23,7 +21,7 @@ internal static class SDATUtils 127, 123, 116, 109, 100, 92, 84, 73, 63, 51, 38, 26, 14, 5, 1, 0, }; - public static ReadOnlySpan DecayTable => new ushort[128] + public static readonly ushort[] DecayTable = new ushort[128] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, @@ -42,7 +40,7 @@ internal static class SDATUtils 549, 591, 640, 698, 768, 853, 960, 1097, 1280, 1536, 1920, 2560, 3840, 7680, 15360, 65535, }; - public static ReadOnlySpan SustainTable => new int[128] + public static readonly int[] SustainTable = new int[128] { -92544, -92416, -92288, -83328, -76928, -71936, -67840, -64384, -61440, -58880, -56576, -54400, -52480, -50688, -49024, -47488, @@ -62,7 +60,7 @@ internal static class SDATUtils -1280, -1024, -896, -768, -512, -384, -128, 0, }; - private static ReadOnlySpan SinTable => new sbyte[33] + private static readonly sbyte[] _sinTable = new sbyte[33] { 000, 006, 012, 019, 025, 031, 037, 043, 049, 054, 060, 065, 071, 076, 081, 085, @@ -74,21 +72,21 @@ public static int Sin(int index) { if (index < 0x20) { - return SinTable[index]; + return _sinTable[index]; } if (index < 0x40) { - return SinTable[0x20 - (index - 0x20)]; + return _sinTable[0x20 - (index - 0x20)]; } if (index < 0x60) { - return -SinTable[index - 0x40]; + return -_sinTable[index - 0x40]; } // < 0x80 - return -SinTable[0x20 - (index - 0x60)]; + return -_sinTable[0x20 - (index - 0x60)]; } - private static ReadOnlySpan PitchTable => new ushort[768] + private static readonly ushort[] _pitchTable = new ushort[768] { 0, 59, 118, 178, 237, 296, 356, 415, 475, 535, 594, 654, 714, 773, 833, 893, @@ -187,7 +185,7 @@ public static int Sin(int index) 63657, 63774, 63890, 64007, 64124, 64241, 64358, 64476, 64593, 64711, 64828, 64946, 65064, 65182, 65300, 65418, }; - private static ReadOnlySpan VolumeTable => new byte[724] + private static readonly byte[] _volumeTable = new byte[724] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -299,7 +297,7 @@ public static ushort GetChannelTimer(ushort baseTimer, int pitch) pitch -= 0x300; } - ulong timer = (PitchTable[pitch] + 0x10000uL) * baseTimer; + ulong timer = (_pitchTable[pitch] + 0x10000uL) * baseTimer; shift -= 16; if (shift <= 0) { @@ -339,6 +337,6 @@ public static byte GetChannelVolume(int vol) { a = 0; } - return VolumeTable[a + 723]; + return _volumeTable[a + 723]; } } diff --git a/VG Music Studio - Core/NDS/SDAT/SSEQ.cs b/VG Music Studio - Core/NDS/SDAT/SSEQ.cs index 22068c7..ec3859c 100644 --- a/VG Music Studio - Core/NDS/SDAT/SSEQ.cs +++ b/VG Music Studio - Core/NDS/SDAT/SSEQ.cs @@ -1,30 +1,31 @@ using Kermalis.EndianBinaryIO; using System.IO; -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SSEQ +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT { - public SDATFileHeader FileHeader; // "SSEQ" - public string BlockType; // "DATA" - public int BlockSize; - public int DataOffset; + internal sealed class SSEQ + { + public FileHeader FileHeader; // "SSEQ" + public string BlockType; // "DATA" + public int BlockSize; + public int DataOffset; - public byte[] Data; + public byte[] Data; - public SSEQ(byte[] bytes) - { - using (var stream = new MemoryStream(bytes)) + public SSEQ(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - BlockType = er.ReadString_Count(4); - BlockSize = er.ReadInt32(); - DataOffset = er.ReadInt32(); + using (var stream = new MemoryStream(bytes)) + { + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + BlockType = er.ReadString_Count(4); + BlockSize = er.ReadInt32(); + DataOffset = er.ReadInt32(); - Data = new byte[FileHeader.FileSize - DataOffset]; - stream.Position = DataOffset; - er.ReadBytes(Data); + Data = new byte[FileHeader.FileSize - DataOffset]; + stream.Position = DataOffset; + er.ReadBytes(Data); + } } } } diff --git a/VG Music Studio - Core/NDS/SDAT/SWAR.cs b/VG Music Studio - Core/NDS/SDAT/SWAR.cs index 5a5e64d..2af20c3 100644 --- a/VG Music Studio - Core/NDS/SDAT/SWAR.cs +++ b/VG Music Studio - Core/NDS/SDAT/SWAR.cs @@ -1,64 +1,64 @@ using Kermalis.EndianBinaryIO; using System.IO; -namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; - -internal sealed class SWAR +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT { - public sealed class SWAV + internal sealed class SWAR { - public SWAVFormat Format; - public bool DoesLoop; - public ushort SampleRate; - /// / - public ushort Timer; - public ushort LoopOffset; - public int Length; + public sealed class SWAV + { + public SWAVFormat Format; + public bool DoesLoop; + public ushort SampleRate; + public ushort Timer; // (NDSUtils.ARM7_CLOCK / SampleRate) + public ushort LoopOffset; + public int Length; - public byte[] Samples; + public byte[] Samples; - public SWAV(EndianBinaryReader er) - { - Format = er.ReadEnum(); - DoesLoop = er.ReadBoolean(); - SampleRate = er.ReadUInt16(); - Timer = er.ReadUInt16(); - LoopOffset = er.ReadUInt16(); - Length = er.ReadInt32(); + public SWAV(EndianBinaryReader er) + { + Format = er.ReadEnum(); + DoesLoop = er.ReadBoolean(); + SampleRate = er.ReadUInt16(); + Timer = er.ReadUInt16(); + LoopOffset = er.ReadUInt16(); + Length = er.ReadInt32(); - Samples = new byte[(LoopOffset * 4) + (Length * 4)]; - er.ReadBytes(Samples); + Samples = new byte[(LoopOffset * 4) + (Length * 4)]; + er.ReadBytes(Samples); + } } - } - public SDATFileHeader FileHeader; // "SWAR" - public string BlockType; // "DATA" - public int BlockSize; - public byte[] Padding; - public int NumWaves; - public int[] WaveOffsets; + public FileHeader FileHeader; // "SWAR" + public string BlockType; // "DATA" + public int BlockSize; + public byte[] Padding; + public int NumWaves; + public int[] WaveOffsets; - public SWAV[] Waves; + public SWAV[] Waves; - public SWAR(byte[] bytes) - { - using (var stream = new MemoryStream(bytes)) + public SWAR(byte[] bytes) { - var er = new EndianBinaryReader(stream, ascii: true); - FileHeader = new SDATFileHeader(er); - BlockType = er.ReadString_Count(4); - BlockSize = er.ReadInt32(); - Padding = new byte[32]; - er.ReadBytes(Padding); - NumWaves = er.ReadInt32(); - WaveOffsets = new int[NumWaves]; - er.ReadInt32s(WaveOffsets); - - Waves = new SWAV[NumWaves]; - for (int i = 0; i < NumWaves; i++) + using (var stream = new MemoryStream(bytes)) { - stream.Position = WaveOffsets[i]; - Waves[i] = new SWAV(er); + var er = new EndianBinaryReader(stream, ascii: true); + FileHeader = new FileHeader(er); + BlockType = er.ReadString_Count(4); + BlockSize = er.ReadInt32(); + Padding = new byte[32]; + er.ReadBytes(Padding); + NumWaves = er.ReadInt32(); + WaveOffsets = new int[NumWaves]; + er.ReadInt32s(WaveOffsets); + + Waves = new SWAV[NumWaves]; + for (int i = 0; i < NumWaves; i++) + { + stream.Position = WaveOffsets[i]; + Waves[i] = new SWAV(er); + } } } } diff --git a/VG Music Studio - Core/NDS/SDAT/Track.cs b/VG Music Studio - Core/NDS/SDAT/Track.cs new file mode 100644 index 0000000..43a1435 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/Track.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; + +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT +{ + internal sealed class Track + { + public readonly byte Index; + private readonly SDATPlayer _player; + + public bool Allocated; + public bool Enabled; + public bool Stopped; + public bool Tie; + public bool Mono; + public bool Portamento; + public bool WaitingForNoteToFinishBeforeContinuingXD; // TODO: Is this necessary? + public byte Voice; + public byte Priority; + public byte Volume; + public byte Expression; + public byte PitchBendRange; + public byte LFORange; + public byte LFOSpeed; + public byte LFODepth; + public ushort LFODelay; + public ushort LFOPhase; + public int LFOParam; + public ushort LFODelayCount; + public LFOType LFOType; + public sbyte PitchBend; + public sbyte Panpot; + public sbyte Transpose; + public byte Attack; + public byte Decay; + public byte Sustain; + public byte Release; + public byte PortamentoKey; + public byte PortamentoTime; + public short SweepPitch; + public int Rest; + public readonly int[] CallStack; + public readonly byte[] CallStackLoops; + public byte CallStackDepth; + public int DataOffset; + public bool VariableFlag; // Set by variable commands (0xB0 - 0xBD) + public bool DoCommandWork; + public ArgType ArgOverrideType; + + public readonly List Channels = new(0x10); + + public Track(byte i, SDATPlayer player) + { + Index = i; + _player = player; + + CallStack = new int[3]; + CallStackLoops = new byte[3]; + } + public void Init() + { + Stopped = Tie = WaitingForNoteToFinishBeforeContinuingXD = Portamento = false; + Allocated = Enabled = Index == 0; + DataOffset = 0; + ArgOverrideType = ArgType.None; + Mono = VariableFlag = DoCommandWork = true; + CallStackDepth = 0; + Voice = LFODepth = 0; + PitchBend = Panpot = Transpose = 0; + LFOPhase = LFODelay = LFODelayCount = 0; + LFORange = 1; + LFOSpeed = 0x10; + Priority = (byte)(_player.Priority + 0x40); + Volume = Expression = 0x7F; + Attack = Decay = Sustain = Release = 0xFF; + PitchBendRange = 2; + PortamentoKey = 60; + PortamentoTime = 0; + SweepPitch = 0; + LFOType = LFOType.Pitch; + Rest = 0; + StopAllChannels(); + } + public void LFOTick() + { + if (Channels.Count == 0) + { + LFOPhase = 0; + LFOParam = 0; + LFODelayCount = LFODelay; + } + else + { + if (LFODelayCount > 0) + { + LFODelayCount--; + LFOPhase = 0; + } + else + { + int param = LFORange * SDATUtils.Sin(LFOPhase >> 8) * LFODepth; + if (LFOType == LFOType.Volume) + { + param = (int)(((long)param * 60) >> 14); + } + else + { + param >>= 8; + } + LFOParam = param; + int counter = LFOPhase + (LFOSpeed << 6); // "<< 6" is "* 0x40" + while (counter >= 0x8000) + { + counter -= 0x8000; + } + LFOPhase = (ushort)counter; + } + } + } + public void Tick() + { + if (Rest > 0) + { + Rest--; + } + if (Channels.Count != 0) + { + // TickNotes: + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + if (c.NoteDuration > 0) + { + c.NoteDuration--; + } + if (!c.AutoSweep && c.SweepCounter < c.SweepLength) + { + c.SweepCounter++; + } + } + } + else + { + WaitingForNoteToFinishBeforeContinuingXD = false; + } + } + public void UpdateChannels() + { + for (int i = 0; i < Channels.Count; i++) + { + Channel c = Channels[i]; + c.LFOType = LFOType; + c.LFOSpeed = LFOSpeed; + c.LFODepth = LFODepth; + c.LFORange = LFORange; + c.LFODelay = LFODelay; + } + } + + public void StopAllChannels() + { + Channel[] chans = Channels.ToArray(); + for (int i = 0; i < chans.Length; i++) + { + chans[i].Stop(); + } + } + + public int GetPitch() + { + //int lfo = LFOType == LFOType.Pitch ? LFOParam : 0; + int lfo = 0; + return (PitchBend * PitchBendRange / 2) + lfo; + } + public int GetVolume() + { + //int lfo = LFOType == LFOType.Volume ? LFOParam : 0; + int lfo = 0; + return SDATUtils.SustainTable[_player.Volume] + SDATUtils.SustainTable[Volume] + SDATUtils.SustainTable[Expression] + lfo; + } + public sbyte GetPan() + { + //int lfo = LFOType == LFOType.Panpot ? LFOParam : 0; + int lfo = 0; + int p = Panpot + lfo; + if (p < -0x40) + { + p = -0x40; + } + else if (p > 0x3F) + { + p = 0x3F; + } + return (sbyte)p; + } + } +} diff --git a/VG Music Studio - Core/NDS/Utils.cs b/VG Music Studio - Core/NDS/Utils.cs new file mode 100644 index 0000000..601e832 --- /dev/null +++ b/VG Music Studio - Core/NDS/Utils.cs @@ -0,0 +1,7 @@ +namespace Kermalis.VGMusicStudio.Core.NDS +{ + internal static class Utils + { + public const int ARM7_CLOCK = 16_756_991; // (33.513982 MHz / 2) == 16.756991 MHz == 16,756,991 Hz + } +} diff --git a/VG Music Studio - Core/Player.cs b/VG Music Studio - Core/Player.cs index 33bd9b0..adb8fc8 100644 --- a/VG Music Studio - Core/Player.cs +++ b/VG Music Studio - Core/Player.cs @@ -1,8 +1,5 @@ -using Kermalis.VGMusicStudio.Core.Util; -using System; +using System; using System.Collections.Generic; -using System.IO; -using System.Threading; namespace Kermalis.VGMusicStudio.Core; @@ -17,180 +14,25 @@ public enum PlayerState : byte public interface ILoadedSong { - List?[] Events { get; } + List[] Events { get; } long MaxTicks { get; } + long ElapsedTicks { get; } } -public abstract class Player : IDisposable +public interface IPlayer : IDisposable { - protected abstract string Name { get; } - protected abstract Mixer Mixer { get; } - - public abstract ILoadedSong? LoadedSong { get; } - public bool ShouldFadeOut { get; set; } - public long NumLoops { get; set; } - - public long ElapsedTicks { get; internal set; } - public PlayerState State { get; protected set; } - public event Action? SongEnded; - - private readonly TimeBarrier _time; - private Thread? _thread; - - protected Player(double ticksPerSecond) - { - _time = new TimeBarrier(ticksPerSecond); - } - - public abstract void LoadSong(int index); - public abstract void UpdateSongState(SongState info); - internal abstract void InitEmulation(); - protected abstract void SetCurTick(long ticks); - protected abstract void OnStopped(); - - protected abstract bool Tick(bool playing, bool recording); - - protected void CreateThread() - { - _thread = new Thread(TimerTick) { Name = Name + " Tick" }; - _thread.Start(); - } - protected void WaitThread() - { - if (_thread is not null && (_thread.ThreadState is ThreadState.Running or ThreadState.WaitSleepJoin)) - { - _thread.Join(); - } - } - protected void UpdateElapsedTicksAfterLoop(List evs, long trackEventOffset, long trackRest) - { - for (int i = 0; i < evs.Count; i++) - { - SongEvent ev = evs[i]; - if (ev.Offset == trackEventOffset) - { - ElapsedTicks = ev.Ticks[0] - trackRest; - return; - } - } - throw new InvalidDataException("No loop point found"); - } - - public void Play() - { - if (LoadedSong is null) - { - SongEnded?.Invoke(); - return; - } - - if (State is not PlayerState.ShutDown) - { - Stop(); - InitEmulation(); - State = PlayerState.Playing; - CreateThread(); - } - } - public void TogglePlaying() - { - switch (State) - { - case PlayerState.Playing: - { - State = PlayerState.Paused; - WaitThread(); - break; - } - case PlayerState.Paused: - case PlayerState.Stopped: - { - State = PlayerState.Playing; - CreateThread(); - break; - } - } - } - public void Stop() - { - if (State is PlayerState.Playing or PlayerState.Paused) - { - State = PlayerState.Stopped; - WaitThread(); - OnStopped(); - } - } - public void Record(string fileName) - { - Mixer.CreateWaveWriter(fileName); - - InitEmulation(); - State = PlayerState.Recording; - CreateThread(); - WaitThread(); - - Mixer.CloseWaveWriter(); - } - public void SetSongPosition(long ticks) - { - if (LoadedSong is null) - { - SongEnded?.Invoke(); - return; - } - - if (State is not PlayerState.Playing and not PlayerState.Paused and not PlayerState.Stopped) - { - return; - } - - if (State is PlayerState.Playing) - { - TogglePlaying(); - } - InitEmulation(); - SetCurTick(ticks); - TogglePlaying(); - } - - private void TimerTick() - { - _time.Start(); - while (true) - { - PlayerState state = State; - bool playing = state == PlayerState.Playing; - bool recording = state == PlayerState.Recording; - if (!playing && !recording) - { - break; - } - - bool allDone = Tick(playing, recording); - if (allDone) - { - // TODO: lock state - _time.Stop(); // TODO: Don't need timer if recording - State = PlayerState.Stopped; - SongEnded?.Invoke(); - return; - } - if (playing) - { - _time.Wait(); - } - } - _time.Stop(); - } - - public void Dispose() - { - GC.SuppressFinalize(this); - if (State != PlayerState.ShutDown) - { - State = PlayerState.ShutDown; - WaitThread(); - } - SongEnded = null; - } + ILoadedSong? LoadedSong { get; } + bool ShouldFadeOut { get; set; } + long NumLoops { get; set; } + + PlayerState State { get; } + event Action? SongEnded; + + void LoadSong(long index); + void SetCurrentPosition(long ticks); + void Play(); + void Pause(); + void Stop(); + void Record(string fileName); + void UpdateSongState(SongState info); } diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index eea96fb..5cada93 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -19,7 +19,7 @@ namespace Kermalis.VGMusicStudio.Core.Properties { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Strings { @@ -141,6 +141,15 @@ public static string ErrorBoolParse { } } + /// + /// Looks up a localized string similar to Color {0} has an invalid key.. + /// + public static string ErrorConfigColorInvalidKey { + get { + return ResourceManager.GetString("ErrorConfigColorInvalidKey", resourceCulture); + } + } + /// /// Looks up a localized string similar to Color {0} is not defined.. /// @@ -519,6 +528,15 @@ public static string MenuSaveWAV { } } + /// + /// Looks up a localized string similar to C;C#;D;D#;E;F;F#;G;G#;A;A#;B. + /// + public static string Notes { + get { + return ResourceManager.GetString("Notes", resourceCulture); + } + } + /// /// Looks up a localized string similar to Next Song. /// @@ -636,15 +654,6 @@ public static string PlayPlaylistBody { } } - /// - /// Looks up a localized string similar to songs|0_0|song|1_1|songs|2_*|. - /// - public static string Song_s_ { - get { - return ResourceManager.GetString("Song(s)", resourceCulture); - } - } - /// /// Looks up a localized string similar to VoiceTable saved to {0}.. /// @@ -734,5 +743,82 @@ public static string TrackViewerTrackX { return ResourceManager.GetString("TrackViewerTrackX", resourceCulture); } } + + /// + /// Looks up a localized string similar to GBA Files. + /// + public static string GTKFilterOpenGBA + { + get + { + return ResourceManager.GetString("GTKFilterOpenGBA", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SDAT Files. + /// + public static string GTKFilterOpenSDAT + { + get + { + return ResourceManager.GetString("GTKFilterOpenSDAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DLS Files. + /// + public static string GTKFilterSaveDLS + { + get + { + return ResourceManager.GetString("GTKFilterSaveDLS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MIDI Files. + /// + public static string GTKFilterSaveMIDI + { + get + { + return ResourceManager.GetString("GTKFilterSaveMIDI", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SF2 Files. + /// + public static string GTKFilterSaveSF2 + { + get + { + return ResourceManager.GetString("GTKFilterSaveSF2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKFilterSaveWAV + { + get + { + return ResourceManager.GetString("GTKFilterSaveWAV", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WAV Files. + /// + public static string GTKAllFiles + { + get + { + return ResourceManager.GetString("GTKAllFiles", resourceCulture); + } + } } } diff --git a/VG Music Studio - Core/Properties/Strings.es.resx b/VG Music Studio - Core/Properties/Strings.es.resx index c524dfd..d98bb26 100644 --- a/VG Music Studio - Core/Properties/Strings.es.resx +++ b/VG Music Studio - Core/Properties/Strings.es.resx @@ -118,10 +118,10 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - ¿Quisiera detener la Lista de Repoducción actual? + Quisiera detener la Lista de Reproducción actual? - Error al Cargar la Canción {0} + Error al Cargar Canción {0} Error al Abrir Carpeta DSE @@ -169,11 +169,14 @@ Abrir Archivo SDAT - Lista de Reproducción + Playlist Exportar Canción como MIDI + + Do;Do#;Re;Re#;Mi;Fa;Fa#;Sol;Sol#;La;La#;Si + Siguiente Canción @@ -211,7 +214,7 @@ Música - ¿Quisiera reproducir la siguiente Lista de Reproducción? + Quisiera reproducir la siguiente Lista de Reproducción? {0} MIDI guardado en {0}. @@ -240,6 +243,9 @@ "{0}" debe ser Verdadero o Falso. + + El color {0} tiene una clave inválida. + El color {0} no está definido. @@ -268,7 +274,7 @@ No hay ningún archivo "bgm(NNNN).smd". - Error al Cargar la Configuración Global + Error al Cargar Configuración Global No se puede copiar, el código del juego "{0}" es inválido. @@ -339,7 +345,4 @@ DLS guardado en {0}. - - canciones|0_0|canción|1_1|canciones|2_*| - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.fr.resx b/VG Music Studio - Core/Properties/Strings.fr.resx deleted file mode 100644 index 0befad5..0000000 --- a/VG Music Studio - Core/Properties/Strings.fr.resx +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Echec de chargement du titre {0} - - - Echec du chargement de la ROM GBA (AlphaDream) - - - Echec de l'exportation en MIDI - - - Fichiers GBA - - - Fichiers MIDI - - - Données - - - Fichier - - - Ouvrir ROM GBA (MP2K) - - - Exporter le titre en MIDI - - - Silence - - - Notes - - - Pause - - - Lecture - - - Position - - - Stop - - - Tempo - - - Type - - - Dé-pause - - - MIDI enregistré sous {0}. - - - Voulez-vous lancer la playlist suivante ?{0} - - - Titre suivant - - - Titre précédent - - - Voulez-vous arrêter la lecture de la playlist en cours ? - - - Echec de chargement du dossier DSE - - - Echec de chargement de la ROM GBA (MP2K) - - - Echec de lecture du fichier SDAT - - - Fichiers SDAT - - - Arrêter la playlist en cours - - - Ouvrir dossier DSE - - - Ouvrir ROM GBA (AlphaDream) - - - Ouvrir fichier SDAT - - - Playlist - - - Musique - - - Arguments - - - Event - - - Offset - - - Ticks - - - Visualiseur de pistes - - - Piste {0} - - - Clé {0} - - - "{0}" doit être Vrai ou Faux - - - La couleur {0} n'est pas définie. - - - La couleur {0} est définie plus d'une fois entre le décimal et l'hexadécimal. - - - "{0}" est invalide. - - - "{0}" est manquante. - - - "{0}" doit avoir au moins une entrée. - - - Version d'en-tête inconnue: 0x{0:X} - - - Clé invalide pour la piste {0} à l'adresse 0x{1:X}: {2} - - - Commande invalide pour la piste {0} à l'adresse 0x{1:X}: 0x{2:X} - - - Il n'y a pas de fichiers "bgm(NNNN).smd". - - - Echec du chargement de la configuration globale. - - - Impossible de copier le code de jeu invalide "{0}" - - - Le code de jeu "{0}" est manquant. - - - Erreur au parsage du code de jeu "{0}" dans "{1}"{2} - - - Le titre {1} de la playlist "{0}" est défini plus d'une fois entre le décimal et l'hexadécimal. - - - Le compte de "{0}" doit être identique au compte de "{1}". - - - Commande de statut de lecture invalide sur la piste {0} à l'adresse 0x{1:X}: 0x{2:X} - - - Trop d'events d'appel imbriqués sur la piste {0} - - - Echec du parsage de "{0}"{1} - - - Cet archive SDAT n'a pas de séquences. - - - "{0}" n'est pas un entier. - - - "{0}" doit être entre {1} et {2}. - - - Echec de l'exportation en WAV - - - Fichiers WAV - - - Exporter le titre en WAV - - - WAV sauvegardé sous {0}. - - - Echec de l'exportation en SF2 - - - Fichiers SF2 - - - Exporter la VoiceTable en SF2 - - - VoiceTable sauvegardée sous {0}. - - - Echec de l'exportation en DLS - - - Fichiers DLS - - - Exporter la VoiceTable en DLS - - - VoiceTable sauvegardée sous {0}. - - - titres|0_0|titre|1_1|titres|2_*| - - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.it.resx b/VG Music Studio - Core/Properties/Strings.it.resx index 6da605e..935f17e 100644 --- a/VG Music Studio - Core/Properties/Strings.it.resx +++ b/VG Music Studio - Core/Properties/Strings.it.resx @@ -144,6 +144,9 @@ Esporta Brano in MIDI + + Do;Do#;Re;Re#;Mi;Fa;Fa#;Sol;Sol#;La;La#;Si + Pausa @@ -240,6 +243,9 @@ "{0}" deve essere Vero o Falso. + + Il colore {0} non ha una chiave valida. + Il colore {0} non è definito. @@ -339,7 +345,4 @@ VoiceTable salvata in {0}. - - canzoni|0_0|canzone|1_1|canzoni|2_*| - \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 916279d..c88d68c 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,16 +128,16 @@ Error Exporting MIDI - GBA Files + Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.* - MIDI Files + MIDI Files (*.mid, *.midi)|*.mid;*.midi - Data + _Data - File + _File Open GBA ROM (MP2K) @@ -145,6 +145,9 @@ Export Song as MIDI + + C;C#;D;D#;E;F;F#;G;G#;A;A#;B + Rest @@ -199,7 +202,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.* End Current Playlist @@ -246,6 +249,10 @@ "{0}" must be True or False. {0} is the value name. + + Color {0} has an invalid key. + {0} is the color number. + Color {0} is not defined. {0} is the color number. @@ -331,7 +338,7 @@ Error Exporting WAV - WAV Files + WAV Files (*.wav)|*.wav Export Song as WAV @@ -344,7 +351,7 @@ Error Exporting SF2 - SF2 Files + SF2 Files (*.sf2)|*.sf2 Export VoiceTable as SF2 @@ -357,7 +364,7 @@ Error Exporting DLS - DLS Files + DLS Files (*.dls)|*.dls Export VoiceTable as DLS @@ -366,7 +373,25 @@ VoiceTable saved to {0}. {0} is the file name. - - songs|0_0|song|1_1|songs|2_*| + + Game Boy Advance binary (*.gba, *.srl) + + + Nitro Soundmaker Sound Data (*.sdat) + + + DLS Soundfont Files (*.dls) + + + MIDI Sequence Files (*.mid, *.midi) + + + SF2 Soundfont Files (*.sf2) + + + Wave Audio Data (*.wav) + + + All files (*.*) \ No newline at end of file diff --git a/VG Music Studio - Core/Properties/Strings.ru.resx b/VG Music Studio - Core/Properties/Strings.ru.resx deleted file mode 100644 index b35e074..0000000 --- a/VG Music Studio - Core/Properties/Strings.ru.resx +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Ошибка во время загрузки мелодии {0} - - - Ошибка во время загрузки GBA-ROMа (AlphaDream) - - - Ошибка во время экспорта MIDI - - - GBA-файлы - - - MIDI-файлы - - - Данные - - - Файл - - - Открыть GBA-ROM (MP2K) - - - Экспортировать мелодию в формате MIDI - - - Длительность - - - Ноты - - - Пауза - - - Проиграть - - - Адрес - - - Остановить - - - Темп - - - Тип - - - Продолжить - - - Мелодия успешно сохранена в MIDI-файл "{0}". - - - Хотите прослушать данный плейлист?{0} - - - Следующая мелодия - - - Предыдущая мелодия - - - Хотите прервать воспроизведение плейлиста? - - - При открытии DSE-папки произошла ошибка - - - При открытии GBA-ROMа (MP2K) произошла ошибка - - - При открытии SDAT-файла произошла ошибка - - - SDAT-файлы - - - Отключить плейлист - - - Открыть DSE-папку - - - Открыть GBA-ROM (AlphaDream) - - - Открыть SDAT-файл - - - Плейлист - - - Музыка - - - Аргументы - - - Событие - - - Адрес - - - Такты - - - Просмотр трека - - - Трек {0} - - - Родительский ключ {0} - - - "{0}" должно принимать значения True или False. - - - Цвет {0} не указан. - - - Цвет {0} указан несколько раз среди десятичных и шестнадцатеричных значений. - - - Родительский ключ "{0}" недопустим. - - - Родительский ключ "{0}" отсутствует. - - - Родительский ключ "{0}" должен содержать хотя бы одно значение. - - - Неизвестная версия заголовка: 0x{0:X} - - - Недопустимый родительский ключ в треке {0} по адресу 0x{1:X}: {2} - - - Недопустимая команда в треке {0} по адресу 0x{1:X}: 0x{2:X} - - - Файлы типа "bgm(NNNN).smd" отсутствуют. - - - Ошибка загрузки глобальной конфигурвции - - - Невозможно скопировать недопустимый игровой код "{0}" - - - Игровой код "{0}" отсутствует. - - - Ошибка во время анализа игрового кода "{0}" в файле "{1}"{2} - - - В плейлисте "{0}" содержится мелодия {1}, которая указана несколько раз среди десятичных и шестнадцатеричных значений. - - - Значения родительских ключей "{0}" и "{1}" должны совпадать. - - - Недопустимая команда состояния в треке {0} по адресу 0x{1:X}: 0x{2:X} - - - Слишком много случаев вызовов вложенных функций в треке {0} - - - Ошибка анализа файла "{0}"{1} - - - В указанном SDAT-архиве отсутствуют секвенции. - - - Значение "{0}" должно содержать целое число. - - - Значение "{0}" должно находиться в диапазоне от "{1}" до "{2}". - - - При экспорте WAV-файла произошла ошибка - - - WAV-файлы - - - Экспортировать мелодию в формате WAV - - - Мелодия успешно сохранена в WAV-файл "{0}". - - - При экспорте SF2-файла произошла ошибка - - - SF2-файлы - - - Экспортировать таблицу семплов в формате SF2 - - - Таблица семплов успешно сохранена в файл "{0}". - - - При экспорте DLS-файла произошла ошибка - - - DLS-файлы - - - Экспортировать таблицу семплов в формате DLS - - - Таблица семплов успешно сохранена в файл "{0}". - - - мелодий|0_0|мелодия|1_1|мелодии|2_4|мелодий|5_*| - - \ No newline at end of file diff --git a/VG Music Studio - Core/SongState.cs b/VG Music Studio - Core/SongState.cs index 02d5e92..8987c14 100644 --- a/VG Music Studio - Core/SongState.cs +++ b/VG Music Studio - Core/SongState.cs @@ -1,73 +1,71 @@ -namespace Kermalis.VGMusicStudio.Core; - -public sealed class SongState +namespace Kermalis.VGMusicStudio.Core { - public sealed class Track + public sealed class SongState { - public long Position; - public byte Voice; - public byte Volume; - public int LFO; - public long Rest; - public sbyte Panpot; - public float LeftVolume; - public float RightVolume; - public int PitchBend; - public byte Extra; - public string Type; - public byte[] Keys; + public sealed class Track + { + public long Position; + public byte Voice; + public byte Volume; + public int LFO; + public long Rest; + public sbyte Panpot; + public float LeftVolume; + public float RightVolume; + public int PitchBend; + public byte Extra; + public string Type; + public byte[] Keys; - public int PreviousKeysTime; // TODO: Fix - public string PreviousKeys; + public int PreviousKeysTime; // TODO: Fix + public string PreviousKeys; - public Track() - { - Keys = new byte[MAX_KEYS]; - for (int i = 0; i < MAX_KEYS; i++) + public Track() { - Keys[i] = byte.MaxValue; + Keys = new byte[MAX_KEYS]; + for (int i = 0; i < MAX_KEYS; i++) + { + Keys[i] = byte.MaxValue; + } } - Type = null!; - PreviousKeys = null!; - } - - public void Reset() - { - Position = Rest = 0; - Voice = Volume = Extra = 0; - LFO = PitchBend = PreviousKeysTime = 0; - Panpot = 0; - LeftVolume = RightVolume = 0f; - Type = PreviousKeys = null!; - for (int i = 0; i < MAX_KEYS; i++) + public void Reset() { - Keys[i] = byte.MaxValue; + Position = Rest = 0; + Voice = Volume = Extra = 0; + LFO = PitchBend = PreviousKeysTime = 0; + Panpot = 0; + LeftVolume = RightVolume = 0f; + Type = PreviousKeys = null; + for (int i = 0; i < MAX_KEYS; i++) + { + Keys[i] = byte.MaxValue; + } } } - } - public const int MAX_KEYS = 32 + 1; // DSE is currently set to use 32 channels - public const int MAX_TRACKS = 18; // PMD2 has a few songs with 18 tracks + public const int MAX_KEYS = 32 + 1; // DSE is currently set to use 32 channels + public const int MAX_TRACKS = 18; // PMD2 has a few songs with 18 tracks - public ushort Tempo; - public readonly Track[] Tracks; + public ushort Tempo; + public Track[] Tracks; - public SongState() - { - Tracks = new Track[MAX_TRACKS]; - for (int i = 0; i < MAX_TRACKS; i++) + public SongState() { - Tracks[i] = new Track(); + Tracks = new Track[MAX_TRACKS]; + for (int i = 0; i < MAX_TRACKS; i++) + { + Tracks[i] = new Track(); + } } - } - public void Reset() - { - Tempo = 0; - for (int i = 0; i < MAX_TRACKS; i++) + public void Reset() { - Tracks[i].Reset(); + Tempo = 0; + for (int i = 0; i < MAX_TRACKS; i++) + { + Tracks[i].Reset(); + } } } } diff --git a/VG Music Studio - Core/Util/ConfigUtils.cs b/VG Music Studio - Core/Util/ConfigUtils.cs index 5238c51..ff25770 100644 --- a/VG Music Studio - Core/Util/ConfigUtils.cs +++ b/VG Music Studio - Core/Util/ConfigUtils.cs @@ -10,9 +10,7 @@ namespace Kermalis.VGMusicStudio.Core.Util; public static class ConfigUtils { public const string PROGRAM_NAME = "VG Music Studio"; - private static ReadOnlySpan Notes => new string[12] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; - private static readonly CultureInfo _enUS = new("en-US"); - private static readonly Dictionary _keyCache = new(128); + private static readonly string[] _notes = Strings.Notes.Split(';'); public static bool TryParseValue(string value, long minValue, long maxValue, out long outValue) { @@ -35,7 +33,8 @@ string GetMessage() return string.Format(Strings.ErrorValueParseRanged, valueName, minValue, maxValue); } - if (value.StartsWith("0x") && long.TryParse(value.AsSpan(2), NumberStyles.HexNumber, _enUS, out long hexp)) + var provider = new CultureInfo("en-US"); + if (value.StartsWith("0x") && long.TryParse(value.AsSpan(2), NumberStyles.HexNumber, provider, out long hexp)) { if (hexp < minValue || hexp > maxValue) { @@ -43,7 +42,7 @@ string GetMessage() } return hexp; } - else if (long.TryParse(value, NumberStyles.Integer, _enUS, out long dec)) + else if (long.TryParse(value, NumberStyles.Integer, provider, out long dec)) { if (dec < minValue || dec > maxValue) { @@ -51,7 +50,7 @@ string GetMessage() } return dec; } - else if (long.TryParse(value, NumberStyles.HexNumber, _enUS, out long hex)) + else if (long.TryParse(value, NumberStyles.HexNumber, provider, out long hex)) { if (hex < minValue || hex > maxValue) { @@ -71,8 +70,7 @@ public static bool ParseBoolean(string valueName, string value) return result; } /// - public static TEnum ParseEnum(string valueName, string value) - where TEnum : unmanaged + public static TEnum ParseEnum(string valueName, string value) where TEnum : unmanaged { if (!Enum.TryParse(value, out TEnum result)) { @@ -82,7 +80,6 @@ public static TEnum ParseEnum(string valueName, string value) } /// public static TValue GetValue(this IDictionary dictionary, TKey key) - where TKey : notnull { try { @@ -107,34 +104,11 @@ public static bool GetValidBoolean(this YamlMappingNode yamlNode, string key) } /// /// - public static TEnum GetValidEnum(this YamlMappingNode yamlNode, string key) - where TEnum : unmanaged + public static TEnum GetValidEnum(this YamlMappingNode yamlNode, string key) where TEnum : unmanaged { return ParseEnum(key, yamlNode.Children.GetValue(key).ToString()); } - public static void TryCreateMasterPlaylist(List playlists) - { - if (playlists.Exists(p => p.Name == "Music")) - { - return; - } - - var songs = new List(); - foreach (Config.Playlist p in playlists) - { - foreach (Config.Song s in p.Songs) - { - if (!songs.Exists(s1 => s1.Index == s.Index)) - { - songs.Add(s); - } - } - } - songs.Sort((s1, s2) => s1.Index.CompareTo(s2.Index)); - playlists.Insert(0, new Config.Playlist(Strings.PlaylistMusic, songs)); - } - public static string CombineWithBaseDirectory(string path) { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path); @@ -142,16 +116,11 @@ public static string CombineWithBaseDirectory(string path) public static string GetNoteName(int note) { - return Notes[note]; + return _notes[note]; } - public static string GetKeyName(int midiNote) + // TODO: Cache results? + public static string GetKeyName(int note) { - if (!_keyCache.TryGetValue(midiNote, out string? str)) - { - // {C} + {5} = "C5" - str = Notes[midiNote % 12] + ((midiNote / 12) + (GlobalConfig.Instance.MiddleCOctave - 5)); - _keyCache.Add(midiNote, str); - } - return str; + return _notes[note % 12] + ((note / 12) + (GlobalConfig.Instance.MiddleCOctave - 5)); } } diff --git a/VG Music Studio - Core/Util/DataUtils.cs b/VG Music Studio - Core/Util/DataUtils.cs deleted file mode 100644 index fe16180..0000000 --- a/VG Music Studio - Core/Util/DataUtils.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.IO; - -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class DataUtils -{ - public static void Align(this Stream s, int num) - { - while (s.Position % num != 0) - { - s.Position++; - } - } -} diff --git a/VG Music Studio - Core/Util/GlobalConfig.cs b/VG Music Studio - Core/Util/GlobalConfig.cs index 87ee284..106f805 100644 --- a/VG Music Studio - Core/Util/GlobalConfig.cs +++ b/VG Music Studio - Core/Util/GlobalConfig.cs @@ -58,9 +58,29 @@ private GlobalConfig() { throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorConfigColorRepeated, i))); } - - string valueName = string.Format(Strings.ConfigKeySubkey, string.Format("{0} {1}", nameof(Colors), i)); - var co = Color.FromArgb((int)(0xFF000000 + (uint)ConfigUtils.ParseValue(valueName, c.Value.ToString(), 0x000000, 0xFFFFFF))); + long h = 0, s = 0, l = 0; + foreach (KeyValuePair v in ((YamlMappingNode)c.Value).Children) + { + string key = v.Key.ToString(); + string valueName = string.Format(Strings.ConfigKeySubkey, string.Format("{0} {1}", nameof(Colors), i)); + if (key == "H") + { + h = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else if (key == "S") + { + s = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else if (key == "L") + { + l = ConfigUtils.ParseValue(valueName, v.Value.ToString(), 0, 240); + } + else + { + throw new Exception(string.Format(Strings.ErrorParseConfig, CONFIG_FILE, Environment.NewLine + string.Format(Strings.ErrorConfigColorInvalidKey, i))); + } + } + var co = HSLColor.ToColor((int)h, (byte)s, (byte)l); Colors[i] = co; Colors[i + 128] = co; } diff --git a/VG Music Studio - Core/Util/HSLColor.cs b/VG Music Studio - Core/Util/HSLColor.cs index b2b7ee7..ab371dd 100644 --- a/VG Music Studio - Core/Util/HSLColor.cs +++ b/VG Music Studio - Core/Util/HSLColor.cs @@ -1,140 +1,144 @@ using System; +using System.Collections.Generic; using System.Drawing; +using System.Linq; namespace Kermalis.VGMusicStudio.Core.Util; -// https://www.rapidtables.com/convert/color/rgb-to-hsl.html -// https://www.rapidtables.com/convert/color/hsl-to-rgb.html -// Not really used right now, but will be very useful if we are going to use OpenGL public readonly struct HSLColor { - /// [0, 1) - public readonly double Hue; - /// [0, 1] - public readonly double Saturation; - /// [0, 1] - public readonly double Lightness; - - public HSLColor(double h, double s, double l) + public readonly int H; + public readonly byte S; + public readonly byte L; + + public HSLColor(int h, byte s, byte l) { - Hue = h; - Saturation = s; - Lightness = l; + H = h; + S = s; + L = l; } public HSLColor(in Color c) { - double nR = c.R / 255.0; - double nG = c.G / 255.0; - double nB = c.B / 255.0; - - double max = Math.Max(Math.Max(nR, nG), nB); - double min = Math.Min(Math.Min(nR, nG), nB); - double delta = max - min; + double modifiedR, modifiedG, modifiedB, min, max, delta, h, s, l; - Lightness = (min + max) * 0.5; + modifiedR = c.R / 255.0; + modifiedG = c.G / 255.0; + modifiedB = c.B / 255.0; - if (delta == 0) - { - Hue = 0; - } - else if (max == nR) - { - Hue = (nG - nB) / delta % 6 / 6; - } - else if (max == nG) - { - Hue = (((nB - nR) / delta) + 2) / 6; - } - else // max == nB - { - Hue = (((nR - nG) / delta) + 4) / 6; - } + min = new List(3) { modifiedR, modifiedG, modifiedB }.Min(); + max = new List(3) { modifiedR, modifiedG, modifiedB }.Max(); + delta = max - min; + l = (min + max) / 2; if (delta == 0) { - Saturation = 0; + h = 0; + s = 0; } else { - Saturation = delta / (1 - Math.Abs((2 * Lightness) - 1)); + s = (l <= 0.5) ? (delta / (min + max)) : (delta / (2 - max - min)); + + if (modifiedR == max) + { + h = (modifiedG - modifiedB) / 6 / delta; + } + else if (modifiedG == max) + { + h = (1.0 / 3) + ((modifiedB - modifiedR) / 6 / delta); + } + else + { + h = (2.0 / 3) + ((modifiedR - modifiedG) / 6 / delta); + } + + h = (h < 0) ? ++h : h; + h = (h > 1) ? --h : h; } + + H = (int)Math.Round(h * 360); + S = (byte)Math.Round(s * 100); + L = (byte)Math.Round(l * 100); } public Color ToColor() { - return ToColor(Hue, Saturation, Lightness); + return ToColor(H, S, L); } - public static void ToRGB(double h, double s, double l, out double r, out double g, out double b) + // https://github.com/iamartyom/ColorHelper/blob/master/ColorHelper/Converter/ColorConverter.cs + public static Color ToColor(int h, byte s, byte l) { - h *= 360; + double modifiedH, modifiedS, modifiedL, + r = 1, g = 1, b = 1, + q, p; - double c = (1 - Math.Abs((2 * l) - 1)) * s; - double x = c * (1 - Math.Abs((h / 60 % 2) - 1)); - double m = l - (c * 0.5); + modifiedH = h / 360.0; + modifiedS = s / 100.0; + modifiedL = l / 100.0; - if (h < 60) + q = (modifiedL < 0.5) ? modifiedL * (1 + modifiedS) : modifiedL + modifiedS - modifiedL * modifiedS; + p = 2 * modifiedL - q; + + if (modifiedL == 0) // If the lightness value is 0 it will always be black { - r = c; - g = x; + r = 0; + g = 0; b = 0; } - else if (h < 120) + else if (modifiedS != 0) { - r = x; - g = c; - b = 0; + r = GetHue(p, q, modifiedH + 1.0 / 3); + g = GetHue(p, q, modifiedH); + b = GetHue(p, q, modifiedH - 1.0 / 3); } - else if (h < 180) + + return Color.FromArgb(255, (byte)Math.Round(r * 255), (byte)Math.Round(g * 255), (byte)Math.Round(b * 255)); + } + private static double GetHue(double p, double q, double t) + { + double value = p; + + if (t < 0) { - r = 0; - g = c; - b = x; + t++; } - else if (h < 240) + else if (t > 1) { - r = 0; - g = x; - b = c; + t--; } - else if (h < 300) + + if (t < 1.0 / 6) { - r = x; - g = 0; - b = c; + value = p + (q - p) * 6 * t; } - else // h < 360 + else if (t < 1.0 / 2) { - r = c; - g = 0; - b = x; + value = q; + } + else if (t < 2.0 / 3) + { + value = p + (q - p) * (2.0 / 3 - t) * 6; } - r += m; - g += m; - b += m; - } - public static Color ToColor(double h, double s, double l) - { - ToRGB(h, s, l, out double r, out double g, out double b); - return Color.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255)); + return value; } public override bool Equals(object? obj) { if (obj is HSLColor other) { - return Hue == other.Hue && Saturation == other.Saturation && Lightness == other.Lightness; + return H == other.H && S == other.S && L == other.L; } return false; } public override int GetHashCode() { - return HashCode.Combine(Hue, Saturation, Lightness); + return HashCode.Combine(H, S, L); } public override string ToString() { - return $"{Hue * 360}° {Saturation:P} {Lightness:P}"; + return $"{H}° {S}% {L}%"; } public static bool operator ==(HSLColor left, HSLColor right) diff --git a/VG Music Studio - Core/Util/LanguageUtils.cs b/VG Music Studio - Core/Util/LanguageUtils.cs deleted file mode 100644 index ad1bc50..0000000 --- a/VG Music Studio - Core/Util/LanguageUtils.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class LanguageUtils -{ - // Try to handle lang strings like "мелодий|0_0|мелодия|1_1|мелодии|2_4|мелодий|5_*|" - public static string HandlePlural(int count, string str) - { - string[] split = str.Split('|', StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < split.Length; i += 2) - { - string text = split[i]; - string range = split[i + 1]; - - int rangeSplit = range.IndexOf('_'); - int rangeStart = GetPluralRangeValue(range.AsSpan(0, rangeSplit), int.MinValue); - int rangeEnd = GetPluralRangeValue(range.AsSpan(rangeSplit + 1), int.MaxValue); - if (count >= rangeStart && count <= rangeEnd) - { - return text; - } - } - throw new ArgumentOutOfRangeException(nameof(str), str, "Could not find plural entry"); - } - private static int GetPluralRangeValue(ReadOnlySpan chars, int star) - { - return chars.Length == 1 && chars[0] == '*' ? star : int.Parse(chars); - } -} diff --git a/VG Music Studio - Core/Util/SampleUtils.cs b/VG Music Studio - Core/Util/SampleUtils.cs index cbce3fb..057499e 100644 --- a/VG Music Studio - Core/Util/SampleUtils.cs +++ b/VG Music Studio - Core/Util/SampleUtils.cs @@ -1,15 +1,19 @@ using System; -namespace Kermalis.VGMusicStudio.Core.Util; - -internal static class SampleUtils +namespace Kermalis.VGMusicStudio.Core.Util { - public static void PCMU8ToPCM16(ReadOnlySpan src, Span dest) + internal static class SampleUtils { - for (int i = 0; i < src.Length; i++) + // TODO: Span output? + public static short[] PCMU8ToPCM16(ReadOnlySpan data) { - byte b = src[i]; - dest[i] = (short)((b - 0x80) << 8); + short[] ret = new short[data.Length]; + for (int i = 0; i < data.Length; i++) + { + byte b = data[i]; + ret[i] = (short)((b - 0x80) << 8); + } + return ret; } } } diff --git a/VG Music Studio - Core/Util/TimeBarrier.cs b/VG Music Studio - Core/Util/TimeBarrier.cs index 5379357..fab0ae5 100644 --- a/VG Music Studio - Core/Util/TimeBarrier.cs +++ b/VG Music Studio - Core/Util/TimeBarrier.cs @@ -13,9 +13,9 @@ internal sealed class TimeBarrier private double _lastTimeStamp; private bool _started; - public TimeBarrier(double ticksPerSecond) + public TimeBarrier(double framesPerSecond) { - _waitInterval = 1.0 / ticksPerSecond; + _waitInterval = 1.0 / framesPerSecond; _started = false; _sw = new Stopwatch(); _timerInterval = 1.0 / Stopwatch.Frequency; diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index 1d8bb4e..c60a0f8 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -1,7 +1,7 @@  - net7.0 + net6.0 Library latest Kermalis.VGMusicStudio.Core @@ -11,31 +11,36 @@ - + - + + + + + + Dependencies\DLS2.dll - - Dependencies\KMIDI.dll - - Dependencies\SoundFont2.dll + Dependencies\SoundFont2.dll - - True - True - Strings.resx - - - PublicResXFileCodeGenerator - Strings.Designer.cs - + + Always + + + Always + + + Always + + + Always + diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..01921eb --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,875 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal sealed class MainWindow : Window + { + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + #endregion + + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + + _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + { + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + } + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + if (Engine.Instance != null) + { + DisposeEngine(); + } + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; + _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..0f13fcc --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..f18377e --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,16 @@ + + + + Exe + net6.0 + + + + + + + + + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..d151b67 --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1369 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; + +using Application = Adw.Application; +using Window = Adw.Window; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class MainWindow : Window +{ + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + private int _duration = 0; + private int _position = 0; + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private readonly Adjustment _volumeAdjustment, _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; + + // Sound Sequence List + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); + _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + //_volumeScale.OnValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + //_positionScale.SetRange(0, double.MaxValue); + _positionGestureClick = GestureClick.New(); + //if (_positionGestureClick.Button == 1) + // { + // _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + // _positionScale.OnValueChanged += PositionScale_MouseButtonPress; + // } + //_positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + + SetContent(_mainBox); + + Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance!.Player.SetCurrentPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + //_positionScale.Adjustment!.Upper = double.MaxValue; + _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); + _positionScale.SetRange(0, _duration); + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; + _positionScale.Show(); + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ enableds; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); + return; + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + _timer.Start(); + Show(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + Show(); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + if (ticks < _duration) + { + // TODO: Implement GStreamer functions to replace Gtk.Adjustment + //_positionScale.SetRange(0, _duration); + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues + } + else + { + return; + } + } + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..a99da5f --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,48 @@ +using Adw; +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..1fd8cf1 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..621175f --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..6d21dc2 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..6077bf9 --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..64ba658 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,281 @@ + + + + Exe + net6.0 + enable + true + + + + + + + + + + + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + + diff --git a/VG Music Studio - MIDI/Chunks/MIDIChunk.cs b/VG Music Studio - MIDI/Chunks/MIDIChunk.cs new file mode 100644 index 0000000..175d966 --- /dev/null +++ b/VG Music Studio - MIDI/Chunks/MIDIChunk.cs @@ -0,0 +1,22 @@ +using Kermalis.EndianBinaryIO; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public abstract class MIDIChunk +{ + protected static long GetEndOffset(EndianBinaryReader r, uint size) + { + return r.Stream.Position + size; + } + protected static void EatRemainingBytes(EndianBinaryReader r, long endOffset, string chunkName, uint size) + { + if (r.Stream.Position > endOffset) + { + throw new InvalidDataException($"Chunk was too short ({chunkName} = {size})"); + } + r.Stream.Position = endOffset; + } + + internal abstract void Write(EndianBinaryWriter w); +} diff --git a/VG Music Studio - MIDI/Chunks/MIDIHeaderChunk.cs b/VG Music Studio - MIDI/Chunks/MIDIHeaderChunk.cs new file mode 100644 index 0000000..846fdcd --- /dev/null +++ b/VG Music Studio - MIDI/Chunks/MIDIHeaderChunk.cs @@ -0,0 +1,79 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Diagnostics; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +// Section 2.1 +public sealed class MIDIHeaderChunk : MIDIChunk +{ + internal const string EXPECTED_NAME = "MThd"; + + public MIDIFormat Format { get; } + public ushort NumTracks { get; internal set; } + public TimeDivisionValue TimeDivision { get; } + + internal MIDIHeaderChunk(MIDIFormat format, TimeDivisionValue timeDivision) + { + if (format > MIDIFormat.Format2) + { + throw new ArgumentOutOfRangeException(nameof(format), format, null); + } + if (!timeDivision.Validate()) + { + throw new ArgumentOutOfRangeException(nameof(timeDivision), timeDivision, null); + } + + Format = format; + TimeDivision = timeDivision; + } + internal MIDIHeaderChunk(uint size, EndianBinaryReader r) + { + if (size < 6) + { + throw new InvalidDataException($"Invalid MIDI header length ({size})"); + } + + long endOffset = GetEndOffset(r, size); + + Format = r.ReadEnum(); + NumTracks = r.ReadUInt16(); + TimeDivision = new TimeDivisionValue(r.ReadUInt16()); + + if (Format > MIDIFormat.Format2) + { + // Section 2.2 states that unknown formats should be supported + Debug.WriteLine($"Unknown MIDI format ({Format}), so behavior is unknown"); + } + if (NumTracks == 0) + { + throw new InvalidDataException("MIDI has no tracks"); + } + if (Format == MIDIFormat.Format0 && NumTracks != 1) + { + throw new InvalidDataException($"MIDI format 0 must have 1 track, but this MIDI has {NumTracks}"); + } + if (!TimeDivision.Validate()) + { + throw new InvalidDataException($"Invalid MIDI time division ({TimeDivision})"); + } + + if (size > 6) + { + // Section 2.2 states that the length should be honored + Debug.WriteLine($"MIDI Header was longer than 6 bytes ({size}), so the extra data is being ignored"); + EatRemainingBytes(r, endOffset, EXPECTED_NAME, size); + } + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteChars_Count(EXPECTED_NAME, 4); + w.WriteUInt32(6); + + w.WriteEnum(Format); + w.WriteUInt16(NumTracks); + w.WriteUInt16(TimeDivision.RawValue); + } +} diff --git a/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs b/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs new file mode 100644 index 0000000..8e21ee2 --- /dev/null +++ b/VG Music Studio - MIDI/Chunks/MIDITrackChunk.cs @@ -0,0 +1,246 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class MIDITrackChunk : MIDIChunk +{ + internal const string EXPECTED_NAME = "MTrk"; + + public MIDIEvent? First { get; private set; } + public MIDIEvent? Last { get; private set; } + + /// Includes the end of track event + public int NumEvents { get; private set; } + public int NumTicks => Last is null ? 0 : Last.Ticks; + + internal MIDITrackChunk() + { + // + } + internal MIDITrackChunk(uint size, EndianBinaryReader r) + { + long endOffset = GetEndOffset(r, size); + + int ticks = 0; + byte runningStatus = 0; + bool foundEnd = false; + bool sysexContinue = false; + while (r.Stream.Position < endOffset) + { + if (foundEnd) + { + throw new InvalidDataException("Events found after the EndOfTrack MetaMessage"); + } + + ticks += MIDIFile.ReadVariableLength(r); + + // Get command + byte cmd = r.ReadByte(); + if (sysexContinue && cmd != 0xF7) + { + throw new InvalidDataException($"SysExContinuationMessage was missing at 0x{r.Stream.Position - 1:X}"); + } + if (cmd < 0x80) + { + cmd = runningStatus; + r.Stream.Position--; + } + + // Check which message it is + if (cmd >= 0x80 && cmd <= 0xEF) + { + runningStatus = cmd; + byte channel = (byte)(cmd & 0xF); + switch (cmd & ~0xF) + { + case 0x80: Insert(ticks, new NoteOnMessage(r, channel)); break; + case 0x90: Insert(ticks, new NoteOffMessage(r, channel)); break; + case 0xA0: Insert(ticks, new PolyphonicPressureMessage(r, channel)); break; + case 0xB0: Insert(ticks, new ControllerMessage(r, channel)); break; + case 0xC0: Insert(ticks, new ProgramChangeMessage(r, channel)); break; + case 0xD0: Insert(ticks, new ChannelPressureMessage(r, channel)); break; + case 0xE0: Insert(ticks, new PitchBendMessage(r, channel)); break; + } + } + else if (cmd == 0xF0) + { + runningStatus = 0; + var msg = new SysExMessage(r); + if (!msg.IsComplete) + { + sysexContinue = true; + } + } + else if (cmd == 0xF7) + { + runningStatus = 0; + if (sysexContinue) + { + var msg = new SysExContinuationMessage(r); + if (msg.IsFinished) + { + sysexContinue = false; + } + } + else + { + Insert(ticks, new EscapeMessage(r)); + } + } + else if (cmd == 0xFF) + { + var msg = new MetaMessage(r); + if (msg.Type == MetaMessageType.EndOfTrack) + { + foundEnd = true; + } + Insert(ticks, msg); + } + else + { + throw new InvalidDataException($"Unknown MIDI command found at 0x{r.Stream.Position - 1:X} (0x{cmd:X})"); + } + } + + if (!foundEnd) + { + throw new InvalidDataException("Could not find EndOfTrack MetaMessage"); + } + if (r.Stream.Position > endOffset) + { + throw new InvalidDataException("Expected to read a certain amount of events, but the data was read incorrectly..."); + } + } + + public void Insert(int ticks, MIDIMessage msg) + { + if (ticks < 0) + { + throw new ArgumentOutOfRangeException(nameof(ticks), ticks, null); + } + + var e = new MIDIEvent(ticks, msg); + + if (NumEvents == 0) + { + First = e; + Last = e; + } + else if (ticks < First!.Ticks) + { + e.Next = First; + First.Prev = e; + First = e; + } + else if (ticks >= Last!.Ticks) + { + e.Prev = Last; + Last.Next = e; + Last = e; + } + else // Somewhere between + { + MIDIEvent next = First; + + while (next.Ticks <= ticks) + { + next = next.Next!; + } + + MIDIEvent prev = next.Prev!; + + e.Next = next; + e.Prev = prev; + prev.Next = e; + next.Prev = e; + } + + NumEvents++; + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteChars_Count(EXPECTED_NAME, 4); + + long sizeOffset = w.Stream.Position; + w.WriteUInt32(0); // We will update the size later + + byte runningStatus = 0; + bool foundEnd = false; + bool sysexContinue = false; + for (MIDIEvent? e = First; e is not null; e = e.Next) + { + if (foundEnd) + { + throw new InvalidDataException("Events found after the EndOfTrack MetaMessage"); + } + + MIDIFile.WriteVariableLength(w, e.DeltaTicks); + + MIDIMessage msg = e.Message; + byte cmd = msg.GetCMDByte(); + if (sysexContinue && cmd != 0xF7) + { + throw new InvalidDataException("SysExContinuationMessage was missing"); + } + + if (cmd >= 0x80 && cmd <= 0xEF) + { + if (runningStatus != cmd) + { + runningStatus = cmd; + w.WriteByte(cmd); + } + } + else if (cmd == 0xF0) + { + runningStatus = 0; + var sysex = (SysExMessage)msg; + if (!sysex.IsComplete) + { + sysexContinue = true; + } + w.WriteByte(0xF0); + } + else if (cmd == 0xF7) + { + runningStatus = 0; + if (sysexContinue) + { + var sysex = (SysExContinuationMessage)msg; + if (sysex.IsFinished) + { + sysexContinue = false; + } + } + w.WriteByte(0xF0); + } + else if (cmd == 0xFF) + { + var meta = (MetaMessage)msg; + if (meta.Type == MetaMessageType.EndOfTrack) + { + foundEnd = true; + } + w.WriteByte(0xFF); + } + else + { + throw new InvalidDataException($"Unknown MIDI command 0x{cmd:X}"); + } + + msg.Write(w); + } + if (!foundEnd) + { + throw new InvalidDataException("You must insert an EndOfTrack MetaMessage"); + } + + // Update size now + uint size = (uint)(w.Stream.Position - sizeOffset + 4); + w.Stream.Position = sizeOffset; + w.WriteUInt32(size); + } +} diff --git a/VG Music Studio - MIDI/Chunks/MIDIUnsupportedChunk.cs b/VG Music Studio - MIDI/Chunks/MIDIUnsupportedChunk.cs new file mode 100644 index 0000000..942411e --- /dev/null +++ b/VG Music Studio - MIDI/Chunks/MIDIUnsupportedChunk.cs @@ -0,0 +1,30 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class MIDIUnsupportedChunk : MIDIChunk +{ + /// Length 4 + public string ChunkName { get; } + public byte[] Data { get; } + + public MIDIUnsupportedChunk(string chunkName, byte[] data) + { + ChunkName = chunkName; + Data = data; + } + internal MIDIUnsupportedChunk(string chunkName, uint size, EndianBinaryReader r) + { + ChunkName = chunkName; + Data = new byte[size]; + r.ReadBytes(Data); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteChars_Count(ChunkName, 4); + w.WriteUInt32((uint)Data.Length); + + w.WriteBytes(Data); + } +} diff --git a/VG Music Studio - MIDI/Events/ChannelPressureMessage.cs b/VG Music Studio - MIDI/Events/ChannelPressureMessage.cs new file mode 100644 index 0000000..f3836fc --- /dev/null +++ b/VG Music Studio - MIDI/Events/ChannelPressureMessage.cs @@ -0,0 +1,48 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class ChannelPressureMessage : MIDIMessage +{ + public byte Channel { get; } + + public byte Pressure { get; } + + internal ChannelPressureMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Pressure = r.ReadByte(); + if (Pressure > 127) + { + throw new InvalidDataException($"Invalid {nameof(ChannelPressureMessage)} pressure at 0x{r.Stream.Position - 1:X} ({Pressure})"); + } + } + + public ChannelPressureMessage(byte channel, byte pressure) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (pressure > 127) + { + throw new ArgumentOutOfRangeException(nameof(pressure), pressure, null); + } + + Channel = channel; + Pressure = pressure; + } + + internal override byte GetCMDByte() + { + return (byte)(0xD0 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteByte(Pressure); + } +} diff --git a/VG Music Studio - MIDI/Events/ControllerMessage.cs b/VG Music Studio - MIDI/Events/ControllerMessage.cs new file mode 100644 index 0000000..b0e3c6f --- /dev/null +++ b/VG Music Studio - MIDI/Events/ControllerMessage.cs @@ -0,0 +1,141 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class ControllerMessage : MIDIMessage +{ + public byte Channel { get; } + + public ControllerType Controller { get; } + public byte Value { get; } + + internal ControllerMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Controller = r.ReadEnum(); + if (Controller >= ControllerType.MAX) + { + throw new InvalidDataException($"Invalid {nameof(ControllerMessage)} controller at 0x{r.Stream.Position - 1:X} ({Controller})"); + } + + Value = r.ReadByte(); + if (Value > 127) + { + throw new InvalidDataException($"Invalid {nameof(ControllerMessage)} value at 0x{r.Stream.Position - 1:X} ({Value})"); + } + } + + public ControllerMessage(byte channel, ControllerType controller, byte value) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (controller >= ControllerType.MAX) + { + throw new ArgumentOutOfRangeException(nameof(controller), controller, null); + } + if (value > 127) + { + throw new ArgumentOutOfRangeException(nameof(value), value, null); + } + + Channel = channel; + Controller = controller; + Value = value; + } + + internal override byte GetCMDByte() + { + return (byte)(0xB0 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Controller); + w.WriteByte(Value); + } +} + +public enum ControllerType : byte +{ + // MSB + BankSelect, + ModulationWheel, + BreathController, + FootController = 4, + PortamentoTime, + DataEntry, + ChannelVolume, + Balance, + Pan = 10, + ExpressionController, + EffectControl1, + EffectControl2, + GeneralPurposeController1 = 16, + GeneralPurposeController2, + GeneralPurposeController3, + GeneralPurposeController4, + // LSB + BankSelectLSB = 32, + ModulationWheelLSB, + BreathControllerLSB, + FootControllerLSB = 36, + PortamentoTimeLSB, + DataEntryLSB, + ChannelVolumeLSB, + BalanceLSB, + PanLSB = 42, + ExpressionControllerLSB, + EffectControl1LSB, + EffectControl2LSB, + GeneralPurposeController1LSB = 48, + GeneralPurposeController2LSB, + GeneralPurposeController3LSB, + GeneralPurposeController4LSB, + SustainToggle = 64, + PortamentoToggle, + SostenutoToggle, + SoftPedalToggle, + LegatoToggle, + Hold2Toggle, + SoundController1, + SoundController2, + SoundController3, + SoundController4, + SoundController5, + SoundController6, + SoundController7, + SoundController8, + SoundController9, + SoundController10, + GeneralPurposeController5, + GeneralPurposeController6, + GeneralPurposeController7, + GeneralPurposeController8, + PortamentoControl, + HighResolutionVelocityPrefix = 88, + Effects1Depth = 91, + Effects2Depth, + Effects3Depth, + Effects4Depth, + Effects5Depth, + DataIncrement, + DataDecrement, + NonRegisteredParameterNumberLSB, + NonRegisteredParameterNumberMSB, + RegisteredParameterNumberLSB, + RegisteredParameterNumberMSB, + AllSoundOff = 120, + ResetAllControllers, + LocalControlToggle, + AllNotesOff, + OmniModeOff, + OmniModeOn, + MonoModeOn, + PolyModeOn, + MAX, +} diff --git a/VG Music Studio - MIDI/Events/EscapeMessage.cs b/VG Music Studio - MIDI/Events/EscapeMessage.cs new file mode 100644 index 0000000..0913029 --- /dev/null +++ b/VG Music Studio - MIDI/Events/EscapeMessage.cs @@ -0,0 +1,39 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class EscapeMessage : MIDIMessage +{ + public byte[] Data { get; } + + internal EscapeMessage(EndianBinaryReader r) + { + int len = MIDIFile.ReadVariableLength(r); + if (len == 0) + { + Data = Array.Empty(); + } + else + { + Data = new byte[len]; + r.ReadBytes(Data); + } + } + + public EscapeMessage(byte[] data) + { + Data = data; + } + + internal override byte GetCMDByte() + { + return 0xF7; + } + + internal override void Write(EndianBinaryWriter w) + { + MIDIFile.WriteVariableLength(w, Data.Length); + w.WriteBytes(Data); + } +} diff --git a/VG Music Studio - MIDI/Events/MIDIEvent.cs b/VG Music Studio - MIDI/Events/MIDIEvent.cs new file mode 100644 index 0000000..0886750 --- /dev/null +++ b/VG Music Studio - MIDI/Events/MIDIEvent.cs @@ -0,0 +1,18 @@ +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class MIDIEvent +{ + public int Ticks { get; internal set; } + public int DeltaTicks => Prev is null ? Ticks : Ticks - Prev.Ticks; + + public MIDIMessage Message { get; set; } + + public MIDIEvent? Prev { get; internal set; } + public MIDIEvent? Next { get; internal set; } + + internal MIDIEvent(int ticks, MIDIMessage msg) + { + Ticks = ticks; + Message = msg; + } +} \ No newline at end of file diff --git a/VG Music Studio - MIDI/Events/MIDIMessage.cs b/VG Music Studio - MIDI/Events/MIDIMessage.cs new file mode 100644 index 0000000..2358769 --- /dev/null +++ b/VG Music Studio - MIDI/Events/MIDIMessage.cs @@ -0,0 +1,10 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public abstract class MIDIMessage +{ + internal abstract byte GetCMDByte(); + + internal abstract void Write(EndianBinaryWriter w); +} diff --git a/VG Music Studio - MIDI/Events/MetaMessage.cs b/VG Music Studio - MIDI/Events/MetaMessage.cs new file mode 100644 index 0000000..1c17f0d --- /dev/null +++ b/VG Music Studio - MIDI/Events/MetaMessage.cs @@ -0,0 +1,122 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class MetaMessage : MIDIMessage +{ + public MetaMessageType Type { get; } + public byte[] Data { get; } + + internal MetaMessage(EndianBinaryReader r) + { + Type = r.ReadEnum(); + if (Type >= MetaMessageType.MAX) + { + throw new InvalidDataException($"Invalid {nameof(MetaMessage)} type at 0x{r.Stream.Position - 1:X} ({Type})"); + } + + int len = MIDIFile.ReadVariableLength(r); + if (len == 0) + { + Data = Array.Empty(); + } + else + { + Data = new byte[len]; + r.ReadBytes(Data); + } + } + + public MetaMessage(MetaMessageType type, byte[] data) + { + if (type >= MetaMessageType.MAX) + { + throw new ArgumentOutOfRangeException(nameof(type), type, null); + } + + Type = type; + Data = data; + } + + public static MetaMessage CreateTempoMessage(int tempo) + { + if (tempo <= 0) + { + throw new ArgumentOutOfRangeException(nameof(tempo), tempo, null); + } + + tempo = 60_000_000 / tempo; + byte[] data = new byte[3]; + for (int i = 0; i < 3; i++) + { + data[2 - i] = (byte)(tempo >> (i * 8)); + } + return new MetaMessage(MetaMessageType.Tempo, data); + } + + public static MetaMessage CreateTimeSignatureMessage(byte numerator, byte denominator, byte clocksPerMetronomeClick = 24, byte num32ndNotesPerQuarterNote = 8) + { + if (numerator == 0) + { + throw new ArgumentOutOfRangeException(nameof(numerator), numerator, null); + } + if (denominator < 2 || denominator > 32) + { + throw new ArgumentOutOfRangeException(nameof(denominator), denominator, null); + } + if ((denominator & (denominator - 1)) != 0) + { + throw new ArgumentException("Denominator must be a power of 2", nameof(denominator)); + } + if (clocksPerMetronomeClick == 0) + { + throw new ArgumentOutOfRangeException(nameof(clocksPerMetronomeClick), clocksPerMetronomeClick, null); + } + if (num32ndNotesPerQuarterNote == 0) + { + throw new ArgumentOutOfRangeException(nameof(num32ndNotesPerQuarterNote), num32ndNotesPerQuarterNote, null); + } + + byte[] data = new byte[4]; + data[0] = numerator; + data[1] = (byte)Math.Log(denominator, 2); + data[2] = clocksPerMetronomeClick; + data[3] = num32ndNotesPerQuarterNote; + return new MetaMessage(MetaMessageType.TimeSignature, data); + } + + internal override byte GetCMDByte() + { + return 0xFF; + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Type); + MIDIFile.WriteVariableLength(w, Data.Length); + w.WriteBytes(Data); + } +} + +public enum MetaMessageType : byte +{ + SequenceNumber, + Text, + Copyright, + TrackName, + InstrumentName, + Lyric, + Marker, + CuePoint, + ProgramName, + DeviceName, + EndOfTrack = 0x2F, + Tempo = 0x51, + SMPTEOffset = 0x54, + TimeSignature = 0x58, + KeySignature, + ProprietaryEvent = 0x7F, + MAX, +} \ No newline at end of file diff --git a/VG Music Studio - MIDI/Events/NoteOffMessage.cs b/VG Music Studio - MIDI/Events/NoteOffMessage.cs new file mode 100644 index 0000000..15adc01 --- /dev/null +++ b/VG Music Studio - MIDI/Events/NoteOffMessage.cs @@ -0,0 +1,61 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class NoteOffMessage : MIDIMessage +{ + public byte Channel { get; } + + public MIDINote Note { get; } + public byte Velocity { get; } + + internal NoteOffMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Note = r.ReadEnum(); + if (Note >= MIDINote.MAX) + { + throw new InvalidDataException($"Invalid {nameof(NoteOffMessage)} note at 0x{r.Stream.Position - 1:X} ({Note})"); + } + + Velocity = r.ReadByte(); + if (Velocity > 127) + { + throw new InvalidDataException($"Invalid {nameof(NoteOffMessage)} velocity at 0x{r.Stream.Position - 1:X} ({Velocity})"); + } + } + + public NoteOffMessage(byte channel, MIDINote note, byte velocity) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (note >= MIDINote.MAX) + { + throw new ArgumentOutOfRangeException(nameof(note), note, null); + } + if (velocity > 127) + { + throw new ArgumentOutOfRangeException(nameof(velocity), velocity, null); + } + + Channel = channel; + Note = note; + Velocity = velocity; + } + + internal override byte GetCMDByte() + { + return (byte)(0x90 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Note); + w.WriteByte(Velocity); + } +} diff --git a/VG Music Studio - MIDI/Events/NoteOnMessage.cs b/VG Music Studio - MIDI/Events/NoteOnMessage.cs new file mode 100644 index 0000000..629cfed --- /dev/null +++ b/VG Music Studio - MIDI/Events/NoteOnMessage.cs @@ -0,0 +1,61 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class NoteOnMessage : MIDIMessage +{ + public byte Channel { get; } + + public MIDINote Note { get; } + public byte Velocity { get; } + + internal NoteOnMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Note = r.ReadEnum(); + if (Note >= MIDINote.MAX) + { + throw new InvalidDataException($"Invalid {nameof(NoteOnMessage)} note at 0x{r.Stream.Position - 1:X} ({Note})"); + } + + Velocity = r.ReadByte(); + if (Velocity > 127) + { + throw new InvalidDataException($"Invalid {nameof(NoteOnMessage)} velocity at 0x{r.Stream.Position - 1:X} ({Velocity})"); + } + } + + public NoteOnMessage(byte channel, MIDINote note, byte velocity) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (note >= MIDINote.MAX) + { + throw new ArgumentOutOfRangeException(nameof(note), note, null); + } + if (velocity > 127) + { + throw new ArgumentOutOfRangeException(nameof(velocity), velocity, null); + } + + Channel = channel; + Note = note; + Velocity = velocity; + } + + internal override byte GetCMDByte() + { + return (byte)(0x80 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Note); + w.WriteByte(Velocity); + } +} diff --git a/VG Music Studio - MIDI/Events/PitchBendMessage.cs b/VG Music Studio - MIDI/Events/PitchBendMessage.cs new file mode 100644 index 0000000..0509578 --- /dev/null +++ b/VG Music Studio - MIDI/Events/PitchBendMessage.cs @@ -0,0 +1,61 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class PitchBendMessage : MIDIMessage +{ + public byte Channel { get; } + + public byte LSB { get; } + public byte MSB { get; } + + internal PitchBendMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + LSB = r.ReadByte(); + if (LSB > 127) + { + throw new InvalidDataException($"Invalid {nameof(PitchBendMessage)} LSB value at 0x{r.Stream.Position - 1:X} ({LSB})"); + } + + MSB = r.ReadByte(); + if (MSB > 127) + { + throw new InvalidDataException($"Invalid {nameof(PitchBendMessage)} MSB value at 0x{r.Stream.Position - 1:X} ({MSB})"); + } + } + + public PitchBendMessage(byte channel, byte lsb, byte msb) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (lsb > 127) + { + throw new ArgumentOutOfRangeException(nameof(lsb), lsb, null); + } + if (msb > 127) + { + throw new ArgumentOutOfRangeException(nameof(msb), msb, null); + } + + Channel = channel; + LSB = lsb; + MSB = msb; + } + + internal override byte GetCMDByte() + { + return (byte)(0xE0 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteByte(LSB); + w.WriteByte(MSB); + } +} diff --git a/VG Music Studio - MIDI/Events/PolyphonicPressureMessage.cs b/VG Music Studio - MIDI/Events/PolyphonicPressureMessage.cs new file mode 100644 index 0000000..ead1ecc --- /dev/null +++ b/VG Music Studio - MIDI/Events/PolyphonicPressureMessage.cs @@ -0,0 +1,53 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class PolyphonicPressureMessage : MIDIMessage +{ + public byte Channel { get; } + + public MIDINote Note { get; } + public byte Pressure { get; } + + internal PolyphonicPressureMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Note = r.ReadEnum(); + + Pressure = r.ReadByte(); + if (Pressure > 127) + { + throw new InvalidDataException($"Invalid PolyphonicPressureMessage pressure at 0x{r.Stream.Position - 1:X} ({Pressure})"); + } + } + + public PolyphonicPressureMessage(byte channel, MIDINote note, byte pressure) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (pressure > 127) + { + throw new ArgumentOutOfRangeException(nameof(pressure), pressure, null); + } + + Channel = channel; + Note = note; + Pressure = pressure; + } + + internal override byte GetCMDByte() + { + return (byte)(0xA0 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Note); + w.WriteByte(Pressure); + } +} diff --git a/VG Music Studio - MIDI/Events/ProgramChangeMessage.cs b/VG Music Studio - MIDI/Events/ProgramChangeMessage.cs new file mode 100644 index 0000000..e8e8829 --- /dev/null +++ b/VG Music Studio - MIDI/Events/ProgramChangeMessage.cs @@ -0,0 +1,181 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class ProgramChangeMessage : MIDIMessage +{ + public byte Channel { get; } + + public MIDIProgram Program { get; } + + internal ProgramChangeMessage(EndianBinaryReader r, byte channel) + { + Channel = channel; + + Program = r.ReadEnum(); + if (Program >= MIDIProgram.MAX) + { + throw new InvalidDataException($"Invalid {nameof(ProgramChangeMessage)} program at 0x{r.Stream.Position - 1:X} ({Program})"); + } + } + + public ProgramChangeMessage(byte channel, MIDIProgram program) + { + if (channel > 15) + { + throw new ArgumentOutOfRangeException(nameof(channel), channel, null); + } + if (program >= MIDIProgram.MAX) + { + throw new ArgumentOutOfRangeException(nameof(program), program, null); + } + + Channel = channel; + Program = program; + } + + internal override byte GetCMDByte() + { + return (byte)(0xC0 + Channel); + } + + internal override void Write(EndianBinaryWriter w) + { + w.WriteEnum(Program); + } +} + +public enum MIDIProgram : byte +{ + AcousticGrandPiano, + BrightAcousticPiano, + ElectricGrandPiano, + HonkyTonkPiano, + ElectricPiano1, + ElectricPiano2, + Harpsichord, + Clavinet, + Celesta, + Glockenspiel, + MusicBox, + Vibraphone, + Marimba, + Xylophone, + TubularBells, + Dulcimer, + DrawbarOrgan, + PercussiveOrgan, + RockOrgan, + ChurchOrgan, + ReedOrgan, + Accordion, + Harmonica, + TangoAccordion, + AcousticGuitarNylon, + AcousticGuitarSteel, + ElectricGuitarJazz, + ElectricGuitarClean, + ElectricGuitarMuted, + OverdrivenGuitar, + DistortionGuitar, + GuitarHarmonics, + AcousticBass, + ElectricBassFinger, + ElectricBassPick, + FretlessBass, + SlapBass1, + SlapBass2, + SynthBass1, + SynthBass2, + Violin, + Viola, + Cello, + Contrabass, + TremoloStrings, + PizzicatoStrings, + OrchestralHarp, + Timpani, + StringEnsemble1, + StringEnsemble2, + SynthStrings1, + SynthStrings2, + ChoirAahs, + VoiceOohs, + SynthVoice, + OrchestraHit, + Trumpet, + Trombone, + Tuba, + MutedTrumpet, + FrenchHorn, + BrassSection, + SynthBrass1, + SynthBrass2, + SopranoSax, + AltoSax, + TenorSax, + BaritoneSax, + Oboe, + EnglishHorn, + Bassoon, + Clarinet, + Piccolo, + Flute, + Recorder, + PanFlute, + BlownBottle, + Shakuhachi, + Whistle, + Ocarina, + Lead1Square, + Lead2Sawtooth, + Lead3Calliope, + Lead4Chiff, + Lead5Charang, + Lead6Voice, + Lead7Fifths, + Lead8BassAndLead, + Pad1NewAge, + Pad2Warm, + Pad3Polysynth, + Pad4Choir, + Pad5Bowed, + Pad6Metallic, + Pad7Halo, + Pad8Sweep, + Fx1Rain, + Fx2Soundtrack, + Fx3Crystal, + Fx4Atmosphere, + Fx5Brightness, + Fx6Goblins, + Fx7Echoes, + Fx8SciFi, + Sitar, + Banjo, + Shamisen, + Koto, + Kalimba, + BagPipe, + Fiddle, + Shanai, + TinkleBell, + Agogo, + SteelDrums, + Woodblock, + TaikoDrum, + MelodicTom, + SynthDrum, + ReverseCymbal, + GuitarFretNoise, + BreathNoise, + Seashore, + BirdTweet, + TelephoneRing, + Helicopter, + Applause, + Gunshot, + MAX, +} \ No newline at end of file diff --git a/VG Music Studio - MIDI/Events/SysExContinuationMessage.cs b/VG Music Studio - MIDI/Events/SysExContinuationMessage.cs new file mode 100644 index 0000000..a55a906 --- /dev/null +++ b/VG Music Studio - MIDI/Events/SysExContinuationMessage.cs @@ -0,0 +1,47 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class SysExContinuationMessage : MIDIMessage +{ + public byte[] Data { get; } + + public bool IsFinished => Data[Data.Length - 1] == 0xF7; + + internal SysExContinuationMessage(EndianBinaryReader r) + { + long offset = r.Stream.Position; + + int len = MIDIFile.ReadVariableLength(r); + if (len == 0) + { + throw new InvalidDataException($"SysEx continuation message at 0x{offset:X} was empty"); + } + + Data = new byte[len]; + r.ReadBytes(Data); + } + + public SysExContinuationMessage(byte[] data) + { + if (data.Length == 0) + { + throw new ArgumentException("SysEx continuation message must not be empty"); + } + + Data = data; + } + + internal override byte GetCMDByte() + { + return 0xF7; + } + + internal override void Write(EndianBinaryWriter w) + { + MIDIFile.WriteVariableLength(w, Data.Length); + w.WriteBytes(Data); + } +} diff --git a/VG Music Studio - MIDI/Events/SysExMessage.cs b/VG Music Studio - MIDI/Events/SysExMessage.cs new file mode 100644 index 0000000..4364c3c --- /dev/null +++ b/VG Music Studio - MIDI/Events/SysExMessage.cs @@ -0,0 +1,47 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +public sealed class SysExMessage : MIDIMessage +{ + public byte[] Data { get; } + + public bool IsComplete => Data[Data.Length - 1] == 0xF7; + + internal SysExMessage(EndianBinaryReader r) + { + long offset = r.Stream.Position; + + int len = MIDIFile.ReadVariableLength(r); + if (len == 0) + { + throw new InvalidDataException($"SysEx message at 0x{offset:X} was empty"); + } + + Data = new byte[len]; + r.ReadBytes(Data); + } + + public SysExMessage(byte[] data) + { + if (data.Length == 0) + { + throw new ArgumentException("SysEx message must not be empty"); + } + + Data = data; + } + + internal override byte GetCMDByte() + { + return 0xF0; + } + + internal override void Write(EndianBinaryWriter w) + { + MIDIFile.WriteVariableLength(w, Data.Length); + w.WriteBytes(Data); + } +} diff --git a/VG Music Studio - MIDI/MIDIFile.cs b/VG Music Studio - MIDI/MIDIFile.cs new file mode 100644 index 0000000..fb2b858 --- /dev/null +++ b/VG Music Studio - MIDI/MIDIFile.cs @@ -0,0 +1,173 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections.Generic; +using System.IO; + +namespace Kermalis.VGMusicStudio.MIDI; + +// Section 2.1 +public enum MIDIFormat : ushort +{ + /// Contains a single multi-channel track + Format0, + /// Contains one or more simultaneous tracks + Format1, + /// Contains one or more independent single-track patterns + Format2, +} + +// https://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html +// http://www.somascape.org/midi/tech/mfile.html +public sealed class MIDIFile +{ + private readonly List _nonHeaderChunks; // Not really important to expose this at the moment + + public MIDIHeaderChunk HeaderChunk { get; } + + private readonly List _tracks; + + public MIDITrackChunk this[int index] + { + get => _tracks[index]; + set => _tracks[index] = value; + } + + public MIDIFile(MIDIFormat format, TimeDivisionValue timeDivision, int tracksInitialCapacity) + { + if (format == MIDIFormat.Format0 && tracksInitialCapacity != 1) + { + throw new ArgumentException("Format 0 must have 1 track", nameof(tracksInitialCapacity)); + } + + HeaderChunk = new MIDIHeaderChunk(format, timeDivision); + _nonHeaderChunks = new List(tracksInitialCapacity); + _tracks = new List(tracksInitialCapacity); + } + public MIDIFile(Stream stream) + { + var r = new EndianBinaryReader(stream, endianness: Endianness.BigEndian, ascii: true); + string chunkName = r.ReadString_Count(4); + if (chunkName != MIDIHeaderChunk.EXPECTED_NAME) + { + throw new InvalidDataException("MIDI header was not at the start of the file"); + } + + HeaderChunk = (MIDIHeaderChunk)ReadChunk(r, alreadyReadName: chunkName); + _nonHeaderChunks = new List(HeaderChunk.NumTracks); + _tracks = new List(HeaderChunk.NumTracks); + + while (stream.Position < stream.Length) + { + MIDIChunk c = ReadChunk(r); + _nonHeaderChunks.Add(c); + if (c is MIDITrackChunk tc) + { + _tracks.Add(tc); + } + } + + if (_tracks.Count != HeaderChunk.NumTracks) + { + throw new InvalidDataException($"Unexpected track count: (Expected {HeaderChunk.NumTracks} but found {_tracks.Count}"); + } + } + + private static MIDIChunk ReadChunk(EndianBinaryReader r, string? alreadyReadName = null) + { + string chunkName = alreadyReadName ?? r.ReadString_Count(4); + uint chunkSize = r.ReadUInt32(); + switch (chunkName) + { + case MIDIHeaderChunk.EXPECTED_NAME: return new MIDIHeaderChunk(chunkSize, r); + case MIDITrackChunk.EXPECTED_NAME: return new MIDITrackChunk(chunkSize, r); + default: return new MIDIUnsupportedChunk(chunkName, chunkSize, r); + } + } + + internal static int ReadVariableLength(EndianBinaryReader r) + { + int value = r.ReadByte(); + + if ((value & 0x80) != 0) + { + value &= 0x7F; + + byte c; + do + { + c = r.ReadByte(); + value = (value << 7) + (c & 0x7F); + } while ((c & 0x80) != 0); + } + + return value; + } + internal static void WriteVariableLength(EndianBinaryWriter w, int value) + { + int buffer = value & 0x7F; + while ((value >>= 7) > 0) + { + buffer <<= 8; + buffer |= 0x80; + buffer += value & 0x7F; + } + + while (true) + { + w.WriteByte((byte)buffer); + if ((buffer & 0x80) == 0) + { + break; + } + buffer >>= 8; + } + } + internal static int GetVariableLengthNumBytes(int value) + { + int buffer = value & 0x7F; + while ((value >>= 7) > 0) + { + buffer <<= 8; + buffer |= 0x80; + buffer += value & 0x7F; + } + + int numBytes = 0; + while (true) + { + numBytes++; + if ((buffer & 0x80) == 0) + { + break; + } + buffer >>= 8; + } + + return numBytes; + } + + public MIDITrackChunk CreateTrack() + { + var tc = new MIDITrackChunk(); + _nonHeaderChunks.Add(tc); + _tracks.Add(tc); + HeaderChunk.NumTracks++; + + return tc; + } + + public void Save(string fileName) + { + using (FileStream stream = File.Create(fileName)) + { + var w = new EndianBinaryWriter(stream, endianness: Endianness.BigEndian, ascii: true); + + HeaderChunk.Write(w); + + foreach (MIDIChunk c in _nonHeaderChunks) + { + c.Write(w); + } + } + } +} diff --git a/VG Music Studio - MIDI/MIDINote.cs b/VG Music Studio - MIDI/MIDINote.cs new file mode 100644 index 0000000..e7de7bc --- /dev/null +++ b/VG Music Studio - MIDI/MIDINote.cs @@ -0,0 +1,134 @@ +namespace Kermalis.VGMusicStudio.MIDI; + +public enum MIDINote : byte +{ + C_M1, + Db_M1, + D_M1, + Eb_M1, + E_M1, + F_M1, + Gb_M1, + G_M1, + Ab_M1, + A_M1, + Bb_M1, + B_M1, + C_0, + Db_0, + D_0, + Eb_0, + E_0, + F_0, + Gb_0, + G_0, + Ab_0, + A_0, + Bb_0, + B_0, + C_1, + Db_1, + D_1, + Eb_1, + E_1, + F_1, + Gb_1, + G_1, + Ab_1, + A_1, + Bb_1, + B_1, + C_2, + Db_2, + D_2, + Eb_2, + E_2, + F_2, + Gb_2, + G_2, + Ab_2, + A_2, + Bb_2, + B_2, + C_3, + Db_3, + D_3, + Eb_3, + E_3, + F_3, + Gb_3, + G_3, + Ab_3, + A_3, + Bb_3, + B_3, + C_4, + Db_4, + D_4, + Eb_4, + E_4, + F_4, + Gb_4, + G_4, + Ab_4, + A_4, + Bb_4, + B_4, + C_5, + Db_5, + D_5, + Eb_5, + E_5, + F_5, + Gb_5, + G_5, + Ab_5, + A_5, + Bb_5, + B_5, + C_6, + Db_6, + D_6, + Eb_6, + E_6, + F_6, + Gb_6, + G_6, + Ab_6, + A_6, + Bb_6, + B_6, + C_7, + Db_7, + D_7, + Eb_7, + E_7, + F_7, + Gb_7, + G_7, + Ab_7, + A_7, + Bb_7, + B_7, + C_8, + Db_8, + D_8, + Eb_8, + E_8, + F_8, + Gb_8, + G_8, + Ab_8, + A_8, + Bb_8, + B_8, + C_9, + Db_9, + D_9, + Eb_9, + E_9, + F_9, + Gb_9, + G_9, + MAX, +} diff --git a/VG Music Studio - MIDI/TimeDivisionValue.cs b/VG Music Studio - MIDI/TimeDivisionValue.cs new file mode 100644 index 0000000..87f783e --- /dev/null +++ b/VG Music Studio - MIDI/TimeDivisionValue.cs @@ -0,0 +1,63 @@ +namespace Kermalis.VGMusicStudio.MIDI; + +public enum DivisionType : byte +{ + PPQN, + SMPTE, +} + +public enum SMPTEFormat : byte +{ + Smpte24 = 24, + Smpte25 = 25, + Smpte30Drop = 29, + Smpte30 = 30, +} + +// Section 2.1 +public readonly struct TimeDivisionValue +{ + public const int PPQN_MIN_DIVISION = 24; + + public readonly ushort RawValue; + + public DivisionType Type => (DivisionType)(RawValue >> 15); + + public ushort PPQN_TicksPerQuarterNote => RawValue; // Type bit is already 0 + + public SMPTEFormat SMPTE_Format => (SMPTEFormat)(-(sbyte)(RawValue >> 8)); // Upper 8 bits, negated + public byte SMPTE_TicksPerFrame => (byte)RawValue; // Lower 8 bits + + public TimeDivisionValue(ushort rawValue) + { + RawValue = rawValue; + } + + public static TimeDivisionValue CreatePPQN(ushort ticksPerQuarterNote) + { + return new TimeDivisionValue(ticksPerQuarterNote); + } + public static TimeDivisionValue CreateSMPTE(SMPTEFormat format, byte ticksPerFrame) + { + ushort rawValue = (ushort)((-(sbyte)format) << 8); + rawValue |= ticksPerFrame; + + return new TimeDivisionValue(rawValue); + } + + public bool Validate() + { + if (Type == DivisionType.PPQN) + { + return PPQN_TicksPerQuarterNote >= PPQN_MIN_DIVISION; + } + + // SMPTE + return SMPTE_Format is SMPTEFormat.Smpte24 or SMPTEFormat.Smpte25 or SMPTEFormat.Smpte30Drop or SMPTEFormat.Smpte30; + } + + public override string ToString() + { + return string.Format("0x{0:X4}", RawValue); + } +} diff --git a/VG Music Studio - MIDI/VG Music Studio - MIDI.csproj b/VG Music Studio - MIDI/VG Music Studio - MIDI.csproj new file mode 100644 index 0000000..ef1e119 --- /dev/null +++ b/VG Music Studio - MIDI/VG Music Studio - MIDI.csproj @@ -0,0 +1,15 @@ + + + + net6.0 + Library + latest + Kermalis.VGMusicStudio.MIDI + enable + + + + + + + diff --git a/VG Music Studio - WinForms/MainForm.cs b/VG Music Studio - WinForms/MainForm.cs index 8820c08..43c381d 100644 --- a/VG Music Studio - WinForms/MainForm.cs +++ b/VG Music Studio - WinForms/MainForm.cs @@ -7,7 +7,6 @@ using Kermalis.VGMusicStudio.Core.Util; using Kermalis.VGMusicStudio.WinForms.Properties; using Kermalis.VGMusicStudio.WinForms.Util; -using Microsoft.WindowsAPICodePack.Taskbar; using System; using System.Collections.Generic; using System.ComponentModel; @@ -28,14 +27,15 @@ internal sealed class MainForm : ThemedForm public readonly bool[] PianoTracks; - private PlayingPlaylist? _playlist; - private int _curSong = -1; + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSongs; + private readonly List _remainingSongs; private TrackViewer? _trackViewer; - private bool _songEnded = false; - private bool _positionBarFree = true; - private bool _autoplay = false; + private bool _stopUI = false; #region Controls @@ -51,19 +51,21 @@ internal sealed class MainForm : ThemedForm private readonly ColorSlider _volumeBar, _positionBar; private readonly SongInfoControl _songInfo; private readonly ImageComboBox _songsComboBox; - private readonly TaskbarPlayerButtons? _taskbar; #endregion private MainForm() { + _playedSongs = new List(); + _remainingSongs = new List(); + PianoTracks = new bool[SongState.MAX_TRACKS]; for (int i = 0; i < SongState.MAX_TRACKS; i++) { PianoTracks[i] = true; } - Mixer.VolumeChanged += Mixer_VolumeChanged; + Mixer.MixerVolumeChanged += SetVolumeBarValue; // File Menu _openDSEItem = new ToolStripMenuItem { Text = Strings.MenuOpenDSE }; @@ -103,11 +105,11 @@ private MainForm() // Buttons _playButton = new ThemedButton { Enabled = false, ForeColor = Color.MediumSpringGreen, Text = Strings.PlayerPlay }; - _playButton.Click += PlayButton_Click; + _playButton.Click += (o, e) => Play(); _pauseButton = new ThemedButton { Enabled = false, ForeColor = Color.DeepSkyBlue, Text = Strings.PlayerPause }; - _pauseButton.Click += PauseButton_Click; + _pauseButton.Click += (o, e) => Pause(); _stopButton = new ThemedButton { Enabled = false, ForeColor = Color.MediumVioletRed, Text = Strings.PlayerStop }; - _stopButton.Click += StopButton_Click; + _stopButton.Click += (o, e) => Stop(); // Numerical _songNumerical = new ThemedNumeric { Enabled = false, Minimum = 0, Visible = false }; @@ -115,7 +117,7 @@ private MainForm() // Timer _timer = new Timer(); - _timer.Tick += Timer_Tick; + _timer.Tick += UpdateUI; // Piano _piano = new PianoControl(); @@ -149,112 +151,152 @@ private MainForm() Resize += OnResize; Text = ConfigUtils.PROGRAM_NAME; - // Taskbar Buttons - if (TaskbarManager.IsPlatformSupported) + OnResize(null, null); + } + + private void VolumeBar_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume(_volumeBar.Value / (float)_volumeBar.Maximum); + } + public void SetVolumeBarValue(float volume) + { + _volumeBar.ValueChanged -= VolumeBar_ValueChanged; + _volumeBar.Value = (int)(volume * _volumeBar.Maximum); + _volumeBar.ValueChanged += VolumeBar_ValueChanged; + } + private bool _positionBarFree = true; + private void PositionBar_MouseUp(object? sender, MouseEventArgs? e) + { + if (e.Button == MouseButtons.Left) { - _taskbar = new TaskbarPlayerButtons(Handle); + Engine.Instance.Player.SetCurrentPosition(_positionBar.Value); + _positionBarFree = true; + LetUIKnowPlayerIsPlaying(); + } + } + private void PositionBar_MouseDown(object? sender, MouseEventArgs? e) + { + if (e.Button == MouseButtons.Left) + { + _positionBarFree = false; } - - OnResize(null, EventArgs.Empty); } - private void SongNumerical_ValueChanged(object? sender, EventArgs e) + private bool _autoplay = false; + private void SongNumerical_ValueChanged(object? sender, EventArgs? e) { _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; - int index = (int)_songNumerical.Value; + long index = (long)_songNumerical.Value; Stop(); Text = ConfigUtils.PROGRAM_NAME; _songsComboBox.SelectedIndex = 0; _songInfo.Reset(); - - Player player = Engine.Instance!.Player; - Config cfg = Engine.Instance.Config; + bool success; try { - player.LoadSong(index); + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) } catch (Exception ex) { - FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, cfg.GetSongName(index))); + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; } _trackViewer?.UpdateTracks(); - ILoadedSong? loadedSong = player.LoadedSong; // LoadedSong is still null when there are no tracks - if (loadedSong is not null) + if (success) { - List songs = cfg.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 - int songIndex = songs.FindIndex(s => s.Index == index); - if (songIndex != -1) + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) { - Text = $"{ConfigUtils.PROGRAM_NAME} ― {songs[songIndex].Name}"; // TODO: Make this a func - _songsComboBox.SelectedIndex = songIndex + 1; // + 1 because the "Music" playlist is first in the combobox + Text = $"{ConfigUtils.PROGRAM_NAME} ― {song.Name}"; // TODO: Make this a func + _songsComboBox.SelectedIndex = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - _positionBar.Maximum = loadedSong.MaxTicks; + _positionBar.Maximum = Engine.Instance!.Player.LoadedSong!.MaxTicks; _positionBar.LargeChange = _positionBar.Maximum / 10; _positionBar.SmallChange = _positionBar.LargeChange / 4; - _songInfo.SetNumTracks(loadedSong.Events.Length); + _songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) { Play(); } - _positionBar.Enabled = true; - _exportWAVItem.Enabled = true; - _exportMIDIItem.Enabled = MP2KEngine.MP2KInstance is not null; - _exportDLSItem.Enabled = _exportSF2Item.Enabled = AlphaDreamEngine.AlphaDreamInstance is not null; } else { _songInfo.SetNumTracks(0); - _positionBar.Enabled = false; - _exportWAVItem.Enabled = false; - _exportMIDIItem.Enabled = false; - _exportDLSItem.Enabled = false; - _exportSF2Item.Enabled = false; } + _positionBar.Enabled = _exportWAVItem.Enabled = success; + _exportMIDIItem.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Enabled = _exportSF2Item.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; _autoplay = true; _songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; } - private void SongsComboBox_SelectedIndexChanged(object? sender, EventArgs e) + private void SongsComboBox_SelectedIndexChanged(object? sender, EventArgs? e) { var item = (ImageComboBoxItem)_songsComboBox.SelectedItem; - switch (item.Item) + if (item.Item is Config.Song song) { - case Config.Song song: + SetAndLoadSong(song.Index); + } + else if (item.Item is Config.Playlist playlist) + { + if (playlist.Songs.Count > 0 + && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) { - SetAndLoadSong(song.Index); - break; + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endPlaylistItem.Enabled = true; + SetAndLoadNextPlaylistSong(); } - case Config.Playlist playlist: + } + } + private void SetAndLoadSong(long index) + { + _curSong = index; + if (_songNumerical.Value == index) + { + SongNumerical_ValueChanged(null, null); + } + else + { + _songNumerical.Value = index; + } + } + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSongs.Count == 0) + { + _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) { - if (playlist.Songs.Count > 0 - && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) - { - ResetPlaylistStuff(false); - Engine.Instance!.Player.ShouldFadeOut = true; - Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; - _endPlaylistItem.Enabled = true; - _playlist = new PlayingPlaylist(playlist); - _playlist.SetAndLoadNextSong(); - } - break; + _remainingSongs.Shuffle(); } } + long nextSong = _remainingSongs[0]; + _remainingSongs.RemoveAt(0); + SetAndLoadSong(nextSong); } - private void ResetPlaylistStuff(bool numericalAndComboboxEnabled) + private void ResetPlaylistStuff(bool enableds) { - if (Engine.Instance is not null) + if (Engine.Instance != null) { Engine.Instance.Player.ShouldFadeOut = false; } + _playlistPlaying = false; + _curPlaylist = null; _curSong = -1; - _playlist = null; + _remainingSongs.Clear(); + _playedSongs.Clear(); _endPlaylistItem.Enabled = false; - _songNumerical.Enabled = numericalAndComboboxEnabled; - _songsComboBox.Enabled = numericalAndComboboxEnabled; + _songNumerical.Enabled = _songsComboBox.Enabled = enableds; } - private void EndCurrentPlaylist(object? sender, EventArgs e) + private void EndCurrentPlaylist(object? sender, EventArgs? e) { if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, MessageBoxButtons.YesNo) == DialogResult.Yes) { @@ -262,7 +304,7 @@ private void EndCurrentPlaylist(object? sender, EventArgs e) } } - private void OpenDSE(object? sender, EventArgs e) + private void OpenDSE(object? sender, EventArgs? e) { var d = new FolderBrowserDialog { @@ -292,10 +334,16 @@ private void OpenDSE(object? sender, EventArgs e) _exportMIDIItem.Visible = false; _exportSF2Item.Visible = false; } - private void OpenAlphaDream(object? sender, EventArgs e) + private void OpenAlphaDream(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".gba", Strings.MenuOpenAlphaDream, Strings.FilterOpenGBA + " (*.gba)|*.gba"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenAlphaDream, + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -303,7 +351,7 @@ private void OpenAlphaDream(object? sender, EventArgs e) DisposeEngine(); try { - _ = new AlphaDreamEngine(File.ReadAllBytes(inFile)); + _ = new AlphaDreamEngine(File.ReadAllBytes(d.FileName)); } catch (Exception ex) { @@ -318,10 +366,16 @@ private void OpenAlphaDream(object? sender, EventArgs e) _exportMIDIItem.Visible = false; _exportSF2Item.Visible = true; } - private void OpenMP2K(object? sender, EventArgs e) + private void OpenMP2K(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".gba", Strings.MenuOpenMP2K, Strings.FilterOpenGBA + " (*.gba)|*.gba"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenMP2K, + Filter = Strings.FilterOpenGBA, + FilterIndex = 1, + DefaultExt = ".gba" + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -329,7 +383,7 @@ private void OpenMP2K(object? sender, EventArgs e) DisposeEngine(); try { - _ = new MP2KEngine(File.ReadAllBytes(inFile)); + _ = new MP2KEngine(File.ReadAllBytes(d.FileName)); } catch (Exception ex) { @@ -344,10 +398,16 @@ private void OpenMP2K(object? sender, EventArgs e) _exportMIDIItem.Visible = true; _exportSF2Item.Visible = false; } - private void OpenSDAT(object? sender, EventArgs e) + private void OpenSDAT(object? sender, EventArgs? e) { - string? inFile = WinFormsUtils.CreateLoadDialog(".sdat", Strings.MenuOpenSDAT, Strings.FilterOpenSDAT + " (*.sdat)|*.sdat"); - if (inFile is null) + var d = new OpenFileDialog + { + Title = Strings.MenuOpenSDAT, + Filter = Strings.FilterOpenSDAT, + FilterIndex = 1, + DefaultExt = ".sdat", + }; + if (d.ShowDialog() != DialogResult.OK) { return; } @@ -355,10 +415,7 @@ private void OpenSDAT(object? sender, EventArgs e) DisposeEngine(); try { - using (FileStream stream = File.OpenRead(inFile)) - { - _ = new SDATEngine(new SDAT(stream)); - } + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.FileName))); } catch (Exception ex) { @@ -374,81 +431,114 @@ private void OpenSDAT(object? sender, EventArgs e) _exportSF2Item.Visible = false; } - private void ExportDLS(object? sender, EventArgs e) + private void ExportDLS(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - string? outFile = WinFormsUtils.CreateSaveDialog(cfg.GetGameName(), ".dls", Strings.MenuSaveDLS, Strings.FilterSaveDLS + " (*.dls)|*.dls"); - if (outFile is null) + + var d = new SaveFileDialog + { + FileName = cfg.GetGameName(), + DefaultExt = ".dls", + ValidateNames = true, + Title = Strings.MenuSaveDLS, + Filter = Strings.FilterSaveDLS, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } try { - AlphaDreamSoundFontSaver_DLS.Save(cfg, outFile); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, outFile), Text); + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); } } - private void ExportMIDI(object? sender, EventArgs e) + private void ExportMIDI(object? sender, EventArgs? e) { - string songName = Engine.Instance!.Config.GetSongName((int)_songNumerical.Value); - string? outFile = WinFormsUtils.CreateSaveDialog(songName, ".mid", Strings.MenuSaveMIDI, Strings.FilterSaveMIDI + " (*.mid;*.midi)|*.mid;*.midi"); - if (outFile is null) + var d = new SaveFileDialog + { + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".mid", + ValidateNames = true, + Title = Strings.MenuSaveMIDI, + Filter = Strings.FilterSaveMIDI, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; - var args = new MIDISaveArgs(true, false, new (int AbsoluteTick, (byte Numerator, byte Denominator))[] + var args = new MIDISaveArgs { - (0, (4, 4)), - }); + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; try { - p.SaveAsMIDI(outFile, args); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, outFile), Text); + p.SaveAsMIDI(d.FileName, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); } } - private void ExportSF2(object? sender, EventArgs e) + private void ExportSF2(object? sender, EventArgs? e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - string? outFile = WinFormsUtils.CreateSaveDialog(cfg.GetGameName(), ".sf2", Strings.MenuSaveSF2, Strings.FilterSaveSF2 + " (*.sf2)|*.sf2"); - if (outFile is null) + + var d = new SaveFileDialog + { + FileName = cfg.GetGameName(), + DefaultExt = ".sf2", + ValidateNames = true, + Title = Strings.MenuSaveSF2, + Filter = Strings.FilterSaveSF2, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } try { - AlphaDreamSoundFontSaver_SF2.Save(outFile, cfg); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, outFile), Text); + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, d.FileName), Text); } catch (Exception ex) { FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); } } - private void ExportWAV(object? sender, EventArgs e) + private void ExportWAV(object? sender, EventArgs? e) { - string songName = Engine.Instance!.Config.GetSongName((int)_songNumerical.Value); - string? outFile = WinFormsUtils.CreateSaveDialog(songName, ".wav", Strings.MenuSaveWAV, Strings.FilterSaveWAV + " (*.wav)|*.wav"); - if (outFile is null) + var d = new SaveFileDialog + { + FileName = Engine.Instance!.Config.GetSongName((long)_songNumerical.Value), + DefaultExt = ".wav", + ValidateNames = true, + Title = Strings.MenuSaveWAV, + Filter = Strings.FilterSaveWAV, + }; + if (d.ShowDialog() != DialogResult.OK) { return; } Stop(); - Player player = Engine.Instance.Player; + IPlayer player = Engine.Instance.Player; bool oldFade = player.ShouldFadeOut; long oldLoops = player.NumLoops; player.ShouldFadeOut = true; @@ -456,8 +546,8 @@ private void ExportWAV(object? sender, EventArgs e) try { - player.Record(outFile); - FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, outFile), Text); + player.Record(d.FileName); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, d.FileName), Text); } catch (Exception ex) { @@ -466,9 +556,21 @@ private void ExportWAV(object? sender, EventArgs e) player.ShouldFadeOut = oldFade; player.NumLoops = oldLoops; - _songEnded = false; // Don't make UI do anything about the song ended event + _stopUI = false; } + public void LetUIKnowPlayerIsPlaying() + { + if (_timer.Enabled) + { + return; + } + + _pauseButton.Enabled = _stopButton.Enabled = true; + _pauseButton.Text = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + _timer.Start(); + } private void Play() { Engine.Instance!.Player.Play(); @@ -476,7 +578,7 @@ private void Play() } private void Pause() { - Engine.Instance!.Player.TogglePlaying(); + Engine.Instance!.Player.Pause(); if (Engine.Instance.Player.State == PlayerState.Paused) { _pauseButton.Text = Strings.PlayerUnpause; @@ -487,26 +589,58 @@ private void Pause() _pauseButton.Text = Strings.PlayerPause; _timer.Start(); } - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); } private void Stop() { Engine.Instance!.Player.Stop(); - _pauseButton.Enabled = false; - _stopButton.Enabled = false; + _pauseButton.Enabled = _stopButton.Enabled = false; _pauseButton.Text = Strings.PlayerPause; _timer.Stop(); _songInfo.Reset(); _piano.UpdateKeys(_songInfo.Info.Tracks, PianoTracks); UpdatePositionIndicators(0L); - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSong(object? sender, EventArgs? e) + { + long prevSong; + if (_playlistPlaying) + { + int index = _playedSongs.Count - 1; + prevSong = _playedSongs[index]; + _playedSongs.RemoveAt(index); + _remainingSongs.Insert(0, _curSong); + } + else + { + prevSong = (long)_songNumerical.Value - 1; + } + SetAndLoadSong(prevSong); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSongs.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSong((long)_songNumerical.Value + 1); + } } private void FinishLoading(long numSongs) { - Engine.Instance!.Player.SongEnded += Player_SongEnded; + Engine.Instance!.Player.SongEnded += SongEnded; foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) { _songsComboBox.Items.Add(new ImageComboBoxItem(playlist, Resources.IconPlaylist, 0)); @@ -519,7 +653,6 @@ private void FinishLoading(long numSongs) _autoplay = false; SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = true; - UpdateTaskbarButtons(); } private void DisposeEngine() { @@ -529,116 +662,71 @@ private void DisposeEngine() Engine.Instance.Dispose(); } - Text = ConfigUtils.PROGRAM_NAME; _trackViewer?.UpdateTracks(); - _taskbar?.DisableAll(); - _songsComboBox.Enabled = false; - _songNumerical.Enabled = false; - _playButton.Enabled = false; - _volumeBar.Enabled = false; - _positionBar.Enabled = false; + Text = ConfigUtils.PROGRAM_NAME; _songInfo.SetNumTracks(0); _songInfo.ResetMutes(); ResetPlaylistStuff(false); UpdatePositionIndicators(0L); - TaskbarPlayerButtons.UpdateState(); - _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged -= SongNumerical_ValueChanged; - _songNumerical.Visible = false; + _songNumerical.Value = _songNumerical.Maximum = 0; _songsComboBox.SelectedItem = null; _songsComboBox.Items.Clear(); - _songsComboBox.SelectedIndexChanged += SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged += SongNumerical_ValueChanged; } - private void UpdatePositionIndicators(long ticks) + private void UpdateUI(object? sender, EventArgs? e) { - if (_positionBarFree) + if (_stopUI) { - _positionBar.Value = ticks; + _stopUI = false; + if (_playlistPlaying) + { + _playedSongs.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + Stop(); + } } - if (GlobalConfig.Instance.TaskbarProgress && TaskbarManager.IsPlatformSupported) + else { - TaskbarManager.Instance.SetProgressValue((int)ticks, (int)_positionBar.Maximum); + if (WindowState != FormWindowState.Minimized) + { + SongState info = _songInfo.Info; + Engine.Instance!.Player.UpdateSongState(info); + _piano.UpdateKeys(info.Tracks, PianoTracks); + _songInfo.Invalidate(); + } + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); } } - private void UpdateTaskbarButtons() + private void SongEnded() { - _taskbar?.UpdateButtons(_playlist, _curSong, (int)_songNumerical.Maximum); + _stopUI = true; } - - private void OpenTrackViewer(object? sender, EventArgs e) + private void UpdatePositionIndicators(long ticks) { - if (_trackViewer is not null) + if (_positionBarFree) { - _trackViewer.Focus(); - return; + _positionBar.Value = ticks; } - - _trackViewer = new TrackViewer { Owner = this }; - _trackViewer.FormClosed += TrackViewer_FormClosed; - _trackViewer.Show(); } - public void TogglePlayback() - { - switch (Engine.Instance!.Player.State) - { - case PlayerState.Stopped: Play(); break; - case PlayerState.Paused: - case PlayerState.Playing: Pause(); break; - } - } - public void PlayPreviousSong() + private void OpenTrackViewer(object? sender, EventArgs? e) { - if (_playlist is not null) - { - _playlist.UndoThenSetAndLoadPrevSong(_curSong); - } - else - { - SetAndLoadSong((int)_songNumerical.Value - 1); - } - } - public void PlayNextSong() - { - if (_playlist is not null) - { - _playlist.AdvanceThenSetAndLoadNextSong(_curSong); - } - else - { - SetAndLoadSong((int)_songNumerical.Value + 1); - } - } - public void LetUIKnowPlayerIsPlaying() - { - if (_timer.Enabled) + if (_trackViewer is not null) { + _trackViewer.Focus(); return; } - _pauseButton.Enabled = true; - _stopButton.Enabled = true; - _pauseButton.Text = Strings.PlayerPause; - _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); - _timer.Start(); - TaskbarPlayerButtons.UpdateState(); - UpdateTaskbarButtons(); - } - public void SetAndLoadSong(int index) - { - _curSong = index; - if (_songNumerical.Value == index) - { - SongNumerical_ValueChanged(null, EventArgs.Empty); - } - else - { - _songNumerical.Value = index; - } + _trackViewer = new TrackViewer { Owner = this }; + _trackViewer.FormClosed += (o, s) => _trackViewer = null; + _trackViewer.Show(); } protected override void OnFormClosing(FormClosingEventArgs e) @@ -646,7 +734,7 @@ protected override void OnFormClosing(FormClosingEventArgs e) DisposeEngine(); base.OnFormClosing(e); } - private void OnResize(object? sender, EventArgs e) + private void OnResize(object? sender, EventArgs? e) { if (WindowState == FormWindowState.Minimized) { @@ -693,7 +781,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Space && _playButton.Enabled && !_songsComboBox.Focused) { - TogglePlayback(); + TogglePlayback(null, null); return true; } return base.ProcessCmdKey(ref msg, keyData); @@ -707,78 +795,4 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } - - private void Timer_Tick(object? sender, EventArgs e) - { - if (_songEnded) - { - _songEnded = false; - if (_playlist is not null) - { - _playlist.AdvanceThenSetAndLoadNextSong(_curSong); - } - else - { - Stop(); - } - } - else - { - Player player = Engine.Instance!.Player; - if (WindowState != FormWindowState.Minimized) - { - SongState info = _songInfo.Info; - player.UpdateSongState(info); - _piano.UpdateKeys(info.Tracks, PianoTracks); - _songInfo.Invalidate(); - } - UpdatePositionIndicators(player.ElapsedTicks); - } - } - private void Mixer_VolumeChanged(float volume) - { - _volumeBar.ValueChanged -= VolumeBar_ValueChanged; - _volumeBar.Value = (int)(volume * _volumeBar.Maximum); - _volumeBar.ValueChanged += VolumeBar_ValueChanged; - } - private void Player_SongEnded() - { - _songEnded = true; - } - private void VolumeBar_ValueChanged(object? sender, EventArgs e) - { - Engine.Instance!.Mixer.SetVolume(_volumeBar.Value / (float)_volumeBar.Maximum); - } - private void PositionBar_MouseUp(object? sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - Engine.Instance!.Player.SetSongPosition(_positionBar.Value); - _positionBarFree = true; - LetUIKnowPlayerIsPlaying(); - } - } - private void PositionBar_MouseDown(object? sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - _positionBarFree = false; - } - } - private void PlayButton_Click(object? sender, EventArgs e) - { - Play(); - } - private void PauseButton_Click(object? sender, EventArgs e) - { - Pause(); - } - private void StopButton_Click(object? sender, EventArgs e) - { - Stop(); - } - private void TrackViewer_FormClosed(object? sender, FormClosedEventArgs e) - { - _trackViewer = null; - } } diff --git a/VG Music Studio - WinForms/PianoControl.cs b/VG Music Studio - WinForms/PianoControl.cs index 9c87c2d..e7947a3 100644 --- a/VG Music Studio - WinForms/PianoControl.cs +++ b/VG Music Studio - WinForms/PianoControl.cs @@ -33,25 +33,73 @@ namespace Kermalis.VGMusicStudio.WinForms; [DesignerCategory("")] -internal sealed partial class PianoControl : Control +internal sealed class PianoControl : Control { private enum KeyType : byte { Black, - White, + White } private const double BLACK_KEY_SCALE = 2.0 / 3; public const int WHITE_KEY_COUNT = 75; - private static ReadOnlySpan KeyTypeTable => new KeyType[12] + private static readonly KeyType[] KeyTypeTable = new KeyType[12] { - // C C# D D# E KeyType.White, KeyType.Black, KeyType.White, KeyType.Black, KeyType.White, - // F F# G G# A A# B KeyType.White, KeyType.Black, KeyType.White, KeyType.Black, KeyType.White, KeyType.Black, KeyType.White, }; + public sealed class PianoKey : Control + { + public bool PrevPressed; + public bool Pressed; + + public readonly SolidBrush OnBrush; + private readonly SolidBrush _offBrush; + + public PianoKey(byte k) + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); + SetStyle(ControlStyles.Selectable, false); + + OnBrush = new(Color.Transparent); + byte l; + if (KeyTypeTable[k % 12] == KeyType.White) + { + if (k / 12 % 2 == 0) + { + l = 240; + } + else + { + l = 120; + } + } + else + { + l = 0; + } + _offBrush = new SolidBrush(HSLColor.ToColor(160, 0, l)); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + OnBrush.Dispose(); + _offBrush.Dispose(); + } + base.Dispose(disposing); + } + protected override void OnPaint(PaintEventArgs e) + { + e.Graphics.FillRectangle(Pressed ? OnBrush : _offBrush, 1, 1, Width - 2, Height - 2); + e.Graphics.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1); + base.OnPaint(e); + } + } + private readonly PianoKey[] _keys; public int WhiteKeyWidth; @@ -104,8 +152,8 @@ public void UpdateKeys(SongState.Track[] tracks, bool[] enabledTracks) for (int k = 0; k <= 0x7F; k++) { PianoKey key = _keys[k]; - key.PrevIsHeld = key.IsHeld; - key.IsHeld = false; + key.PrevPressed = key.Pressed; + key.Pressed = false; } for (int i = SongState.MAX_TRACKS - 1; i >= 0; i--) { @@ -125,13 +173,13 @@ public void UpdateKeys(SongState.Track[] tracks, bool[] enabledTracks) PianoKey key = _keys[k]; key.OnBrush.Color = GlobalConfig.Instance.Colors[track.Voice]; - key.IsHeld = true; + key.Pressed = true; } } for (int k = 0; k <= 0x7F; k++) { PianoKey key = _keys[k]; - if (key.IsHeld != key.PrevIsHeld) + if (key.Pressed != key.PrevPressed) { key.Invalidate(); } diff --git a/VG Music Studio - WinForms/PianoControl_PianoKey.cs b/VG Music Studio - WinForms/PianoControl_PianoKey.cs deleted file mode 100644 index 5fb41f3..0000000 --- a/VG Music Studio - WinForms/PianoControl_PianoKey.cs +++ /dev/null @@ -1,86 +0,0 @@ -using Kermalis.VGMusicStudio.Core.Util; -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace Kermalis.VGMusicStudio.WinForms; - -partial class PianoControl -{ - private sealed class PianoKey : Control - { - public bool PrevIsHeld; - public bool IsHeld; - - public readonly SolidBrush OnBrush; - private readonly SolidBrush _offBrush; - - private readonly string? _cName; - - public PianoKey(byte k) - { - SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); - SetStyle(ControlStyles.Selectable, false); - - OnBrush = new(Color.Transparent); - byte c; - if (KeyTypeTable[k % 12] == KeyType.White) - { - if (k / 12 % 2 == 0) - { - c = 255; - } - else - { - c = 127; - } - } - else - { - c = 0; - } - _offBrush = new SolidBrush(Color.FromArgb(c, c, c)); - - if (k % 12 == 0) - { - _cName = ConfigUtils.GetKeyName(k); - Font = new Font(Font.FontFamily, GetFontSize()); - } - } - - private float GetFontSize() - { - return Math.Max(1, Width / 2.75f); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - OnBrush.Dispose(); - _offBrush.Dispose(); - } - base.Dispose(disposing); - } - protected override void OnPaint(PaintEventArgs e) - { - e.Graphics.FillRectangle(IsHeld ? OnBrush : _offBrush, 1, 1, Width - 2, Height - 2); - e.Graphics.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1); - - if (_cName is not null) - { - SizeF strSize = e.Graphics.MeasureString(_cName, Font); - float x = (Width - strSize.Width) / 2f; - float y = Height - strSize.Height - 2; - e.Graphics.DrawString(_cName, Font, Brushes.Black, new RectangleF(x, y, 0, 0)); - } - - base.OnPaint(e); - } - protected override void OnResize(EventArgs e) - { - Font = new Font(Font.FontFamily, GetFontSize()); - base.OnResize(e); - } - } -} diff --git a/VG Music Studio - WinForms/PlayingPlaylist.cs b/VG Music Studio - WinForms/PlayingPlaylist.cs deleted file mode 100644 index 100f88f..0000000 --- a/VG Music Studio - WinForms/PlayingPlaylist.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Kermalis.VGMusicStudio.Core; -using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Util; -using System.Collections.Generic; -using System.Linq; - -namespace Kermalis.VGMusicStudio.WinForms; - -internal sealed class PlayingPlaylist -{ - public readonly List _playedSongs; - public readonly List _remainingSongs; - public readonly Config.Playlist _curPlaylist; - - public PlayingPlaylist(Config.Playlist play) - { - _playedSongs = new List(); - _remainingSongs = new List(); - _curPlaylist = play; - } - - public void AdvanceThenSetAndLoadNextSong(int curSong) - { - _playedSongs.Add(curSong); - SetAndLoadNextSong(); - } - public void UndoThenSetAndLoadPrevSong(int curSong) - { - int prevIndex = _playedSongs.Count - 1; - int prevSong = _playedSongs[prevIndex]; - _playedSongs.RemoveAt(prevIndex); - _remainingSongs.Insert(0, curSong); - MainForm.Instance.SetAndLoadSong(prevSong); - } - public void SetAndLoadNextSong() - { - if (_remainingSongs.Count == 0) - { - _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); - if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) - { - _remainingSongs.Shuffle(); - } - } - int nextSong = _remainingSongs[0]; - _remainingSongs.RemoveAt(0); - MainForm.Instance.SetAndLoadSong(nextSong); - } -} diff --git a/VG Music Studio - WinForms/Program.cs b/VG Music Studio - WinForms/Program.cs index 24f9e89..c207096 100644 --- a/VG Music Studio - WinForms/Program.cs +++ b/VG Music Studio - WinForms/Program.cs @@ -12,11 +12,6 @@ internal static class Program private static void Main() { #if DEBUG - //VGMSDebug.SimulateLanguage("en"); - //VGMSDebug.SimulateLanguage("es"); - //VGMSDebug.SimulateLanguage("fr"); - //VGMSDebug.SimulateLanguage("it"); - //VGMSDebug.SimulateLanguage("ru"); //VGMSDebug.GBAGameCodeScan(@"C:\Users\Kermalis\Documents\Emulation\GBA\Games"); #endif try diff --git a/VG Music Studio - WinForms/SongInfoControl.cs b/VG Music Studio - WinForms/SongInfoControl.cs index 36cfe49..9b2c9f2 100644 --- a/VG Music Studio - WinForms/SongInfoControl.cs +++ b/VG Music Studio - WinForms/SongInfoControl.cs @@ -69,7 +69,7 @@ public SongInfoControl() private void TogglePiano(object? sender, EventArgs e) { - var check = (CheckBox)sender!; + var check = (CheckBox)sender; CheckBox master = _pianos[SongState.MAX_TRACKS]; if (check == master) { @@ -100,7 +100,7 @@ private void TogglePiano(object? sender, EventArgs e) } private void ToggleMute(object? sender, EventArgs e) { - var check = (CheckBox)sender!; + var check = (CheckBox)sender; CheckBox master = _mutes[SongState.MAX_TRACKS]; if (check == master) { @@ -117,7 +117,7 @@ private void ToggleMute(object? sender, EventArgs e) { if (_mutes[i] == check) { - Engine.Instance!.Mixer.Mutes[i] = !check.Checked; + Engine.Instance.Mixer.Mutes[i] = !check.Checked; } if (_mutes[i].Checked) { @@ -284,24 +284,17 @@ private void DrawVerticalBars(Graphics g, SongState.Track track, int vBarY1, int // Try to draw velocity bar var rect = new Rectangle((int)(_barStartX + (_barWidth / 2) - (track.LeftVolume * _barWidth / 2)) + _bwd, - vBarY1, - (int)((track.LeftVolume + track.RightVolume) * _barWidth / 2), - _barHeight); + vBarY1, + (int)((track.LeftVolume + track.RightVolume) * _barWidth / 2), + _barHeight); if (rect.Width > 0) { - float velocity = track.LeftVolume + track.RightVolume; - int alpha; - if (velocity >= 2f) + float velocity = (track.LeftVolume + track.RightVolume) * 2f; + if (velocity > 1f) { - alpha = 255; + velocity = 1f; } - else - { - const int DELTA = 125; - alpha = (int)WinFormsUtils.Lerp(velocity * 0.5f, 0f, DELTA); - alpha += 255 - DELTA; - } - _solidBrush.Color = Color.FromArgb(alpha, color); + _solidBrush.Color = Color.FromArgb((int)WinFormsUtils.Lerp(velocity, 20f, 255f), color); g.FillRectangle(_solidBrush, rect); g.DrawRectangle(_pen, rect); //_solidBrush.Color = color; diff --git a/VG Music Studio - WinForms/TaskbarPlayerButtons.cs b/VG Music Studio - WinForms/TaskbarPlayerButtons.cs deleted file mode 100644 index d6185e4..0000000 --- a/VG Music Studio - WinForms/TaskbarPlayerButtons.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Kermalis.VGMusicStudio.Core; -using Kermalis.VGMusicStudio.Core.Properties; -using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Properties; -using Microsoft.WindowsAPICodePack.Taskbar; -using System; - -namespace Kermalis.VGMusicStudio.WinForms; - -internal sealed class TaskbarPlayerButtons -{ - private readonly ThumbnailToolBarButton _prevTButton, _toggleTButton, _nextTButton; - - public TaskbarPlayerButtons(IntPtr handle) - { - _prevTButton = new ThumbnailToolBarButton(Resources.IconPrevious, Strings.PlayerPreviousSong); - _prevTButton.Click += PrevTButton_Click; - _toggleTButton = new ThumbnailToolBarButton(Resources.IconPlay, Strings.PlayerPlay); - _toggleTButton.Click += ToggleTButton_Click; - _nextTButton = new ThumbnailToolBarButton(Resources.IconNext, Strings.PlayerNextSong); - _nextTButton.Click += NextTButton_Click; - _prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = false; - TaskbarManager.Instance.ThumbnailToolBars.AddButtons(handle, _prevTButton, _toggleTButton, _nextTButton); - } - - private void PrevTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.PlayPreviousSong(); - } - private void ToggleTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.TogglePlayback(); - } - private void NextTButton_Click(object? sender, ThumbnailButtonClickedEventArgs e) - { - MainForm.Instance.PlayNextSong(); - } - - public void DisableAll() - { - _prevTButton.Enabled = false; - _toggleTButton.Enabled = false; - _nextTButton.Enabled = false; - } - public void UpdateButtons(PlayingPlaylist? playlist, int curSong, int maxSong) - { - if (playlist is not null) - { - _prevTButton.Enabled = playlist._playedSongs.Count > 0; - _nextTButton.Enabled = true; - } - else - { - _prevTButton.Enabled = curSong > 0; - _nextTButton.Enabled = curSong < maxSong; - } - switch (Engine.Instance!.Player.State) - { - case PlayerState.Stopped: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerPlay; break; - case PlayerState.Playing: _toggleTButton.Icon = Resources.IconPause; _toggleTButton.Tooltip = Strings.PlayerPause; break; - case PlayerState.Paused: _toggleTButton.Icon = Resources.IconPlay; _toggleTButton.Tooltip = Strings.PlayerUnpause; break; - } - _toggleTButton.Enabled = true; - } - public static void UpdateState() - { - if (!GlobalConfig.Instance.TaskbarProgress || !TaskbarManager.IsPlatformSupported) - { - return; - } - - TaskbarProgressBarState state; - switch (Engine.Instance?.Player.State) - { - case PlayerState.Playing: state = TaskbarProgressBarState.Normal; break; - case PlayerState.Paused: state = TaskbarProgressBarState.Paused; break; - default: state = TaskbarProgressBarState.NoProgress; break; - } - TaskbarManager.Instance.SetProgressState(state); - } -} diff --git a/VG Music Studio - WinForms/Theme.cs b/VG Music Studio - WinForms/Theme.cs index c8803e6..0652802 100644 --- a/VG Music Studio - WinForms/Theme.cs +++ b/VG Music Studio - WinForms/Theme.cs @@ -24,7 +24,7 @@ public static readonly Color public static Color DrainColor(Color c) { var hsl = new HSLColor(c); - return HSLColor.ToColor(hsl.Hue, hsl.Saturation / 2.5, hsl.Lightness); + return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); } } diff --git a/VG Music Studio - WinForms/TrackViewer.cs b/VG Music Studio - WinForms/TrackViewer.cs index 81520cc..80949f3 100644 --- a/VG Music Studio - WinForms/TrackViewer.cs +++ b/VG Music Studio - WinForms/TrackViewer.cs @@ -72,7 +72,7 @@ private void ListView_ItemActivate(object? sender, EventArgs e) List list = ((SongEvent)_listView.SelectedItem.RowObject).Ticks; if (list.Count > 0) { - Engine.Instance!.Player.SetSongPosition(list[0]); + Engine.Instance?.Player.SetCurrentPosition(list[0]); MainForm.Instance.LetUIKnowPlayerIsPlaying(); } } diff --git a/VG Music Studio - WinForms/Util/ColorSlider.cs b/VG Music Studio - WinForms/Util/ColorSlider.cs index fba1516..fa6171e 100644 --- a/VG Music Studio - WinForms/Util/ColorSlider.cs +++ b/VG Music Studio - WinForms/Util/ColorSlider.cs @@ -25,6 +25,7 @@ #endregion + using System; using System.ComponentModel; using System.Drawing; @@ -34,9 +35,9 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; [DesignerCategory(""), ToolboxBitmap(typeof(TrackBar))] -internal sealed class ColorSlider : Control +internal class ColorSlider : Control { - private const int THUMB_SIZE = 14; + private const int thumbSize = 14; private Rectangle thumbRect; private long _value = 0L; @@ -45,13 +46,16 @@ public long Value get => _value; set { - if (value < _minimum || value > _maximum) + if (value >= _minimum && value <= _maximum) + { + _value = value; + ValueChanged?.Invoke(this, EventArgs.Empty); + Invalidate(); + } + else { throw new ArgumentOutOfRangeException(nameof(Value), $"{nameof(Value)} must be between {nameof(Minimum)} and {nameof(Maximum)}."); } - _value = value; - ValueChanged?.Invoke(this, EventArgs.Empty); - Invalidate(); } } private long _minimum = 0L; @@ -60,17 +64,20 @@ public long Minimum get => _minimum; set { - if (value > _maximum) + if (value <= _maximum) { - throw new ArgumentOutOfRangeException(nameof(Minimum), $"{nameof(Minimum)} cannot be higher than {nameof(Maximum)}."); + _minimum = value; + if (_value < _minimum) + { + _value = _minimum; + ValueChanged?.Invoke(this, new EventArgs()); + } + Invalidate(); } - _minimum = value; - if (_value < _minimum) + else { - _value = _minimum; - ValueChanged?.Invoke(this, new EventArgs()); + throw new ArgumentOutOfRangeException(nameof(Minimum), $"{nameof(Minimum)} cannot be higher than {nameof(Maximum)}."); } - Invalidate(); } } private long _maximum = 10L; @@ -79,17 +86,20 @@ public long Maximum get => _maximum; set { - if (value < _minimum) + if (value >= _minimum) { - throw new ArgumentOutOfRangeException(nameof(Maximum), $"{nameof(Maximum)} cannot be lower than {nameof(Minimum)}."); + _maximum = value; + if (_value > _maximum) + { + _value = _maximum; + ValueChanged?.Invoke(this, new EventArgs()); + } + Invalidate(); } - _maximum = value; - if (_value > _maximum) + else { - _value = _maximum; - ValueChanged?.Invoke(this, new EventArgs()); + throw new ArgumentOutOfRangeException(nameof(Maximum), $"{nameof(Maximum)} cannot be lower than {nameof(Minimum)}."); } - Invalidate(); } } private long _smallChange = 1L; @@ -98,11 +108,14 @@ public long SmallChange get => _smallChange; set { - if (value < 0) + if (value >= 0) + { + _smallChange = value; + } + else { throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); } - _smallChange = value; } } private long _largeChange = 5L; @@ -111,11 +124,14 @@ public long LargeChange get => _largeChange; set { - if (value < 0) + if (value >= 0) + { + _largeChange = value; + } + else { throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); } - _largeChange = value; } } private bool _acceptKeys = true; @@ -129,7 +145,7 @@ public bool AcceptKeys } } - public event EventHandler? ValueChanged; + public event EventHandler ValueChanged; private readonly Color _thumbOuterColor = Color.White; private readonly Color _thumbInnerColor = Color.White; @@ -216,12 +232,12 @@ private void Draw(PaintEventArgs e, } long a = _maximum - _minimum; - long x = a == 0 ? 0 : (_value - _minimum) * (ClientRectangle.Width - THUMB_SIZE) / a; - thumbRect = new Rectangle((int)x, ClientRectangle.Y + ClientRectangle.Height / 2 - THUMB_SIZE / 2, THUMB_SIZE, THUMB_SIZE); + long x = a == 0 ? 0 : (_value - _minimum) * (ClientRectangle.Width - thumbSize) / a; + thumbRect = new Rectangle((int)x, ClientRectangle.Y + ClientRectangle.Height / 2 - thumbSize / 2, thumbSize, thumbSize); Rectangle barRect = ClientRectangle; barRect.Inflate(-1, -barRect.Height / 3); Rectangle elapsedRect = barRect; - elapsedRect.Width = thumbRect.Left + THUMB_SIZE / 2; + elapsedRect.Width = thumbRect.Left + thumbSize / 2; pen.Color = barInnerColorPaint; e.Graphics.DrawLine(pen, barRect.X, barRect.Y + barRect.Height / 2, barRect.X + barRect.Width, barRect.Y + barRect.Height / 2); @@ -248,7 +264,7 @@ private void Draw(PaintEventArgs e, newthumbOuterColorPaint = Color.FromArgb(175, thumbOuterColorPaint); newthumbInnerColorPaint = Color.FromArgb(175, thumbInnerColorPaint); } - using (GraphicsPath thumbPath = CreateRoundRectPath(thumbRect, THUMB_SIZE)) + using (GraphicsPath thumbPath = CreateRoundRectPath(thumbRect, thumbSize)) { using (var lgbThumb = new LinearGradientBrush(thumbRect, newthumbOuterColorPaint, newthumbInnerColorPaint, LinearGradientMode.Vertical) { WrapMode = WrapMode.TileFlipXY }) { @@ -289,7 +305,7 @@ private void Draw(PaintEventArgs e, private void SetValueFromPoint(Point p) { int x = p.X; - int margin = THUMB_SIZE / 2; + int margin = thumbSize / 2; x -= margin; _value = (long)(x * ((_maximum - _minimum) / (ClientSize.Width - 2f * margin)) + _minimum); if (_value < _minimum) diff --git a/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs b/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs index 05c12e9..ed3a13c 100644 --- a/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs +++ b/VG Music Studio - WinForms/Util/FlexibleMessageBox.cs @@ -1,5 +1,4 @@ -using Kermalis.VGMusicStudio.WinForms.Properties; -using System; +using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; @@ -81,7 +80,7 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; * - Initial Version */ -internal sealed class FlexibleMessageBox +internal class FlexibleMessageBox { #region Public statics @@ -167,13 +166,13 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, #region Internal form class - private sealed class FlexibleMessageBoxForm : ThemedForm + class FlexibleMessageBoxForm : ThemedForm { - IContainer components; + IContainer components = null; protected override void Dispose(bool disposing) { - if (disposing && components is not null) + if (disposing && components != null) { components.Dispose(); } @@ -285,7 +284,7 @@ void InitializeComponent() Controls.Add(panel1); Controls.Add(button1); DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); - Icon = Resources.Icon; + Icon = Properties.Resources.Icon; MaximizeBox = false; MinimizeBox = false; MinimumSize = new Size(276, 140); @@ -338,21 +337,10 @@ private enum TwoLetterISOLanguageID { en, de, es, it }; private FlexibleMessageBoxForm() { - components = null!; - button1 = null!; - button2 = null!; - button3 = null!; - FlexibleMessageBoxFormBindingSource = null!; - richTextBoxMessage = null!; - panel1 = null!; - pictureBoxForIcon = null!; - CaptionText = null!; - MessageText = null!; - InitializeComponent(); //Try to evaluate the language. If this fails, the fallback language English will be used - _ = Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); KeyPreview = true; KeyUp += FlexibleMessageBoxForm_KeyUp; @@ -362,7 +350,7 @@ private FlexibleMessageBoxForm() #region Private helper functions - static string[]? GetStringRows(string message) + static string[] GetStringRows(string message) { if (string.IsNullOrEmpty(message)) { @@ -405,15 +393,15 @@ static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) return workingAreaFactor; } - static void SetDialogStartPosition(FlexibleMessageBoxForm flexibleMessageBoxForm, IWin32Window? owner) + static void SetDialogStartPosition(FlexibleMessageBoxForm flexibleMessageBoxForm, IWin32Window owner) { - // If no owner given: Center on current screen - if (owner is null) + //If no owner given: Center on current screen + if (owner == null) { var screen = Screen.FromPoint(Cursor.Position); flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; - flexibleMessageBoxForm.Left = screen.Bounds.Left + (screen.Bounds.Width / 2) - (flexibleMessageBoxForm.Width / 2); - flexibleMessageBoxForm.Top = screen.Bounds.Top + (screen.Bounds.Height / 2) - (flexibleMessageBoxForm.Height / 2); + flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; } } @@ -424,8 +412,8 @@ static void SetDialogSizes(FlexibleMessageBoxForm flexibleMessageBoxForm, string Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); //Get rows. Exit if there are no rows to render... - string[]? stringRows = GetStringRows(text); - if (stringRows is null) + string[] stringRows = GetStringRows(text); + if (stringRows == null) { return; } @@ -575,9 +563,9 @@ static void SetDialogButtons(FlexibleMessageBoxForm flexibleMessageBoxForm, Mess #region Private event handlers - void FlexibleMessageBoxForm_Shown(object? sender, EventArgs e) + void FlexibleMessageBoxForm_Shown(object sender, EventArgs e) { - int buttonIndexToFocus; + int buttonIndexToFocus = 1; Button buttonToFocus; //Set the default button... @@ -616,16 +604,16 @@ void FlexibleMessageBoxForm_Shown(object? sender, EventArgs e) buttonToFocus.Focus(); } - void LinkClicked(object? sender, LinkClickedEventArgs e) + void LinkClicked(object sender, LinkClickedEventArgs e) { try { Cursor.Current = Cursors.WaitCursor; - Process.Start(e.LinkText!); + Process.Start(e.LinkText); } catch (Exception) { - // Let the caller of FlexibleMessageBoxForm decide what to do with this exception... + //Let the caller of FlexibleMessageBoxForm decide what to do with this exception... throw; } finally @@ -634,7 +622,7 @@ void LinkClicked(object? sender, LinkClickedEventArgs e) } } - void FlexibleMessageBoxForm_KeyUp(object? sender, KeyEventArgs e) + void FlexibleMessageBoxForm_KeyUp(object sender, KeyEventArgs e) { //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) @@ -668,7 +656,7 @@ void FlexibleMessageBoxForm_KeyUp(object? sender, KeyEventArgs e) #region Public show function - public static DialogResult Show(IWin32Window? owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { //Create a new instance of the FlexibleMessageBox form var flexibleMessageBoxForm = new FlexibleMessageBoxForm diff --git a/VG Music Studio - WinForms/Util/ImageComboBox.cs b/VG Music Studio - WinForms/Util/ImageComboBox.cs index bfcb4ff..45bca24 100644 --- a/VG Music Studio - WinForms/Util/ImageComboBox.cs +++ b/VG Music Studio - WinForms/Util/ImageComboBox.cs @@ -4,9 +4,9 @@ namespace Kermalis.VGMusicStudio.WinForms.Util; -internal sealed class ImageComboBox : ComboBox +internal class ImageComboBox : ComboBox { - private const int IMG_SIZE = 15; + private const int _imgSize = 15; private bool _open = false; public ImageComboBox() @@ -24,8 +24,8 @@ protected override void OnDrawItem(DrawItemEventArgs e) { ImageComboBoxItem item = Items[e.Index] as ImageComboBoxItem ?? throw new InvalidCastException($"Item was not of type \"{nameof(ImageComboBoxItem)}\""); int indent = _open ? item.IndentLevel : 0; - e.Graphics.DrawImage(item.Image, e.Bounds.Left + (indent * IMG_SIZE), e.Bounds.Top, IMG_SIZE, IMG_SIZE); - e.Graphics.DrawString(item.ToString(), e.Font!, new SolidBrush(e.ForeColor), e.Bounds.Left + (indent * IMG_SIZE) + IMG_SIZE, e.Bounds.Top); + e.Graphics.DrawImage(item.Image, e.Bounds.Left + indent * _imgSize, e.Bounds.Top, _imgSize, _imgSize); + e.Graphics.DrawString(item.ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left + indent * _imgSize + _imgSize, e.Bounds.Top); } base.OnDrawItem(e); @@ -41,7 +41,7 @@ protected override void OnDropDownClosed(EventArgs e) base.OnDropDownClosed(e); } } -internal sealed class ImageComboBoxItem +internal class ImageComboBoxItem { public object Item { get; } public Image Image { get; } @@ -54,7 +54,7 @@ public ImageComboBoxItem(object item, Image image, int indentLevel) IndentLevel = indentLevel; } - public override string? ToString() + public override string ToString() { return Item.ToString(); } diff --git a/VG Music Studio - WinForms/Util/VGMSDebug.cs b/VG Music Studio - WinForms/Util/VGMSDebug.cs index 9b3c7e8..1c7bd11 100644 --- a/VG Music Studio - WinForms/Util/VGMSDebug.cs +++ b/VG Music Studio - WinForms/Util/VGMSDebug.cs @@ -3,10 +3,8 @@ using Kermalis.VGMusicStudio.Core; using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; -using System.Threading; namespace Kermalis.VGMusicStudio.WinForms.Util; @@ -49,14 +47,12 @@ internal static class VGMSDebug public static void EventScan(List songs, bool showIndexes) { Console.WriteLine($"{nameof(EventScan)} started."); - var scans = new Dictionary>(); - Player player = Engine.Instance!.Player; foreach (Config.Song song in songs) { try { - player.LoadSong(song.Index); + Engine.Instance.Player.LoadSong(song.Index); } catch (Exception ex) { @@ -64,22 +60,23 @@ public static void EventScan(List songs, bool showIndexes) continue; } - if (player.LoadedSong is null) + if (Engine.Instance.Player.LoadedSong is null) { continue; } - foreach (string cmd in player.LoadedSong.Events.Where(ev => ev is not null).SelectMany(ev => ev!).Select(ev => ev.Command.Label).Distinct()) + foreach (string cmd in Engine.Instance.Player.LoadedSong.Events.Where(ev => ev != null).SelectMany(ev => ev).Select(ev => ev.Command.Label).Distinct()) { - if (!scans.TryGetValue(cmd, out List? list)) + if (scans.ContainsKey(cmd)) + { + scans[cmd].Add(song); + } + else { - list = new List(); - scans.Add(cmd, list); + scans.Add(cmd, new List { song }); } - list.Add(song); } } - foreach (KeyValuePair> kvp in scans.OrderBy(k => k.Key)) { Console.WriteLine("{0} ({1})", kvp.Key, showIndexes ? string.Join(", ", kvp.Value.Select(s => s.Index)) : string.Join(", ", kvp.Value.Select(s => s.Name))); @@ -90,7 +87,6 @@ public static void EventScan(List songs, bool showIndexes) public static void GBAGameCodeScan(string path) { Console.WriteLine($"{nameof(GBAGameCodeScan)} started."); - string[] files = Directory.GetFiles(path, "*.gba", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { @@ -99,17 +95,14 @@ public static void GBAGameCodeScan(string path) { using (FileStream stream = File.OpenRead(file)) { - var r = new EndianBinaryReader(stream, ascii: true); - + var reader = new EndianBinaryReader(stream, ascii: true); stream.Position = 0xAC; - string gameCode = r.ReadString_Count(3); + string gameCode = reader.ReadString_Count(3); stream.Position = 0xAF; - char regionCode = r.ReadChar(); + char regionCode = reader.ReadChar(); stream.Position = 0xBC; - byte version = r.ReadByte(); - - files[i] = string.Format("Code: {0}\tRegion: {1}\tVersion: {2}\tFile: {3}", - gameCode, regionCode, version, file); + byte version = reader.ReadByte(); + files[i] = string.Format("Code: {0}\tRegion: {1}\tVersion: {2}\tFile: {3}", gameCode, regionCode, version, file); } } catch (Exception ex) @@ -125,10 +118,5 @@ public static void GBAGameCodeScan(string path) } Console.WriteLine($"{nameof(GBAGameCodeScan)} ended."); } - - public static void SimulateLanguage(string lang) - { - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang); - } } #endif \ No newline at end of file diff --git a/VG Music Studio - WinForms/Util/WinFormsUtils.cs b/VG Music Studio - WinForms/Util/WinFormsUtils.cs index 33a0766..0c64c71 100644 --- a/VG Music Studio - WinForms/Util/WinFormsUtils.cs +++ b/VG Music Studio - WinForms/Util/WinFormsUtils.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Windows.Forms; namespace Kermalis.VGMusicStudio.WinForms.Util; @@ -37,40 +36,4 @@ public static float Lerp(float value, float a1, float a2, float b1, float b2) { return b1 + ((value - a1) / (a2 - a1) * (b2 - b1)); } - - public static string? CreateLoadDialog(string extension, string title, string filter) - { - var d = new OpenFileDialog - { - DefaultExt = extension, - ValidateNames = true, - CheckFileExists = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } - public static string? CreateSaveDialog(string fileName, string extension, string title, string filter) - { - var d = new SaveFileDialog - { - FileName = fileName, - DefaultExt = extension, - AddExtension = true, - ValidateNames = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } } diff --git a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj index cd3552b..bf42797 100644 --- a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj +++ b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj @@ -1,55 +1,27 @@  - net7.0-windows + net6.0-windows WinExe latest Kermalis.VGMusicStudio.WinForms enable true - true + true ..\Build Kermalis Kermalis - VG Music Studio - VG Music Studio - VG Music Studio + VGMusicStudio + VGMusicStudio + VGMusicStudio 0.3.0 - Properties\Icon.ico - False - - - - - NU1701 - - - NU1701 - - - NU1701 - - + + - - - Always - - - Always - - - Always - - - Always - - - \ No newline at end of file diff --git a/VG Music Studio - WinForms/ValueTextBox.cs b/VG Music Studio - WinForms/ValueTextBox.cs index f05190f..8a69ae5 100644 --- a/VG Music Studio - WinForms/ValueTextBox.cs +++ b/VG Music Studio - WinForms/ValueTextBox.cs @@ -6,8 +6,6 @@ namespace Kermalis.VGMusicStudio.WinForms; internal sealed class ValueTextBox : ThemedTextBox { - public event EventHandler? ValueChanged; - private bool _hex = false; public bool Hexadecimal { @@ -93,8 +91,14 @@ protected override void OnTextChanged(EventArgs e) Value = old; } + private EventHandler _onValueChanged = null; + public event EventHandler ValueChanged + { + add => _onValueChanged += value; + remove => _onValueChanged -= value; + } private void OnValueChanged(EventArgs e) { - ValueChanged?.Invoke(this, e); + _onValueChanged?.Invoke(this, e); } } diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 31bb2a2..37b7672 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -7,6 +7,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - WinForms" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "VG Music Studio - Core\VG Music Studio - Core.csproj", "{5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - MIDI", "VG Music Studio - MIDI\VG Music Studio - MIDI.csproj", "{6756ED81-71F6-457D-AD23-9C03B6C934E4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{A171BF23-4281-46CD-AE0B-ED6CD118744E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +29,22 @@ Global {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.Build.0 = Release|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.Build.0 = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From b3e547be6cffc9d050b762f2af63ac2b310ef280 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Sun, 19 Nov 2023 22:38:03 +1100 Subject: [PATCH 13/20] Merged the changes from the net-6 branch properly this time --- .gitignore | 28 +- README.md | 129 +- .../Properties/Strings.Designer.cs | 75 +- .../Properties/Strings.resx | 33 +- VG Music Studio - GTK3/MainWindow.cs | 875 +++++++++++ VG Music Studio - GTK3/Program.cs | 23 + .../VG Music Studio - GTK3.csproj | 16 + .../ExtraLibBindings/Gtk.cs | 199 +++ .../ExtraLibBindings/GtkInternal.cs | 425 +++++ VG Music Studio - GTK4/MainWindow.cs | 1369 +++++++++++++++++ VG Music Studio - GTK4/Program.cs | 48 + VG Music Studio - GTK4/Theme.cs | 224 +++ .../Util/FlexibleMessageBox.cs | 763 +++++++++ VG Music Studio - GTK4/Util/ScaleControl.cs | 86 ++ .../Util/SoundSequenceList.cs | 156 ++ .../VG Music Studio - GTK4.csproj | 281 ++++ VG Music Studio.sln | 24 + 17 files changed, 4739 insertions(+), 15 deletions(-) create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj diff --git a/.gitignore b/.gitignore index 80921d3..181a70e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,30 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ +/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs +/VG Music Studio - Core/GBA/AlphaDream/Commands.cs +/VG Music Studio - Core/GBA/AlphaDream/Enums.cs +/VG Music Studio - Core/GBA/AlphaDream/Structs.cs +/VG Music Studio - Core/GBA/AlphaDream/Track.cs +/VG Music Studio - Core/GBA/MP2K/Channel.cs +/VG Music Studio - Core/GBA/MP2K/Commands.cs +/VG Music Studio - Core/GBA/MP2K/Enums.cs +/VG Music Studio - Core/GBA/MP2K/Structs.cs +/VG Music Studio - Core/GBA/MP2K/Track.cs +/VG Music Studio - Core/GBA/MP2K/Utils.cs +/VG Music Studio - Core/NDS/DSE/Channel.cs +/VG Music Studio - Core/NDS/DSE/Commands.cs +/VG Music Studio - Core/NDS/DSE/Enums.cs +/VG Music Studio - Core/NDS/DSE/Track.cs +/VG Music Studio - Core/NDS/DSE/Utils.cs +/VG Music Studio - Core/NDS/SDAT/Channel.cs +/VG Music Studio - Core/NDS/SDAT/Commands.cs +/VG Music Studio - Core/NDS/SDAT/Enums.cs +/VG Music Studio - Core/NDS/SDAT/FileHeader.cs +/VG Music Studio - Core/NDS/SDAT/Track.cs +/VG Music Studio - Core/NDS/Utils.cs +/VG Music Studio - MIDI +/.vscode +/ObjectListView diff --git a/README.md b/README.md index 83a0af9..d214231 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,138 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General * Stich991 - Italian translation * tuku473 - Design suggestions, colors, Spanish translation -* Lachesis - French translation -* Delusional Moonlight - Russian translation ### AlphaDream Engine * irdkwia - Finding games that used the engine diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index eea96fb..8004fe2 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -358,7 +358,7 @@ public static string ErrorValueParseRanged { } /// - /// Looks up a localized string similar to GBA Files. + /// Looks up a localized string similar to Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.*. /// public static string FilterOpenGBA { get { @@ -367,7 +367,7 @@ public static string FilterOpenGBA { } /// - /// Looks up a localized string similar to SDAT Files. + /// Looks up a localized string similar to Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.*. /// public static string FilterOpenSDAT { get { @@ -376,7 +376,7 @@ public static string FilterOpenSDAT { } /// - /// Looks up a localized string similar to DLS Files. + /// Looks up a localized string similar to DLS Files (*.dls)|*.dls. /// public static string FilterSaveDLS { get { @@ -385,7 +385,7 @@ public static string FilterSaveDLS { } /// - /// Looks up a localized string similar to MIDI Files. + /// Looks up a localized string similar to MIDI Files (*.mid, *.midi)|*.mid;*.midi. /// public static string FilterSaveMIDI { get { @@ -394,7 +394,7 @@ public static string FilterSaveMIDI { } /// - /// Looks up a localized string similar to SF2 Files. + /// Looks up a localized string similar to SF2 Files (*.sf2)|*.sf2. /// public static string FilterSaveSF2 { get { @@ -403,7 +403,7 @@ public static string FilterSaveSF2 { } /// - /// Looks up a localized string similar to WAV Files. + /// Looks up a localized string similar to WAV Files (*.wav)|*.wav. /// public static string FilterSaveWAV { get { @@ -411,6 +411,69 @@ public static string FilterSaveWAV { } } + /// + /// Looks up a localized string similar to All files (*.*). + /// + public static string GTKAllFiles { + get { + return ResourceManager.GetString("GTKAllFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Game Boy Advance binary (*.gba, *.srl). + /// + public static string GTKFilterOpenGBA { + get { + return ResourceManager.GetString("GTKFilterOpenGBA", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Nitro Soundmaker Sound Data (*.sdat). + /// + public static string GTKFilterOpenSDAT { + get { + return ResourceManager.GetString("GTKFilterOpenSDAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DLS Soundfont Files (*.dls). + /// + public static string GTKFilterSaveDLS { + get { + return ResourceManager.GetString("GTKFilterSaveDLS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MIDI Sequence Files (*.mid, *.midi). + /// + public static string GTKFilterSaveMIDI { + get { + return ResourceManager.GetString("GTKFilterSaveMIDI", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SF2 Soundfont Files (*.sf2). + /// + public static string GTKFilterSaveSF2 { + get { + return ResourceManager.GetString("GTKFilterSaveSF2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Wave Audio Data (*.wav). + /// + public static string GTKFilterSaveWAV { + get { + return ResourceManager.GetString("GTKFilterSaveWAV", resourceCulture); + } + } + /// /// Looks up a localized string similar to Data. /// diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 916279d..9626f71 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,10 +128,10 @@ Error Exporting MIDI - GBA Files + Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.* - MIDI Files + MIDI Files (*.mid, *.midi)|*.mid;*.midi Data @@ -199,7 +199,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.* End Current Playlist @@ -331,7 +331,7 @@ Error Exporting WAV - WAV Files + WAV Files (*.wav)|*.wav Export Song as WAV @@ -344,7 +344,7 @@ Error Exporting SF2 - SF2 Files + SF2 Files (*.sf2)|*.sf2 Export VoiceTable as SF2 @@ -357,7 +357,7 @@ Error Exporting DLS - DLS Files + DLS Files (*.dls)|*.dls Export VoiceTable as DLS @@ -369,4 +369,25 @@ songs|0_0|song|1_1|songs|2_*| + + Game Boy Advance binary (*.gba, *.srl) + + + Nitro Soundmaker Sound Data (*.sdat) + + + DLS Soundfont Files (*.dls) + + + MIDI Sequence Files (*.mid, *.midi) + + + SF2 Soundfont Files (*.sf2) + + + Wave Audio Data (*.wav) + + + All files (*.*) + \ No newline at end of file diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..01921eb --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,875 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal sealed class MainWindow : Window + { + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + #endregion + + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + + _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + { + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + } + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + if (Engine.Instance != null) + { + DisposeEngine(); + } + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; + _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..0f13fcc --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..f18377e --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,16 @@ + + + + Exe + net6.0 + + + + + + + + + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..d151b67 --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1369 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; + +using Application = Adw.Application; +using Window = Adw.Window; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class MainWindow : Window +{ + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + private int _duration = 0; + private int _position = 0; + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private readonly Adjustment _volumeAdjustment, _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; + + // Sound Sequence List + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = Adjustment.New(0, 0, 100, 1, 1, 1); + _volumeScale = Scale.New(Orientation.Horizontal, _volumeAdjustment); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + //_volumeScale.OnValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + //_positionScale.SetRange(0, double.MaxValue); + _positionGestureClick = GestureClick.New(); + //if (_positionGestureClick.Button == 1) + // { + // _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + // _positionScale.OnValueChanged += PositionScale_MouseButtonPress; + // } + //_positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + + SetContent(_mainBox); + + Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance!.Player.SetCurrentPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + //_positionScale.Adjustment!.Upper = double.MaxValue; + _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); + _positionScale.SetRange(0, _duration); + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; + _positionScale.Show(); + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ enableds; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(path))); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); + return; + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + _timer.Start(); + Show(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + Show(); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + if (ticks < _duration) + { + // TODO: Implement GStreamer functions to replace Gtk.Adjustment + //_positionScale.SetRange(0, _duration); + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues + } + else + { + return; + } + } + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..a99da5f --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,48 @@ +using Adw; +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..1fd8cf1 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..621175f --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..6d21dc2 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..6077bf9 --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..64ba658 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,281 @@ + + + + Exe + net6.0 + enable + true + + + + + + + + + + + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 31bb2a2..37b7672 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -7,6 +7,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - WinForms" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "VG Music Studio - Core\VG Music Studio - Core.csproj", "{5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - MIDI", "VG Music Studio - MIDI\VG Music Studio - MIDI.csproj", "{6756ED81-71F6-457D-AD23-9C03B6C934E4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{A171BF23-4281-46CD-AE0B-ED6CD118744E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +29,22 @@ Global {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.Build.0 = Release|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6756ED81-71F6-457D-AD23-9C03B6C934E4}.Release|Any CPU.Build.0 = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A171BF23-4281-46CD-AE0B-ED6CD118744E}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From b0d14fb4aac46b5ac2328e3d635702150f109b48 Mon Sep 17 00:00:00 2001 From: Kermalis <29823718+Kermalis@users.noreply.github.com> Date: Mon, 5 Feb 2024 05:52:28 -0500 Subject: [PATCH 14/20] [MP2K] Sonic Advance 2 --- VG Music Studio - Core/MP2K.yaml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/VG Music Studio - Core/MP2K.yaml b/VG Music Studio - Core/MP2K.yaml index 7235295..d73128c 100644 --- a/VG Music Studio - Core/MP2K.yaml +++ b/VG Music Studio - Core/MP2K.yaml @@ -1,3 +1,21 @@ +A2NE_00: + Name: "Sonic Advance 2 (USA)" + SongTableOffsets: 0xAD4F4C + SongTableSizes: 507 + SampleRate: 2 + ReverbType: "Normal" + Reverb: 0 + Volume: 15 + HasGoldenSunSynths: False + HasPokemonCompression: False +A2NP_00: + Name: "Sonic Advance 2 (Europe)" + SongTableOffsets: 0xAD4F4C + Copy: "A2NE_00" +A2NJ_00: + Name: "Sonic Advance 2 (Japan)" + SongTableOffsets: 0xAD4B14 + Copy: "A2NE_00" A2UJ_00: Name: "Mother 1 + 2 (Japan)" SongTableOffsets: 0x10B530 From f2c0375a88bc597ea00a89f1724b246dbdee902a Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Wed, 28 Feb 2024 22:17:23 +1100 Subject: [PATCH 15/20] Updated nuget packages --- .gitignore | 28 +- README.md | 129 +- .../Properties/Strings.Designer.cs | 75 +- .../Properties/Strings.resx | 33 +- .../VG Music Studio - Core.csproj | 6 +- VG Music Studio - GTK3/MainWindow.cs | 875 +++++++++++ VG Music Studio - GTK3/Program.cs | 23 + .../VG Music Studio - GTK3.csproj | 16 + .../ExtraLibBindings/Gtk.cs | 199 +++ .../ExtraLibBindings/GtkInternal.cs | 425 ++++++ VG Music Studio - GTK4/MainWindow.cs | 1355 +++++++++++++++++ VG Music Studio - GTK4/PlayingPlaylist.cs | 53 + VG Music Studio - GTK4/Program.cs | 48 + VG Music Studio - GTK4/Theme.cs | 224 +++ .../Util/FlexibleMessageBox.cs | 763 ++++++++++ VG Music Studio - GTK4/Util/GTK4Utils.cs | 162 ++ VG Music Studio - GTK4/Util/ScaleControl.cs | 86 ++ .../Util/SoundSequenceList.cs | 156 ++ .../VG Music Studio - GTK4.csproj | 285 ++++ VG Music Studio.sln | 12 + 20 files changed, 4935 insertions(+), 18 deletions(-) create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/PlayingPlaylist.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/Util/GTK4Utils.cs create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj diff --git a/.gitignore b/.gitignore index 80921d3..181a70e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,30 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ +/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs +/VG Music Studio - Core/GBA/AlphaDream/Commands.cs +/VG Music Studio - Core/GBA/AlphaDream/Enums.cs +/VG Music Studio - Core/GBA/AlphaDream/Structs.cs +/VG Music Studio - Core/GBA/AlphaDream/Track.cs +/VG Music Studio - Core/GBA/MP2K/Channel.cs +/VG Music Studio - Core/GBA/MP2K/Commands.cs +/VG Music Studio - Core/GBA/MP2K/Enums.cs +/VG Music Studio - Core/GBA/MP2K/Structs.cs +/VG Music Studio - Core/GBA/MP2K/Track.cs +/VG Music Studio - Core/GBA/MP2K/Utils.cs +/VG Music Studio - Core/NDS/DSE/Channel.cs +/VG Music Studio - Core/NDS/DSE/Commands.cs +/VG Music Studio - Core/NDS/DSE/Enums.cs +/VG Music Studio - Core/NDS/DSE/Track.cs +/VG Music Studio - Core/NDS/DSE/Utils.cs +/VG Music Studio - Core/NDS/SDAT/Channel.cs +/VG Music Studio - Core/NDS/SDAT/Commands.cs +/VG Music Studio - Core/NDS/SDAT/Enums.cs +/VG Music Studio - Core/NDS/SDAT/FileHeader.cs +/VG Music Studio - Core/NDS/SDAT/Track.cs +/VG Music Studio - Core/NDS/Utils.cs +/VG Music Studio - MIDI +/.vscode +/ObjectListView diff --git a/README.md b/README.md index 83a0af9..d214231 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,138 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General * Stich991 - Italian translation * tuku473 - Design suggestions, colors, Spanish translation -* Lachesis - French translation -* Delusional Moonlight - Russian translation ### AlphaDream Engine * irdkwia - Finding games that used the engine diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index eea96fb..8004fe2 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -358,7 +358,7 @@ public static string ErrorValueParseRanged { } /// - /// Looks up a localized string similar to GBA Files. + /// Looks up a localized string similar to Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.*. /// public static string FilterOpenGBA { get { @@ -367,7 +367,7 @@ public static string FilterOpenGBA { } /// - /// Looks up a localized string similar to SDAT Files. + /// Looks up a localized string similar to Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.*. /// public static string FilterOpenSDAT { get { @@ -376,7 +376,7 @@ public static string FilterOpenSDAT { } /// - /// Looks up a localized string similar to DLS Files. + /// Looks up a localized string similar to DLS Files (*.dls)|*.dls. /// public static string FilterSaveDLS { get { @@ -385,7 +385,7 @@ public static string FilterSaveDLS { } /// - /// Looks up a localized string similar to MIDI Files. + /// Looks up a localized string similar to MIDI Files (*.mid, *.midi)|*.mid;*.midi. /// public static string FilterSaveMIDI { get { @@ -394,7 +394,7 @@ public static string FilterSaveMIDI { } /// - /// Looks up a localized string similar to SF2 Files. + /// Looks up a localized string similar to SF2 Files (*.sf2)|*.sf2. /// public static string FilterSaveSF2 { get { @@ -403,7 +403,7 @@ public static string FilterSaveSF2 { } /// - /// Looks up a localized string similar to WAV Files. + /// Looks up a localized string similar to WAV Files (*.wav)|*.wav. /// public static string FilterSaveWAV { get { @@ -411,6 +411,69 @@ public static string FilterSaveWAV { } } + /// + /// Looks up a localized string similar to All files (*.*). + /// + public static string GTKAllFiles { + get { + return ResourceManager.GetString("GTKAllFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Game Boy Advance binary (*.gba, *.srl). + /// + public static string GTKFilterOpenGBA { + get { + return ResourceManager.GetString("GTKFilterOpenGBA", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Nitro Soundmaker Sound Data (*.sdat). + /// + public static string GTKFilterOpenSDAT { + get { + return ResourceManager.GetString("GTKFilterOpenSDAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DLS Soundfont Files (*.dls). + /// + public static string GTKFilterSaveDLS { + get { + return ResourceManager.GetString("GTKFilterSaveDLS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MIDI Sequence Files (*.mid, *.midi). + /// + public static string GTKFilterSaveMIDI { + get { + return ResourceManager.GetString("GTKFilterSaveMIDI", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SF2 Soundfont Files (*.sf2). + /// + public static string GTKFilterSaveSF2 { + get { + return ResourceManager.GetString("GTKFilterSaveSF2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Wave Audio Data (*.wav). + /// + public static string GTKFilterSaveWAV { + get { + return ResourceManager.GetString("GTKFilterSaveWAV", resourceCulture); + } + } + /// /// Looks up a localized string similar to Data. /// diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 916279d..9626f71 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,10 +128,10 @@ Error Exporting MIDI - GBA Files + Game Boy Advance binary (*.gba, *srl)|*.gba;*.srl|All files (*.*)|*.* - MIDI Files + MIDI Files (*.mid, *.midi)|*.mid;*.midi Data @@ -199,7 +199,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat)|*.sdat|All files (*.*)|*.* End Current Playlist @@ -331,7 +331,7 @@ Error Exporting WAV - WAV Files + WAV Files (*.wav)|*.wav Export Song as WAV @@ -344,7 +344,7 @@ Error Exporting SF2 - SF2 Files + SF2 Files (*.sf2)|*.sf2 Export VoiceTable as SF2 @@ -357,7 +357,7 @@ Error Exporting DLS - DLS Files + DLS Files (*.dls)|*.dls Export VoiceTable as DLS @@ -369,4 +369,25 @@ songs|0_0|song|1_1|songs|2_*| + + Game Boy Advance binary (*.gba, *.srl) + + + Nitro Soundmaker Sound Data (*.sdat) + + + DLS Soundfont Files (*.dls) + + + MIDI Sequence Files (*.mid, *.midi) + + + SF2 Soundfont Files (*.sf2) + + + Wave Audio Data (*.wav) + + + All files (*.*) + \ No newline at end of file diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index 1d8bb4e..b83b088 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -12,9 +12,9 @@ - - - + + + Dependencies\DLS2.dll diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..01921eb --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,875 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal sealed class MainWindow : Window + { + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + #endregion + + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + + _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + { + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + } + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + if (Engine.Instance != null) + { + DisposeEngine(); + } + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; + _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..0f13fcc --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..f78e051 --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0 + + + + + + + + + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..c276ab2 --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1355 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; + +using Application = Adw.Application; +using Window = Adw.Window; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class MainWindow : Window +{ + private int _duration = 0; + private int _position = 0; + + private PlayingPlaylist? _playlist; + private int _curSong = -1; + + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. + + private bool _songEnded = false; + private bool _stopUI = false; + private bool _autoplay = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private readonly Adjustment _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; + + // Sound Sequence List + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer.VolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += Timer_Tick; + + // Volume Scale + _volumeScale = Scale.NewWithRange(Orientation.Horizontal, 0, 100, 1); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + + // Position Scale + _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + _positionScale.SetRange(1, double.MaxValue); + _positionGestureClick = GestureClick.New(); + if (_positionGestureClick.Button == 1) + { + _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + _positionScale.OnValueChanged -= PositionScale_MouseButtonRelease; + _positionScale.OnValueChanged += PositionScale_MouseButtonPress; + _positionScale.OnValueChanged -= PositionScale_MouseButtonPress; + } + //_positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + + SetContent(_mainBox); + + Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeScale.Adjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeScale.Adjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance!.Player.SetSongPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + int index = (int)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + int songIndex = songs.FindIndex(s => s.Index == index); + if (songIndex != -1) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {songs[songIndex].Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + //_positionScale.Adjustment!.Upper = double.MaxValue; + _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); + _positionScale.SetRange(0, _duration); + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; + _positionScale.Show(); + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} + public void SetAndLoadSequence(int index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + //private void SetAndLoadNextPlaylistSong() + //{ + // if (_remainingSequences.Count == 0) + // { + // _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + // if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + // { + // _remainingSequences.Any(); + // } + // } + // long nextSequence = _remainingSequences[0]; + // _remainingSequences.RemoveAt(0); + // SetAndLoadSequence(nextSequence); + //} + private void ResetPlaylistStuff(bool spinButtonAndListBoxEnabled) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _curSong = -1; + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ spinButtonAndListBoxEnabled; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.GTKFilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + using (FileStream stream = File.OpenRead(path)) + { + _ = new SDATEngine(new SDAT(stream)); + } + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.GTKFilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); + return; + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((int)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs(true, false, new (int AbsoluteTick, (byte Numerator, byte Denominator))[] + { + (0, (4, 4)), + }); + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(path, cfg); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(path!, cfg); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(string path, AlphaDreamConfig config) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(path, config); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.GTKFilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((int)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + Player player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + _timer.Start(); + Show(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.TogglePlaying(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + Show(); + } + private void TogglePlayback() + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence() + { + + if (_playlist is not null) + { + _playlist.UndoThenSetAndLoadPrevSong(this, _curSong); + } + else + { + SetAndLoadSequence((int)_sequenceNumberSpinButton.Value - 1); + } + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlist is not null) + { + _playlist.AdvanceThenSetAndLoadNextSong(this, _curSong); + } + else + { + SetAndLoadSequence((int)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this GUI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void Timer_Tick(object? sender, EventArgs e) + { + if (_songEnded) + { + _songEnded = false; + if (_playlist is not null) + { + _playlist.AdvanceThenSetAndLoadNextSong(this, _curSong); + } + else + { + Stop(); + } + } + else + { + Player player = Engine.Instance!.Player; + UpdatePositionIndicators(player.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + if (ticks < _duration) + { + // TODO: Implement GStreamer functions to replace Gtk.Adjustment + _positionScale.SetRange(1, _duration); + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues + } + else + { + return; + } + } + } +} diff --git a/VG Music Studio - GTK4/PlayingPlaylist.cs b/VG Music Studio - GTK4/PlayingPlaylist.cs new file mode 100644 index 0000000..e1b1d0d --- /dev/null +++ b/VG Music Studio - GTK4/PlayingPlaylist.cs @@ -0,0 +1,53 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class PlayingPlaylist +{ + public readonly List _playedSongs; + public readonly List _remainingSongs; + public readonly Config.Playlist _curPlaylist; + + public PlayingPlaylist(Config.Playlist play) + { + _playedSongs = new List(); + _remainingSongs = new List(); + _curPlaylist = play; + } + + public void AdvanceThenSetAndLoadNextSong(MainWindow parent, int curSong) + { + _playedSongs.Add(curSong); + SetAndLoadNextSong(parent); + } + public void UndoThenSetAndLoadPrevSong(MainWindow parent, int curSong) + { + int prevIndex = _playedSongs.Count - 1; + int prevSong = _playedSongs[prevIndex]; + _playedSongs.RemoveAt(prevIndex); + _remainingSongs.Insert(0, curSong); + parent.SetAndLoadSequence(prevSong); + } + public void SetAndLoadNextSong(MainWindow parent) + { + if (_remainingSongs.Count == 0) + { + _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSongs.Shuffle(); + } + } + int nextSong = _remainingSongs[0]; + _remainingSongs.RemoveAt(0); + parent.SetAndLoadSequence(nextSong); + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..a99da5f --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,48 @@ +using Adw; +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..1fd8cf1 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..621175f --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/Util/GTK4Utils.cs b/VG Music Studio - GTK4/Util/GTK4Utils.cs new file mode 100644 index 0000000..41956e6 --- /dev/null +++ b/VG Music Studio - GTK4/Util/GTK4Utils.cs @@ -0,0 +1,162 @@ +using GObject; +using Gtk; +using Kermalis.VGMusicStudio.Core.Properties; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal static class GTK4Utils +{ + + // Error Handle + private static GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Callback + private static Gio.Internal.AsyncReadyCallback? _saveCallback { get; set; } + private static Gio.Internal.AsyncReadyCallback? _openCallback { get; set; } + private static Gio.Internal.AsyncReadyCallback? _selectFolderCallback { get; set; } + + + private static readonly Random _rng = new(); + + public static string Print(this IEnumerable source, bool parenthesis = true) + { + string str = parenthesis ? "( " : ""; + str += string.Join(", ", source); + str += parenthesis ? " )" : ""; + return str; + } + /// Fisher-Yates Shuffle + public static void Shuffle(this IList source) + { + for (int a = 0; a < source.Count - 1; a++) + { + int b = _rng.Next(a, source.Count); + (source[b], source[a]) = (source[a], source[b]); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static float Lerp(float progress, float from, float to) + { + return from + ((to - from) * progress); + } + /// Maps a value in the range [a1, a2] to [b1, b2]. Divide by zero occurs if a1 and a2 are equal + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static float Lerp(float value, float a1, float a2, float b1, float b2) + { + return b1 + ((value - a1) / (a2 - a1) * (b2 - b1)); + } + + public static string? CreateLoadDialog(Span filterExtensions, string title, Span filterNames, Window parent) + { + var ff = FileFilter.New(); + for (int i = 0; i < filterNames.Length; i++) + { + ff.SetName(filterNames[i]); + } + for (int i = 0; i < filterExtensions.Length; i++) + { + ff.AddPattern(filterExtensions[i]); + } + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + var d = FileDialog.New(); + d.SetTitle(title); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + filters.Append(allFiles); + d.SetFilters(filters); + string? path = null; + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + Gtk.Internal.FileDialog.Open(d.Handle, parent.Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + return null; + } + + public static string? CreateSaveDialog(string fileName, Span filterExtensions, string title, Span filterNames, Window parent) + { + var ff = FileFilter.New(); + for (int i = 0; i < filterNames.Length; i++) + { + ff.SetName(filterNames[i]); + } + for (int i = 0; i < filterExtensions.Length; i++) + { + ff.AddPattern(filterExtensions[i]); + } + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.GTKAllFiles); + allFiles.AddPattern("*.*"); + + var d = FileDialog.New(); + d.SetTitle(title); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + filters.Append(allFiles); + d.SetFilters(filters); + string? path = null; + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + Gtk.Internal.FileDialog.Save(d.Handle, parent.Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + return null; + } + public static string? CreateFolderDialog(string title, Window parent) + { + var d = FileDialog.New(); + d.SetTitle(title); + + string? path = null; + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + Gtk.Internal.FileDialog.SelectFolder(d.Handle, parent.Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + return null; + } +} diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..6d21dc2 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..6077bf9 --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..b3d37e9 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,285 @@ + + + + Exe + net8.0 + enable + true + + + + + + + + + + + + + Always + %(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 31bb2a2..3bd2974 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -7,6 +7,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - WinForms" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "VG Music Studio - Core\VG Music Studio - Core.csproj", "{5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +25,14 @@ Global {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 56ec3fb5a05e291309f9a37052ec7f73ef727827 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Wed, 28 Feb 2024 23:05:21 +1100 Subject: [PATCH 16/20] Added PortAudio backend --- .gitignore | 28 +- README.md | 129 +- VG Music Studio - Core/Backend.cs | 744 ++++++++ VG Music Studio - Core/Engine.cs | 3 +- .../Formats/Enumerations/WaveEncodingEnums.cs | 455 +++++ VG Music Studio - Core/Formats/Wave.cs | 399 ++++ .../GBA/AlphaDream/AlphaDreamEngine.cs | 14 +- .../GBA/AlphaDream/AlphaDreamMixer.cs | 16 +- .../GBA/AlphaDream/AlphaDreamMixer_NAudio.cs | 127 ++ .../GBA/AlphaDream/AlphaDreamPlayer.cs | 89 +- .../GBA/AlphaDream/AlphaDreamTrack.cs | 14 + .../AlphaDream/Channels/AlphaDreamChannel.cs | 5 + .../Channels/AlphaDreamPCMChannel.cs | 79 +- .../Channels/AlphaDreamSquareChannel.cs | 21 +- .../GBA/MP2K/Channels/MP2KChannel.cs | 9 +- .../GBA/MP2K/Channels/MP2KNoiseChannel.cs | 19 +- .../GBA/MP2K/Channels/MP2KPCM4Channel.cs | 24 +- .../GBA/MP2K/Channels/MP2KPCM8Channel.cs | 180 +- .../GBA/MP2K/Channels/MP2KPSGChannel.cs | 5 + .../GBA/MP2K/Channels/MP2KSquareChannel.cs | 19 +- VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs | 54 +- .../GBA/MP2K/MP2KLoadedSong_Runtime.cs | 88 +- VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 75 +- .../GBA/MP2K/MP2KMixer_NAudio.cs | 265 +++ VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs | 75 +- VG Music Studio - Core/Mixer.cs | 424 ++++- VG Music Studio - Core/Mixer_NAudio.cs | 109 ++ VG Music Studio - Core/NDS/DSE/DSEEngine.cs | 14 +- VG Music Studio - Core/NDS/DSE/DSEMixer.cs | 11 +- .../NDS/DSE/DSEMixer_NAudio.cs | 214 +++ VG Music Studio - Core/NDS/DSE/DSEPlayer.cs | 55 +- VG Music Studio - Core/NDS/SDAT/SDATEngine.cs | 14 +- .../NDS/SDAT/SDATLoadedSong_Events.cs | 24 +- .../NDS/SDAT/SDATLoadedSong_Runtime.cs | 5 +- VG Music Studio - Core/NDS/SDAT/SDATMixer.cs | 11 +- .../NDS/SDAT/SDATMixer_NAudio.cs | 244 +++ VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs | 102 +- VG Music Studio - Core/Player.cs | 1 + .../PortAudio/Enumerations/ErrorCode.cs | 44 + .../PortAudio/Enumerations/SampleFormat.cs | 47 + .../Enumerations/StreamCallbackFlags.cs | 50 + .../Enumerations/StreamCallbackResult.cs | 27 + .../PortAudio/Enumerations/StreamFlags.cs | 57 + VG Music Studio - Core/PortAudio/PortAudio.cs | 285 +++ .../PortAudio/PortAudioException.cs | 44 + VG Music Studio - Core/PortAudio/Stream.cs | 576 ++++++ .../PortAudio/Structures/DeviceInfo.cs | 59 + .../Structures/StreamCallbackTimeInfo.cs | 36 + .../PortAudio/Structures/StreamParameters.cs | 78 + .../PortAudio/Structures/VersionInfo.cs | 38 + .../Properties/Strings.Designer.cs | 21 +- .../Properties/Strings.resx | 15 +- .../Util/ActionExtensions.cs | 186 ++ .../Util/ArrayExtensions.cs | 1605 +++++++++++++++++ VG Music Studio - Core/Util/DialogUtils.cs | 27 + VG Music Studio - Core/Util/GUIUtils.cs | 39 + VG Music Studio - Core/Util/Int24.cs | 1515 ++++++++++++++++ VG Music Studio - Core/Util/SampleUtils.cs | 40 +- VG Music Studio - Core/Util/UInt24.cs | 1517 ++++++++++++++++ .../VG Music Studio - Core.csproj | 9 +- VG Music Studio - GTK3/MainWindow.cs | 875 +++++++++ VG Music Studio - GTK3/Program.cs | 23 + .../VG Music Studio - GTK3.csproj | 16 + .../ExtraLibBindings/Gtk.cs | 199 ++ .../ExtraLibBindings/GtkInternal.cs | 425 +++++ VG Music Studio - GTK4/MainWindow.cs | 1365 ++++++++++++++ VG Music Studio - GTK4/PlayingPlaylist.cs | 53 + VG Music Studio - GTK4/Program.cs | 48 + VG Music Studio - GTK4/Theme.cs | 224 +++ .../Util/FlexibleMessageBox.cs | 763 ++++++++ VG Music Studio - GTK4/Util/GTK4Utils.cs | 214 +++ VG Music Studio - GTK4/Util/ScaleControl.cs | 86 + .../Util/SoundSequenceList.cs | 156 ++ .../VG Music Studio - GTK4.csproj | 285 +++ VG Music Studio - WinForms/PlayingPlaylist.cs | 1 - VG Music Studio - WinForms/SongInfoControl.cs | 3 +- .../Util/WinFormsUtils.cs | 202 ++- VG Music Studio.sln | 48 + 78 files changed, 15039 insertions(+), 426 deletions(-) create mode 100644 VG Music Studio - Core/Backend.cs create mode 100644 VG Music Studio - Core/Formats/Enumerations/WaveEncodingEnums.cs create mode 100644 VG Music Studio - Core/Formats/Wave.cs create mode 100644 VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer_NAudio.cs create mode 100644 VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs create mode 100644 VG Music Studio - Core/Mixer_NAudio.cs create mode 100644 VG Music Studio - Core/NDS/DSE/DSEMixer_NAudio.cs create mode 100644 VG Music Studio - Core/NDS/SDAT/SDATMixer_NAudio.cs create mode 100644 VG Music Studio - Core/PortAudio/Enumerations/ErrorCode.cs create mode 100644 VG Music Studio - Core/PortAudio/Enumerations/SampleFormat.cs create mode 100644 VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackFlags.cs create mode 100644 VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackResult.cs create mode 100644 VG Music Studio - Core/PortAudio/Enumerations/StreamFlags.cs create mode 100644 VG Music Studio - Core/PortAudio/PortAudio.cs create mode 100644 VG Music Studio - Core/PortAudio/PortAudioException.cs create mode 100644 VG Music Studio - Core/PortAudio/Stream.cs create mode 100644 VG Music Studio - Core/PortAudio/Structures/DeviceInfo.cs create mode 100644 VG Music Studio - Core/PortAudio/Structures/StreamCallbackTimeInfo.cs create mode 100644 VG Music Studio - Core/PortAudio/Structures/StreamParameters.cs create mode 100644 VG Music Studio - Core/PortAudio/Structures/VersionInfo.cs create mode 100644 VG Music Studio - Core/Util/ActionExtensions.cs create mode 100644 VG Music Studio - Core/Util/ArrayExtensions.cs create mode 100644 VG Music Studio - Core/Util/DialogUtils.cs create mode 100644 VG Music Studio - Core/Util/GUIUtils.cs create mode 100644 VG Music Studio - Core/Util/Int24.cs create mode 100644 VG Music Studio - Core/Util/UInt24.cs create mode 100644 VG Music Studio - GTK3/MainWindow.cs create mode 100644 VG Music Studio - GTK3/Program.cs create mode 100644 VG Music Studio - GTK3/VG Music Studio - GTK3.csproj create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs create mode 100644 VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs create mode 100644 VG Music Studio - GTK4/MainWindow.cs create mode 100644 VG Music Studio - GTK4/PlayingPlaylist.cs create mode 100644 VG Music Studio - GTK4/Program.cs create mode 100644 VG Music Studio - GTK4/Theme.cs create mode 100644 VG Music Studio - GTK4/Util/FlexibleMessageBox.cs create mode 100644 VG Music Studio - GTK4/Util/GTK4Utils.cs create mode 100644 VG Music Studio - GTK4/Util/ScaleControl.cs create mode 100644 VG Music Studio - GTK4/Util/SoundSequenceList.cs create mode 100644 VG Music Studio - GTK4/VG Music Studio - GTK4.csproj diff --git a/.gitignore b/.gitignore index 80921d3..181a70e 100644 --- a/.gitignore +++ b/.gitignore @@ -259,4 +259,30 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc \ No newline at end of file +*.pyc +/VG Music Studio - GTK4/share/ +/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamChannel.cs +/VG Music Studio - Core/GBA/AlphaDream/Commands.cs +/VG Music Studio - Core/GBA/AlphaDream/Enums.cs +/VG Music Studio - Core/GBA/AlphaDream/Structs.cs +/VG Music Studio - Core/GBA/AlphaDream/Track.cs +/VG Music Studio - Core/GBA/MP2K/Channel.cs +/VG Music Studio - Core/GBA/MP2K/Commands.cs +/VG Music Studio - Core/GBA/MP2K/Enums.cs +/VG Music Studio - Core/GBA/MP2K/Structs.cs +/VG Music Studio - Core/GBA/MP2K/Track.cs +/VG Music Studio - Core/GBA/MP2K/Utils.cs +/VG Music Studio - Core/NDS/DSE/Channel.cs +/VG Music Studio - Core/NDS/DSE/Commands.cs +/VG Music Studio - Core/NDS/DSE/Enums.cs +/VG Music Studio - Core/NDS/DSE/Track.cs +/VG Music Studio - Core/NDS/DSE/Utils.cs +/VG Music Studio - Core/NDS/SDAT/Channel.cs +/VG Music Studio - Core/NDS/SDAT/Commands.cs +/VG Music Studio - Core/NDS/SDAT/Enums.cs +/VG Music Studio - Core/NDS/SDAT/FileHeader.cs +/VG Music Studio - Core/NDS/SDAT/Track.cs +/VG Music Studio - Core/NDS/Utils.cs +/VG Music Studio - MIDI +/.vscode +/ObjectListView diff --git a/README.md b/README.md index 83a0af9..d214231 100644 --- a/README.md +++ b/README.md @@ -50,13 +50,138 @@ If you want to talk or would like a game added to our configs, join our [Discord ### SDAT Engine * Find proper formulas for LFO +---- +## Building +### Windows +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the Windows executable (.exe). + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install MSYS2 from [the official website](https://www.msys2.org/), and ensure it is installed in the default directory: ``C:\``. +2. After installation, run the following commands in the MSYS2 terminal: ``pacman -Syy`` to reload the package database, then ``pacman -Syuu`` to update all the packages. +3. Run each of the following commands to install the required packages: +``pacman -S mingw-w64-x86_64-gtk4`` +``pacman -S mingw-w64-x86_64-libadwaita`` +``pacman -S mingw-w64-x86_64-gtksourceview5`` + +### macOS +#### Intel (x86-64) +Even though it will build without any issues, since VG Music Studio runs on GTK4 bindings via Gir.Core, it requires some C libraries to be installed or placed within the same directory as the macOS executable. + +Otherwise it will complain upon launch with the following System.TypeInitializationException error: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.dylib' or one of its dependencies: The specified module could not be found. (0x8007007E)`` + +To avoid this error while debugging VG Music Studio, you will need to do the following: +1. Download and install [Homebrew](https://brew.sh/) with the following macOS terminal command: +``/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`` +This will ensure Homebrew is installed in the default directory, which is ``/usr/local``. +2. After installation, run the following command from the macOS terminal to update all packages: ``brew update`` +3. Run each of the following commands to install the required packages: +``brew install gtk4`` +``brew install libadwaita`` +``brew install gtksourceview5`` + +#### Apple Silicon (AArch64) +Currently unknown if this will work on Apple Silicon, since it's a completely different CPU architecture, it may need some ARM-specific APIs to build or function correctly. + +If you have figured out a way to get it to run under Apple Silicon, please let us know! + +### Linux +Most Linux distributions should be able to build this without anything extra to download and install. + +However, if you get the following System.TypeInitializationException error upon launching VG Music Studio during debugging: +``DllNotFoundException: Unable to load DLL 'libgtk-4-1.so.0' or one of its dependencies: The specified module could not be found. (0x8007007E)`` +Then it means that either ``gtk4``, ``libadwaita`` or ``gtksourceview5`` is missing from your current installation of your Linux distribution. Often occurs if a non-GTK based desktop environment is installed by default, or the Linux distribution has been installed without a GUI. + +To install them, run the following commands: +#### Debian (or Debian based distributions, such as Ubuntu, elementary OS, Pop!_OS, Zorin OS, Kali Linux etc.) +First, update the current packages with ``sudo apt update && sudo apt upgrade`` and install any updates, then run: +``sudo apt install libgtk-4-1`` +``sudo apt install libadwaita-1`` +``sudo apt install libgtksourceview-5`` + +##### Vanilla OS (Debian based distribution) +Debian based distribution, Vanilla OS, uses the Distrobox based package management system called 'apx' instead of apt (apx as in 'apex', not to be confused with Microsoft Windows's UWP appx packages). +But it is still a Debian based distribution, nonetheless. And fortunately, it comes pre-installed with GNOME, which means you don't need to install any libraries! + +You will, however, still need to install the .NET SDK and .NET Runtime using apx, and cannot be used with 'sudo'. + +Instead, run any commands to install packages like this: +``apx install [package-name]`` + +#### Arch Linux (or Arch Linux based distributions, such as Manjaro, Garuda Linux, EndeavourOS, SteamOS etc.) +First, update the current packages with ``sudo pacman -Syy && sudo pacman -Syuu`` and install any updates, then run: +``sudo pacman -S gtk4`` +``sudo pacman -S libadwaita`` +``sudo pacman -S gtksourceview5`` + +##### ChimeraOS (Arch based distribution) +Note: Not to be confused with Chimera Linux, the Linux distribution made from scratch with a custom Linux kernel. This one is an Arch Linux based distribution. + +Arch Linux based distribution, ChimeraOS, comes pre-installed with the GNOME desktop environment. To access it, open the terminal and type ``chimera-session desktop``. + +But because it is missing the .NET SDK and .NET Runtime, and the root directory is read-only, you will need to run the following command: ``sudo frzr-unlock`` + +Then install any required packages like this example: ``sudo pacman -S [package-name]`` + +Note: Any installed packages installed in the root directory with the pacman utility will be undone when ChimeraOS is updated, due to the way [frzr](https://github.com/ChimeraOS/frzr) functions. Also, frzr may be what inspired Vanilla OS's [ABRoot](https://github.com/Vanilla-OS/ABRoot) utility. + +#### Fedora (or other Red Hat based distributions, such as Red Hat Enterprise Linux, AlmaLinux, Rocky Linux etc.) +First, update the current packages with ``sudo dnf check-update && sudo dnf update`` and install any updates, then run: +``sudo dnf install gtk4`` +``sudo dnf install libadwaita`` +``sudo dnf install gtksourceview5`` + +#### openSUSE (or other SUSE Linux based distributions, such as SUSE Linux Enterprise, GeckoLinux etc.) +First, update the current packages with ``sudo zypper up`` and install any updates, then run: +``sudo zypper in libgtk-4-1`` +``sudo zypper in libadwaita-1-0`` +``sudo zypper in libgtksourceview-5-0`` + +#### Alpine Linux (or Alpine Linux based distributions, such as postmarketOS etc.) +First, update the current packages with ``apk -U upgrade`` to their latest versions, then run: +``apk add gtk4.0`` +``apk add libadwaita`` +``apk add gtksourceview5`` + +Please note that VG Music Studio may not be able to build on other CPU architectures (such as AArch64, ppc64le, s390x etc.), since it hasn't been developed to support those architectures yet. Same thing applies for postmarketOS. + +#### Puppy Linux +Puppy Linux is an independent distribution that has many variants, each with packages from other Linux distributions. + +It's not possible to find the gtk4, libadwaita and gtksourceview5 libraries or their dependencies in the GUI package management tool, Puppy Package Manager. Because Puppy Linux is built to be a portable and lightweight distribution and to be compatible with older hardware. And because of this, it is only possible to find gtk+2 libraries and other legacy dependencies that it relies on. + +So therefore, VG Music Studio isn't supported on Puppy Linux. + +#### Chimera Linux +Note: Not to be confused with the Arch Linux based distribution named ChimeraOS. This one is completely different and written from scratch, and uses a modified Linux kernel. + +Chimera Linux already comes pre-installed with the GNOME desktop environment and uses the Alpine Package Kit. If you need to install any necessary packages, run the following command example: +``apk add [package-name]`` + +#### Void Linux +First, update the current packages with ``sudo xbps-install -Su`` to their latest versions, then run: +``sudo xbps-install gtk4`` +``sudo xbps-install libadwaita`` +``sudo xbps-install gtksourceview5`` + +### FreeBSD +It may be possible to build VG Music Studio on FreeBSD (and FreeBSD based operating systems), however this section will need to be updated with better accuracy on how to build on this platform. + +If your operating system is FreeBSD, or is based on FreeBSD, the [portmaster](https://cgit.freebsd.org/ports/tree/ports-mgmt/portmaster/) utility will need to be installed before installing ``gtk40``, ``libadwaita`` and ``gtksourceview5``. A guide on how to do so can be found [here](https://docs.freebsd.org/en/books/handbook/ports/). + +Once installed and configured, run the following commands to install these ports: +``portmaster -PP gtk40`` +``portmaster -PP libadwaita`` +``portmaster -PP gtksourceview5`` + ---- ## Special Thanks To: ### General * Stich991 - Italian translation * tuku473 - Design suggestions, colors, Spanish translation -* Lachesis - French translation -* Delusional Moonlight - Russian translation ### AlphaDream Engine * irdkwia - Finding games that used the engine diff --git a/VG Music Studio - Core/Backend.cs b/VG Music Studio - Core/Backend.cs new file mode 100644 index 0000000..5fda723 --- /dev/null +++ b/VG Music Studio - Core/Backend.cs @@ -0,0 +1,744 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.Wave; +using PortAudio; +using Kermalis.EndianBinaryIO; + +namespace Kermalis.VGMusicStudio.Core; + +public class Backend +{ + /// + /// The output parameters for an output stream + /// + internal static StreamParameters OParams; + + /// + /// The default settings for an output stream + /// + public StreamParameters DefaultOutputParams { get; private set; } + + /// + /// How many frames to give each audio buffer + /// + public int FramesPerBuffer { get; private set; } = 4096; + + /// + /// The sample rate of the audio data + /// + public int SampleRate { get; private set; } + + /// + /// The instance of the backend currently running. + /// + /// `null` if the backend isn't activated. Otherwise, it should contain a value. + public static Backend Instance { get; private set; } = null; + + public Backend() + { + } + + public void Init(BufferedWaveProvider waveProvider) + { + // Check if a backend is already initialized + if (Instance == null) + return; + + Pa.Initialize(); + + // Try setting up an output device + OParams.device = Pa.DefaultOutputDevice; + if (OParams.device == Pa.NoDevice) + throw new Exception("PortAudio Error:\nThere's no default audio device available."); + + OParams.channelCount = 2; + OParams.sampleFormat = SampleFormat.Float32; + OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; + OParams.hostApiSpecificStreamInfo = IntPtr.Zero; + + // Set it as the default audio device + DefaultOutputParams = OParams; + + + Instance = this; + } + + public void OnVolumeChanged(float volume, bool isMuted) + { + + } + public void OnDisplayNameChanged(string displayName) + { + throw new NotImplementedException(); + } + public void OnIconPathChanged(string iconPath) + { + throw new NotImplementedException(); + } + public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) + { + throw new NotImplementedException(); + } + public void OnGroupingParamChanged(ref Guid groupingId) + { + throw new NotImplementedException(); + } + // Fires on @out.Play() and @out.Stop() + public void OnStateChanged(uint state) + { + + } + public void OnSessionDisconnected(uint disconnectReason) + { + throw new NotImplementedException(); + } + public void SetVolume(float volume) + { + + } + + public virtual void Dispose() + { + + } + + public class WaveBuffer + { + // + // Summary: + // Number of Bytes + public int numberOfBytes; + + private byte[] byteBuffer; + + private float[] floatBuffer; + + private short[] shortBuffer; + + private int[] intBuffer; + + // + // Summary: + // Gets the byte buffer. + // + // Value: + // The byte buffer. + public byte[] ByteBuffer => byteBuffer; + + // + // Summary: + // Gets the float buffer. + // + // Value: + // The float buffer. + public float[] FloatBuffer => floatBuffer; + + // + // Summary: + // Gets the short buffer. + // + // Value: + // The short buffer. + public short[] ShortBuffer => shortBuffer; + + // + // Summary: + // Gets the int buffer. + // + // Value: + // The int buffer. + public int[] IntBuffer => intBuffer; + + // + // Summary: + // Gets the max size in bytes of the byte buffer.. + // + // Value: + // Maximum number of bytes in the buffer. + public int MaxSize => byteBuffer.Length; + + // + // Summary: + // Gets or sets the byte buffer count. + // + // Value: + // The byte buffer count. + public int ByteBufferCount + { + get + { + return numberOfBytes; + } + set + { + numberOfBytes = CheckValidityCount("ByteBufferCount", value, 1); + } + } + + // + // Summary: + // Gets or sets the float buffer count. + // + // Value: + // The float buffer count. + public int FloatBufferCount + { + get + { + return numberOfBytes / 4; + } + set + { + numberOfBytes = CheckValidityCount("FloatBufferCount", value, 4); + } + } + + // + // Summary: + // Gets or sets the short buffer count. + // + // Value: + // The short buffer count. + public int ShortBufferCount + { + get + { + return numberOfBytes / 2; + } + set + { + numberOfBytes = CheckValidityCount("ShortBufferCount", value, 2); + } + } + + // + // Summary: + // Gets or sets the int buffer count. + // + // Value: + // The int buffer count. + public int IntBufferCount + { + get + { + return numberOfBytes / 4; + } + set + { + numberOfBytes = CheckValidityCount("IntBufferCount", value, 4); + } + } + + // + // Summary: + // Checks the validity of the count parameters. + // + // Parameters: + // argName: + // Name of the arg. + // + // value: + // The value. + // + // sizeOfValue: + // The size of value. + private int CheckValidityCount(string argName, int value, int sizeOfValue) + { + int num = value * sizeOfValue; + if (num % 4 != 0) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); + } + + if (value < 0 || value > byteBuffer.Length / sizeOfValue) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceed max count {byteBuffer.Length / sizeOfValue}"); + } + + return num; + } + + // + // Summary: + // Initializes a new instance of the NAudio.Wave.WaveBuffer class. + // + // Parameters: + // sizeToAllocateInBytes: + // The number of bytes. The size of the final buffer will be aligned on 4 Bytes + // (upper bound) + public WaveBuffer(int sizeToAllocateInBytes) + { + Instance.FramesPerBuffer = sizeToAllocateInBytes / sizeof(float); + + int num = sizeToAllocateInBytes % 4; + sizeToAllocateInBytes = ((num == 0) ? sizeToAllocateInBytes : (sizeToAllocateInBytes + 4 - num)); + byteBuffer = new byte[sizeToAllocateInBytes]; + numberOfBytes = 0; + } + } + + public class BufferedWaveProvider + { + private readonly WaveFormat waveFormat; + + // + // Summary: + // If true, always read the amount of data requested, padding with zeroes if necessary + // By default is set to true + public bool ReadFully { get; set; } + + // + // Summary: + // Buffer length in bytes + public int BufferLength { get; set; } + + // + // Summary: + // If true, when the buffer is full, start throwing away data if false, AddSamples + // will throw an exception when buffer is full + public bool DiscardOnBufferOverflow { get; set; } + + public BufferedWaveProvider(WaveFormat waveFormat) + { + //this.waveFormat = waveFormat; + //Instance.FramesPerBuffer = BufferLength = waveFormat.averageBytesPerSecond * 5; + //ReadFully = true; + } + + public void AddSamples(byte[] buffer, int offset, int count) + { + + } + } + + public class WaveFormat + { + // + // Summary: + // number of channels + protected short Channels; + + // + // Summary: + // sample rate + protected int SampleRate; + + // + // Summary: + // for buffer estimation + public int AverageBytesPerSecond; + + // + // Summary: + // block size of data + protected short BlockAlign; + + // + // Summary: + // number of bits per sample of mono data + protected short BitsPerSample; + + // + // Summary: + // number of following bytes + protected short ExtraSize; + + public WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels) + { + WaveFormat waveFormat = new WaveFormat(); + waveFormat.Channels = (short)channels; + waveFormat.BitsPerSample = 32; + Instance.SampleRate = waveFormat.SampleRate = sampleRate; + waveFormat.BlockAlign = (short)(4 * channels); + waveFormat.AverageBytesPerSecond = sampleRate * waveFormat.BlockAlign; + waveFormat.ExtraSize = 0; + return waveFormat; + } + } + + public class WaveFileWriter + { + private Stream outStream; + + private readonly EndianBinaryWriter writer; + + private long dataSizePos; + + private long factSampleCountPos; + + private long dataChunkSize; + + private readonly WaveFormat format; + + private readonly string filename; + + private readonly byte[] value24 = new byte[3]; + + // + // Summary: + // The wave file name or null if not applicable + public string Filename => filename; + + // + // Summary: + // Number of bytes of audio in the data chunk + public long Length => dataChunkSize; + + // + // Summary: + // Total time (calculated from Length and average bytes per second) + public TimeSpan TotalTime => TimeSpan.FromSeconds((double)Length / (double)WaveFormat.AverageBytesPerSecond); + + // + // Summary: + // WaveFormat of this wave file + public WaveFormat WaveFormat => format; + + // + // Summary: + // Returns false: Cannot read from a WaveFileWriter + public bool CanRead => false; + + // + // Summary: + // Returns true: Can write to a WaveFileWriter + public bool CanWrite => true; + + // + // Summary: + // Returns false: Cannot seek within a WaveFileWriter + public bool CanSeek => false; + + // + // Summary: + // Gets the Position in the WaveFile (i.e. number of bytes written so far) + public long Position + { + get + { + return dataChunkSize; + } + set + { + throw new InvalidOperationException("Repositioning a WaveFileWriter is not supported"); + } + } + + public void Write(byte[] data, int offset, int count) + { + + } + } + + public class PortAudio : IDisposable + { + // License: APL 2.0 + // Author: Benjamin N. Summerton + // Based on the code from Bassoon, modified for use in VGMS + + // Flag used for the IDispoable interface + private bool disposed = false; + + /// + /// Audio level, should be between [0.0, 1.0]. + /// 0.0 = silent, 1.0 = full volume + /// + internal float volume = 1; + + /// + /// Where in the audio (in bytes) we are. + /// + internal long Cursor = 0; + + /// + /// If we should be currently playing audio + /// + internal bool playingBack = false; + + private Stream stream; + + /// + /// How much data needs to be read when doing a playback + /// + internal int finalFrameSize; + + /// + /// How many frames of audio are in the loaded file. + /// + private readonly long totalFrames; + + public PortAudio() + { + // Setup the playback stream + // Get the channel count + StreamParameters oParams = Instance.DefaultOutputParams; + oParams.channelCount = OParams.channelCount; + + // Create the stream + stream = new Stream( + null, + oParams, + Instance.SampleRate, + (uint)Instance.FramesPerBuffer, + StreamFlags.ClipOff, + PlayCallback, + this + ); + } + + ~PortAudio() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + protected virtual void Dispose(bool disposing) + { + + } + + #region Math + /// + /// Clamp a value between a range (inclusive). + /// + /// This exists in .NET Core, but not in .NET standard + /// + /// Valume to clamp + /// minimum possible value + /// maximum possible value + /// The orignal value (clamped between the range) + public static float Clamp(float value, float min, float max) => + Math.Max(Math.Min(value, max), min); + + /// + /// Clamp a value between a range (inclusive). + /// + /// This exists in .NET Core, but not in .NET standard + /// + /// Valume to clamp + /// minimum possible value + /// maximum possible value + /// The orignal value (clamped between the range) + public static long Clamp(long value, long min, long max) => + Math.Max(Math.Min(value, max), min); + + #endregion + + #region Properties + /// + /// Level to play back the audio at. default is 100%. + /// + /// When setting, this will be clamped within range in the `value`. + /// + /// [0.0, 1.0] + public float Volume + { + get => volume; + set => volume = Clamp(value, 0, 1); + } + + /// + /// See if the sound is being played back rightnow + /// + /// true if so, false otherwise + public bool IsPlaying + { + get => playingBack; + } + + + #endregion // Properties + + #region Methods + /// + /// Start playing the sound + /// + public void Play() + { + playingBack = true; + + if (stream.IsStopped) + stream.Start(); + } + + /// + /// Stop audio playback + /// + public void Pause() + { + playingBack = false; + + if (stream.IsActive) + stream.Stop(); + } + + /// + /// Pause audio playback + /// + public void Stop() + { + playingBack = false; + + if (stream.IsActive) + Cursor = 0; + stream.Stop(); + } + #endregion // Methods + + #region PortAudio Callbacks + /// + /// Performs the actual audio playback + /// + private static StreamCallbackResult PlayCallback( + IntPtr input, IntPtr output, + uint frameCount, + ref StreamCallbackTimeInfo timeInfo, + StreamCallbackFlags statusFlags, + IntPtr dataPtr + ) + { + // NOTE: make sure there are no malloc in this block, as it can cause issues. + PortAudio data = Stream.GetUserData(dataPtr); + + long numRead = 0; + unsafe + { + // Do a zero-out memset + float* buffer = (float*)output; + for (uint i = 0; i < data.finalFrameSize; i++) + *buffer++ = 0; + + // If we are reading data, then play it back + if (data.playingBack) + { + // Read data + //numRead = data.audioFile.readFloat(output, data.finalFrameSize); + + + // Apply volume + buffer = (float*)output; + for (int i = 0; i < numRead; i++) + *buffer++ *= data.volume; + } + } + + // Increment the counter + data.Cursor += numRead; + + // Did we hit the end? + if (data.playingBack && (numRead < frameCount)) + { + // Stop playback, and reset to the beginning + data.Cursor = 0; + data.playingBack = false; + } + + // Continue on + return StreamCallbackResult.Continue; + } + #endregion // PortAudio Callbacks + } + + public abstract class NAudio : IAudioSessionEventsHandler, IDisposable + { + public static event Action? VolumeChanged; + + public readonly bool[] Mutes; + private IWavePlayer _out; + private AudioSessionControl _appVolume; + + private bool _shouldSendVolUpdateEvent = true; + + protected WaveFileWriter? _waveWriter; + protected abstract WaveFormat WaveFormat { get; } + + + protected NAudio() + { + Mutes = new bool[SongState.MAX_TRACKS]; + _out = null!; + _appVolume = null!; + } + + protected void Init(IWaveProvider waveProvider) + { + _out = new WasapiOut(); + _out.Init(waveProvider); + using (var en = new MMDeviceEnumerator()) + { + SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; + int id = Environment.ProcessId; + for (int i = 0; i < sessions.Count; i++) + { + AudioSessionControl session = sessions[i]; + if (session.GetProcessID == id) + { + _appVolume = session; + _appVolume.RegisterEventClient(this); + break; + } + } + } + _out.Play(); + } + + public void OnVolumeChanged(float volume, bool isMuted) + { + if (_shouldSendVolUpdateEvent) + { + VolumeChanged?.Invoke(volume); + } + _shouldSendVolUpdateEvent = true; + } + public void OnDisplayNameChanged(string displayName) + { + throw new NotImplementedException(); + } + public void OnIconPathChanged(string iconPath) + { + throw new NotImplementedException(); + } + public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) + { + throw new NotImplementedException(); + } + public void OnGroupingParamChanged(ref Guid groupingId) + { + throw new NotImplementedException(); + } + // Fires on @out.Play() and @out.Stop() + public void OnStateChanged(AudioSessionState state) + { + if (state == AudioSessionState.AudioSessionStateActive) + { + OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); + } + } + public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) + { + throw new NotImplementedException(); + } + public void SetVolume(float volume) + { + _shouldSendVolUpdateEvent = false; + _appVolume.SimpleAudioVolume.Volume = volume; + } + + public virtual void Dispose() + { + GC.SuppressFinalize(this); + _out.Stop(); + _out.Dispose(); + _appVolume.Dispose(); + } + } +} diff --git a/VG Music Studio - Core/Engine.cs b/VG Music Studio - Core/Engine.cs index a37f0e0..d5c4b33 100644 --- a/VG Music Studio - Core/Engine.cs +++ b/VG Music Studio - Core/Engine.cs @@ -9,8 +9,9 @@ public abstract class Engine : IDisposable public abstract Config Config { get; } public abstract Mixer Mixer { get; } public abstract Player Player { get; } + public abstract bool UseNewMixer { get; } - public virtual void Dispose() + public virtual void Dispose() { Config.Dispose(); Mixer.Dispose(); diff --git a/VG Music Studio - Core/Formats/Enumerations/WaveEncodingEnums.cs b/VG Music Studio - Core/Formats/Enumerations/WaveEncodingEnums.cs new file mode 100644 index 0000000..7cace6b --- /dev/null +++ b/VG Music Studio - Core/Formats/Enumerations/WaveEncodingEnums.cs @@ -0,0 +1,455 @@ +#region Original License Info +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright 2020 Mark Heath + * + * 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. + * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +#endregion + +// From NAudio.Wave, modified by Platinum Lucario for use in VG Music Studio + +namespace Kermalis.VGMusicStudio.Core.Formats; + +/// +/// Summary description for WaveFormatEncoding. +/// +public enum WaveEncoding : ushort +{ + /// WAVE_FORMAT_UNKNOWN, Microsoft Corporation + Unknown = 0x0000, + + /// WAVE_FORMAT_PCM Microsoft Corporation + Pcm = 0x0001, + + /// WAVE_FORMAT_PCM4 Microsoft Corporation + Pcm4 = Pcm, + + /// WAVE_FORMAT_PCM8 Microsoft Corporation + Pcm8 = Pcm, + + /// WAVE_FORMAT_PCM16 Microsoft Corporation + Pcm16 = Pcm, + + /// WAVE_FORMAT_ADPCM Microsoft Corporation + Adpcm = 0x0002, + + /// WAVE_FORMAT_IEEE_FLOAT Microsoft Corporation + IeeeFloat = 0x0003, + + /// WAVE_FORMAT_VSELP Compaq Computer Corp. + Vselp = 0x0004, + + /// WAVE_FORMAT_IBM_CVSD IBM Corporation + IbmCvsd = 0x0005, + + /// WAVE_FORMAT_ALAW Microsoft Corporation + ALaw = 0x0006, + + /// WAVE_FORMAT_MULAW Microsoft Corporation + MuLaw = 0x0007, + + /// WAVE_FORMAT_DTS Microsoft Corporation + Dts = 0x0008, + + /// WAVE_FORMAT_DRM Microsoft Corporation + Drm = 0x0009, + + /// WAVE_FORMAT_WMAVOICE9 + WmaVoice9 = 0x000A, + + /// WAVE_FORMAT_OKI_ADPCM OKI + OkiAdpcm = 0x0010, + + /// WAVE_FORMAT_DVI_ADPCM Intel Corporation + DviAdpcm = 0x0011, + + /// WAVE_FORMAT_IMA_ADPCM Intel Corporation + ImaAdpcm = DviAdpcm, + + /// WAVE_FORMAT_MEDIASPACE_ADPCM Videologic + MediaspaceAdpcm = 0x0012, + + /// WAVE_FORMAT_SIERRA_ADPCM Sierra Semiconductor Corp + SierraAdpcm = 0x0013, + + /// WAVE_FORMAT_G723_ADPCM Antex Electronics Corporation + G723Adpcm = 0x0014, + + /// WAVE_FORMAT_DIGISTD DSP Solutions, Inc. + DigiStd = 0x0015, + + /// WAVE_FORMAT_DIGIFIX DSP Solutions, Inc. + DigiFix = 0x0016, + + /// WAVE_FORMAT_DIALOGIC_OKI_ADPCM Dialogic Corporation + DialogicOkiAdpcm = 0x0017, + + /// WAVE_FORMAT_MEDIAVISION_ADPCM Media Vision, Inc. + MediaVisionAdpcm = 0x0018, + + /// WAVE_FORMAT_CU_CODEC Hewlett-Packard Company + CUCodec = 0x0019, + + /// WAVE_FORMAT_YAMAHA_ADPCM Yamaha Corporation of America + YamahaAdpcm = 0x0020, + + /// WAVE_FORMAT_SONARC Speech Compression + SonarC = 0x0021, + + /// WAVE_FORMAT_DSPGROUP_TRUESPEECH DSP Group, Inc + DspGroupTrueSpeech = 0x0022, + + /// WAVE_FORMAT_ECHOSC1 Echo Speech Corporation + EchoSpeechCorporation1 = 0x0023, + + /// WAVE_FORMAT_AUDIOFILE_AF36, Virtual Music, Inc. + AudioFileAf36 = 0x0024, + + /// WAVE_FORMAT_APTX Audio Processing Technology + Aptx = 0x0025, + + /// WAVE_FORMAT_AUDIOFILE_AF10, Virtual Music, Inc. + AudioFileAf10 = 0x0026, + + /// WAVE_FORMAT_PROSODY_1612, Aculab plc + Prosody1612 = 0x0027, + + /// WAVE_FORMAT_LRC, Merging Technologies S.A. + Lrc = 0x0028, + + /// WAVE_FORMAT_DOLBY_AC2, Dolby Laboratories + DolbyAc2 = 0x0030, + + /// WAVE_FORMAT_GSM610, Microsoft Corporation + Gsm610 = 0x0031, + + /// WAVE_FORMAT_MSNAUDIO, Microsoft Corporation + MsnAudio = 0x0032, + + /// WAVE_FORMAT_ANTEX_ADPCME, Antex Electronics Corporation + AntexAdpcme = 0x0033, + + /// WAVE_FORMAT_CONTROL_RES_VQLPC, Control Resources Limited + ControlResVqlpc = 0x0034, + + /// WAVE_FORMAT_DIGIREAL, DSP Solutions, Inc. + DigiReal = 0x0035, + + /// WAVE_FORMAT_DIGIADPCM, DSP Solutions, Inc. + DigiAdpcm = 0x0036, + + /// WAVE_FORMAT_CONTROL_RES_CR10, Control Resources Limited + ControlResCr10 = 0x0037, + + /// + WAVE_FORMAT_NMS_VBXADPCM = 0x0038, // Natural MicroSystems + /// + WAVE_FORMAT_CS_IMAADPCM = 0x0039, // Crystal Semiconductor IMA ADPCM + /// + WAVE_FORMAT_ECHOSC3 = 0x003A, // Echo Speech Corporation + /// + WAVE_FORMAT_ROCKWELL_ADPCM = 0x003B, // Rockwell International + /// + WAVE_FORMAT_ROCKWELL_DIGITALK = 0x003C, // Rockwell International + /// + WAVE_FORMAT_XEBEC = 0x003D, // Xebec Multimedia Solutions Limited + /// + WAVE_FORMAT_G721_ADPCM = 0x0040, // Antex Electronics Corporation + /// + WAVE_FORMAT_G728_CELP = 0x0041, // Antex Electronics Corporation + /// + WAVE_FORMAT_MSG723 = 0x0042, // Microsoft Corporation + /// WAVE_FORMAT_MPEG, Microsoft Corporation + Mpeg = 0x0050, + + /// + WAVE_FORMAT_RT24 = 0x0052, // InSoft, Inc. + /// + WAVE_FORMAT_PAC = 0x0053, // InSoft, Inc. + /// WAVE_FORMAT_MPEGLAYER3, ISO/MPEG Layer3 Format Tag + MpegLayer3 = 0x0055, + + /// + WAVE_FORMAT_LUCENT_G723 = 0x0059, // Lucent Technologies + /// + WAVE_FORMAT_CIRRUS = 0x0060, // Cirrus Logic + /// + WAVE_FORMAT_ESPCM = 0x0061, // ESS Technology + /// + WAVE_FORMAT_VOXWARE = 0x0062, // Voxware Inc + /// + WAVE_FORMAT_CANOPUS_ATRAC = 0x0063, // Canopus, co., Ltd. + /// + WAVE_FORMAT_G726_ADPCM = 0x0064, // APICOM + /// + WAVE_FORMAT_G722_ADPCM = 0x0065, // APICOM + /// + WAVE_FORMAT_DSAT_DISPLAY = 0x0067, // Microsoft Corporation + /// + WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 0x0069, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_AC8 = 0x0070, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_AC10 = 0x0071, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_AC16 = 0x0072, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_AC20 = 0x0073, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_RT24 = 0x0074, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_RT29 = 0x0075, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_RT29HW = 0x0076, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_VR12 = 0x0077, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_VR18 = 0x0078, // Voxware Inc + /// + WAVE_FORMAT_VOXWARE_TQ40 = 0x0079, // Voxware Inc + /// + WAVE_FORMAT_SOFTSOUND = 0x0080, // Softsound, Ltd. + /// + WAVE_FORMAT_VOXWARE_TQ60 = 0x0081, // Voxware Inc + /// + WAVE_FORMAT_MSRT24 = 0x0082, // Microsoft Corporation + /// + WAVE_FORMAT_G729A = 0x0083, // AT&T Labs, Inc. + /// + WAVE_FORMAT_MVI_MVI2 = 0x0084, // Motion Pixels + /// + WAVE_FORMAT_DF_G726 = 0x0085, // DataFusion Systems (Pty) (Ltd) + /// + WAVE_FORMAT_DF_GSM610 = 0x0086, // DataFusion Systems (Pty) (Ltd) + /// + WAVE_FORMAT_ISIAUDIO = 0x0088, // Iterated Systems, Inc. + /// + WAVE_FORMAT_ONLIVE = 0x0089, // OnLive! Technologies, Inc. + /// + WAVE_FORMAT_SBC24 = 0x0091, // Siemens Business Communications Sys + /// + WAVE_FORMAT_DOLBY_AC3_SPDIF = 0x0092, // Sonic Foundry + /// + WAVE_FORMAT_MEDIASONIC_G723 = 0x0093, // MediaSonic + /// + WAVE_FORMAT_PROSODY_8KBPS = 0x0094, // Aculab plc + /// + WAVE_FORMAT_ZYXEL_ADPCM = 0x0097, // ZyXEL Communications, Inc. + /// + WAVE_FORMAT_PHILIPS_LPCBB = 0x0098, // Philips Speech Processing + /// + WAVE_FORMAT_PACKED = 0x0099, // Studer Professional Audio AG + /// + WAVE_FORMAT_MALDEN_PHONYTALK = 0x00A0, // Malden Electronics Ltd. + /// WAVE_FORMAT_GSM + Gsm = 0x00A1, + + /// WAVE_FORMAT_G729 + G729 = 0x00A2, + + /// WAVE_FORMAT_G723 + G723 = 0x00A3, + + /// WAVE_FORMAT_ACELP + Acelp = 0x00A4, + + /// + /// WAVE_FORMAT_RAW_AAC1 + /// + RawAac = 0x00FF, + /// + WAVE_FORMAT_RHETOREX_ADPCM = 0x0100, // Rhetorex Inc. + /// + WAVE_FORMAT_IRAT = 0x0101, // BeCubed Software Inc. + /// + WAVE_FORMAT_VIVO_G723 = 0x0111, // Vivo Software + /// + WAVE_FORMAT_VIVO_SIREN = 0x0112, // Vivo Software + /// + WAVE_FORMAT_DIGITAL_G723 = 0x0123, // Digital Equipment Corporation + /// + WAVE_FORMAT_SANYO_LD_ADPCM = 0x0125, // Sanyo Electric Co., Ltd. + /// + WAVE_FORMAT_SIPROLAB_ACEPLNET = 0x0130, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_SIPROLAB_ACELP4800 = 0x0131, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_SIPROLAB_ACELP8V3 = 0x0132, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_SIPROLAB_G729 = 0x0133, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_SIPROLAB_G729A = 0x0134, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_SIPROLAB_KELVIN = 0x0135, // Sipro Lab Telecom Inc. + /// + WAVE_FORMAT_G726ADPCM = 0x0140, // Dictaphone Corporation + /// + WAVE_FORMAT_QUALCOMM_PUREVOICE = 0x0150, // Qualcomm, Inc. + /// + WAVE_FORMAT_QUALCOMM_HALFRATE = 0x0151, // Qualcomm, Inc. + /// + WAVE_FORMAT_TUBGSM = 0x0155, // Ring Zero Systems, Inc. + /// + WAVE_FORMAT_MSAUDIO1 = 0x0160, // Microsoft Corporation + /// + /// Windows Media Audio, WAVE_FORMAT_WMAUDIO2, Microsoft Corporation + /// + WindowsMediaAudio = 0x0161, + + /// + /// Windows Media Audio Professional WAVE_FORMAT_WMAUDIO3, Microsoft Corporation + /// + WindowsMediaAudioProfessional = 0x0162, + + /// + /// Windows Media Audio Lossless, WAVE_FORMAT_WMAUDIO_LOSSLESS + /// + WindowsMediaAudioLosseless = 0x0163, + + /// + /// Windows Media Audio Professional over SPDIF WAVE_FORMAT_WMASPDIF (0x0164) + /// + WindowsMediaAudioSpdif = 0x0164, + + /// + WAVE_FORMAT_UNISYS_NAP_ADPCM = 0x0170, // Unisys Corp. + /// + WAVE_FORMAT_UNISYS_NAP_ULAW = 0x0171, // Unisys Corp. + /// + WAVE_FORMAT_UNISYS_NAP_ALAW = 0x0172, // Unisys Corp. + /// + WAVE_FORMAT_UNISYS_NAP_16K = 0x0173, // Unisys Corp. + /// + WAVE_FORMAT_CREATIVE_ADPCM = 0x0200, // Creative Labs, Inc + /// + WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 0x0202, // Creative Labs, Inc + /// + WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 0x0203, // Creative Labs, Inc + /// + WAVE_FORMAT_UHER_ADPCM = 0x0210, // UHER informatic GmbH + /// + WAVE_FORMAT_QUARTERDECK = 0x0220, // Quarterdeck Corporation + /// + WAVE_FORMAT_ILINK_VC = 0x0230, // I-link Worldwide + /// + WAVE_FORMAT_RAW_SPORT = 0x0240, // Aureal Semiconductor + /// + WAVE_FORMAT_ESST_AC3 = 0x0241, // ESS Technology, Inc. + /// + WAVE_FORMAT_IPI_HSX = 0x0250, // Interactive Products, Inc. + /// + WAVE_FORMAT_IPI_RPELP = 0x0251, // Interactive Products, Inc. + /// + WAVE_FORMAT_CS2 = 0x0260, // Consistent Software + /// + WAVE_FORMAT_SONY_SCX = 0x0270, // Sony Corp. + /// + WAVE_FORMAT_FM_TOWNS_SND = 0x0300, // Fujitsu Corp. + /// + WAVE_FORMAT_BTV_DIGITAL = 0x0400, // Brooktree Corporation + /// + WAVE_FORMAT_QDESIGN_MUSIC = 0x0450, // QDesign Corporation + /// + WAVE_FORMAT_VME_VMPCM = 0x0680, // AT&T Labs, Inc. + /// + WAVE_FORMAT_TPC = 0x0681, // AT&T Labs, Inc. + /// + WAVE_FORMAT_OLIGSM = 0x1000, // Ing C. Olivetti & C., S.p.A. + /// + WAVE_FORMAT_OLIADPCM = 0x1001, // Ing C. Olivetti & C., S.p.A. + /// + WAVE_FORMAT_OLICELP = 0x1002, // Ing C. Olivetti & C., S.p.A. + /// + WAVE_FORMAT_OLISBC = 0x1003, // Ing C. Olivetti & C., S.p.A. + /// + WAVE_FORMAT_OLIOPR = 0x1004, // Ing C. Olivetti & C., S.p.A. + /// + WAVE_FORMAT_LH_CODEC = 0x1100, // Lernout & Hauspie + /// + WAVE_FORMAT_NORRIS = 0x1400, // Norris Communications, Inc. + /// + WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 0x1500, // AT&T Labs, Inc. + + /// + /// Advanced Audio Coding (AAC) audio in Audio Data Transport Stream (ADTS) format. + /// The format block is a WAVEFORMATEX structure with wFormatTag equal to WAVE_FORMAT_MPEG_ADTS_AAC. + /// + /// + /// The WAVEFORMATEX structure specifies the core AAC-LC sample rate and number of channels, + /// prior to applying spectral band replication (SBR) or parametric stereo (PS) tools, if present. + /// No additional data is required after the WAVEFORMATEX structure. + /// + /// http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + MPEG_ADTS_AAC = 0x1600, + + /// + /// Source wmCodec.h + MPEG_RAW_AAC = 0x1601, + + /// + /// MPEG-4 audio transport stream with a synchronization layer (LOAS) and a multiplex layer (LATM). + /// The format block is a WAVEFORMATEX structure with wFormatTag equal to WAVE_FORMAT_MPEG_LOAS. + /// + /// + /// The WAVEFORMATEX structure specifies the core AAC-LC sample rate and number of channels, + /// prior to applying spectral SBR or PS tools, if present. + /// No additional data is required after the WAVEFORMATEX structure. + /// + /// http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + MPEG_LOAS = 0x1602, + + /// NOKIA_MPEG_ADTS_AAC + /// Source wmCodec.h + NOKIA_MPEG_ADTS_AAC = 0x1608, + + /// NOKIA_MPEG_RAW_AAC + /// Source wmCodec.h + NOKIA_MPEG_RAW_AAC = 0x1609, + + /// VODAFONE_MPEG_ADTS_AAC + /// Source wmCodec.h + VODAFONE_MPEG_ADTS_AAC = 0x160A, + + /// VODAFONE_MPEG_RAW_AAC + /// Source wmCodec.h + VODAFONE_MPEG_RAW_AAC = 0x160B, + + /// + /// High-Efficiency Advanced Audio Coding (HE-AAC) stream. + /// The format block is an HEAACWAVEFORMAT structure. + /// + /// http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + MPEG_HEAAC = 0x1610, + + /// WAVE_FORMAT_DVM + WAVE_FORMAT_DVM = 0x2000, // FAST Multimedia AG + + // others - not from MS headers + /// WAVE_FORMAT_VORBIS1 "Og" Original stream compatible + Vorbis1 = 0x674f, + + /// WAVE_FORMAT_VORBIS2 "Pg" Have independent header + Vorbis2 = 0x6750, + + /// WAVE_FORMAT_VORBIS3 "Qg" Have no codebook header + Vorbis3 = 0x6751, + + /// WAVE_FORMAT_VORBIS1P "og" Original stream compatible + Vorbis1P = 0x676f, + + /// WAVE_FORMAT_VORBIS2P "pg" Have independent headere + Vorbis2P = 0x6770, + + /// WAVE_FORMAT_VORBIS3P "qg" Have no codebook header + Vorbis3P = 0x6771, + + /// WAVE_FORMAT_EXTENSIBLE + Extensible = 0xFFFE, // Microsoft + /// + WAVE_FORMAT_DEVELOPMENT = 0xFFFF, +} \ No newline at end of file diff --git a/VG Music Studio - Core/Formats/Wave.cs b/VG Music Studio - Core/Formats/Wave.cs new file mode 100644 index 0000000..5be041f --- /dev/null +++ b/VG Music Studio - Core/Formats/Wave.cs @@ -0,0 +1,399 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.IO; + +namespace Kermalis.VGMusicStudio.Core.Formats; + +public class Wave +{ + public string? FileName; + public ushort Channels; + public uint SampleRate; + public ushort BitsPerSample; + public ushort ExtraSize; + public ushort BlockAlign; + public uint AverageBytesPerSecond; + public bool IsLooped = false; + public uint LoopStart; + public uint LoopEnd; + + public bool DiscardOnBufferOverflow; + public int BufferLength; + + public byte[]? Buffer; + private int ReadPosition; + private int WritePosition; + private int ByteCount; + private object? LockObject; + + private long DataChunkSize; + private long DataChunkLength; + private long DataChunkPosition; + private readonly Stream? InStream; + private readonly Stream? OutStream; + + public long Position + { + get + { + return InStream!.Position - DataChunkPosition; + } + set + { + lock (LockObject!) + { + value = Math.Min(value, DataChunkLength); + // To keep it in sync + value -= (value % BlockAlign); + InStream!.Position = value + DataChunkPosition; + } + } + } + + public Wave() + { + InStream = new MemoryStream(); + OutStream = new MemoryStream(); + } + public Wave(string fileName) + { + InStream = new MemoryStream(); + OutStream = new MemoryStream(); + FileName = fileName; + } + + public Wave CreateFormat(uint sampleRate, ushort channels, ushort blockAlign, uint averageBytesPerSecond, ushort bitsPerSample) + { + Channels = channels; + SampleRate = sampleRate; + AverageBytesPerSecond = averageBytesPerSecond; + BlockAlign = blockAlign; + BitsPerSample = bitsPerSample; + ExtraSize = 0; + return new Wave(); + } + public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate* BlockAlign, 32); + public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels, ushort bits) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate * BlockAlign, bits); + + public void AddSamples(Span buffer, int offset, int count) + { + if (Buffer == null) + { + Buffer = new byte[BufferLength]; + LockObject = new object(); + } + + if (WriteBuffer(buffer, offset, count) < count && !DiscardOnBufferOverflow) + { + throw new InvalidOperationException("The buffer is full and cannot be written to."); + } + } + + public int ReadBuffer(Span data, int offset, int count) + { + lock (LockObject!) + { + if (count > ByteCount) + { + count = ByteCount; + } + + int num = 0; + int num2 = Math.Min(Buffer!.Length - ReadPosition, count); + Array.Copy(Buffer, ReadPosition, data.ToArray(), offset, num2); + num += num2; + ReadPosition += num2; + ReadPosition %= Buffer.Length; + if (num < count) + { + Array.Copy(Buffer, ReadPosition, data.ToArray(), offset + num, count - num); + ReadPosition += count - num; + num = count; + } + + ByteCount -= num; + return num; + } + } + + public int WriteBuffer(Span data, int offset, int count) + { + lock (LockObject!) + { + int num = 0; + if (count > Buffer!.Length - ByteCount) + { + count = Buffer.Length - ByteCount; + } + + int num2 = Math.Min(Buffer.Length - WritePosition, count); + Array.Copy(data.ToArray(), offset, Buffer, WritePosition, num2); + WritePosition += num2; + WritePosition %= Buffer.Length; + num += num2; + if (num < count) + { + Array.Copy(data.ToArray(), offset + num, Buffer, WritePosition, count - num); + WritePosition += count - num; + num = count; + } + + ByteCount += num; + return num; + } + } + + public int Read(Span array, int offset, int count) + { + if (count % BlockAlign != 0) + { + throw new ArgumentException( + $"Must read complete blocks: requested {count}, block align is {BlockAlign}"); + } + lock (LockObject!) + { + // sometimes there is more junk at the end of the file past the data chunk + if (Position + count > DataChunkLength) + { + count = (int)(DataChunkLength - Position); + } + return InStream!.Read(array.ToArray(), offset, count); + } + } + + public void Write(Span data, int offset, int count) + { + if (OutStream!.Length + count > uint.MaxValue) + { + throw new ArgumentException("WAV file too large", nameof(count)); + } + + OutStream.Write(data.ToArray(), offset, count); + DataChunkSize += count; + } + + public Span WriteBytes(Span data) => WriteBytes(data, WaveEncoding.Pcm16); + + public Span WriteBytes(Span data, WaveEncoding encoding) + { + var convertedData = new byte[data.Length * 2]; + int index = 0; + for (int i = 0; i < data.Length; i++) + { + convertedData[index++] = (byte)(data[i] & 0xff); + convertedData[index++] = (byte)(data[i] >> 8); + convertedData[index++] = (byte)(data[i] >> 16); + convertedData[index++] = (byte)(data[i] >> 24); + convertedData[index++] = (byte)(data[i] >> 32); + convertedData[index++] = (byte)(data[i] >> 40); + convertedData[index++] = (byte)(data[i] >> 48); + convertedData[index++] = (byte)(data[i] >> 56); + } + + return WriteBytes(convertedData, encoding); + } + + public Span WriteBytes(Span data) => WriteBytes(data, WaveEncoding.Pcm16); + + public Span WriteBytes(Span data, WaveEncoding encoding) + { + var convertedData = new byte[data.Length * 2]; + int index = 0; + for (int i = 0; i < data.Length; i++) + { + convertedData[index++] = (byte)(data[i] & 0xff); + convertedData[index++] = (byte)(data[i] >> 8); + convertedData[index++] = (byte)(data[i] >> 16); + convertedData[index++] = (byte)(data[i] >> 24); + } + + return WriteBytes(convertedData, encoding); + } + + public Span WriteBytes(Span data) => WriteBytes(data, WaveEncoding.Pcm16); + + public Span WriteBytes(Span data, WaveEncoding encoding) + { + var convertedData = new byte[data.Length * 2]; + int index = 0; + for (int i = 0; i < data.Length; i++) + { + convertedData[index++] = (byte)(data[i] & 0xff); + convertedData[index++] = (byte)(data[i] >> 8); + } + + return WriteBytes(convertedData, encoding); + } + + public Span WriteBytes(Span data) => WriteBytes(data, WaveEncoding.Pcm16); + + public Span WriteBytes(Span data, WaveEncoding encoding) + { + // Creating the RIFF Wave header + string fileID = "RIFF"; + uint fileSize = (uint)(data.Length + 44); // File size must match the size of the samples and header size + string waveID = "WAVE"; + string formatID = "fmt "; + uint formatLength = 16; // Always a length 16 + ushort formatType = (ushort)encoding; // 1 is PCM16, 2 is ADPCM, etc. + // Number of channels is already manually defined + uint sampleRate = SampleRate; // Sample Rate is read directly from the Info context + ushort bitsPerSample = 16; // bitsPerSample must be written to AFTER numNibbles + uint numNibbles = sampleRate * bitsPerSample * Channels / 8; // numNibbles must be written BEFORE bitsPerSample is written + ushort bitRate = (ushort)(bitsPerSample * Channels / 8); + string dataID = "data"; + uint dataSize = (uint)data.Length; + + byte[] samplerChunk; + + if (IsLooped) + { + string samplerID = "smpl"; + uint samplerSize = 0; + + uint manufacturer = 0; + uint product = 0; + uint samplePeriod = 0; + uint midiUnityNote = 0; + uint midiPitchFraction = 0; + uint smpteFormat = 0; + uint smpteOffset = 0; + uint numSampleLoops = 1; + uint samplerDataSize = 0; + + samplerSize += 36; + + if (numSampleLoops > 0) + { + var loopID = new uint[numSampleLoops]; + var loopType = new uint[numSampleLoops]; + var loopStart = new uint[numSampleLoops]; + var loopEnd = new uint[numSampleLoops]; + var loopFraction = new uint[numSampleLoops]; + var loopNumPlayback = new uint[numSampleLoops]; + + var loopHeaderSize = 0; + for (int i = 0; i < numSampleLoops; i++) + { + loopID[i] = 0; + loopType[i] = 0; + loopStart[i] = LoopStart; + loopEnd[i] = LoopEnd; + loopFraction[i] = 0; + loopNumPlayback[i] = 0; + + loopHeaderSize += 24; + samplerSize += 24; + } + var loopHeader = new byte[loopHeaderSize]; + var lw = new EndianBinaryWriter(new MemoryStream(loopHeader)); + for (int i = 0; i < numSampleLoops; i++) + { + lw.WriteUInt32(loopID[i]); + lw.WriteUInt32(loopType[i]); + lw.WriteUInt32(loopStart[i]); + lw.WriteUInt32(loopEnd[i]); + lw.WriteUInt32(loopFraction[i]); + lw.WriteUInt32(loopNumPlayback[i]); + } + samplerChunk = new byte[samplerSize + 8]; + + var sw = new EndianBinaryWriter(new MemoryStream(samplerChunk)); + sw.WriteChars(samplerID); + sw.WriteUInt32(samplerSize); + sw.WriteUInt32(manufacturer); + sw.WriteUInt32(product); + sw.WriteUInt32(samplePeriod); + sw.WriteUInt32(midiUnityNote); + sw.WriteUInt32(midiPitchFraction); + sw.WriteUInt32(smpteFormat); + sw.WriteUInt32(smpteOffset); + sw.WriteUInt32(numSampleLoops); + sw.WriteUInt32(samplerDataSize); + sw.WriteBytes(loopHeader); + + fileSize += (uint)samplerChunk.Length; + + var waveData = new byte[fileSize]; + var w = new EndianBinaryWriter(new MemoryStream(waveData)); + w.WriteChars(fileID); + w.WriteUInt32(fileSize); + w.WriteChars(waveID); + w.WriteChars(formatID); + w.WriteUInt32(formatLength); + w.WriteUInt16(formatType); + w.WriteUInt16(Channels); + w.WriteUInt32(sampleRate); + w.WriteUInt32(numNibbles); + w.WriteUInt16(bitRate); + w.WriteUInt16(bitsPerSample); + w.WriteChars(dataID); + w.WriteUInt32(dataSize); + w.WriteBytes(data); + w.WriteBytes(samplerChunk); + + return waveData; + } + else + { + samplerChunk = new byte[samplerSize + 8]; + + var sw = new EndianBinaryWriter(new MemoryStream(samplerChunk)); + sw.WriteChars(samplerID); + sw.WriteUInt32(samplerSize); + sw.WriteUInt32(manufacturer); + sw.WriteUInt32(product); + sw.WriteUInt32(samplePeriod); + sw.WriteUInt32(midiUnityNote); + sw.WriteUInt32(midiPitchFraction); + sw.WriteUInt32(smpteFormat); + sw.WriteUInt32(smpteOffset); + sw.WriteUInt32(numSampleLoops); + sw.WriteUInt32(samplerDataSize); + + fileSize += (uint)samplerChunk.Length; + + var waveData = new byte[fileSize]; + var w = new EndianBinaryWriter(new MemoryStream(waveData)); + w.WriteChars(fileID); + w.WriteUInt32(fileSize); + w.WriteChars(waveID); + w.WriteChars(formatID); + w.WriteUInt32(formatLength); + w.WriteUInt16(formatType); + w.WriteUInt16(Channels); + w.WriteUInt32(sampleRate); + w.WriteUInt32(numNibbles); + w.WriteUInt16(bitRate); + w.WriteUInt16(bitsPerSample); + w.WriteChars(dataID); + w.WriteUInt32(dataSize); + w.WriteBytes(data); + w.WriteBytes(samplerChunk); + + return waveData; + } + } + else + { + var waveData = new byte[fileSize]; + var w = new EndianBinaryWriter(new MemoryStream(waveData)); + w.WriteChars(fileID); + w.WriteUInt32(fileSize); + w.WriteChars(waveID); + w.WriteChars(formatID); + w.WriteUInt32(formatLength); + w.WriteUInt16(formatType); + w.WriteUInt16(Channels); + w.WriteUInt32(sampleRate); + w.WriteUInt32(numNibbles); + w.WriteUInt16(bitRate); + w.WriteUInt16(bitsPerSample); + w.WriteChars(dataID); + w.WriteUInt32(dataSize); + w.WriteBytes(data); + + return waveData; + } + } +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs index fdee70e..c5966b7 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs @@ -8,7 +8,9 @@ public sealed class AlphaDreamEngine : Engine public override AlphaDreamConfig Config { get; } public override AlphaDreamMixer Mixer { get; } + public AlphaDreamMixer_NAudio Mixer_NAudio { get; } public override AlphaDreamPlayer Player { get; } + public override bool UseNewMixer { get => false; } public AlphaDreamEngine(byte[] rom) { @@ -18,8 +20,16 @@ public AlphaDreamEngine(byte[] rom) } Config = new AlphaDreamConfig(rom); - Mixer = new AlphaDreamMixer(Config); - Player = new AlphaDreamPlayer(Config, Mixer); + if (Engine.Instance!.UseNewMixer) + { + Mixer = new AlphaDreamMixer(Config); + Player = new AlphaDreamPlayer(Config, Mixer); + } + else + { + Mixer_NAudio = new AlphaDreamMixer_NAudio(Config); + Player = new AlphaDreamPlayer(Config, Mixer_NAudio); + } AlphaDreamInstance = this; Instance = this; diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs index 1cc823c..04a02df 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs @@ -1,5 +1,5 @@ using Kermalis.VGMusicStudio.Core.Util; -using NAudio.Wave; +using Kermalis.VGMusicStudio.Core.Formats; using System; namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; @@ -15,11 +15,9 @@ public sealed class AlphaDreamMixer : Mixer private float _fadeStepPerMicroframe; public readonly AlphaDreamConfig Config; - private readonly WaveBuffer _audio; + private readonly Audio _audio; private readonly float[][] _trackBuffers = new float[AlphaDreamPlayer.NUM_TRACKS][]; - private readonly BufferedWaveProvider _buffer; - - protected override WaveFormat WaveFormat => _buffer.WaveFormat; + private readonly Wave _buffer; internal AlphaDreamMixer(AlphaDreamConfig config) { @@ -30,16 +28,18 @@ internal AlphaDreamMixer(AlphaDreamConfig config) _samplesReciprocal = 1f / SamplesPerBuffer; int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _audio = new Audio(amt) { FloatBufferCount = amt }; for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) { _trackBuffers[i] = new float[amt]; } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 2)) // TODO + _buffer = new Wave() { DiscardOnBufferOverflow = true, BufferLength = SamplesPerBuffer * 64 }; + _buffer.CreateIeeeFloatWave(sampleRate, 2); // TODO + Init(_buffer); } @@ -110,7 +110,7 @@ internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) track.Channel.Process(buf); for (int j = 0; j < SamplesPerBuffer; j++) { - _audio.FloatBuffer[j * 2] += buf[j * 2] * level; + _audio.FloatBuffer![j * 2] += buf[j * 2] * level; _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; level += masterStep; } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer_NAudio.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer_NAudio.cs new file mode 100644 index 0000000..d98c64a --- /dev/null +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer_NAudio.cs @@ -0,0 +1,127 @@ +using Kermalis.VGMusicStudio.Core.Util; +using NAudio.Wave; +using System; + +namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream; + +public sealed class AlphaDreamMixer_NAudio : Mixer_NAudio +{ + public readonly float SampleRateReciprocal; + private readonly float _samplesReciprocal; + public readonly int SamplesPerBuffer; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; + + public readonly AlphaDreamConfig Config; + private readonly WaveBuffer _audio; + private readonly float[][] _trackBuffers = new float[AlphaDreamPlayer.NUM_TRACKS][]; + private readonly BufferedWaveProvider _buffer; + + protected override WaveFormat WaveFormat => _buffer.WaveFormat; + + internal AlphaDreamMixer_NAudio(AlphaDreamConfig config) + { + Config = config; + const int sampleRate = 13_379; // TODO: Actual value unknown + SamplesPerBuffer = 224; // TODO + SampleRateReciprocal = 1f / sampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 2)) // TODO + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64 + }; + Init(_buffer); + } + + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } + + internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) + { + _audio.Clear(); + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) + { + AlphaDreamTrack track = tracks[i]; + if (!track.IsEnabled || track.NoteDuration == 0 || track.Channel.Stopped || Mutes[i]) + { + continue; + } + + float level = masterLevel; + float[] buf = _trackBuffers[i]; + Array.Clear(buf, 0, buf.Length); + track.Channel.Process(buf); + for (int j = 0; j < SamplesPerBuffer; j++) + { + _audio.FloatBuffer[j * 2] += buf[j * 2] * level; + _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + level += masterStep; + } + } + if (output) + { + _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + if (recording) + { + _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + } +} diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs index e202a38..124cda7 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamPlayer.cs @@ -12,6 +12,7 @@ public sealed class AlphaDreamPlayer : Player internal readonly AlphaDreamTrack[] Tracks; internal readonly AlphaDreamConfig Config; private readonly AlphaDreamMixer _mixer; + private readonly AlphaDreamMixer_NAudio _mixer_NAudio; private AlphaDreamLoadedSong? _loadedSong; internal byte Tempo; @@ -20,6 +21,7 @@ public sealed class AlphaDreamPlayer : Player public override ILoadedSong? LoadedSong => _loadedSong; protected override Mixer Mixer => _mixer; + protected override Mixer_NAudio Mixer_NAudio => _mixer_NAudio; internal AlphaDreamPlayer(AlphaDreamConfig config, AlphaDreamMixer mixer) : base(GBAUtils.AGB_FPS) @@ -34,6 +36,19 @@ internal AlphaDreamPlayer(AlphaDreamConfig config, AlphaDreamMixer mixer) } } + internal AlphaDreamPlayer(AlphaDreamConfig config, AlphaDreamMixer_NAudio mixer) + : base(GBAUtils.AGB_FPS) + { + Config = config; + _mixer_NAudio = mixer; + + Tracks = new AlphaDreamTrack[NUM_TRACKS]; + for (byte i = 0; i < NUM_TRACKS; i++) + { + Tracks[i] = new AlphaDreamTrack(i, mixer); + } + } + public override void LoadSong(int index) { if (_loadedSong is not null) @@ -70,7 +85,10 @@ internal override void InitEmulation() TempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - _mixer.ResetFade(); + if (Engine.Instance!.UseNewMixer) + _mixer.ResetFade(); + else + _mixer_NAudio.ResetFade(); for (int i = 0; i < NUM_TRACKS; i++) { Tracks[i].Init(); @@ -88,28 +106,56 @@ protected override void OnStopped() protected override bool Tick(bool playing, bool recording) { bool allDone = false; // TODO: Individual track tempo - while (!allDone && TempoStack >= 75) + if (Engine.Instance!.UseNewMixer) { - TempoStack -= 75; - allDone = true; - for (int i = 0; i < NUM_TRACKS; i++) + while (!allDone && TempoStack >= 75) { - AlphaDreamTrack track = Tracks[i]; - if (track.IsEnabled) + TempoStack -= 75; + allDone = true; + for (int i = 0; i < NUM_TRACKS; i++) { - TickTrack(track, ref allDone); + AlphaDreamTrack track = Tracks[i]; + if (track.IsEnabled) + { + TickTrack(track, ref allDone); + } + } + if (_mixer.IsFadeDone()) + { + allDone = true; } } - if (_mixer.IsFadeDone()) + if (!allDone) { - allDone = true; + TempoStack += Tempo; } + _mixer.Process(Tracks, playing, recording); } - if (!allDone) + else { - TempoStack += Tempo; + while (!allDone && TempoStack >= 75) + { + TempoStack -= 75; + allDone = true; + for (int i = 0; i < NUM_TRACKS; i++) + { + AlphaDreamTrack track = Tracks[i]; + if (track.IsEnabled) + { + TickTrack(track, ref allDone); + } + } + if (_mixer_NAudio.IsFadeDone()) + { + allDone = true; + } + } + if (!allDone) + { + TempoStack += Tempo; + } + _mixer_NAudio.Process(Tracks, playing, recording); } - _mixer.Process(Tracks, playing, recording); return allDone; } private void TickTrack(AlphaDreamTrack track, ref bool allDone) @@ -158,10 +204,21 @@ private void HandleTicksAndLoop(AlphaDreamLoadedSong s, AlphaDreamTrack track) } _elapsedLoops++; - UpdateElapsedTicksAfterLoop(s.Events[track.Index]!, track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !_mixer.IsFading()) + if (Engine.Instance!.UseNewMixer) { - _mixer.BeginFadeOut(); + UpdateElapsedTicksAfterLoop(s.Events[track.Index]!, track.DataOffset, track.Rest); + if (ShouldFadeOut && _elapsedLoops > NumLoops && !_mixer.IsFading()) + { + _mixer.BeginFadeOut(); + } + } + else + { + UpdateElapsedTicksAfterLoop(s.Events[track.Index]!, track.DataOffset, track.Rest); + if (ShouldFadeOut && _elapsedLoops > NumLoops && !_mixer_NAudio.IsFading()) + { + _mixer_NAudio.BeginFadeOut(); + } } } } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs index ded6a34..6dffcc4 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamTrack.cs @@ -38,6 +38,20 @@ public AlphaDreamTrack(byte i, AlphaDreamMixer mixer) Channel = new AlphaDreamPCMChannel(mixer); } } + public AlphaDreamTrack(byte i, AlphaDreamMixer_NAudio mixer) + { + Index = i; + if (i >= 8) + { + Type = GBAUtils.PSGTypes[i & 3]; + Channel = new AlphaDreamSquareChannel(mixer); // TODO: PSG Channels 3 and 4 + } + else + { + Type = "PCM8"; + Channel = new AlphaDreamPCMChannel(mixer); + } + } // 0x819B040 public void Init() { diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs index 471fdb4..d566243 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamChannel.cs @@ -3,6 +3,7 @@ internal abstract class AlphaDreamChannel { protected readonly AlphaDreamMixer _mixer; + protected readonly AlphaDreamMixer_NAudio _mixer_NAudio; public EnvelopeState State; public byte Key; public bool Stopped; @@ -20,6 +21,10 @@ protected AlphaDreamChannel(AlphaDreamMixer mixer) { _mixer = mixer; } + protected AlphaDreamChannel(AlphaDreamMixer_NAudio mixer) + { + _mixer_NAudio = mixer; + } public ChannelVolume GetVolume() { diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs index 455dc77..81a740e 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamPCMChannel.cs @@ -12,6 +12,10 @@ public AlphaDreamPCMChannel(AlphaDreamMixer mixer) : base(mixer) { // } + public AlphaDreamPCMChannel(AlphaDreamMixer_NAudio mixer) : base(mixer) + { + // + } public void Init(byte key, ADSR adsr, int sampleOffset, bool bFixed) { _velocity = adsr.A; @@ -20,7 +24,10 @@ public void Init(byte key, ADSR adsr, int sampleOffset, bool bFixed) Key = key; _adsr = adsr; - _sampleHeader = new SampleHeader(_mixer.Config.ROM, sampleOffset, out _sampleOffset); + if (Engine.Instance!.UseNewMixer) + _sampleHeader = new SampleHeader(_mixer.Config.ROM, sampleOffset, out _sampleOffset); + else + _sampleHeader = new SampleHeader(_mixer_NAudio.Config.ROM, sampleOffset, out _sampleOffset); _bFixed = bFixed; Stopped = false; } @@ -80,31 +87,63 @@ public override void Process(float[] buffer) StepEnvelope(); ChannelVolume vol = GetVolume(); - float interStep = (_bFixed ? _sampleHeader.SampleRate >> 10 : _frequency) * _mixer.SampleRateReciprocal; - int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + if (Engine.Instance!.UseNewMixer) { - float samp = (_mixer.Config.ROM[_pos + _sampleOffset] - 0x80) / (float)0x80; + float interStep = (_bFixed ? _sampleHeader.SampleRate >> 10 : _frequency) * _mixer.SampleRateReciprocal; + int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + do + { + float samp = (_mixer.Config.ROM[_pos + _sampleOffset] - 0x80) / (float)0x80; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; - _interPos += interStep; - int posDelta = (int)_interPos; - _interPos -= posDelta; - _pos += posDelta; - if (_pos >= _sampleHeader.Length) - { - if (_sampleHeader.DoesLoop == 0x40000000) + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _sampleHeader.Length) { - _pos = _sampleHeader.LoopOffset; + if (_sampleHeader.DoesLoop == 0x40000000) + { + _pos = _sampleHeader.LoopOffset; + } + else + { + Stopped = true; + break; + } } - else + } while (--samplesPerBuffer > 0); + } + else + { + float interStep = (_bFixed ? _sampleHeader.SampleRate >> 10 : _frequency) * _mixer_NAudio.SampleRateReciprocal; + int bufPos = 0; int samplesPerBuffer = _mixer_NAudio.SamplesPerBuffer; + do + { + float samp = (_mixer_NAudio.Config.ROM[_pos + _sampleOffset] - 0x80) / (float)0x80; + + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + + _interPos += interStep; + int posDelta = (int)_interPos; + _interPos -= posDelta; + _pos += posDelta; + if (_pos >= _sampleHeader.Length) { - Stopped = true; - break; + if (_sampleHeader.DoesLoop == 0x40000000) + { + _pos = _sampleHeader.LoopOffset; + } + else + { + Stopped = true; + break; + } } - } - } while (--samplesPerBuffer > 0); + } while (--samplesPerBuffer > 0); + } } } \ No newline at end of file diff --git a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs index a627bf0..9141b29 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/Channels/AlphaDreamSquareChannel.cs @@ -12,6 +12,11 @@ public AlphaDreamSquareChannel(AlphaDreamMixer mixer) { _pat = null!; } + public AlphaDreamSquareChannel(AlphaDreamMixer_NAudio mixer) + : base(mixer) + { + _pat = null!; + } public void Init(byte key, ADSR env, byte vol, sbyte pan, int pitch) { _pat = MP2KUtils.SquareD50; // TODO: Which square pattern? @@ -77,9 +82,19 @@ public override void Process(float[] buffer) StepEnvelope(); ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; - - int bufPos = 0; int samplesPerBuffer = _mixer.SamplesPerBuffer; + float interStep; + int bufPos = 0; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + { + interStep = _frequency * _mixer.SampleRateReciprocal; + samplesPerBuffer = _mixer.SamplesPerBuffer; + } + else + { + interStep = _frequency * _mixer_NAudio.SampleRateReciprocal; + samplesPerBuffer = _mixer_NAudio.SamplesPerBuffer; + } do { float samp = _pat[_pos]; diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs index 3d35241..07b099c 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KChannel.cs @@ -4,7 +4,8 @@ internal abstract class MP2KChannel { public EnvelopeState State; public MP2KTrack? Owner; - protected readonly MP2KMixer _mixer; + protected readonly MP2KMixer? _mixer; + protected readonly MP2KMixer_NAudio? _mixer_NAudio; public NoteInfo Note; protected ADSR _adsr; @@ -21,6 +22,12 @@ protected MP2KChannel(MP2KMixer mixer) State = EnvelopeState.Dead; } + protected MP2KChannel(MP2KMixer_NAudio mixer) + { + _mixer_NAudio = mixer; + State = EnvelopeState.Dead; + } + public abstract ChannelVolume GetVolume(); public abstract void SetVolume(byte vol, sbyte pan); public abstract void SetPitch(int pitch); diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs index 4389352..8491f09 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KNoiseChannel.cs @@ -12,6 +12,11 @@ public MP2KNoiseChannel(MP2KMixer mixer) { _pat = null!; } + public MP2KNoiseChannel(MP2KMixer_NAudio mixer) + : base(mixer) + { + _pat = null!; + } public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, NoisePattern pattern) { Init(owner, note, env, instPan); @@ -49,10 +54,20 @@ public override void Process(float[] buffer) } ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; + float interStep; int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + { + interStep = _frequency * _mixer!.SampleRateReciprocal; + samplesPerBuffer = _mixer!.SamplesPerBuffer; + } + else + { + interStep = _frequency * _mixer_NAudio!.SampleRateReciprocal; + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + } do { float samp = _pat[_pos & (_pat.Length - 1)] ? 0.5f : -0.5f; diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs index 90ba63b..73b50f1 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM4Channel.cs @@ -11,10 +11,18 @@ public MP2KPCM4Channel(MP2KMixer mixer) { _sample = new float[0x20]; } + public MP2KPCM4Channel(MP2KMixer_NAudio mixer) + : base(mixer) + { + _sample = new float[0x20]; + } public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, int sampleOffset) { Init(owner, note, env, instPan); - MP2KUtils.PCM4ToFloat(_mixer.Config.ROM.AsSpan(sampleOffset), _sample); + if (Engine.Instance!.UseNewMixer) + MP2KUtils.PCM4ToFloat(_mixer!.Config.ROM.AsSpan(sampleOffset), _sample); + else + MP2KUtils.PCM4ToFloat(_mixer_NAudio!.Config.ROM.AsSpan(sampleOffset), _sample); } public override void SetPitch(int pitch) @@ -31,10 +39,20 @@ public override void Process(float[] buffer) } ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; + float interStep; int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + { + interStep = _frequency * _mixer!.SampleRateReciprocal; + samplesPerBuffer = _mixer!.SamplesPerBuffer; + } + else + { + interStep = _frequency * _mixer_NAudio!.SampleRateReciprocal; + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + } do { float samp = _sample[_pos]; diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs index 552e230..fedb7f3 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPCM8Channel.cs @@ -19,6 +19,11 @@ public MP2KPCM8Channel(MP2KMixer mixer) { // } + public MP2KPCM8Channel(MP2KMixer_NAudio mixer) + : base(mixer) + { + // + } public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed) { State = EnvelopeState.Initializing; @@ -33,12 +38,19 @@ public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, by Note = note; _adsr = adsr; _instPan = instPan; - byte[] rom = _mixer.Config.ROM; + byte[] rom; + if (Engine.Instance!.UseNewMixer) + rom = _mixer!.Config.ROM; + else + rom = _mixer_NAudio!.Config.ROM; _sampleHeader = SampleHeader.Get(rom, sampleOffset, out _sampleOffset); _bFixed = bFixed; _bCompressed = bCompressed; _decompressedSample = bCompressed ? MP2KUtils.Decompress(rom.AsSpan(_sampleOffset), _sampleHeader.Length) : null; - _bGoldenSun = _mixer.Config.HasGoldenSunSynths && _sampleHeader.Length == 0 && _sampleHeader.DoesLoop == SampleHeader.LOOP_TRUE && _sampleHeader.LoopOffset == 0; + if (Engine.Instance!.UseNewMixer) + _bGoldenSun = _mixer!.Config.HasGoldenSunSynths && _sampleHeader.Length == 0 && _sampleHeader.DoesLoop == SampleHeader.LOOP_TRUE && _sampleHeader.LoopOffset == 0; + else + _bGoldenSun = _mixer_NAudio!.Config.HasGoldenSunSynths && _sampleHeader.Length == 0 && _sampleHeader.DoesLoop == SampleHeader.LOOP_TRUE && _sampleHeader.LoopOffset == 0; if (_bGoldenSun) { _gsPSG = GoldenSunPSG.Get(rom.AsSpan(_sampleOffset)); @@ -50,11 +62,22 @@ public void Init(MP2KTrack owner, NoteInfo note, ADSR adsr, int sampleOffset, by public override ChannelVolume GetVolume() { const float MAX = 0x10_000; - return new ChannelVolume + if (Engine.Instance!.UseNewMixer) + { + return new ChannelVolume + { + LeftVol = _leftVol * _velocity / MAX * _mixer!.PCM8MasterVolume, + RightVol = _rightVol * _velocity / MAX * _mixer!.PCM8MasterVolume + }; + } + else { - LeftVol = _leftVol * _velocity / MAX * _mixer.PCM8MasterVolume, - RightVol = _rightVol * _velocity / MAX * _mixer.PCM8MasterVolume - }; + return new ChannelVolume + { + LeftVol = _leftVol * _velocity / MAX * _mixer_NAudio!.PCM8MasterVolume, + RightVol = _rightVol * _velocity / MAX * _mixer_NAudio!.PCM8MasterVolume + }; + } } public override void SetVolume(byte vol, sbyte pan) { @@ -153,7 +176,11 @@ public override void Process(float[] buffer) } ChannelVolume vol = GetVolume(); - float interStep = _bFixed && !_bGoldenSun ? _mixer.SampleRate * _mixer.SampleRateReciprocal : _frequency * _mixer.SampleRateReciprocal; + float interStep; + if (Engine.Instance!.UseNewMixer) + interStep = _bFixed && !_bGoldenSun ? _mixer!.SampleRate * _mixer!.SampleRateReciprocal : _frequency * _mixer!.SampleRateReciprocal; + else + interStep = _bFixed && !_bGoldenSun ? _mixer_NAudio!.SampleRate * _mixer_NAudio!.SampleRateReciprocal : _frequency * _mixer_NAudio!.SampleRateReciprocal; if (_bGoldenSun) // Most Golden Sun processing is thanks to ipatix { Process_GS(buffer, vol, interStep); @@ -164,7 +191,10 @@ public override void Process(float[] buffer) } else { - Process_Standard(buffer, vol, interStep, _mixer.Config.ROM); + if (Engine.Instance!.UseNewMixer) + Process_Standard(buffer, vol, interStep, _mixer!.Config.ROM); + else + Process_Standard(buffer, vol, interStep, _mixer_NAudio!.Config.ROM); } } private void Process_GS(float[] buffer, ChannelVolume vol, float interStep) @@ -173,79 +203,95 @@ private void Process_GS(float[] buffer, ChannelVolume vol, float interStep) switch (_gsPSG.Type) { case GoldenSunPSGType.Square: - { - _pos += _gsPSG.CycleSpeed << 24; - int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; - iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; - iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); - float threshold = iThreshold / (float)0x100_000_000; - - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do { - float samp = _interPos < threshold ? 0.5f : -0.5f; - samp += 0.5f - threshold; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; + _pos += _gsPSG.CycleSpeed << 24; + int iThreshold = (_gsPSG.MinimumCycle << 24) + _pos; + iThreshold = (iThreshold < 0 ? ~iThreshold : iThreshold) >> 8; + iThreshold = (iThreshold * _gsPSG.CycleAmplitude) + (_gsPSG.InitialCycle << 24); + float threshold = iThreshold / (float)0x100_000_000; - _interPos += interStep; - if (_interPos >= 1) + int bufPos = 0; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + samplesPerBuffer = _mixer!.SamplesPerBuffer; + else + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + do { - _interPos--; - } - } while (--samplesPerBuffer > 0); - break; - } - case GoldenSunPSGType.Saw: - { - const int FIX = 0x70; + float samp = _interPos < threshold ? 0.5f : -0.5f; + samp += 0.5f - threshold; + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + } while (--samplesPerBuffer > 0); + break; + } + case GoldenSunPSGType.Saw: { - _interPos += interStep; - if (_interPos >= 1) + const int FIX = 0x70; + + int bufPos = 0; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + samplesPerBuffer = _mixer!.SamplesPerBuffer; + else + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + do { - _interPos--; - } - int var1 = (int)(_interPos * 0x100) - FIX; - int var2 = (int)(_interPos * 0x10000) << 17; - int var3 = var1 - (var2 >> 27); - _pos = var3 + (_pos >> 1); + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + int var1 = (int)(_interPos * 0x100) - FIX; + int var2 = (int)(_interPos * 0x10000) << 17; + int var3 = var1 - (var2 >> 27); + _pos = var3 + (_pos >> 1); - float samp = _pos / (float)0x100; + float samp = _pos / (float)0x100; - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; - } + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } case GoldenSunPSGType.Triangle: - { - int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; - do { - _interPos += interStep; - if (_interPos >= 1) + int bufPos = 0; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + samplesPerBuffer = _mixer!.SamplesPerBuffer; + else + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + do { - _interPos--; - } - float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); + _interPos += interStep; + if (_interPos >= 1) + { + _interPos--; + } + float samp = _interPos < 0.5f ? (_interPos * 4) - 1 : 3 - (_interPos * 4); - buffer[bufPos++] += samp * vol.LeftVol; - buffer[bufPos++] += samp * vol.RightVol; - } while (--samplesPerBuffer > 0); - break; - } + buffer[bufPos++] += samp * vol.LeftVol; + buffer[bufPos++] += samp * vol.RightVol; + } while (--samplesPerBuffer > 0); + break; + } } } private void Process_Compressed(float[] buffer, ChannelVolume vol, float interStep) { int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + samplesPerBuffer = _mixer!.SamplesPerBuffer; + else + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; do { float samp = _decompressedSample![_pos] / (float)0x80; @@ -267,7 +313,11 @@ private void Process_Compressed(float[] buffer, ChannelVolume vol, float interSt private void Process_Standard(float[] buffer, ChannelVolume vol, float interStep, byte[] rom) { int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + samplesPerBuffer = _mixer!.SamplesPerBuffer; + else + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; do { float samp = (sbyte)rom[_pos + _sampleOffset] / (float)0x80; diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs index bc795df..939c174 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KPSGChannel.cs @@ -20,6 +20,11 @@ public MP2KPSGChannel(MP2KMixer mixer) { // } + public MP2KPSGChannel(MP2KMixer_NAudio mixer) + : base(mixer) + { + // + } protected void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan) { State = EnvelopeState.Initializing; diff --git a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs index 4e655ff..74ea7e7 100644 --- a/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs +++ b/VG Music Studio - Core/GBA/MP2K/Channels/MP2KSquareChannel.cs @@ -11,6 +11,11 @@ public MP2KSquareChannel(MP2KMixer mixer) { _pat = null!; } + public MP2KSquareChannel(MP2KMixer_NAudio mixer) + : base(mixer) + { + _pat = null!; + } public void Init(MP2KTrack owner, NoteInfo note, ADSR env, int instPan, SquarePattern pattern) { Init(owner, note, env, instPan); @@ -37,10 +42,20 @@ public override void Process(float[] buffer) } ChannelVolume vol = GetVolume(); - float interStep = _frequency * _mixer.SampleRateReciprocal; + float interStep; int bufPos = 0; - int samplesPerBuffer = _mixer.SamplesPerBuffer; + int samplesPerBuffer; + if (Engine.Instance!.UseNewMixer) + { + interStep = _frequency * _mixer!.SampleRateReciprocal; + samplesPerBuffer = _mixer!.SamplesPerBuffer; + } + else + { + interStep = _frequency * _mixer_NAudio!.SampleRateReciprocal; + samplesPerBuffer = _mixer_NAudio!.SamplesPerBuffer; + } do { float samp = _pat[_pos]; diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs index 43c40ba..f832aad 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs @@ -4,30 +4,40 @@ namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; public sealed class MP2KEngine : Engine { - public static MP2KEngine? MP2KInstance { get; private set; } + public static MP2KEngine? MP2KInstance { get; private set; } - public override MP2KConfig Config { get; } - public override MP2KMixer Mixer { get; } - public override MP2KPlayer Player { get; } + public override MP2KConfig Config { get; } + public override MP2KMixer Mixer { get; } + public MP2KMixer_NAudio Mixer_NAudio { get; } + public override MP2KPlayer Player { get; } + public override bool UseNewMixer { get => true; } - public MP2KEngine(byte[] rom) - { - if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) - { - throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); - } + public MP2KEngine(byte[] rom) + { + if (rom.Length > GBAUtils.CARTRIDGE_CAPACITY) + { + throw new InvalidDataException($"The ROM is too large. Maximum size is 0x{GBAUtils.CARTRIDGE_CAPACITY:X7} bytes."); + } - Config = new MP2KConfig(rom); - Mixer = new MP2KMixer(Config); - Player = new MP2KPlayer(Config, Mixer); + Config = new MP2KConfig(rom); + if (UseNewMixer) + { + Mixer = new MP2KMixer(Config); + Player = new MP2KPlayer(Config, Mixer); + } + else + { + Mixer_NAudio = new MP2KMixer_NAudio(Config); + Player = new MP2KPlayer(Config, Mixer_NAudio); + } + + MP2KInstance = this; + Instance = this; + } - MP2KInstance = this; - Instance = this; - } - - public override void Dispose() - { - base.Dispose(); - MP2KInstance = null; - } + public override void Dispose() + { + base.Dispose(); + MP2KInstance = null; + } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs index b3c038c..c11ee31 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KLoadedSong_Runtime.cs @@ -57,36 +57,72 @@ private void PlayNote(byte[] rom, MP2KTrack track, byte note, byte velocity, byt switch (type) { case VoiceType.PCM8: - { - bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; - bool bCompressed = _player.Config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); - _player.MMixer.AllocPCM8Channel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - bFixed, bCompressed, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } + { + bool bFixed = (v.Type & (int)VoiceFlags.Fixed) != 0; + bool bCompressed = _player.Config.HasPokemonCompression && ((v.Type & (int)VoiceFlags.Compressed) != 0); + if (Engine.Instance!.UseNewMixer) + { + _player.MMixer.AllocPCM8Channel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + bFixed, bCompressed, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); + } + else + { + _player.MMixer_NAudio.AllocPCM8Channel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + bFixed, bCompressed, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); + } + return; + } case VoiceType.Square1: case VoiceType.Square2: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (SquarePattern)v.Int4); - return; - } + { + if (Engine.Instance!.UseNewMixer) + { + _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (SquarePattern)v.Int4); + } + else + { + _player.MMixer_NAudio.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (SquarePattern)v.Int4); + } + return; + } case VoiceType.PCM4: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); - return; - } + { + if (Engine.Instance!.UseNewMixer) + { + _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); + } + else + { + _player.MMixer_NAudio.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, v.Int4 - GBAUtils.CARTRIDGE_OFFSET); + } + return; + } case VoiceType.Noise: - { - _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, - track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), - type, (NoisePattern)v.Int4); - return; - } + { + if (Engine.Instance!.UseNewMixer) + { + _player.MMixer.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (NoisePattern)v.Int4); + } + else + { + _player.MMixer_NAudio.AllocPSGChannel(track, v.ADSR, ni, + track.GetVolume(), track.GetPanpot(), instPan, track.GetPitch(), + type, (NoisePattern)v.Int4); + } + return; + } } return; // Prevent infinite loop with invalid instruments } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index 8997f70..9e725e4 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -1,5 +1,5 @@ -using Kermalis.VGMusicStudio.Core.Util; -using NAudio.Wave; +using Kermalis.VGMusicStudio.Core.Formats; +using Kermalis.VGMusicStudio.Core.Util; using System; using System.Linq; @@ -18,7 +18,7 @@ public sealed class MP2KMixer : Mixer private float _fadeStepPerMicroframe; internal readonly MP2KConfig Config; - private readonly WaveBuffer _audio; + private readonly Audio _audio; private readonly float[][] _trackBuffers; private readonly MP2KPCM8Channel[] _pcm8Channels; private readonly MP2KSquareChannel _sq1; @@ -26,9 +26,7 @@ public sealed class MP2KMixer : Mixer private readonly MP2KPCM4Channel _pcm4; private readonly MP2KNoiseChannel _noise; private readonly MP2KPSGChannel[] _psgChannels; - private readonly BufferedWaveProvider _buffer; - - protected override WaveFormat WaveFormat => _buffer.WaveFormat; + private readonly Wave _buffer; internal MP2KMixer(MP2KConfig config) { @@ -46,17 +44,20 @@ internal MP2KMixer(MP2KConfig config) _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; int amt = SamplesPerBuffer * 2; - _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + Instance = this; + _audio = new Audio(amt) { FloatBufferCount = amt }; _trackBuffers = new float[0x10][]; for (int i = 0; i < _trackBuffers.Length; i++) { _trackBuffers[i] = new float[amt]; } - _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + _buffer = new Wave() { DiscardOnBufferOverflow = true, BufferLength = SamplesPerBuffer * 64, }; + _buffer.CreateIeeeFloatWave((uint)SampleRate, 2); + Init(_buffer); } @@ -114,45 +115,45 @@ internal MP2KMixer(MP2KConfig config) switch (type) { case VoiceType.Square1: - { - nChn = _sq1; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) { - return null; + nChn = _sq1; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); + break; } - _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } case VoiceType.Square2: - { - nChn = _sq2; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) { - return null; + nChn = _sq2; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); + break; } - _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } case VoiceType.PCM4: - { - nChn = _pcm4; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) { - return null; + nChn = _pcm4; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _pcm4.Init(owner, note, env, instPan, (int)arg); + break; } - _pcm4.Init(owner, note, env, instPan, (int)arg); - break; - } case VoiceType.Noise: - { - nChn = _noise; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) { - return null; + nChn = _noise; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _noise.Init(owner, note, env, instPan, (NoisePattern)arg); + break; } - _noise.Init(owner, note, env, instPan, (NoisePattern)arg); - break; - } default: return null; } nChn.SetVolume(vol, pan); @@ -248,7 +249,7 @@ internal void Process(bool output, bool recording) float[] buf = _trackBuffers[i]; for (int j = 0; j < SamplesPerBuffer; j++) { - _audio.FloatBuffer[j * 2] += buf[j * 2] * level; + _audio.FloatBuffer![j * 2] += buf[j * 2] * level; _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; level += masterStep; } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs new file mode 100644 index 0000000..871c53f --- /dev/null +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer_NAudio.cs @@ -0,0 +1,265 @@ +using Kermalis.VGMusicStudio.Core.Util; +using NAudio.Wave; +using System; +using System.Linq; + +namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; + +public sealed class MP2KMixer_NAudio : Mixer_NAudio +{ + internal readonly int SampleRate; + internal readonly int SamplesPerBuffer; + internal readonly float SampleRateReciprocal; + private readonly float _samplesReciprocal; + internal readonly float PCM8MasterVolume; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; + + internal readonly MP2KConfig Config; + private readonly WaveBuffer _audio; + private readonly float[][] _trackBuffers; + private readonly MP2KPCM8Channel[] _pcm8Channels; + private readonly MP2KSquareChannel _sq1; + private readonly MP2KSquareChannel _sq2; + private readonly MP2KPCM4Channel _pcm4; + private readonly MP2KNoiseChannel _noise; + private readonly MP2KPSGChannel[] _psgChannels; + private readonly BufferedWaveProvider _buffer; + + protected override WaveFormat WaveFormat => _buffer.WaveFormat; + + internal MP2KMixer_NAudio(MP2KConfig config) + { + Config = config; + (SampleRate, SamplesPerBuffer) = MP2KUtils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; + + _pcm8Channels = new MP2KPCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new MP2KPCM8Channel(this); + } + _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; + + int amt = SamplesPerBuffer * 2; + _audio = new WaveBuffer(amt * sizeof(float)) { FloatBufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + Init(_buffer); + } + + internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) + { + MP2KPCM8Channel? nChn = null; + IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner is null ? 0xFF : c.Owner.Index); + foreach (MP2KPCM8Channel i in byOwner) // Find free + { + if (i.State == EnvelopeState.Dead || i.Owner is null) + { + nChn = i; + break; + } + } + if (nChn is null) // Find releasing + { + foreach (MP2KPCM8Channel i in byOwner) + { + if (i.State == EnvelopeState.Releasing) + { + nChn = i; + break; + } + } + } + if (nChn is null) // Find prioritized + { + foreach (MP2KPCM8Channel i in byOwner) + { + if (owner.Priority > i.Owner!.Priority) + { + nChn = i; + break; + } + } + } + if (nChn is null) // None available + { + MP2KPCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one + if (lowest.Owner!.Index >= owner.Index) + { + nChn = lowest; + } + } + if (nChn is not null) // Could still be null from the above if + { + nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); + } + return nChn; + } + internal MP2KPSGChannel? AllocPSGChannel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) + { + MP2KPSGChannel nChn; + switch (type) + { + case VoiceType.Square1: + { + nChn = _sq1; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.Square2: + { + nChn = _sq2; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.PCM4: + { + nChn = _pcm4; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _pcm4.Init(owner, note, env, instPan, (int)arg); + break; + } + case VoiceType.Noise: + { + nChn = _noise; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _noise.Init(owner, note, env, instPan, (NoisePattern)arg); + break; + } + default: return null; + } + nChn.SetVolume(vol, pan); + nChn.SetPitch(pitch); + return nChn; + } + + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } + + internal void Process(bool output, bool recording) + { + for (int i = 0; i < _trackBuffers.Length; i++) + { + float[] buf = _trackBuffers[i]; + Array.Clear(buf, 0, buf.Length); + } + _audio.Clear(); + + for (int i = 0; i < _pcm8Channels.Length; i++) + { + MP2KPCM8Channel c = _pcm8Channels[i]; + if (c.Owner is not null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } + + for (int i = 0; i < _psgChannels.Length; i++) + { + MP2KPSGChannel c = _psgChannels[i]; + if (c.Owner is not null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } + + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < _trackBuffers.Length; i++) + { + if (Mutes[i]) + { + continue; + } + + float level = masterLevel; + float[] buf = _trackBuffers[i]; + for (int j = 0; j < SamplesPerBuffer; j++) + { + _audio.FloatBuffer[j * 2] += buf[j * 2] * level; + _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + level += masterStep; + } + } + if (output) + { + _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + if (recording) + { + _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + } +} diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs index 7ebe510..57e773b 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KPlayer.cs @@ -7,6 +7,7 @@ public sealed partial class MP2KPlayer : Player private readonly string?[] _voiceTypeCache; internal readonly MP2KConfig Config; internal readonly MP2KMixer MMixer; + internal readonly MP2KMixer_NAudio MMixer_NAudio; private MP2KLoadedSong? _loadedSong; internal ushort Tempo; @@ -17,7 +18,8 @@ public sealed partial class MP2KPlayer : Player public override ILoadedSong? LoadedSong => _loadedSong; protected override Mixer Mixer => MMixer; - + protected override Mixer_NAudio Mixer_NAudio => MMixer_NAudio; + internal MP2KPlayer(MP2KConfig config, MP2KMixer mixer) : base(GBAUtils.AGB_FPS) { @@ -26,6 +28,14 @@ internal MP2KPlayer(MP2KConfig config, MP2KMixer mixer) _voiceTypeCache = new string[256]; } + internal MP2KPlayer(MP2KConfig config, MP2KMixer_NAudio mixer) + : base(GBAUtils.AGB_FPS) + { + Config = config; + MMixer_NAudio = mixer; + + _voiceTypeCache = new string[256]; + } public override void LoadSong(int index) { @@ -56,7 +66,10 @@ internal override void InitEmulation() TempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - MMixer.ResetFade(); + if (Engine.Instance!.UseNewMixer) + MMixer.ResetFade(); + else + MMixer_NAudio.ResetFade(); MP2KTrack[] tracks = _loadedSong!.Tracks; for (int i = 0; i < tracks.Length; i++) { @@ -81,24 +94,48 @@ protected override bool Tick(bool playing, bool recording) MP2KLoadedSong s = _loadedSong!; bool allDone = false; - while (!allDone && TempoStack >= 150) + if (Engine.Instance!.UseNewMixer) { - TempoStack -= 150; - allDone = true; - for (int i = 0; i < s.Tracks.Length; i++) + while (!allDone && TempoStack >= 150) { - TickTrack(s, s.Tracks[i], ref allDone); + TempoStack -= 150; + allDone = true; + for (int i = 0; i < s.Tracks.Length; i++) + { + TickTrack(s, s.Tracks[i], ref allDone); + } + if (MMixer.IsFadeDone()) + { + allDone = true; + } } - if (MMixer.IsFadeDone()) + if (!allDone) { - allDone = true; + TempoStack += Tempo; } + MMixer.Process(playing, recording); } - if (!allDone) + else { - TempoStack += Tempo; + while (!allDone && TempoStack >= 150) + { + TempoStack -= 150; + allDone = true; + for (int i = 0; i < s.Tracks.Length; i++) + { + TickTrack(s, s.Tracks[i], ref allDone); + } + if (MMixer_NAudio.IsFadeDone()) + { + allDone = true; + } + } + if (!allDone) + { + TempoStack += Tempo; + } + MMixer_NAudio.Process(playing, recording); } - MMixer.Process(playing, recording); return allDone; } private void TickTrack(MP2KLoadedSong s, MP2KTrack track, ref bool allDone) @@ -142,9 +179,19 @@ private void HandleTicksAndLoop(MP2KLoadedSong s, MP2KTrack track) _elapsedLoops++; UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.DataOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !MMixer.IsFading()) + if (Engine.Instance!.UseNewMixer) + { + if (ShouldFadeOut && _elapsedLoops > NumLoops && !MMixer.IsFading()) + { + MMixer.BeginFadeOut(); + } + } + else { - MMixer.BeginFadeOut(); + if (ShouldFadeOut && _elapsedLoops > NumLoops && !MMixer_NAudio.IsFading()) + { + MMixer_NAudio.BeginFadeOut(); + } } } diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 7b8d4c5..e059b8b 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -1,109 +1,419 @@ -using NAudio.CoreAudioApi; -using NAudio.CoreAudioApi.Interfaces; -using NAudio.Wave; +using PortAudio; using System; +using System.Runtime.InteropServices; +using Kermalis.EndianBinaryIO; +using Kermalis.VGMusicStudio.Core.Formats; +using System.IO; +using Stream = PortAudio.Stream; namespace Kermalis.VGMusicStudio.Core; -public abstract class Mixer : IAudioSessionEventsHandler, IDisposable +public abstract class Mixer : IDisposable { public static event Action? VolumeChanged; + public Wave? WaveData; + public EndianBinaryReader? Reader; + public byte[] Buffer; + public readonly bool[] Mutes; - private IWavePlayer _out; - private AudioSessionControl _appVolume; + public int SizeInBytes; + public uint CombinedSamplesPerBuffer; + public int SizeToAllocateInBytes; + public long FinalFrameSize; + public long TotalFrames; + internal long Pos = 0; + internal float Vol = 1; + + public int freePos = 0; + public int dataPos = 0; + public int freeCount; + public int dataCount = 0; + + public readonly object CountLock = new object(); private bool _shouldSendVolUpdateEvent = true; - protected WaveFileWriter? _waveWriter; - protected abstract WaveFormat WaveFormat { get; } + protected Wave? _waveWriter; + + internal bool PlayingBack = false; + public StreamParameters OParams; + public StreamParameters DefaultOutputParams { get; private set; } + + private Stream? Stream; + private bool IsDisposed = false; + + public static Mixer? Instance { get; set; } protected Mixer() { Mutes = new bool[SongState.MAX_TRACKS]; - _out = null!; - _appVolume = null!; } - protected void Init(IWaveProvider waveProvider) + protected void Init(Wave waveData) { - _out = new WasapiOut(); - _out.Init(waveProvider); - using (var en = new MMDeviceEnumerator()) + // First, check if the instance contains something + if (WaveData == null) { - SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; - int id = Environment.ProcessId; - for (int i = 0; i < sessions.Count; i++) - { - AudioSessionControl session = sessions[i]; - if (session.GetProcessID == id) - { - _appVolume = session; - _appVolume.RegisterEventClient(this); - break; - } - } + IsDisposed = false; + + Pa.Initialize(); + WaveData = waveData; + Reader = new EndianBinaryReader(new MemoryStream(Buffer!)); + //Instance = this; + + // Try setting up an output device + OParams.device = Pa.DefaultOutputDevice; + if (OParams.device == Pa.NoDevice) + throw new Exception("No default audio output device is available."); + + OParams.channelCount = 2; + OParams.sampleFormat = SampleFormat.Float32; + OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; + OParams.hostApiSpecificStreamInfo = IntPtr.Zero; + + // Set it as a the default + DefaultOutputParams = OParams; } - _out.Play(); + + Sound(); + + Play(); } - public void CreateWaveWriter(string fileName) + private void Sound() { - _waveWriter = new WaveFileWriter(fileName, WaveFormat); + Stream = new Stream( + null, + OParams, + WaveData!.SampleRate, + CombinedSamplesPerBuffer, + StreamFlags.ClipOff, + PlayCallback, + this + ); + + FinalFrameSize = CombinedSamplesPerBuffer; + TotalFrames = WaveData.Channels * WaveData.BufferLength; } - public void CloseWaveWriter() + + private static StreamCallbackResult PlayCallback( + nint input, nint output, + uint frameCount, + ref StreamCallbackTimeInfo timeInfo, + StreamCallbackFlags statusFlags, + nint data + ) { - _waveWriter!.Dispose(); - _waveWriter = null; + // Ensure there's no memory allocated in this block to prevent issues + Mixer d = Stream.GetUserData(data); + + long numRead = 0; + unsafe + { + // Do a zero-out memset + float* buffer = (float*)output; + for (uint i = 0; i < d.FinalFrameSize; i++) + *buffer++ = 0; + + // If we're reading data, play it back + if (d.PlayingBack) + { + // Read the data + numRead = 8192; + //numRead = d.ReadFloat(output, d.FinalFrameSize); + + // Apply volume + buffer = (float*)output; + for (int i = 0; i < numRead; i++) + *buffer++ *= d.Volume; + } + } + + // Increment counter + d.Pos += numRead; + + // If it's at end of the data + if (d.PlayingBack && (numRead < frameCount)) + { + if (d.WaveData!.IsLooped) + d.Cursor = d.WaveData.LoopStart; + else + d.Cursor = 0; + d.PlayingBack = false; + } + + // Continue on + return StreamCallbackResult.Continue; } - public void OnVolumeChanged(float volume, bool isMuted) + private long ReadFloat(nint outData, long nElements) { - if (_shouldSendVolUpdateEvent) + if (Reader == null) + { + Reader = new EndianBinaryReader(new MemoryStream(WaveData!.Buffer!)); + } + if (outData > nElements) + { + Reader.Stream.Position = outData = (nint)WaveData!.LoopStart; + return WaveData.LoopStart; + } + else { - VolumeChanged?.Invoke(volume); + Reader.Stream.Position = outData; + return Reader!.ReadInt16(); } - _shouldSendVolUpdateEvent = true; + //if (dataCount < nElements) + //{ + // // underrun + // std::fill(outData, outData + nElements, sample{ 0.0f, 0.0f}); + //} + //else + //{ + // // output + // std::unique_lock < std::mutex > lock (CountLock) ; + // while (nElements > 0) + // { + // int count = takeChunk(outData, nElements); + // outData += count; + // nElements -= count; + // } + // sig.notify_one(); + //} } - public void OnDisplayNameChanged(string displayName) + + public float Volume { - throw new NotImplementedException(); + get => Vol; + set => Vol = Math.Max(Math.Min(value, 0), 1); } - public void OnIconPathChanged(string iconPath) + + public bool IsPlaying { - throw new NotImplementedException(); + get => PlayingBack; } - public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) + + public float Cursor { - throw new NotImplementedException(); + get => (float)(Pos) / (float)(TotalFrames) * (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; + set + { + // Do math + float per = value / (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; + long frame = (long)(per * TotalFrames); + + // Clamp + frame = Math.Max(Math.Min(frame, 0), TotalFrames); + + // Set (stop playback for a very short while, to stop some back skipping noises) + bool wasPlaying = IsPlaying; + if (Pos != TotalFrames) // this check stops a segfault when the audio has reached the end of playback + Pause(); + + Pos = frame; + Reader!.Stream.Seek(Pos / WaveData!.Channels, SeekOrigin.Begin); + + if (wasPlaying) + Play(); + } } - public void OnGroupingParamChanged(ref Guid groupingId) + + public void Play() { - throw new NotImplementedException(); + PlayingBack = true; + + if (Stream!.IsStopped) + Stream.Start(); } - // Fires on @out.Play() and @out.Stop() - public void OnStateChanged(AudioSessionState state) + + public void Pause() { - if (state == AudioSessionState.AudioSessionStateActive) - { - OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); - } + PlayingBack = false; + + if (Stream!.IsActive) + Stream.Stop(); } - public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) + + public float GetVolume() { - throw new NotImplementedException(); + return Vol; } + public void SetVolume(float volume) { - _shouldSendVolUpdateEvent = false; - _appVolume.SimpleAudioVolume.Volume = volume; + Vol = Math.Max(Math.Min(volume, 0), 1); + } + + public void CreateWaveWriter(string fileName) + { + _waveWriter = new Wave(fileName); + } + public void CloseWaveWriter() + { + } public virtual void Dispose() { + if (IsDisposed) return; + + Stream!.Dispose(); + Reader!.Stream.Dispose(); GC.SuppressFinalize(this); - _out.Stop(); - _out.Dispose(); - _appVolume.Dispose(); + + IsDisposed = true; + } + + public interface IAudio + { + byte[] ByteBuffer { get; } + float[] FloatBuffer { get; } + short[] ShortBuffer { get; } + int[] IntBuffer { get; } + } + + [StructLayout(LayoutKind.Explicit, Pack = 2)] + public class Audio : IAudio + { + [FieldOffset(0)] + public int NumberOfBytes; + [FieldOffset(8)] + public byte[] ByteBuffer; + [FieldOffset(8)] + public float[]? FloatBuffer; + [FieldOffset(8)] + public short[]? ShortBuffer; + [FieldOffset(8)] + public int[]? IntBuffer; + + byte[] IAudio.ByteBuffer => ByteBuffer; + float[] IAudio.FloatBuffer => FloatBuffer!; + short[] IAudio.ShortBuffer => ShortBuffer!; + int[] IAudio.IntBuffer => IntBuffer!; + + public int ByteBufferCount + { + get + { + return NumberOfBytes; + } + set + { + NumberOfBytes = CheckValidityCount("ByteBufferCount", value, 1); + } + } + + public int ShortBufferCount + { + get + { + return NumberOfBytes / 2; + } + set + { + NumberOfBytes = CheckValidityCount("ShortBufferCount", value, 2); + } + } + + public int IntBufferCount + { + get + { + return NumberOfBytes / 4; + } + set + { + NumberOfBytes = CheckValidityCount("IntBufferCount", value, 4); + } + } + + public int LongBufferCount + { + get + { + return NumberOfBytes / 8; + } + set + { + NumberOfBytes = CheckValidityCount("LongBufferCount", value, 8); + } + } + + public int HalfBufferCount + { + get + { + return NumberOfBytes / 2; + } + set + { + NumberOfBytes = CheckValidityCount("HalfBufferCount", value, 2); + } + } + + public int FloatBufferCount + { + get + { + return NumberOfBytes / 4; + } + set + { + NumberOfBytes = CheckValidityCount("FloatBufferCount", value, 4); + } + } + + public int DoubleBufferCount + { + get + { + return NumberOfBytes / 8; + } + set + { + NumberOfBytes = CheckValidityCount("DoubleBufferCount", value, 8); + } + } + + public Audio(int combinedSamplesPerBuffer) + { + Instance!.CombinedSamplesPerBuffer = (uint)combinedSamplesPerBuffer; + Instance.SizeInBytes = combinedSamplesPerBuffer * sizeof(float); + int num = Instance.SizeInBytes % 4; + Instance.SizeToAllocateInBytes = (num == 0) ? Instance.SizeInBytes : (Instance.SizeInBytes + 4 - num); + Instance.Buffer = ByteBuffer = new byte[Instance.SizeToAllocateInBytes]; + NumberOfBytes = 0; + } + + public static implicit operator byte[](Audio waveBuffer) + { + return waveBuffer.ByteBuffer; + } + + private int CheckValidityCount(string argName, int value, int sizeOfValue) + { + int num = value * sizeOfValue; + if (num % 4 != 0) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); + } + + if (value < 0 || value > ByteBuffer.Length / sizeOfValue) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceed max count {ByteBuffer.Length / sizeOfValue}"); + } + + return num; + } + + public void Clear() + { + Array.Clear(ByteBuffer, 0, ByteBuffer.Length); + } + + public void Copy(Array destinationArray) + { + Array.Copy(ByteBuffer, destinationArray, NumberOfBytes); + } } } diff --git a/VG Music Studio - Core/Mixer_NAudio.cs b/VG Music Studio - Core/Mixer_NAudio.cs new file mode 100644 index 0000000..59e83e7 --- /dev/null +++ b/VG Music Studio - Core/Mixer_NAudio.cs @@ -0,0 +1,109 @@ +using NAudio.CoreAudioApi; +using NAudio.CoreAudioApi.Interfaces; +using NAudio.Wave; +using System; + +namespace Kermalis.VGMusicStudio.Core; + +public abstract class Mixer_NAudio : IAudioSessionEventsHandler, IDisposable +{ + public static event Action? VolumeChanged; + + public readonly bool[] Mutes; + private IWavePlayer _out; + private AudioSessionControl _appVolume; + + private bool _shouldSendVolUpdateEvent = true; + + protected WaveFileWriter? _waveWriter; + protected abstract WaveFormat WaveFormat { get; } + + protected Mixer_NAudio() + { + Mutes = new bool[SongState.MAX_TRACKS]; + _out = null!; + _appVolume = null!; + } + + protected void Init(IWaveProvider waveProvider) + { + _out = new WasapiOut(); + _out.Init(waveProvider); + using (var en = new MMDeviceEnumerator()) + { + SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; + int id = Environment.ProcessId; + for (int i = 0; i < sessions.Count; i++) + { + AudioSessionControl session = sessions[i]; + if (session.GetProcessID == id) + { + _appVolume = session; + _appVolume.RegisterEventClient(this); + break; + } + } + } + _out.Play(); + } + + public void CreateWaveWriter(string fileName) + { + _waveWriter = new WaveFileWriter(fileName, WaveFormat); + } + public void CloseWaveWriter() + { + _waveWriter!.Dispose(); + _waveWriter = null; + } + + public void OnVolumeChanged(float volume, bool isMuted) + { + if (_shouldSendVolUpdateEvent) + { + VolumeChanged?.Invoke(volume); + } + _shouldSendVolUpdateEvent = true; + } + public void OnDisplayNameChanged(string displayName) + { + throw new NotImplementedException(); + } + public void OnIconPathChanged(string iconPath) + { + throw new NotImplementedException(); + } + public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) + { + throw new NotImplementedException(); + } + public void OnGroupingParamChanged(ref Guid groupingId) + { + throw new NotImplementedException(); + } + // Fires on @out.Play() and @out.Stop() + public void OnStateChanged(AudioSessionState state) + { + if (state == AudioSessionState.AudioSessionStateActive) + { + OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); + } + } + public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) + { + throw new NotImplementedException(); + } + public void SetVolume(float volume) + { + _shouldSendVolUpdateEvent = false; + _appVolume.SimpleAudioVolume.Volume = volume; + } + + public virtual void Dispose() + { + GC.SuppressFinalize(this); + _out.Stop(); + _out.Dispose(); + _appVolume.Dispose(); + } +} diff --git a/VG Music Studio - Core/NDS/DSE/DSEEngine.cs b/VG Music Studio - Core/NDS/DSE/DSEEngine.cs index a7a933e..5fe7228 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEEngine.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEEngine.cs @@ -6,13 +6,23 @@ public sealed class DSEEngine : Engine public override DSEConfig Config { get; } public override DSEMixer Mixer { get; } + public DSEMixer_NAudio Mixer_NAudio { get; } public override DSEPlayer Player { get; } + public override bool UseNewMixer { get => false; } public DSEEngine(string bgmPath) { Config = new DSEConfig(bgmPath); - Mixer = new DSEMixer(); - Player = new DSEPlayer(Config, Mixer); + if (Engine.Instance!.UseNewMixer) + { + Mixer = new DSEMixer(); + Player = new DSEPlayer(Config, Mixer); + } + else + { + Mixer_NAudio = new DSEMixer_NAudio(); + Player = new DSEPlayer(Config, Mixer_NAudio); + } DSEInstance = this; Instance = this; diff --git a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs index 89f6c52..212f2a5 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEMixer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEMixer.cs @@ -1,6 +1,6 @@ -using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Formats; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; using Kermalis.VGMusicStudio.Core.Util; -using NAudio.Wave; using System; namespace Kermalis.VGMusicStudio.Core.NDS.DSE; @@ -17,9 +17,7 @@ public sealed class DSEMixer : Mixer private float _fadeStepPerMicroframe; private readonly DSEChannel[] _channels; - private readonly BufferedWaveProvider _buffer; - - protected override WaveFormat WaveFormat => _buffer.WaveFormat; + private readonly Wave _buffer; public DSEMixer() { @@ -36,11 +34,12 @@ public DSEMixer() _channels[i] = new DSEChannel(i); } - _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) + _buffer = new Wave() { DiscardOnBufferOverflow = true, BufferLength = _samplesPerBuffer * 64, }; + _buffer.CreateIeeeFloatWave(sampleRate, 2, 16); Init(_buffer); } diff --git a/VG Music Studio - Core/NDS/DSE/DSEMixer_NAudio.cs b/VG Music Studio - Core/NDS/DSE/DSEMixer_NAudio.cs new file mode 100644 index 0000000..dffaea7 --- /dev/null +++ b/VG Music Studio - Core/NDS/DSE/DSEMixer_NAudio.cs @@ -0,0 +1,214 @@ +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Util; +using NAudio.Wave; +using System; + +namespace Kermalis.VGMusicStudio.Core.NDS.DSE; + +public sealed class DSEMixer_NAudio : Mixer_NAudio +{ + private const int NUM_CHANNELS = 0x20; // Actual value unknown for now + + private readonly float _samplesReciprocal; + private readonly int _samplesPerBuffer; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; + + private readonly DSEChannel[] _channels; + private readonly BufferedWaveProvider _buffer; + + protected override WaveFormat WaveFormat => _buffer.WaveFormat; + + public DSEMixer_NAudio() + { + // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. + // - gbatek + // I'm not using either of those because the samples per buffer leads to an overflow eventually + const int sampleRate = 65_456; + _samplesPerBuffer = 341; // TODO + _samplesReciprocal = 1f / _samplesPerBuffer; + + _channels = new DSEChannel[NUM_CHANNELS]; + for (byte i = 0; i < NUM_CHANNELS; i++) + { + _channels[i] = new DSEChannel(i); + } + + _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = _samplesPerBuffer * 64, + }; + Init(_buffer); + } + + internal DSEChannel? AllocateChannel() + { + static int GetScore(DSEChannel c) + { + // Free channels should be used before releasing channels + return c.Owner is null ? -2 : DSEUtils.IsStateRemovable(c.State) ? -1 : 0; + } + DSEChannel? nChan = null; + for (int i = 0; i < NUM_CHANNELS; i++) + { + DSEChannel c = _channels[i]; + if (nChan is null) + { + nChan = c; + } + else + { + int nScore = GetScore(nChan); + int cScore = GetScore(c); + if (cScore <= nScore && (cScore < nScore || c.Volume <= nChan.Volume)) + { + nChan = c; + } + } + } + return nChan is not null && 0 >= GetScore(nChan) ? nChan : null; + } + + internal void ChannelTick() + { + for (int i = 0; i < NUM_CHANNELS; i++) + { + DSEChannel chan = _channels[i]; + if (chan.Owner is null) + { + continue; + } + + chan.Volume = (byte)chan.StepEnvelope(); + if (chan.NoteLength == 0 && !DSEUtils.IsStateRemovable(chan.State)) + { + chan.SetEnvelopePhase7_2074ED8(); + } + int vol = SDATUtils.SustainTable[chan.NoteVelocity] + SDATUtils.SustainTable[chan.Volume] + SDATUtils.SustainTable[chan.Owner.Volume] + SDATUtils.SustainTable[chan.Owner.Expression]; + //int pitch = ((chan.Key - chan.BaseKey) << 6) + chan.SweepMain() + chan.Owner.GetPitch(); // "<< 6" is "* 0x40" + int pitch = (chan.Key - chan.RootKey) << 6; // "<< 6" is "* 0x40" + if (DSEUtils.IsStateRemovable(chan.State) && vol <= -92544) + { + chan.Stop(); + } + else + { + chan.Volume = SDATUtils.GetChannelVolume(vol); + chan.Panpot = chan.Owner.Panpot; + chan.Timer = SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); + } + } + } + + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1000.0 * 192); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1000.0 * 192); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } + + private readonly byte[] _b = new byte[4]; + internal void Process(bool output, bool recording) + { + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < _samplesPerBuffer; i++) + { + int left = 0, + right = 0; + for (int j = 0; j < NUM_CHANNELS; j++) + { + DSEChannel chan = _channels[j]; + if (chan.Owner is null) + { + continue; + } + + bool muted = Mutes[chan.Owner.Index]; // Get mute first because chan.Process() can call chan.Stop() which sets chan.Owner to null + chan.Process(out short channelLeft, out short channelRight); + if (!muted) + { + left += channelLeft; + right += channelRight; + } + } + float f = left * masterLevel; + if (f < short.MinValue) + { + f = short.MinValue; + } + else if (f > short.MaxValue) + { + f = short.MaxValue; + } + left = (int)f; + _b[0] = (byte)left; + _b[1] = (byte)(left >> 8); + f = right * masterLevel; + if (f < short.MinValue) + { + f = short.MinValue; + } + else if (f > short.MaxValue) + { + f = short.MaxValue; + } + right = (int)f; + _b[2] = (byte)right; + _b[3] = (byte)(right >> 8); + masterLevel += masterStep; + if (output) + { + _buffer.AddSamples(_b, 0, 4); + } + if (recording) + { + _waveWriter!.Write(_b, 0, 4); + } + } + } +} diff --git a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs index bfdcda2..3abde7c 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEPlayer.cs @@ -8,6 +8,7 @@ public sealed class DSEPlayer : Player private readonly DSEConfig _config; internal readonly DSEMixer DMixer; + internal readonly DSEMixer_NAudio DMixer_NAudio; internal readonly SWD MasterSWD; private DSELoadedSong? _loadedSong; @@ -17,6 +18,7 @@ public sealed class DSEPlayer : Player public override ILoadedSong? LoadedSong => _loadedSong; protected override Mixer Mixer => DMixer; + protected override Mixer_NAudio Mixer_NAudio => DMixer_NAudio; public DSEPlayer(DSEConfig config, DSEMixer mixer) : base(192) @@ -26,6 +28,14 @@ public DSEPlayer(DSEConfig config, DSEMixer mixer) MasterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); } + public DSEPlayer(DSEConfig config, DSEMixer_NAudio mixer) + : base(192) + { + DMixer_NAudio = mixer; + _config = config; + + MasterSWD = new SWD(Path.Combine(config.BGMPath, "bgm.swd")); + } public override void LoadSong(int index) { @@ -49,7 +59,10 @@ internal override void InitEmulation() TempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - DMixer.ResetFade(); + if (Engine.Instance!.UseNewMixer) + DMixer.ResetFade(); + else + DMixer_NAudio.ResetFade(); DSETrack[] tracks = _loadedSong!.Tracks; for (int i = 0; i < tracks.Length; i++) { @@ -82,17 +95,35 @@ protected override bool Tick(bool playing, bool recording) { TickTrack(s, s.Tracks[i], ref allDone); } - if (DMixer.IsFadeDone()) + if (Engine.Instance!.UseNewMixer) + { + if (DMixer.IsFadeDone()) + { + allDone = true; + } + } + else { - allDone = true; + if (DMixer_NAudio.IsFadeDone()) + { + allDone = true; + } } } if (!allDone) { TempoStack += Tempo; } - DMixer.ChannelTick(); - DMixer.Process(playing, recording); + if (Engine.Instance!.UseNewMixer) + { + DMixer.ChannelTick(); + DMixer.Process(playing, recording); + } + else + { + DMixer_NAudio.ChannelTick(); + DMixer_NAudio.Process(playing, recording); + } return allDone; } private void TickTrack(DSELoadedSong s, DSETrack track, ref bool allDone) @@ -127,9 +158,19 @@ private void HandleTicksAndLoop(DSELoadedSong s, DSETrack track) _elapsedLoops++; UpdateElapsedTicksAfterLoop(s.Events[track.Index], track.CurOffset, track.Rest); - if (ShouldFadeOut && _elapsedLoops > NumLoops && !DMixer.IsFading()) + if (Engine.Instance!.UseNewMixer) { - DMixer.BeginFadeOut(); + if (ShouldFadeOut && _elapsedLoops > NumLoops && !DMixer.IsFading()) + { + DMixer.BeginFadeOut(); + } + } + else + { + if (ShouldFadeOut && _elapsedLoops > NumLoops && !DMixer_NAudio.IsFading()) + { + DMixer_NAudio.BeginFadeOut(); + } } } } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs b/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs index 7611c7f..f2bc349 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs @@ -6,13 +6,23 @@ public sealed class SDATEngine : Engine public override SDATConfig Config { get; } public override SDATMixer Mixer { get; } + public SDATMixer_NAudio Mixer_NAudio { get; } public override SDATPlayer Player { get; } + public override bool UseNewMixer { get => false; } public SDATEngine(SDAT sdat) { Config = new SDATConfig(sdat); - Mixer = new SDATMixer(); - Player = new SDATPlayer(Config, Mixer); + if (UseNewMixer) + { + Mixer = new SDATMixer(); + Player = new SDATPlayer(Config, Mixer); + } + else + { + Mixer_NAudio = new SDATMixer_NAudio(); + Player = new SDATPlayer(Config, Mixer_NAudio); + } SDATInstance = this; Instance = this; diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs index 6d69009..26f8cd8 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Events.cs @@ -693,8 +693,16 @@ public void SetTicks() _player.ElapsedTicks++; } _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); + if (Engine.Instance!.UseNewMixer) + { + _player.SMixer.ChannelTick(); + _player.SMixer.EmulateProcess(); + } + else + { + _player.SMixer_NAudio.ChannelTick(); + _player.SMixer_NAudio.EmulateProcess(); + } } for (int trackIndex = 0; trackIndex < 0x10; trackIndex++) { @@ -732,8 +740,16 @@ internal void SetCurTick(long ticks) } } _player.TempoStack += _player.Tempo; - _player.SMixer.ChannelTick(); - _player.SMixer.EmulateProcess(); + if (Engine.Instance!.UseNewMixer) + { + _player.SMixer.ChannelTick(); + _player.SMixer.EmulateProcess(); + } + else + { + _player.SMixer_NAudio.ChannelTick(); + _player.SMixer_NAudio.EmulateProcess(); + } } finish: for (int i = 0; i < 0x10; i++) diff --git a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs index c9a87d0..1f440be 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATLoadedSong_Runtime.cs @@ -78,7 +78,10 @@ private int ReadArg(SDATTrack track, ArgType type) private void TryStartChannel(SBNK.InstrumentData inst, SDATTrack track, byte note, byte velocity, int duration, out SDATChannel? channel) { InstrumentType type = inst.Type; - channel = _player.SMixer.AllocateChannel(type, track); + if (Engine.Instance!.UseNewMixer) + channel = _player.SMixer.AllocateChannel(type, track); + else + channel = _player.SMixer_NAudio.AllocateChannel(type, track); if (channel is null) { return; diff --git a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs index e516e15..55e44d3 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATMixer.cs @@ -1,5 +1,5 @@ -using Kermalis.VGMusicStudio.Core.Util; -using NAudio.Wave; +using Kermalis.VGMusicStudio.Core.Formats; +using Kermalis.VGMusicStudio.Core.Util; using System; namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; @@ -14,9 +14,7 @@ public sealed class SDATMixer : Mixer private float _fadeStepPerMicroframe; internal SDATChannel[] Channels; - private readonly BufferedWaveProvider _buffer; - - protected override WaveFormat WaveFormat => _buffer.WaveFormat; + private readonly Wave _buffer; internal SDATMixer() { @@ -33,11 +31,12 @@ internal SDATMixer() Channels[i] = new SDATChannel(i); } - _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) + _buffer = new Wave() { DiscardOnBufferOverflow = true, BufferLength = _samplesPerBuffer * 64 }; + _buffer.CreateIeeeFloatWave(sampleRate, 2, 16); Init(_buffer); } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATMixer_NAudio.cs b/VG Music Studio - Core/NDS/SDAT/SDATMixer_NAudio.cs new file mode 100644 index 0000000..abf42c6 --- /dev/null +++ b/VG Music Studio - Core/NDS/SDAT/SDATMixer_NAudio.cs @@ -0,0 +1,244 @@ +using Kermalis.VGMusicStudio.Core.Util; +using NAudio.Wave; +using System; + +namespace Kermalis.VGMusicStudio.Core.NDS.SDAT; + +public sealed class SDATMixer_NAudio : Mixer_NAudio +{ + private readonly float _samplesReciprocal; + private readonly int _samplesPerBuffer; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; + + internal SDATChannel[] Channels; + private readonly BufferedWaveProvider _buffer; + + protected override WaveFormat WaveFormat => _buffer.WaveFormat; + + internal SDATMixer_NAudio() + { + // The sampling frequency of the mixer is 1.04876 MHz with an amplitude resolution of 24 bits, but the sampling frequency after mixing with PWM modulation is 32.768 kHz with an amplitude resolution of 10 bits. + // - gbatek + // I'm not using either of those because the samples per buffer leads to an overflow eventually + const int sampleRate = 65456; + _samplesPerBuffer = 341; // TODO + _samplesReciprocal = 1f / _samplesPerBuffer; + + Channels = new SDATChannel[0x10]; + for (byte i = 0; i < 0x10; i++) + { + Channels[i] = new SDATChannel(i); + } + + _buffer = new BufferedWaveProvider(new WaveFormat(sampleRate, 16, 2)) + { + DiscardOnBufferOverflow = true, + BufferLength = _samplesPerBuffer * 64 + }; + Init(_buffer); + } + + private static readonly int[] _pcmChanOrder = new int[] { 4, 5, 6, 7, 2, 0, 3, 1, 8, 9, 10, 11, 14, 12, 15, 13 }; + private static readonly int[] _psgChanOrder = new int[] { 8, 9, 10, 11, 12, 13 }; + private static readonly int[] _noiseChanOrder = new int[] { 14, 15 }; + internal SDATChannel? AllocateChannel(InstrumentType type, SDATTrack track) + { + int[] allowedChannels; + switch (type) + { + case InstrumentType.PCM: allowedChannels = _pcmChanOrder; break; + case InstrumentType.PSG: allowedChannels = _psgChanOrder; break; + case InstrumentType.Noise: allowedChannels = _noiseChanOrder; break; + default: return null; + } + SDATChannel? nChan = null; + for (int i = 0; i < allowedChannels.Length; i++) + { + SDATChannel c = Channels[allowedChannels[i]]; + if (nChan is not null && c.Priority >= nChan.Priority && (c.Priority != nChan.Priority || nChan.Volume <= c.Volume)) + { + continue; + } + nChan = c; + } + if (nChan is null || track.Priority < nChan.Priority) + { + return null; + } + return nChan; + } + + internal void ChannelTick() + { + for (int i = 0; i < 0x10; i++) + { + SDATChannel chan = Channels[i]; + if (chan.Owner is null) + { + continue; + } + + chan.StepEnvelope(); + if (chan.NoteDuration == 0 && !chan.Owner.WaitingForNoteToFinishBeforeContinuingXD) + { + chan.Priority = 1; + chan.State = EnvelopeState.Release; + } + int vol = SDATUtils.SustainTable[chan.NoteVelocity] + chan.Velocity + chan.Owner.GetVolume(); + int pitch = ((chan.Note - chan.BaseNote) << 6) + chan.SweepMain() + chan.Owner.GetPitch(); // "<< 6" is "* 0x40" + int pan = 0; + chan.LFOTick(); + switch (chan.LFOType) + { + case LFOType.Pitch: pitch += chan.LFOParam; break; + case LFOType.Volume: vol += chan.LFOParam; break; + case LFOType.Panpot: pan += chan.LFOParam; break; + } + if (chan.State == EnvelopeState.Release && vol <= -92544) + { + chan.Stop(); + } + else + { + chan.Volume = SDATUtils.GetChannelVolume(vol); + chan.Timer = SDATUtils.GetChannelTimer(chan.BaseTimer, pitch); + int p = chan.StartingPan + chan.Owner.GetPan() + pan; + if (p < -0x40) + { + p = -0x40; + } + else if (p > 0x3F) + { + p = 0x3F; + } + chan.Pan = (sbyte)p; + } + } + } + + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * 192); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * 192); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } + + internal void EmulateProcess() + { + for (int i = 0; i < _samplesPerBuffer; i++) + { + for (int j = 0; j < 0x10; j++) + { + SDATChannel chan = Channels[j]; + if (chan.Owner is not null) + { + chan.EmulateProcess(); + } + } + } + } + private readonly byte[] _b = new byte[4]; + internal void Process(bool output, bool recording) + { + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < _samplesPerBuffer; i++) + { + int left = 0, + right = 0; + for (int j = 0; j < 0x10; j++) + { + SDATChannel chan = Channels[j]; + if (chan.Owner is null) + { + continue; + } + + bool muted = Mutes[chan.Owner.Index]; // Get mute first because chan.Process() can call chan.Stop() which sets chan.Owner to null + chan.Process(out short channelLeft, out short channelRight); + if (!muted) + { + left += channelLeft; + right += channelRight; + } + } + float f = left * masterLevel; + if (f < short.MinValue) + { + f = short.MinValue; + } + else if (f > short.MaxValue) + { + f = short.MaxValue; + } + left = (int)f; + _b[0] = (byte)left; + _b[1] = (byte)(left >> 8); + f = right * masterLevel; + if (f < short.MinValue) + { + f = short.MinValue; + } + else if (f > short.MaxValue) + { + f = short.MaxValue; + } + right = (int)f; + _b[2] = (byte)right; + _b[3] = (byte)(right >> 8); + masterLevel += masterStep; + if (output) + { + _buffer.AddSamples(_b, 0, 4); + } + if (recording) + { + _waveWriter!.Write(_b, 0, 4); + } + } + } +} diff --git a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs index 97fb6ae..40fc72f 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATPlayer.cs @@ -13,6 +13,7 @@ public sealed class SDATPlayer : Player private readonly string?[] _voiceTypeCache = new string?[256]; internal readonly SDATConfig Config; internal readonly SDATMixer SMixer; + internal readonly SDATMixer_NAudio SMixer_NAudio; private SDATLoadedSong? _loadedSong; internal byte Volume; @@ -24,6 +25,7 @@ public sealed class SDATPlayer : Player public override ILoadedSong? LoadedSong => _loadedSong; protected override Mixer Mixer => SMixer; + protected override Mixer_NAudio Mixer_NAudio => SMixer_NAudio; internal SDATPlayer(SDATConfig config, SDATMixer mixer) : base(192) @@ -36,6 +38,17 @@ internal SDATPlayer(SDATConfig config, SDATMixer mixer) Tracks[i] = new SDATTrack(i, this); } } + internal SDATPlayer(SDATConfig config, SDATMixer_NAudio mixer) + : base(192) + { + Config = config; + SMixer_NAudio = mixer; + + for (byte i = 0; i < 0x10; i++) + { + Tracks[i] = new SDATTrack(i, this); + } + } public override void LoadSong(int index) { @@ -80,7 +93,10 @@ internal override void InitEmulation() TempoStack = 0; _elapsedLoops = 0; ElapsedTicks = 0; - SMixer.ResetFade(); + if (Engine.Instance!.UseNewMixer) + SMixer.ResetFade(); + else + SMixer_NAudio.ResetFade(); _loadedSong!.InitEmulation(); for (int i = 0; i < 0x10; i++) { @@ -107,34 +123,68 @@ protected override void OnStopped() protected override bool Tick(bool playing, bool recording) { bool allDone = false; - while (!allDone && TempoStack >= 240) + if (Engine.Instance!.UseNewMixer) { - TempoStack -= 240; - allDone = true; - for (int i = 0; i < 0x10; i++) + while (!allDone && TempoStack >= 240) { - TickTrack(i, ref allDone); + TempoStack -= 240; + allDone = true; + for (int i = 0; i < 0x10; i++) + { + TickTrack(i, ref allDone); + } + if (SMixer.IsFadeDone()) + { + allDone = true; + } } - if (SMixer.IsFadeDone()) + if (!allDone) { - allDone = true; + TempoStack += Tempo; } + for (int i = 0; i < 0x10; i++) + { + SDATTrack track = Tracks[i]; + if (track.Enabled) + { + track.UpdateChannels(); + } + } + SMixer.ChannelTick(); + SMixer.Process(playing, recording); + return allDone; } - if (!allDone) - { - TempoStack += Tempo; - } - for (int i = 0; i < 0x10; i++) + else { - SDATTrack track = Tracks[i]; - if (track.Enabled) + while (!allDone && TempoStack >= 240) + { + TempoStack -= 240; + allDone = true; + for (int i = 0; i < 0x10; i++) + { + TickTrack(i, ref allDone); + } + if (SMixer_NAudio.IsFadeDone()) + { + allDone = true; + } + } + if (!allDone) + { + TempoStack += Tempo; + } + for (int i = 0; i < 0x10; i++) { - track.UpdateChannels(); + SDATTrack track = Tracks[i]; + if (track.Enabled) + { + track.UpdateChannels(); + } } + SMixer_NAudio.ChannelTick(); + SMixer_NAudio.Process(playing, recording); + return allDone; } - SMixer.ChannelTick(); - SMixer.Process(playing, recording); - return allDone; } private void TickTrack(int trackIndex, ref bool allDone) { @@ -187,9 +237,19 @@ private void HandleTicksAndLoop(SDATLoadedSong s, SDATTrack track) break; } } - if (ShouldFadeOut && _elapsedLoops > NumLoops && !SMixer.IsFading()) + if (Engine.Instance!.UseNewMixer) + { + if (ShouldFadeOut && _elapsedLoops > NumLoops && !SMixer.IsFading()) + { + SMixer.BeginFadeOut(); + } + } + else { - SMixer.BeginFadeOut(); + if (ShouldFadeOut && _elapsedLoops > NumLoops && !SMixer_NAudio.IsFading()) + { + SMixer_NAudio.BeginFadeOut(); + } } } } diff --git a/VG Music Studio - Core/Player.cs b/VG Music Studio - Core/Player.cs index 33bd9b0..9d1e0da 100644 --- a/VG Music Studio - Core/Player.cs +++ b/VG Music Studio - Core/Player.cs @@ -25,6 +25,7 @@ public abstract class Player : IDisposable { protected abstract string Name { get; } protected abstract Mixer Mixer { get; } + protected abstract Mixer_NAudio Mixer_NAudio { get; } public abstract ILoadedSong? LoadedSong { get; } public bool ShouldFadeOut { get; set; } diff --git a/VG Music Studio - Core/PortAudio/Enumerations/ErrorCode.cs b/VG Music Studio - Core/PortAudio/Enumerations/ErrorCode.cs new file mode 100644 index 0000000..c3cb486 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Enumerations/ErrorCode.cs @@ -0,0 +1,44 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +namespace PortAudio +{ + /// + /// Error codes returned by PortAudio functions. + /// Note that with the exception of paNoError, all PaErrorCodes are negative. + /// + public enum ErrorCode + { + NoError = 0, + + NotInitialized = -10000, + UnanticipatedHostError, + InvalidChannelCount, + InvalidSampleRate, + InvalidDevice, + InvalidFlag, + SampleFormatNotSupported, + BadIODeviceCombination, + InsufficientMemory, + BufferTooBig, + BufferTooSmall, + NullCallback, + BadStreamPtr, + TimedOut, + InternalError, + DeviceUnavailable, + IncompatibleHostApiSpecificStreamInfo, + StreamIsStopped, + StreamIsNotStopped, + InputOverflowed, + OutputUnderflowed, + HostApiNotFound, + InvalidHostApi, + CanNotReadFromACallbackStream, + CanNotWriteToACallbackStream, + CanNotReadFromAnOutputOnlyStream, + CanNotWriteToAnInputOnlyStream, + IncompatibleStreamHostApi, + BadBufferPtr + } +} diff --git a/VG Music Studio - Core/PortAudio/Enumerations/SampleFormat.cs b/VG Music Studio - Core/PortAudio/Enumerations/SampleFormat.cs new file mode 100644 index 0000000..9780cae --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Enumerations/SampleFormat.cs @@ -0,0 +1,47 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; + +namespace PortAudio +{ + /// + /// NOTE: this doesn't exist an as actual enum in the native library, but we can make it a bit safer in C# + /// + /// A type used to specify one or more sample formats. Each value indicates + /// a possible format for sound data passed to and from the stream callback, + /// Pa_ReadStream and Pa_WriteStream. + /// + /// The standard formats paFloat32, paInt16, paInt32, paInt24, paInt8 + /// and aUInt8 are usually implemented by all implementations. + /// + /// The floating point representation (paFloat32) uses +1.0 and -1.0 as the + /// maximum and minimum respectively. + /// + /// paUInt8 is an unsigned 8 bit format where 128 is considered "ground" + /// + /// The paNonInterleaved flag indicates that audio data is passed as an array + /// of pointers to separate buffers, one buffer for each channel. Usually, + /// when this flag is not used, audio data is passed as a single buffer with + /// all channels interleaved. + /// + /// @see Pa_OpenStream, Pa_OpenDefaultStream, PaDeviceInfo + /// @see paFloat32, paInt16, paInt32, paInt24, paInt8 + /// @see paUInt8, paCustomFormat, paNonInterleaved + /// + public enum SampleFormat : System.UInt32 + { + Float32 = 0x00000001, + Int32 = 0x00000002, + + /// Packed 24 bit format. + Int24 = 0x00000004, + + Int16 = 0x00000008, + Int8 = 0x00000010, + UInt8 = 0x00000020, + CustomFormat = 0x00010000, + + NonInterleaved = 0x80000000, + } +} diff --git a/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackFlags.cs b/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackFlags.cs new file mode 100644 index 0000000..ba41c14 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackFlags.cs @@ -0,0 +1,50 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; + +namespace PortAudio +{ + /// + /// NOTE: this doesn't exist an as actual enum in the native library, but we can make it a bit safer in C# + /// + /// Flag bit constants for the statusFlags to PaStreamCallback. + /// + public enum StreamCallbackFlags : System.UInt32 + { + /// + /// In a stream opened with paFramesPerBufferUnspecified, indicates that + /// input data is all silence (zeros) because no real data is available. In a + /// stream opened without paFramesPerBufferUnspecified, it indicates that one or + /// more zero samples have been inserted into the input buffer to compensate + /// for an input underflow. + /// + InputUnderflow = 0x00000001, + + /// + /// In a stream opened with paFramesPerBufferUnspecified, indicates that data + /// prior to the first sample of the input buffer was discarded due to an + /// overflow, possibly because the stream callback is using too much CPU time. + /// Otherwise indicates that data prior to one or more samples in the + /// input buffer was discarded. + /// + InputOverflow = 0x00000002, + + /// + /// Indicates that output data (or a gap) was inserted, possibly because the + /// stream callback is using too much CPU time. + /// + OutputUnderflow = 0x00000004, + + /// + /// Indicates that output data will be discarded because no room is available. + /// + OutputOverflow = 0x00000008, + + /// + /// Some of all of the output data will be used to prime the stream, input + /// data may be zero. + /// + PrimingOutput = 0x00000010 + } +} diff --git a/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackResult.cs b/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackResult.cs new file mode 100644 index 0000000..29b5a9e --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Enumerations/StreamCallbackResult.cs @@ -0,0 +1,27 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +namespace PortAudio +{ + /// + /// Allowable return values for the PaStreamCallback. + /// @see PaStreamCallback + /// + public enum StreamCallbackResult + { + /// + /// Signal that the stream should continue invoking the callback and processing audio. + /// + Continue = 0, + + /// + /// Signal that the stream should stop invoking the callback and finish once all output samples have played. + /// + Complete = 1, + + /// + /// Signal that the stream should stop invoking the callback and finish as soon as possible. + /// + Abort = 2, + } +} diff --git a/VG Music Studio - Core/PortAudio/Enumerations/StreamFlags.cs b/VG Music Studio - Core/PortAudio/Enumerations/StreamFlags.cs new file mode 100644 index 0000000..2c43f01 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Enumerations/StreamFlags.cs @@ -0,0 +1,57 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; + +namespace PortAudio +{ + /// + /// NOTE: this doesn't exist an as actual enum in the native library, but we can make it a bit safer in C# + /// + /// Flags used to control the behavior of a stream. They are passed as + /// parameters to Pa_OpenStream or Pa_OpenDefaultStream. Multiple flags may be + /// ORed together. + /// + /// @see Pa_OpenStream, Pa_OpenDefaultStream + /// @see paNoFlag, paClipOff, paDitherOff, paNeverDropInput, + /// paPrimeOutputBuffersUsingStreamCallback, paPlatformSpecificFlags + /// + public enum StreamFlags : System.UInt32 + { + NoFlag = 0, + + /// + /// Disable default clipping of out of range samples. + /// + ClipOff = 0x00000001, + + /// + /// Disable default dithering. + /// + DitherOff = 0x00000002, + + /// + /// Flag requests that where possible a full duplex stream will not discard + /// overflowed input samples without calling the stream callback. This flag is + /// only valid for full duplex callback streams and only when used in combination + /// with the paFramesPerBufferUnspecified (0) framesPerBuffer parameter. Using + /// this flag incorrectly results in a paInvalidFlag error being returned from + /// Pa_OpenStream and Pa_OpenDefaultStream. + /// + /// @see paFramesPerBufferUnspecified + /// + NeverDropInput = 0x00000004, + + /// + /// Call the stream callback to fill initial output buffers, rather than the + /// default behavior of priming the buffers with zeros (silence). This flag has + /// no effect for input-only and blocking read/write streams. + /// + PrimeOutputBuffersUsingStreamCallback = 0x00000008, + + /// + /// A mask specifying the platform specific bits. + /// + PlatformSpecificFlags = 0xFFFF0000, + } +} diff --git a/VG Music Studio - Core/PortAudio/PortAudio.cs b/VG Music Studio - Core/PortAudio/PortAudio.cs new file mode 100644 index 0000000..199ef3d --- /dev/null +++ b/VG Music Studio - Core/PortAudio/PortAudio.cs @@ -0,0 +1,285 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +using DeviceIndex = System.Int32; + +namespace PortAudio +{ + internal static partial class Native + { + public const string PortAudioDLL = "portaudio"; + + [DllImport(PortAudioDLL)] + public static extern int Pa_GetVersion(); + + [DllImport(PortAudioDLL)] + public static extern IntPtr Pa_GetVersionInfo(); // Originally returns `const PaVersionInfo *` + + [DllImport(PortAudioDLL)] + public static extern IntPtr Pa_GetErrorText([MarshalAs(UnmanagedType.I4)] ErrorCode errorCode); // Orignially returns `const char *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_Initialize(); + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_Terminate(); + + [DllImport(PortAudioDLL)] + public static extern DeviceIndex Pa_GetDefaultOutputDevice(); + + [DllImport(PortAudioDLL)] + public static extern DeviceIndex Pa_GetDefaultInputDevice(); + + [DllImport(PortAudioDLL)] + public static extern IntPtr Pa_GetDeviceInfo(DeviceIndex device); // Originally returns `const PaDeviceInfo *` + + [DllImport(PortAudioDLL)] + public static extern DeviceIndex Pa_GetDeviceCount(); + + [DllImport(PortAudioDLL)] + public static extern void Pa_Sleep(System.Int32 msec); + } + + public static class Pa + { + #region Constants + /// + /// A special PaDeviceIndex value indicating that no device is available, + /// or should be used. + /// + /// @see PaDeviceIndex + /// + public const DeviceIndex NoDevice = -1; + + /// + /// Can be passed as the framesPerBuffer parameter to Pa_OpenStream() + /// or Pa_OpenDefaultStream() to indicate that the stream callback will + /// accept buffers of any size. + /// + public const System.UInt32 FramesPerBufferUnspecified = 0; + #endregion // Constants + + #region Properties + /// + /// Retrieve the release number of the currently running PortAudio build. + /// For example, for version "19.5.1" this will return 0x00130501. + /// + /// @see paMakeVersionNumber + /// + /// + public static int Version + { + get => Native.Pa_GetVersion(); + } + + /// + /// Retrieve version information for the currently running PortAudio build. + /// @return A pointer to an immutable PaVersionInfo structure. + /// + /// @note This function can be called at any time. It does not require PortAudio + /// to be initialized. The structure pointed to is statically allocated. Do not + /// attempt to free it or modify it. + /// + /// @see PaVersionInfo, paMakeVersionNumber + /// @version Available as of 19.5.0. + /// + public static VersionInfo VersionInfo + { + get => Marshal.PtrToStructure(Native.Pa_GetVersionInfo()); + } + + /// + /// Retrieve the index of the default output device. The result can be + /// used in the outputDevice parameter to Pa_OpenStream(). + /// + /// @return The default output device index for the default host API, or paNoDevice + /// if no default output device is available or an error was encountered. + /// + /// @note + /// On the PC, the user can specify a default device by + /// setting an environment variable. For example, to use device #1. + ///
      +        /// set PA_RECOMMENDED_OUTPUT_DEVICE=1
      +        /// 
      + /// The user should first determine the available device ids by using + /// the supplied application "pa_devs". + ///
      + public static DeviceIndex DefaultOutputDevice + { + get => Native.Pa_GetDefaultOutputDevice(); + } + + /// + /// Retrieve the index of the default input device. The result can be + /// used in the inputDevice parameter to Pa_OpenStream(). + /// + /// @return The default input device index for the default host API, or paNoDevice + /// if no default input device is available or an error was encountered. + /// + public static DeviceIndex DefaultInputDevice + { + get => Native.Pa_GetDefaultInputDevice(); + } + + /// + /// Retrieve the number of available devices. The number of available devices + /// may be zero. + /// + /// @return A non-negative value indicating the number of available devices + /// or, a PaErrorCode (which are always negative) if PortAudio is not initialized + /// or an error is encountered. + /// + public static DeviceIndex DeviceCount + { + get => Native.Pa_GetDeviceCount(); + } + #endregion + + #region Methods + /// + /// Retrieve the release number of the currently running PortAudio build. + /// For example, for version "19.5.1" this will return 0x00130501. + /// + /// @see paMakeVersionNumber + /// + /// + public static int GetVersion() => + Native.Pa_GetVersion(); + + /// + /// Retrieve version information for the currently running PortAudio build. + /// @return A pointer to an immutable PaVersionInfo structure. + /// + /// @note This function can be called at any time. It does not require PortAudio + /// to be initialized. The structure pointed to is statically allocated. Do not + /// attempt to free it or modify it. + /// + /// @see PaVersionInfo, paMakeVersionNumber + /// @version Available as of 19.5.0. + /// + public static VersionInfo GetVersionInfo() => + Marshal.PtrToStructure(Native.Pa_GetVersionInfo()); + + /// + /// Retrieve the index of the default output device. The result can be + /// used in the outputDevice parameter to Pa_OpenStream(). + /// + /// @return The default output device index for the default host API, or paNoDevice + /// if no default output device is available or an error was encountered. + /// + /// @note + /// On the PC, the user can specify a default device by + /// setting an environment variable. For example, to use device #1. + ///
      +        /// set PA_RECOMMENDED_OUTPUT_DEVICE=1
      +        /// 
      + /// The user should first determine the available device ids by using + /// the supplied application "pa_devs". + ///
      + public static DeviceIndex GetDefaultOutputDevice() => + Native.Pa_GetDefaultOutputDevice(); + + /// + /// Retrieve the index of the default input device. The result can be + /// used in the inputDevice parameter to Pa_OpenStream(). + /// + /// @return The default input device index for the default host API, or paNoDevice + /// if no default input device is available or an error was encountered. + /// + public static DeviceIndex GetDefaultInputDevice() => + Native.Pa_GetDefaultInputDevice(); + + /// + /// Retrieve the number of available devices. The number of available devices + /// may be zero. + /// + /// @return A non-negative value indicating the number of available devices + /// or, a PaErrorCode (which are always negative) if PortAudio is not initialized + /// or an error is encountered. + /// + public static DeviceIndex GetDeviceCount() => + Native.Pa_GetDeviceCount(); + + /// + /// Retrieve a pointer to a PaDeviceInfo structure containing information + /// about the specified device. + /// @return A pointer to an immutable PaDeviceInfo structure. If the device + /// parameter is out of range the function returns NULL. + /// + /// @param device A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + /// + /// @note PortAudio manages the memory referenced by the returned pointer, + /// the client must not manipulate or free the memory. The pointer is only + /// guaranteed to be valid between calls to Pa_Initialize() and Pa_Terminate(). + /// + /// @see PaDeviceInfo, PaDeviceIndex + /// + public static DeviceInfo GetDeviceInfo(DeviceIndex device) => + Marshal.PtrToStructure(Native.Pa_GetDeviceInfo(device)); + + /// + /// Translate the supplied PortAudio error code into a human readable + /// message. + /// + public static string GetErrorText(ErrorCode errorCode) => + Marshal.PtrToStringAnsi(Native.Pa_GetErrorText(errorCode)); + + /// + /// Library termination function - call this when finished using PortAudio. + /// This function deallocates all resources allocated by PortAudio since it was + /// initialized by a call to Pa_Initialize(). In cases where Pa_Initialise() has + /// been called multiple times, each call must be matched with a corresponding call + /// to Pa_Terminate(). The final matching call to Pa_Terminate() will automatically + /// close any PortAudio streams that are still open. + /// + /// Pa_Terminate() MUST be called before exiting a program which uses PortAudio. + /// Failure to do so may result in serious resource leaks, such as audio devices + /// not being available until the next reboot. + /// + /// @return paNoError if successful, otherwise an error code indicating the cause + /// of failure. + /// + /// @see Pa_Initialize + /// + public static void Terminate() + { + ErrorCode ec = Native.Pa_Terminate(); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error terminating PortAudio"); + } + + /// + /// Library initialization function - call this before using PortAudio. + /// This function initializes internal data structures and prepares underlying + /// host APIs for use. With the exception of Pa_GetVersion(), Pa_GetVersionText(), + /// and Pa_GetErrorText(), this function MUST be called before using any other + /// PortAudio API functions. + /// + /// If Pa_Initialize() is called multiple times, each successful + /// call must be matched with a corresponding call to Pa_Terminate(). + /// Pairs of calls to Pa_Initialize()/Pa_Terminate() may overlap, and are not + /// required to be fully nested. + /// + /// Note that if Pa_Initialize() returns an error code, Pa_Terminate() should + /// NOT be called. + /// + /// @return paNoError if successful, otherwise an error code indicating the cause + /// of failure. + /// + /// @see Pa_Terminate + /// + public static void Initialize() + { + ErrorCode ec = Native.Pa_Initialize(); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error initializing PortAudio"); + } + #endregion + } +} diff --git a/VG Music Studio - Core/PortAudio/PortAudioException.cs b/VG Music Studio - Core/PortAudio/PortAudioException.cs new file mode 100644 index 0000000..73664f9 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/PortAudioException.cs @@ -0,0 +1,44 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; + +namespace PortAudio +{ + public class PortAudioException : Exception + { + /// + /// Error code (from the native PortAudio library). Use `PortAudio.GetErrorText()` for some more details. + /// + public ErrorCode ErrorCode { get; private set; } + + /// + /// Creates a new PortAudio error. + /// + public PortAudioException(ErrorCode ec) : base() + { + this.ErrorCode = ec; + } + + /// + /// Creates a new PortAudio error with a message attached. + /// + /// Message to send + public PortAudioException(ErrorCode ec, string message) + : base(message) + { + this.ErrorCode = ec; + } + + /// + /// Creates a new PortAudio error with a message attached and an inner error. + /// + /// Message to send + /// The exception that occured inside of this one + public PortAudioException(ErrorCode ec, string message, Exception inner) + : base(message, inner) + { + this.ErrorCode = ec; + } + } +} diff --git a/VG Music Studio - Core/PortAudio/Stream.cs b/VG Music Studio - Core/PortAudio/Stream.cs new file mode 100644 index 0000000..28aed76 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Stream.cs @@ -0,0 +1,576 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Runtime.InteropServices; + +namespace PortAudio +{ + internal static partial class Native + { + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_OpenStream( + out IntPtr stream, // `PaStream **` + IntPtr inputParameters, // `const PaStreamParameters *` + IntPtr outputParameters, // `const PaStreamParameters *` + double sampleRate, + System.UInt32 framesPerBuffer, + StreamFlags streamFlags, + IntPtr streamCallback, // `PaStreamCallback *` + IntPtr userData // `void *` + ); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + [return: MarshalAs(UnmanagedType.I4)] + public delegate StreamCallbackResult Callback( + IntPtr input, IntPtr output, // Originally `const void *, void *` + System.UInt32 frameCount, + ref StreamCallbackTimeInfo timeInfo, // Originally `const PaStreamCallbackTimeInfo*` + StreamCallbackFlags statusFlags, + IntPtr userData // Orignially `void *` + ); + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_CloseStream(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_SetStreamFinishedCallback( + IntPtr stream, // `PaStream *` + IntPtr streamFinishedCallback // `PaStreamFinishedCallback *` + ); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate void FinishedCallback( + IntPtr userData // Originally `void *` + ); + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_StartStream(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_StopStream(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_AbortStream(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_IsStreamStopped(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_IsStreamActive(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + public static extern double Pa_GetStreamCpuLoad(IntPtr stream); // `PaStream *` + } + + /// + /// A single PaStream can provide multiple channels of real-time + /// streaming audio input and output to a client application. A stream + /// provides access to audio hardware represented by one or more + /// PaDevices. Depending on the underlying Host API, it may be possible + /// to open multiple streams using the same device, however this behavior + /// is implementation defined. Portable applications should assume that + /// a PaDevice may be simultaneously used by at most one PaStream. + /// + /// Pointers to PaStream objects are passed between PortAudio functions that + /// operate on streams. + /// + /// @see Pa_OpenStream, Pa_OpenDefaultStream, Pa_OpenDefaultStream, Pa_CloseStream, + /// Pa_StartStream, Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive, + /// Pa_GetStreamTime, Pa_GetStreamCpuLoad + /// + public class Stream : IDisposable + { + // Clean & manually managed data + private bool disposed = false; + private IntPtr streamPtr = IntPtr.Zero; // `Stream *` + private GCHandle userDataHandle; + + // Callback structures + private _NativeInterfacingCallback streamCallback = null; + private _NativeInterfacingCallback finishedCallback = null; + + /// + /// The input parameters for this stream, if any + /// + /// will be `null` if the user never supplied any + public StreamParameters? InputParameters { get; private set; } + + /// + /// The output parameters for this stream, if any + /// + /// will be `null` if the user never supplied any + public StreamParameters? OutputParameters { get; private set; } + + + #region Constructors & Cleanup + /// + /// Opens a stream for either input, output or both. + /// + /// @param stream The address of a PaStream pointer which will receive + /// a pointer to the newly opened stream. + /// + /// @param inputParameters A structure that describes the input parameters used by + /// the opened stream. See PaStreamParameters for a description of these parameters. + /// inputParameters must be NULL for output-only streams. + /// + /// @param outputParameters A structure that describes the output parameters used by + /// the opened stream. See PaStreamParameters for a description of these parameters. + /// outputParameters must be NULL for input-only streams. + /// + /// @param sampleRate The desired sampleRate. For full-duplex streams it is the + /// sample rate for both input and output + /// + /// @param framesPerBuffer The number of frames passed to the stream callback + /// function, or the preferred block granularity for a blocking read/write stream. + /// The special value paFramesPerBufferUnspecified (0) may be used to request that + /// the stream callback will receive an optimal (and possibly varying) number of + /// frames based on host requirements and the requested latency settings. + /// Note: With some host APIs, the use of non-zero framesPerBuffer for a callback + /// stream may introduce an additional layer of buffering which could introduce + /// additional latency. PortAudio guarantees that the additional latency + /// will be kept to the theoretical minimum however, it is strongly recommended + /// that a non-zero framesPerBuffer value only be used when your algorithm + /// requires a fixed number of frames per stream callback. + /// + /// @param streamFlags Flags which modify the behavior of the streaming process. + /// This parameter may contain a combination of flags ORed together. Some flags may + /// only be relevant to certain buffer formats. + /// + /// @param streamCallback A pointer to a client supplied function that is responsible + /// for processing and filling input and output buffers. If this parameter is NULL + /// the stream will be opened in 'blocking read/write' mode. In blocking mode, + /// the client can receive sample data using Pa_ReadStream and write sample data + /// using Pa_WriteStream, the number of samples that may be read or written + /// without blocking is returned by Pa_GetStreamReadAvailable and + /// Pa_GetStreamWriteAvailable respectively. + /// + /// @param userData A client supplied pointer which is passed to the stream callback + /// function. It could for example, contain a pointer to instance data necessary + /// for processing the audio buffers. This parameter is ignored if streamCallback + /// is NULL. + /// NOTE: userData will no longer be automatically GC'd normally by C#. The cleanup + /// of that will be handled by this class upon `Dipose()` or deletion. You (the + /// programmer), shouldn't have to worry about this. + /// + /// @return + /// Upon success Pa_OpenStream() returns paNoError and places a pointer to a + /// valid PaStream in the stream argument. The stream is inactive (stopped). + /// If a call to Pa_OpenStream() fails, a non-zero error code is returned (see + /// PaError for possible error codes) and the value of stream is invalid. + /// + /// @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream, + /// Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable + /// + public Stream( + StreamParameters? inParams, + StreamParameters? outParams, + double sampleRate, + System.UInt32 framesPerBuffer, + StreamFlags streamFlags, + Callback callback, + object userData + ) + { + // Setup the steam's callback + streamCallback = new _NativeInterfacingCallback(callback); + + // Take control of the userdata object + userDataHandle = GCHandle.Alloc(userData); + + // Set the ins and the outs + InputParameters = inParams; + OutputParameters = outParams; + + // If the in/out params are set, then we need to make some P/Invoke friendly memory + IntPtr inParamsPtr = IntPtr.Zero; + IntPtr outParamsPtr = IntPtr.Zero; + if (inParams.HasValue) + { + inParamsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(inParams.Value)); + Marshal.StructureToPtr(inParams.Value, inParamsPtr, false); + } + if (outParams.HasValue) + { + outParamsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(outParams.Value)); + Marshal.StructureToPtr(outParams.Value, outParamsPtr, false); + } + + // Open the stream + ErrorCode ec = Native.Pa_OpenStream( + out streamPtr, + inParamsPtr, + outParamsPtr, + sampleRate, + framesPerBuffer, + streamFlags, + streamCallback.Ptr, + GCHandle.ToIntPtr(userDataHandle) + ); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error opening PortAudio Stream.\nError Code: " + ec.ToString()); + + // Cleanup the in/out params ptrs + if (inParamsPtr != IntPtr.Zero) + Marshal.FreeHGlobal(inParamsPtr); + if (outParamsPtr != IntPtr.Zero) + Marshal.FreeHGlobal(outParamsPtr); + } + + ~Stream() + { + Dispose(false); + } + + /// + /// Cleanup resources (for the IDisposable interface) + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Does the actual disposing work + /// + protected virtual void Dispose(bool disposing) + { + if (disposed) + return; + + // Free Managed Resources + if (disposing) + { + } + + // Free Unmanaged resources + Close(); + userDataHandle.Free(); + streamCallback.Free(); + if (finishedCallback != null) + finishedCallback.Free(); + + disposed = true; + } + #endregion // Constructors & Cleanup + + /// + /// Set a callback to be triggered when the stream is done. + /// + public void SetFinishedCallback(FinishedCallback fcb) + { + finishedCallback = new _NativeInterfacingCallback(fcb); + + // TODO what happens if a callback is already set? Find out and make the necessary adjustments + ErrorCode ec = Native.Pa_SetStreamFinishedCallback(streamPtr, finishedCallback.Ptr); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error setting finished callback for PortAudio Stream.\nError Code: " + ec.ToString()); + } + + #region Operations + /// + /// Closes an audio stream. If the audio stream is active it + /// discards any pending buffers as if Pa_AbortStream() had been called. + /// + public void Close() + { + // Did we already clean up? + if (streamPtr == IntPtr.Zero) + return; + + ErrorCode ec = Native.Pa_CloseStream(streamPtr); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error closing PortAudio Stream.\nError Code: " + ec.ToString()); + + // Reset the handle, since we've cleaned up + streamPtr = IntPtr.Zero; + } + + /// + /// Commences audio processing. + /// + public void Start() + { + ErrorCode ec = Native.Pa_StartStream(streamPtr); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error starting PortAudio Stream.\nError Code: " + ec.ToString()); + } + + /// + /// Terminates audio processing. It waits until all pending + /// audio buffers have been played before it returns. + /// + public void Stop() + { + ErrorCode ec = Native.Pa_StopStream(streamPtr); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error stopping PortAudio Stream.\nError Code: " + ec.ToString()); + } + + /// + /// Terminates audio processing immediately without waiting for pending + /// buffers to complete. + /// + public void Abort() + { + ErrorCode ec = Native.Pa_AbortStream(streamPtr); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error aborting PortAudio Stream.\nError Code: " + ec.ToString()); + } + #endregion // Operations + + #region Properties + /// + /// Determine whether the stream is stopped. + /// A stream is considered to be stopped prior to a successful call to + /// Pa_StartStream and after a successful call to Pa_StopStream or Pa_AbortStream. + /// If a stream callback returns a value other than paContinue the stream is NOT + /// considered to be stopped. + /// + /// @return Returns one (1) when the stream is stopped, zero (0) when + /// the stream is running or, a PaErrorCode (which are always negative) if + /// PortAudio is not initialized or an error is encountered. + /// + /// @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive + /// + public bool IsStopped + { + get + { + ErrorCode ec = Native.Pa_IsStreamStopped(streamPtr); + + // Yes, No, or wat? + if ((int)ec == 1) + return true; + else if ((int)ec == 0) + return false; + else + throw new PortAudioException(ec, "Error checking if PortAudio Stream is stopped"); + } + } + + /// + /// Determine whether the stream is active. + /// A stream is active after a successful call to Pa_StartStream(), until it + /// becomes inactive either as a result of a call to Pa_StopStream() or + /// Pa_AbortStream(), or as a result of a return value other than paContinue from + /// the stream callback. In the latter case, the stream is considered inactive + /// after the last buffer has finished playing. + /// + /// @return Returns one (1) when the stream is active (ie playing or recording + /// audio), zero (0) when not playing or, a PaErrorCode (which are always negative) + /// if PortAudio is not initialized or an error is encountered. + /// + /// @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamStopped + /// + public bool IsActive + { + get + { + ErrorCode ec = Native.Pa_IsStreamActive(streamPtr); + + // Yes, No, or wat? + if ((int)ec == 1) + return true; + else if ((int)ec == 0) + return false; + else + throw new PortAudioException(ec, "Error checking if PortAudio Stream is active"); + } + } + + /// + /// Retrieve CPU usage information for the specified stream. + /// The "CPU Load" is a fraction of total CPU time consumed by a callback stream's + /// audio processing routines including, but not limited to the client supplied + /// stream callback. This function does not work with blocking read/write streams. + /// + /// This function may be called from the stream callback function or the + /// application. + /// + /// @return + /// A floating point value, typically between 0.0 and 1.0, where 1.0 indicates + /// that the stream callback is consuming the maximum number of CPU cycles possible + /// to maintain real-time operation. A value of 0.5 would imply that PortAudio and + /// the stream callback was consuming roughly 50% of the available CPU time. The + /// return value may exceed 1.0. A value of 0.0 will always be returned for a + /// blocking read/write stream, or if an error occurs. + /// + public double CpuLoad + { + get => Native.Pa_GetStreamCpuLoad(streamPtr); + } + #endregion Properties + + #region Programmer Friendly Callbacks + /// + /// Functions of type PaStreamCallback are implemented by PortAudio clients. + /// They consume, process or generate audio in response to requests from an + /// active PortAudio stream. + /// + /// When a stream is running, PortAudio calls the stream callback periodically. + /// The callback function is responsible for processing buffers of audio samples + /// passed via the input and output parameters. + /// + /// The PortAudio stream callback runs at very high or real-time priority. + /// It is required to consistently meet its time deadlines. Do not allocate + /// memory, access the file system, call library functions or call other functions + /// from the stream callback that may block or take an unpredictable amount of + /// time to complete. + /// + /// In order for a stream to maintain glitch-free operation the callback + /// must consume and return audio data faster than it is recorded and/or + /// played. PortAudio anticipates that each callback invocation may execute for + /// a duration approaching the duration of frameCount audio frames at the stream + /// sample rate. It is reasonable to expect to be able to utilise 70% or more of + /// the available CPU time in the PortAudio callback. However, due to buffer size + /// adaption and other factors, not all host APIs are able to guarantee audio + /// stability under heavy CPU load with arbitrary fixed callback buffer sizes. + /// When high callback CPU utilisation is required the most robust behavior + /// can be achieved by using paFramesPerBufferUnspecified as the + /// Pa_OpenStream() framesPerBuffer parameter. + /// + /// @param input and @param output are either arrays of interleaved samples or; + /// if non-interleaved samples were requested using the paNonInterleaved sample + /// format flag, an array of buffer pointers, one non-interleaved buffer for + /// each channel. + /// + /// The format, packing and number of channels used by the buffers are + /// determined by parameters to Pa_OpenStream(). + /// + /// @param frameCount The number of sample frames to be processed by + /// the stream callback. + /// + /// @param timeInfo Timestamps indicating the ADC capture time of the first sample + /// in the input buffer, the DAC output time of the first sample in the output buffer + /// and the time the callback was invoked. + /// See PaStreamCallbackTimeInfo and Pa_GetStreamTime() + /// + /// @param statusFlags Flags indicating whether input and/or output buffers + /// have been inserted or will be dropped to overcome underflow or overflow + /// conditions. + /// + /// @param userData The value of a user supplied pointer passed to + /// Pa_OpenStream() intended for storing synthesis data etc. + /// NOTE: In the implementing callback, you can use the `GetUserData()` method to + /// retrive the actual object. + /// + /// @return + /// The stream callback should return one of the values in the + /// ::PaStreamCallbackResult enumeration. To ensure that the callback continues + /// to be called, it should return paContinue (0). Either paComplete or paAbort + /// can be returned to finish stream processing, after either of these values is + /// returned the callback will not be called again. If paAbort is returned the + /// stream will finish as soon as possible. If paComplete is returned, the stream + /// will continue until all buffers generated by the callback have been played. + /// This may be useful in applications such as soundfile players where a specific + /// duration of output is required. However, it is not necessary to utilize this + /// mechanism as Pa_StopStream(), Pa_AbortStream() or Pa_CloseStream() can also + /// be used to stop the stream. The callback must always fill the entire output + /// buffer irrespective of its return value. + /// + /// @see Pa_OpenStream, Pa_OpenDefaultStream + /// + /// @note With the exception of Pa_GetStreamCpuLoad() it is not permissible to call + /// PortAudio API functions from within the stream callback. + /// + public delegate StreamCallbackResult Callback( + IntPtr input, IntPtr output, // Originally `const void *, void *` + System.UInt32 frameCount, + ref StreamCallbackTimeInfo timeInfo, // Originally `const PaStreamCallbackTimeInfo*` + StreamCallbackFlags statusFlags, + IntPtr userDataPtr // Orignially `void *` + ); + + /// + /// Functions of type PaStreamFinishedCallback are implemented by PortAudio + /// clients. They can be registered with a stream using the Pa_SetStreamFinishedCallback + /// function. Once registered they are called when the stream becomes inactive + /// (ie once a call to Pa_StopStream() will not block). + /// A stream will become inactive after the stream callback returns non-zero, + /// or when Pa_StopStream or Pa_AbortStream is called. For a stream providing audio + /// output, if the stream callback returns paComplete, or Pa_StopStream() is called, + /// the stream finished callback will not be called until all generated sample data + /// has been played. + /// + /// @param userData The userData parameter supplied to Pa_OpenStream() + /// NOTE: In the implementing callback, you can use the `GetUserData()` method to + /// retrive the actual object. + /// + /// @see Pa_SetStreamFinishedCallback + /// + public delegate void FinishedCallback( + IntPtr userDataPtr // Originally `void *` + ); + #endregion // Callbacks + + /// + /// This function will retrieve the `userData` of the stream from it's pointer. + /// + /// This is meant to be used by the callbacks for `Callback` and `FinishedCallback`, and + /// their `userDataPtr`. + /// + /// + /// The type of data that was put into the stream + /// + public static UD GetUserData(IntPtr userDataPtr) => + (UD)GCHandle.FromIntPtr(userDataPtr).Target; + + + /// + /// This is an internal structure to aid with C# Callbacks that interface with P/Invoke functions. + /// + /// The constructor, the `Free()` method, and the `Ptr` property are all that you can use, and are + /// the most important parts. + /// + /// Callback + private class _NativeInterfacingCallback + where CB : Delegate + { + /// + /// The callback itself (needs to be a delegate) + /// + private CB callback; + + /// + /// GC Handle to the callback + /// + private GCHandle handle; + + /// + /// Get the pointer to where the function/delegate lives in memory + /// + public IntPtr Ptr { get; private set; } = IntPtr.Zero; + + /// + /// Setup the data structure. + /// + /// When done with it, don't forget to call the Free() method. + /// + /// + public _NativeInterfacingCallback(CB cb) + { + callback = cb ?? throw new ArgumentNullException(nameof(cb)); + handle = GCHandle.Alloc(cb); + Ptr = Marshal.GetFunctionPointerForDelegate(cb); + } + + /// + /// Manually clean up memory + /// + public void Free() + { + handle.Free(); + } + } + } +} diff --git a/VG Music Studio - Core/PortAudio/Structures/DeviceInfo.cs b/VG Music Studio - Core/PortAudio/Structures/DeviceInfo.cs new file mode 100644 index 0000000..bb9919d --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Structures/DeviceInfo.cs @@ -0,0 +1,59 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Text; +using System.Runtime.InteropServices; + +using HostApiIndex = System.Int32; +using Time = System.Double; + +namespace PortAudio +{ + /// + /// A structure providing information and capabilities of PortAudio devices. + /// Devices may support input, output or both input and output. + /// + [StructLayout(LayoutKind.Sequential)] + public struct DeviceInfo + { + public int structVersion; // this is struct version 2 + + [MarshalAs(UnmanagedType.LPStr)] + public string name; // Originally: `const char *` + + public HostApiIndex hostApi; // note this is a host API index, not a type id + + public int maxInputChannels; + public int maxOutputChannels; + + // Default latency values for interactive performance. + public Time defaultLowInputLatency; + public Time defaultLowOutputLatency; + + // Default latency values for robust non-interactive applications (eg. playing sound files). + public Time defaultHighInputLatency; + public Time defaultHighOutputLatency; + + public double defaultSampleRate; + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine("DeviceInfo ["); + sb.AppendLine($" structVersion={structVersion}"); + sb.AppendLine($" name={name}"); + sb.AppendLine($" hostApi={hostApi}"); + sb.AppendLine($" maxInputChannels={maxInputChannels}"); + sb.AppendLine($" maxOutputChannels={maxOutputChannels}"); + sb.AppendLine($" defaultSampleRate={defaultSampleRate}"); + sb.AppendLine($" defaultLowInputLatency={defaultLowInputLatency}"); + sb.AppendLine($" defaultLowOutputLatency={defaultLowOutputLatency}"); + sb.AppendLine($" defaultHighInputLatency={defaultHighInputLatency}"); + sb.AppendLine($" defaultHighOutputLatency={defaultHighOutputLatency}"); + sb.AppendLine($" defaultHighSampleRate={defaultSampleRate}"); + sb.AppendLine("]"); + return sb.ToString(); + } + } +} diff --git a/VG Music Studio - Core/PortAudio/Structures/StreamCallbackTimeInfo.cs b/VG Music Studio - Core/PortAudio/Structures/StreamCallbackTimeInfo.cs new file mode 100644 index 0000000..4ad4a41 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Structures/StreamCallbackTimeInfo.cs @@ -0,0 +1,36 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Runtime.InteropServices; + +using Time = System.Double; + +namespace PortAudio +{ + /// + /// Timing information for the buffers passed to the stream callback. + /// + /// Time values are expressed in seconds and are synchronised with the time base used by Pa_GetStreamTime() for the associated stream. + /// + /// @see PaStreamCallback, Pa_GetStreamTime + /// + [StructLayout(LayoutKind.Sequential)] + public struct StreamCallbackTimeInfo + { + /// + /// The time when the first sample of the input buffer was captured at the ADC input + /// + public Time inputBufferAdcTime; + + /// + /// The time when the stream callback was invoked + /// + public Time currentTime; + + /// + /// The time when the first sample of the output buffer will output the DAC + /// + public Time outputBufferDacTime; + } +} diff --git a/VG Music Studio - Core/PortAudio/Structures/StreamParameters.cs b/VG Music Studio - Core/PortAudio/Structures/StreamParameters.cs new file mode 100644 index 0000000..7c172d3 --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Structures/StreamParameters.cs @@ -0,0 +1,78 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Text; +using System.Runtime.InteropServices; + +using DeviceIndex = System.Int32; +using Time = System.Double; + +namespace PortAudio +{ + /// + /// Parameters for one direction (input or output) of a stream. + /// + [StructLayout(LayoutKind.Sequential)] + public struct StreamParameters + { + /// + /// A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + /// specifying the device to be used or the special constant + /// paUseHostApiSpecificDeviceSpecification which indicates that the actual + /// device(s) to use are specified in hostApiSpecificStreamInfo. + /// This field must not be set to paNoDevice. + /// + public DeviceIndex device; + + /// + /// The number of channels of sound to be delivered to the + /// stream callback or accessed by Pa_ReadStream() or Pa_WriteStream(). + /// It can range from 1 to the value of maxInputChannels in the + /// PaDeviceInfo record for the device specified by the device parameter. + /// + public int channelCount; + + /// + /// The sample format of the buffer provided to the stream callback, + /// a_ReadStream() or Pa_WriteStream(). It may be any of the formats described + /// by the PaSampleFormat enumeration. + /// + public SampleFormat sampleFormat; + + /// + /// The desired latency in seconds. Where practical, implementations should + /// configure their latency based on these parameters, otherwise they may + /// choose the closest viable latency instead. Unless the suggested latency + /// is greater than the absolute upper limit for the device implementations + /// should round the suggestedLatency up to the next practical value - ie to + /// provide an equal or higher latency than suggestedLatency wherever possible. + /// Actual latency values for an open stream may be retrieved using the + /// inputLatency and outputLatency fields of the PaStreamInfo structure + /// returned by Pa_GetStreamInfo(). + /// @see default*Latency in PaDeviceInfo, *Latency in PaStreamInfo + /// + public Time suggestedLatency; + + /// + /// An optional pointer to a host api specific data structure + /// containing additional information for device setup and/or stream processing. + /// hostApiSpecificStreamInfo is never required for correct operation, + /// if not used it should be set to NULL. + /// + public IntPtr hostApiSpecificStreamInfo; // Originally `void *` + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine("StreamParameters ["); + sb.AppendLine($" device={device}"); + sb.AppendLine($" channelCount={channelCount}"); + sb.AppendLine($" sampleFormat={sampleFormat}"); + sb.AppendLine($" suggestedLatency={suggestedLatency}"); + sb.AppendLine($" hostApiSpecificStreamInfo?=[{hostApiSpecificStreamInfo != IntPtr.Zero}]"); + sb.AppendLine("]"); + return sb.ToString(); + } + } +} diff --git a/VG Music Studio - Core/PortAudio/Structures/VersionInfo.cs b/VG Music Studio - Core/PortAudio/Structures/VersionInfo.cs new file mode 100644 index 0000000..69efccd --- /dev/null +++ b/VG Music Studio - Core/PortAudio/Structures/VersionInfo.cs @@ -0,0 +1,38 @@ +// License: APL 2.0 +// Author: Benjamin N. Summerton + +using System; +using System.Runtime.InteropServices; + +namespace PortAudio +{ + /// + /// A structure containing PortAudio API version information. + /// @see Pa_GetVersionInfo, paMakeVersionNumber + /// @version Available as of 19.5.0. + /// + [StructLayout(LayoutKind.Sequential)] + public struct VersionInfo + { + public int versionMajor; + public int versionMinor; + public int versionSubMinor; + + /// + /// This is currently the Git revision hash but may change in the future. + /// The versionControlRevision is updated by running a script before compiling the library. + /// If the update does not occur, this value may refer to an earlier revision. + /// + [MarshalAs(UnmanagedType.LPStr)] + public string versionControlRevision; // Orignally `const char *` + + /// + /// Version as a string, for example "PortAudio V19.5.0-devel, revision 1952M" + /// + [MarshalAs(UnmanagedType.LPStr)] + public string versionText; // Orignally `const char *` + + public override string ToString() => + $"VersionInfo: v{versionMajor}.{versionMinor}.{versionSubMinor}"; + } +} diff --git a/VG Music Studio - Core/Properties/Strings.Designer.cs b/VG Music Studio - Core/Properties/Strings.Designer.cs index eea96fb..540d38e 100644 --- a/VG Music Studio - Core/Properties/Strings.Designer.cs +++ b/VG Music Studio - Core/Properties/Strings.Designer.cs @@ -358,7 +358,16 @@ public static string ErrorValueParseRanged { } /// - /// Looks up a localized string similar to GBA Files. + /// Looks up a localized string similar to All files (*.*). + /// + public static string FilterAllFiles { + get { + return ResourceManager.GetString("FilterAllFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Game Boy Advance ROM (*.gba, *.srl). /// public static string FilterOpenGBA { get { @@ -367,7 +376,7 @@ public static string FilterOpenGBA { } /// - /// Looks up a localized string similar to SDAT Files. + /// Looks up a localized string similar to Nitro Soundmaker Sound Data (*.sdat). /// public static string FilterOpenSDAT { get { @@ -376,7 +385,7 @@ public static string FilterOpenSDAT { } /// - /// Looks up a localized string similar to DLS Files. + /// Looks up a localized string similar to DLS Format (*.dls). /// public static string FilterSaveDLS { get { @@ -385,7 +394,7 @@ public static string FilterSaveDLS { } /// - /// Looks up a localized string similar to MIDI Files. + /// Looks up a localized string similar to MIDI Format (*.mid, *.midi). /// public static string FilterSaveMIDI { get { @@ -394,7 +403,7 @@ public static string FilterSaveMIDI { } /// - /// Looks up a localized string similar to SF2 Files. + /// Looks up a localized string similar to SoundFont2 Format (*.sf2). /// public static string FilterSaveSF2 { get { @@ -403,7 +412,7 @@ public static string FilterSaveSF2 { } /// - /// Looks up a localized string similar to WAV Files. + /// Looks up a localized string similar to RIFF Wave (*.wav). /// public static string FilterSaveWAV { get { diff --git a/VG Music Studio - Core/Properties/Strings.resx b/VG Music Studio - Core/Properties/Strings.resx index 916279d..fce9432 100644 --- a/VG Music Studio - Core/Properties/Strings.resx +++ b/VG Music Studio - Core/Properties/Strings.resx @@ -128,10 +128,10 @@ Error Exporting MIDI - GBA Files + Game Boy Advance ROM (*.gba, *.srl) - MIDI Files + MIDI Format (*.mid, *.midi) Data @@ -199,7 +199,7 @@ Error Loading SDAT File - SDAT Files + Nitro Soundmaker Sound Data (*.sdat) End Current Playlist @@ -331,7 +331,7 @@ Error Exporting WAV - WAV Files + RIFF Wave (*.wav) Export Song as WAV @@ -344,7 +344,7 @@ Error Exporting SF2 - SF2 Files + SoundFont2 Format (*.sf2) Export VoiceTable as SF2 @@ -357,7 +357,7 @@ Error Exporting DLS - DLS Files + DLS Format (*.dls) Export VoiceTable as DLS @@ -369,4 +369,7 @@ songs|0_0|song|1_1|songs|2_*| + + All files (*.*) + \ No newline at end of file diff --git a/VG Music Studio - Core/Util/ActionExtensions.cs b/VG Music Studio - Core/Util/ActionExtensions.cs new file mode 100644 index 0000000..c6c753c --- /dev/null +++ b/VG Music Studio - Core/Util/ActionExtensions.cs @@ -0,0 +1,186 @@ +//****************************************************************************************************** +// ActionExtensions.cs - Gbtc +// +// Copyright © 2016, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 02/02/2016 - Stephen C. Wills +// Generated original version of source code. +// 10/01/2019 - Stephen C. Wills +// Updated implementation of DelayAndExecute to use TPL instead of ThreadPool. +// +//****************************************************************************************************** + +using System.Threading.Tasks; +using System.Threading; + +namespace System; + +/// +/// Defines extension methods for actions. +/// +public static class ActionExtensions +{ + /// + /// Execute an action on the thread pool after a specified number of milliseconds. + /// + /// The action to be executed. + /// The amount of time to wait before execution, in milliseconds. + /// The token used to cancel execution. + /// The action to be performed if an exception is thrown from the action. + /// + /// End users should attach to the or + /// events to log exceptions if the is not defined. + /// + public static void DelayAndExecute(this Action action, int delay, CancellationToken cancellationToken, Action? exceptionAction = null) => + new Action(_ => action()).DelayAndExecute(delay, cancellationToken, exceptionAction); + + /// + /// Execute a cancellable action on the thread pool after a specified number of milliseconds. + /// + /// The action to be executed. + /// The amount of time to wait before execution, in milliseconds. + /// The token used to cancel execution. + /// The action to be performed if an exception is thrown from the action. + /// + /// End users should attach to the or + /// events to log exceptions if the is not defined. + /// + public static void DelayAndExecute(this Action action, int delay, CancellationToken cancellationToken, Action? exceptionAction = null) => + Task.Delay(delay, cancellationToken) + .ContinueWith(_ => action(cancellationToken), cancellationToken) + .ContinueWith(task => + { + // ReSharper disable once PossibleNullReferenceException + if (exceptionAction is null) + throw task.Exception ?? new Exception("Task failed without an exception."); + + exceptionAction(task.Exception ?? new Exception("Task failed without an exception.")); + }, + cancellationToken, + TaskContinuationOptions.OnlyOnFaulted, + TaskScheduler.Default); + + /// + /// Execute an action on the thread pool after a specified number of milliseconds. + /// + /// The action to be executed. + /// The amount of time to wait before execution, in milliseconds. + /// The action to be performed if an exception is thrown from the action. + /// + /// A function to call which will cancel the operation. + /// Cancel function returns true if is canceled in time, false if not. + /// + /// + /// End users should attach to the or + /// events to log exceptions if the is not defined. + /// + public static Func DelayAndExecute(this Action action, int delay, Action? exceptionAction = null) => + new Action(_ => action()).DelayAndExecute(delay, exceptionAction); + + /// + /// Execute a cancellable action on the thread pool after a specified number of milliseconds. + /// + /// The action to be executed. + /// The amount of time to wait before execution, in milliseconds. + /// The action to be performed if an exception is thrown from the action. + /// + /// A function to call which will cancel the operation. + /// Cancel function returns true if is canceled, false if not. + /// + /// + /// End users should attach to the or + /// events to log exceptions if the is not defined. + /// + public static Func DelayAndExecute(this Action action, int delay, Action? exceptionAction = null) + { + // All this state complexity ensures that the token source + // is not disposed until after the action finishes executing; + // otherwise, token.ThrowIfCancellationRequested() might unexpectedly + // throw an ObjectDisposedException if used in the action + const int NotCancelled = 0; + const int Cancelling = 1; + const int Cancelled = 2; + const int Disposing = 3; + + CancellationTokenSource tokenSource = new(); + CancellationToken token = tokenSource.Token; + int state = NotCancelled; + + bool cancelFunc() + { + // if (state == NotCancelled) + // state = Cancelling; + // else + // return false; + // + // tokenSource.Cancel(); + // + // if (state == Cancelling) + // state = Canceled; + // else if (state == Disposing) + // tokenSource.Dispose(); + // + // return true; + + int previousState = Interlocked.CompareExchange(ref state, Cancelling, NotCancelled); + + if (previousState != NotCancelled) + return false; + + tokenSource.Cancel(); + + previousState = Interlocked.CompareExchange(ref state, Cancelled, Cancelling); + + // If the state changed to Disposing while cancelFunc was cancelling, + // executeAction will prevent the race condition by not calling + // tokenSource.Dispose() so it must be called here instead + if (previousState == Disposing) + tokenSource.Dispose(); + + return true; + } + + Action executeAction = _ => + { + try + { + if (!token.IsCancellationRequested) + action(token); + } + finally + { + // int previousState = state; + // state = Disposing; + // + // if (previousState != Cancelling) + // tokenSource.Dispose(); + + int previousState = Interlocked.Exchange(ref state, Disposing); + + // The Cancelling state is the only state in which it is not + // safe to dispose on this thread because Cancelling means that + // cancelFunc is in the process of calling tokenSource.Cancel() + if (previousState != Cancelling) + tokenSource.Dispose(); + } + }; + + executeAction.DelayAndExecute(delay, token, exceptionAction); + + return cancelFunc; + } +} + diff --git a/VG Music Studio - Core/Util/ArrayExtensions.cs b/VG Music Studio - Core/Util/ArrayExtensions.cs new file mode 100644 index 0000000..5f82a05 --- /dev/null +++ b/VG Music Studio - Core/Util/ArrayExtensions.cs @@ -0,0 +1,1605 @@ + +//****************************************************************************************************** +// ArrayExtensions.cs - Gbtc +// +// Copyright © 2012, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 09/19/2008 - J. Ritchie Carroll +// Generated original version of source code. +// 12/03/2008 - J. Ritchie Carroll +// Added "Combine" and "IndexOfSequence" overloaded extensions. +// 02/13/2009 - Josh L. Patterson +// Edited Code Comments. +// 09/14/2009 - Stephen C. Wills +// Added new header and license agreement. +// 12/31/2009 - Andrew K. Hill +// Modified the following methods per unit testing: +// BlockCopy(T[], int, int) +// Combine(T[], T[]) +// Combine(T[], int, int, T[], int, int) +// Combine(T[][]) +// IndexOfSequence(T[], T[]) +// IndexOfSequence(T[], T[], int) +// IndexOfSequence(T[], T[], int, int) +// 11/22/2011 - J. Ritchie Carroll +// Added common case array parameter validation extensions +// 12/14/2012 - Starlynn Danyelle Gilliam +// Modified Header. +// 11/02/2023 - AJ Stadlin +// Added Extensions: +// CountOfSequence(T[], T[]) +// CountOfSequence(T[], T[], int) +// CountOfSequence(T[], T[], int, int) +// +//****************************************************************************************************** + +//****************************************************************************************************** +// BlockAllocatedMemoryStream.cs - Gbtc +// +// Copyright © 2016, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 06/14/2013 - J. Ritchie Carroll +// Adapted from the "MemoryTributary" class written by Sebastian Friston: +// Source Code: http://memorytributary.codeplex.com/ +// Article: http://www.codeproject.com/Articles/348590/A-replacement-for-MemoryStream +// 11/21/2016 - Steven E. Chisholm +// A complete refresh of BlockAllocatedMemoryStream and how it works. +// +//****************************************************************************************************** + +//****************************************************************************************************** +// BufferPool.cs - Gbtc +// +// Copyright © 2016, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 11/17/2016 - Steven E. Chisholm +// Generated original version of source code. +// 12/26/2019 - J. Ritchie Carroll +// Simplified DynamicObjectPool as an internal resource renaming to BufferPool. +// +//****************************************************************************************************** + + +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace System; + +public static class ArrayExtensions +{ + /// + /// Zero the given buffer in a way that will not be optimized away. + /// + /// Buffer to zero. + /// of array. + public static void Zero(this T[] buffer) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + // Zero buffer + for (int i = 0; i < buffer.Length; i++) + buffer[i] = default!; + } + + /// + /// Validates that the specified and are valid within the given . + /// + /// Array to validate. + /// 0-based start index into the . + /// Valid number of items within from . + /// is null. + /// + /// or is less than 0 -or- + /// and will exceed length. + /// + /// of array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidateParameters(this T[]? array, int startIndex, int length) + { + if (array is null || startIndex < 0 || length < 0 || startIndex + length > array.Length) + RaiseValidationError(array, startIndex, length); + } + + // This method will raise the actual error - this is needed since .NET will not inline anything that might throw an exception + [MethodImpl(MethodImplOptions.NoInlining)] + private static void RaiseValidationError(T[]? array, int startIndex, int length) + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (startIndex < 0) + throw new ArgumentOutOfRangeException(nameof(startIndex), "cannot be negative"); + + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), "cannot be negative"); + + if (startIndex + length > array.Length) + throw new ArgumentOutOfRangeException(nameof(length), $"startIndex of {startIndex} and length of {length} will exceed array size of {array.Length}"); + } + + /// + /// Returns a copy of the specified portion of the array. + /// + /// Source array. + /// Offset into array. + /// Length of array to copy at offset. + /// An array of data copied from the specified portion of the source array. + /// + /// + /// Returned array will be extended as needed to make it the specified , but + /// it will never be less than the source array length - . + /// + /// + /// If an existing array of primitives is already available, using the directly + /// instead of this extension method may be optimal since this method always allocates a new return array. + /// Unlike , however, this function also works with non-primitive types. + /// + /// + /// + /// is outside the range of valid indexes for the source array -or- + /// is less than 0. + /// + /// of array. + public static T[] BlockCopy(this T[] array, int startIndex, int length) + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (startIndex < 0) + throw new ArgumentOutOfRangeException(nameof(startIndex), "cannot be negative"); + + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), "cannot be negative"); + + if (startIndex >= array.Length) + throw new ArgumentOutOfRangeException(nameof(startIndex), "not a valid index into the array"); + + length = array.Length - startIndex < length ? array.Length - startIndex : length; + T[] copiedBytes = new T[length]; + + if (typeof(T).IsPrimitive) + Buffer.BlockCopy(array, startIndex, copiedBytes, 0, length); + else + Array.Copy(array, startIndex, copiedBytes, 0, length); + + return copiedBytes; + } + + /// + /// Combines arrays together into a single array. + /// + /// Source array. + /// Other array to combine to array. + /// Combined arrays. + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of array. + public static T[] Combine(this T[] source, T[] other) + { + if (source is null) + throw new ArgumentNullException(nameof(source)); + + if (other is null) + throw new ArgumentNullException(nameof(other)); + + return source.Combine(0, source.Length, other, 0, other.Length); + } + + /// + /// Combines specified portions of arrays together into a single array. + /// + /// Source array. + /// Offset into array to begin copy. + /// Number of bytes to copy from array. + /// Other array to combine to array. + /// Offset into array to begin copy. + /// Number of bytes to copy from array. + /// Combined specified portions of both arrays. + /// + /// or is outside the range of valid indexes for the associated array -or- + /// or is less than 0 -or- + /// or , + /// and or do not specify a valid section in the associated array. + /// + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of array. + public static T[] Combine(this T[] source, int sourceOffset, int sourceCount, T[] other, int otherOffset, int otherCount) + { + if (source is null) + throw new ArgumentNullException(nameof(source)); + + if (other is null) + throw new ArgumentNullException(nameof(other)); + + if (sourceOffset < 0) + throw new ArgumentOutOfRangeException(nameof(sourceOffset), "cannot be negative"); + + if (otherOffset < 0) + throw new ArgumentOutOfRangeException(nameof(otherOffset), "cannot be negative"); + + if (sourceCount < 0) + throw new ArgumentOutOfRangeException(nameof(sourceCount), "cannot be negative"); + + if (otherCount < 0) + throw new ArgumentOutOfRangeException(nameof(otherCount), "cannot be negative"); + + if (sourceOffset >= source.Length) + throw new ArgumentOutOfRangeException(nameof(sourceOffset), "not a valid index into source array"); + + if (otherOffset >= other.Length) + throw new ArgumentOutOfRangeException(nameof(otherOffset), "not a valid index into other array"); + + if (sourceOffset + sourceCount > source.Length) + throw new ArgumentOutOfRangeException(nameof(sourceCount), "exceeds source array size"); + + if (otherOffset + otherCount > other.Length) + throw new ArgumentOutOfRangeException(nameof(otherCount), "exceeds other array size"); + + // Overflow is possible, but unlikely. Therefore, this is omitted for performance + // if ((int.MaxValue - sourceCount - otherCount) < 0) + // throw new ArgumentOutOfRangeException("sourceCount + otherCount", "exceeds maximum array size"); + + // Combine arrays together as a single image + T[] combinedBuffer = new T[sourceCount + otherCount]; + + if (typeof(T).IsPrimitive) + { + Buffer.BlockCopy(source, sourceOffset, combinedBuffer, 0, sourceCount); + Buffer.BlockCopy(other, otherOffset, combinedBuffer, sourceCount, otherCount); + } + else + { + Array.Copy(source, sourceOffset, combinedBuffer, 0, sourceCount); + Array.Copy(other, otherOffset, combinedBuffer, sourceCount, otherCount); + } + + return combinedBuffer; + } + + /// + /// Combines arrays together into a single array. + /// + /// Source array. + /// First array to combine to array. + /// Second array to combine to array. + /// Combined arrays. + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of array. + public static T[] Combine(this T[] source, T[] other1, T[] other2) + { + return new[] { source, other1, other2 }.Combine(); + } + + /// + /// Combines arrays together into a single array. + /// + /// Source array. + /// First array to combine to array. + /// Second array to combine to array. + /// Third array to combine to array. + /// Combined arrays. + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of array. + public static T[] Combine(this T[] source, T[] other1, T[] other2, T[] other3) + { + return new[] { source, other1, other2, other3 }.Combine(); + } + + /// + /// Combines arrays together into a single array. + /// + /// Source array. + /// First array to combine to array. + /// Second array to combine to array. + /// Third array to combine to array. + /// Fourth array to combine to array. + /// Combined arrays. + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of array. + public static T[] Combine(this T[] source, T[] other1, T[] other2, T[] other3, T[] other4) + { + return new[] { source, other1, other2, other3, other4 }.Combine(); + } + + /// + /// Combines array of arrays together into a single array. + /// + /// Array of arrays to combine. + /// Combined arrays. + /// + /// + /// Only use this function if you need a copy of the combined arrays, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined arrays. + /// + /// + /// This function can easily throw an out of memory exception if there is not enough + /// contiguous memory to create an array sized with the combined lengths. + /// + /// + /// of arrays. + public static T[] Combine(this T[][] arrays) + { + if (arrays is null) + throw new ArgumentNullException(nameof(arrays)); + + int size = arrays.Sum(array => array.Length); + int offset = 0; + + // Combine arrays together as a single image + T[] combinedBuffer = new T[size]; + + for (int i = 0; i < arrays.Length; i++) + { + if (arrays[i] is null) + throw new ArgumentNullException($"arrays[{i}]"); + + int length = arrays[i].Length; + + if (length == 0) + continue; + + Array.Copy(arrays[i], 0, combinedBuffer, offset, length); + + offset += length; + } + + return combinedBuffer; + } + + /// + /// Searches for the specified and returns the index of the first occurrence within the . + /// + /// Array to search. + /// Sequence of items to search for. + /// The zero-based index of the first occurrence of the in the , if found; otherwise, -1. + /// of array. + public static int IndexOfSequence(this T[] array, T[] sequenceToFind) where T : IComparable + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToFind is null) + throw new ArgumentNullException(nameof(sequenceToFind)); + + return array.IndexOfSequence(sequenceToFind, 0, array.Length); + } + + /// + /// Searches for the specified and returns the index of the first occurrence within the range of elements in the + /// that starts at the specified index. + /// + /// Array to search. + /// Sequence of items to search for. + /// Start index in the to start searching. + /// The zero-based index of the first occurrence of the in the , if found; otherwise, -1. + /// of array. + public static int IndexOfSequence(this T[] array, T[] sequenceToFind, int startIndex) where T : IComparable + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToFind is null) + throw new ArgumentNullException(nameof(sequenceToFind)); + + return array.IndexOfSequence(sequenceToFind, startIndex, array.Length - startIndex); + } + + /// + /// Searches for the specified and returns the index of the first occurrence within the range of elements in the + /// that starts at the specified index and contains the specified number of elements. + /// + /// Array to search. + /// Sequence of items to search for. + /// Start index in the to start searching. + /// Number of bytes in the to search through. + /// The zero-based index of the first occurrence of the in the , if found; otherwise, -1. + /// + /// is null or has zero length. + /// + /// + /// is outside the range of valid indexes for the source array -or- + /// is less than 0. + /// + /// of array. + public static int IndexOfSequence(this T[] array, T[] sequenceToFind, int startIndex, int length) where T : IComparable + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToFind is null || sequenceToFind.Length == 0) + throw new ArgumentNullException(nameof(sequenceToFind)); + + if (startIndex < 0) + throw new ArgumentOutOfRangeException(nameof(startIndex), "cannot be negative"); + + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), "cannot be negative"); + + if (startIndex >= array.Length) + throw new ArgumentOutOfRangeException(nameof(startIndex), "not a valid index into source array"); + + if (startIndex + length > array.Length) + throw new ArgumentOutOfRangeException(nameof(length), "exceeds array size"); + + // Overflow is possible, but unlikely. Therefore, this is omitted for performance + // if ((int.MaxValue - startIndex - length) < 0) + // throw new ArgumentOutOfRangeException("startIndex + length", "exceeds maximum array size"); + + // Search for first item in the sequence, if this doesn't exist then sequence doesn't exist + int index = Array.IndexOf(array, sequenceToFind[0], startIndex, length); + + if (sequenceToFind.Length <= 1) + return index; + + bool foundSequence = false; + + while (index > -1 && !foundSequence) + { + // See if next bytes in sequence match + for (int x = 1; x < sequenceToFind.Length; x++) + { + // Make sure there's enough array remaining to accommodate this item + if (index + x < startIndex + length) + { + // If sequence doesn't match, search for next first-item + if (array[index + x].CompareTo(sequenceToFind[x]) != 0) + { + index = Array.IndexOf(array, sequenceToFind[0], index + 1, startIndex + length - (index + 1)); + break; + } + + // If each item to find matched, we found the sequence + foundSequence = x == sequenceToFind.Length - 1; + } + else + { + // Ran out of array, return -1 + index = -1; + } + } + } + + return index; + } + + /// + /// Searches for the specified and returns the occurrence count within the . + /// + /// Array to search. + /// Sequence of items to search for. + /// The occurrence count of the in the , if found; otherwise, -1. + /// of array. + public static int CountOfSequence(this T[] array, T[] sequenceToCount) where T : IComparable + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToCount is null) + throw new ArgumentNullException(nameof(sequenceToCount)); + + return array.CountOfSequence(sequenceToCount, 0, array.Length); + } + + /// + /// Searches for the specified and returns the occurence count within the range of elements in the + /// that starts at the specified index. + /// + /// Array to search. + /// Sequence of items to search for. + /// Start index in the to start searching. + /// The occurrence count of the in the , if found; otherwise, -1. + /// of array. + public static int CountOfSequence(this T[] array, T[] sequenceToCount, int startIndex) where T : IComparable + { + if (array is null) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToCount is null) + throw new ArgumentNullException(nameof(sequenceToCount)); + + return array.CountOfSequence(sequenceToCount, startIndex, array.Length - startIndex); + } + + /// + /// Searches for the specified and returns the occurrence count within the range of elements in the + /// that starts at the specified index and contains the specified number of elements. + /// + /// Array to search. + /// Sequence of items to search for. + /// Start index in the to start searching. + /// Number of bytes in the to search through. + /// The occurrence count of the in the , if found; otherwise, -1. + /// + /// is null or has zero length. + /// + /// + /// is outside the range of valid indexes for the source array -or- + /// is less than 0. + /// + /// of array. + public static int CountOfSequence(this T[] array, T[] sequenceToCount, int startIndex, int searchLength) where T : IComparable + { + if (array is null || array.Length == 0) + throw new ArgumentNullException(nameof(array)); + + if (sequenceToCount is null || sequenceToCount.Length == 0) + throw new ArgumentNullException(nameof(sequenceToCount)); + + if (startIndex < 0) + throw new ArgumentOutOfRangeException(nameof(startIndex), "cannot be negative"); + + if (startIndex >= array.Length) + throw new ArgumentOutOfRangeException(nameof(startIndex), "not a valid index into source array"); + + if (searchLength < 0) + throw new ArgumentOutOfRangeException(nameof(searchLength), "cannot be negative"); + + if (startIndex + searchLength > array.Length) + throw new ArgumentOutOfRangeException(nameof(searchLength), "exceeds array size"); + + // Overflow is possible, but unlikely. Therefore, this is omitted for performance + // if ((int.MaxValue - startIndex - length) < 0) + // throw new ArgumentOutOfRangeException("startIndex + length", "exceeds maximum array size"); + + // Search for first item in the sequence, if this doesn't exist then sequence doesn't exist + int index = Array.IndexOf(array, sequenceToCount[0], startIndex, searchLength); + + if (index < 0) + return 0; + + // Occurrences counter + int foundCount = 0; + + // Search when the first array element is found, and the sequence can fit in the search range + bool searching = sequenceToCount.Length <= startIndex + searchLength - index; + + while (searching) + { + // See if bytes in sequence match + for (int x = 0; x < sequenceToCount.Length; x++) + { + // If sequence doesn't match, search for next item + if (array[index + x].CompareTo(sequenceToCount[x]) != 0) + { + index++; + index = Array.IndexOf(array, sequenceToCount[0], index, startIndex + searchLength - index); + break; + } + + // When each item to find matched, we found the sequence + if (x == sequenceToCount.Length - 1) + { + foundCount++; + index++; + index = Array.IndexOf(array, sequenceToCount[0], index, startIndex + searchLength - index); + } + } + + // Continue searching if the array remaining can accommodate the sequence to find + searching = index > -1 && sequenceToCount.Length <= startIndex + searchLength - index; + } + + return foundCount; + } + + /// Returns comparison results of two binary arrays. + /// Source array. + /// Other array to compare to array. + /// + /// Note that if both arrays are null the arrays will be considered equal. + /// If one array is null and the other array is not null, the non-null array will be considered larger. + /// If the array lengths are not equal, the array with the larger length will be considered larger. + /// If the array lengths are equal, the arrays will be compared based on content. + /// + /// + /// + /// A signed integer that indicates the relative comparison of array and array. + /// + /// + /// + /// + /// Return Value + /// Description + /// + /// + /// Less than zero + /// Source array is less than other array. + /// + /// + /// Zero + /// Source array is equal to other array. + /// + /// + /// Greater than zero + /// Source array is greater than other array. + /// + /// + /// + /// + /// of array. + public static int CompareTo(this T[]? source, T[]? other) where T : IComparable + { + // If both arrays are assumed equal if both are nothing + if (source is null && other is null) + return 0; + + // If other array has data and source array is nothing, other array is assumed larger + if (source is null) + return -1; + + // If source array has data and other array is nothing, source array is assumed larger + if (other is null) + return 1; + + int length1 = source.Length; + int length2 = other.Length; + + // If array lengths are unequal, array with the largest number of elements is assumed to be largest + if (length1 != length2) + return length1.CompareTo(length2); + + int comparison = 0; + + // Compares elements of arrays that are of equal size. + for (int x = 0; x < length1; x++) + { + comparison = source[x].CompareTo(other[x]); + + if (comparison != 0) + break; + } + + return comparison; + } + + /// + /// Returns comparison results of two binary arrays. + /// + /// Source array. + /// Offset into array to begin compare. + /// Other array to compare to array. + /// Offset into array to begin compare. + /// Number of bytes to compare in both arrays. + /// + /// Note that if both arrays are null the arrays will be considered equal. + /// If one array is null and the other array is not null, the non-null array will be considered larger. + /// + /// + /// + /// A signed integer that indicates the relative comparison of array and array. + /// + /// + /// + /// + /// Return Value + /// Description + /// + /// + /// Less than zero + /// Source array is less than other array. + /// + /// + /// Zero + /// Source array is equal to other array. + /// + /// + /// Greater than zero + /// Source array is greater than other array. + /// + /// + /// + /// + /// + /// or is outside the range of valid indexes for the associated array -or- + /// is less than 0 -or- + /// or and do not specify a valid section in the associated array. + /// + /// of array. + public static int CompareTo(this T[]? source, int sourceOffset, T[]? other, int otherOffset, int count) where T : IComparable + { + // If both arrays are assumed equal if both are nothing + if (source is null && other is null) + return 0; + + // If other array has data and source array is nothing, other array is assumed larger + if (source is null) + return -1; + + // If source array has data and other array is nothing, source array is assumed larger + if (other is null) + return 1; + + if (sourceOffset < 0) + throw new ArgumentOutOfRangeException(nameof(sourceOffset), "cannot be negative"); + + if (otherOffset < 0) + throw new ArgumentOutOfRangeException(nameof(otherOffset), "cannot be negative"); + + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), "cannot be negative"); + + if (sourceOffset >= source.Length) + throw new ArgumentOutOfRangeException(nameof(sourceOffset), "not a valid index into source array"); + + if (otherOffset >= other.Length) + throw new ArgumentOutOfRangeException(nameof(otherOffset), "not a valid index into other array"); + + if (sourceOffset + count > source.Length) + throw new ArgumentOutOfRangeException(nameof(count), "exceeds source array size"); + + if (otherOffset + count > other.Length) + throw new ArgumentOutOfRangeException(nameof(count), "exceeds other array size"); + + // Overflow is possible, but unlikely. Therefore, this is omitted for performance + // if ((int.MaxValue - sourceOffset - count) < 0) + // throw new ArgumentOutOfRangeException("sourceOffset + count", "exceeds maximum array size"); + + // Overflow is possible, but unlikely. Therefore, this is omitted for performance + // if ((int.MaxValue - otherOffset - count) < 0) + // throw new ArgumentOutOfRangeException("sourceOffset + count", "exceeds maximum array size"); + + int comparison = 0; + + // Compares elements of arrays that are of equal size. + for (int x = 0; x < count; x++) + { + comparison = source[sourceOffset + x].CompareTo(other[otherOffset + x]); + + if (comparison != 0) + break; + } + + return comparison; + } + + // Handling byte arrays as a special case for combining multiple buffers since this can + // use a block allocated memory stream + + /// + /// Combines buffers together as a single image. + /// + /// Source buffer. + /// First buffer to combine to buffer. + /// Second buffer to combine to buffer. + /// Combined buffers. + /// Cannot create a byte array with more than 2,147,483,591 elements. + /// + /// Only use this function if you need a copy of the combined buffers, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined buffers. + /// + public static byte[] Combine(this byte[] source, byte[] other1, byte[] other2) + { + return new[] { source, other1, other2 }.Combine(); + } + + /// + /// Combines buffers together as a single image. + /// + /// Source buffer. + /// First buffer to combine to buffer. + /// Second buffer to combine to buffer. + /// Third buffer to combine to buffer. + /// Combined buffers. + /// Cannot create a byte array with more than 2,147,483,591 elements. + /// + /// Only use this function if you need a copy of the combined buffers, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined buffers. + /// + public static byte[] Combine(this byte[] source, byte[] other1, byte[] other2, byte[] other3) + { + return new[] { source, other1, other2, other3 }.Combine(); + } + + /// + /// Combines buffers together as a single image. + /// + /// Source buffer. + /// First buffer to combine to buffer. + /// Second buffer to combine to buffer. + /// Third buffer to combine to buffer. + /// Fourth buffer to combine to buffer. + /// Combined buffers. + /// Cannot create a byte array with more than 2,147,483,591 elements. + /// + /// Only use this function if you need a copy of the combined buffers, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined buffers. + /// + public static byte[] Combine(this byte[] source, byte[] other1, byte[] other2, byte[] other3, byte[] other4) + { + return new[] { source, other1, other2, other3, other4 }.Combine(); + } + + /// + /// Combines an array of buffers together as a single image. + /// + /// Array of byte buffers. + /// Combined buffers. + /// Cannot create a byte array with more than 2,147,483,591 elements. + /// + /// Only use this function if you need a copy of the combined buffers, it will be optimal + /// to use the Linq function if you simply need to + /// iterate over the combined buffers. + /// + public static byte[] Combine(this byte[][] buffers) + { + if (buffers is null) + throw new ArgumentNullException(nameof(buffers)); + + using BlockAllocatedMemoryStream combinedBuffer = new(); + + // Combine all currently queued buffers + for (int x = 0; x < buffers.Length; x++) + { + if (buffers[x] is null) + throw new ArgumentNullException($"buffers[{x}]"); + + combinedBuffer.Write(buffers[x], 0, buffers[x].Length); + } + + // return combined data buffers + return combinedBuffer.ToArray(); + } + + /// + /// Reads a structure from a byte array. + /// + /// Type of structure to read. + /// Bytes containing structure. + /// A structure from . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe T? ReadStructure(this byte[] bytes) where T : struct + { + T? structure; + + fixed (byte* ptrToBytes = bytes) + structure = (T?)Marshal.PtrToStructure(new IntPtr(ptrToBytes), typeof(T)); + + return structure; + } + + /// + /// Reads a structure from a . + /// + /// Type of structure to read. + /// positioned at desired structure. + /// A structure read from . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T? ReadStructure(this BinaryReader reader) where T : struct => + reader.ReadBytes(Marshal.SizeOf(typeof(T))).ReadStructure(); + + + #region [ Block Allocated Memory Stream ] + + /// + /// Defines a stream whose backing store is memory. Externally this class operates similar to a , + /// internally it uses dynamically allocated buffer blocks instead of one large contiguous array of data. + /// + /// + /// + /// The has two primary benefits over a normal , first, the + /// allocation of a large contiguous array of data in can fail when the requested amount of contiguous + /// memory is unavailable - the prevents this; second, a will + /// constantly reallocate the buffer size as the stream grows and shrinks and then copy all the data from the old buffer to the + /// new - the maintains its blocks over its life cycle, unless manually cleared, thus + /// eliminating unnecessary allocations and garbage collections when growing and reusing a stream. + /// + /// + /// Important: Unlike , the will not use a user provided buffer + /// as its backing buffer. Any user provided buffers used to instantiate the class will be copied into internally managed reusable + /// memory buffers. Subsequently, the does not support the notion of a non-expandable + /// stream. If you are using a with your own buffer, the will + /// not provide any immediate benefit. + /// + /// + /// Note that the will maintain all allocated blocks for stream use until the + /// method is called or the class is disposed. + /// + /// + /// No members in the are guaranteed to be thread safe. Make sure any calls are + /// synchronized when simultaneously accessed from different threads. + /// + /// + public class BlockAllocatedMemoryStream : Stream + { + // Note: Since byte blocks are pooled, they will not be + // initialized unless a Read/Write operation occurs + // when m_position > m_length + + #region [ Members ] + + // Constants + private const int BlockSize = 8 * 1024; + private const int ShiftBits = 3 + 10; + private const int BlockMask = BlockSize - 1; + + // Fields + private List m_blocks; + private long m_length; + private long m_position; + private long m_capacity; + private bool m_disposed; + + #endregion + + #region [ Constructors ] + + /// + /// Initializes a new instance of . + /// + public BlockAllocatedMemoryStream() => m_blocks = new List(); + + /// + /// Initializes a new instance of from specified . + /// + /// Initial buffer to copy into stream. + /// is null. + /// + /// Unlike , the will not use the provided + /// as its backing buffer. The buffer will be copied into internally managed reusable + /// memory buffers. Subsequently, the notion of a non-expandable stream is not supported. + /// + public BlockAllocatedMemoryStream(byte[] buffer) : this(buffer, 0, buffer.Length) + { + } + + /// + /// Initializes a new instance of from specified region of . + /// + /// Initial buffer to copy into stream. + /// 0-based start index into the . + /// Valid number of bytes within from . + /// is null. + /// + /// or is less than 0 -or- + /// and will exceed length. + /// + /// + /// Unlike , the will not use the provided + /// as its backing buffer. The buffer will be copied into internally managed reusable + /// memory buffers. Subsequently, the notion of a non-expandable stream is not supported. + /// + public BlockAllocatedMemoryStream(byte[] buffer, int startIndex, int length) : this() + { + buffer.ValidateParameters(startIndex, length); + Write(buffer, startIndex, length); + } + + /// + /// Initializes a new instance of for specified . + /// + /// Initial length of the stream. + public BlockAllocatedMemoryStream(int capacity) : this() => SetLength(capacity); + + #endregion + + #region [ Properties ] + + /// + /// Gets a value that indicates whether the object supports reading. + /// + /// + /// This is always true. + /// + public override bool CanRead => true; + + /// + /// Gets a value that indicates whether the object supports seeking. + /// + /// + /// This is always true. + /// + public override bool CanSeek => true; + + /// + /// Gets a value that indicates whether the object supports writing. + /// + /// + /// This is always true. + /// + public override bool CanWrite => true; + + /// + /// Gets current stream length for this instance. + /// + /// The stream is closed. + public override long Length + { + get + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + return m_length; + } + } + + /// + /// Gets current stream position for this instance. + /// + /// Seeking was attempted before the beginning of the stream. + /// The stream is closed. + public override long Position + { + get + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + return m_position; + } + set + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + if (value < 0L) + throw new IOException("Seek was attempted before the beginning of the stream."); + + m_position = value; + } + } + + #endregion + + #region [ Methods ] + + /// + /// Releases the unmanaged resources used by the object and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; otherwise, false to release only unmanaged resources. + protected override void Dispose(bool disposing) + { + if (m_disposed) + return; + + try + { + // Make sure buffer blocks get returned to the pool + if (disposing) + Clear(); + } + finally + { + m_disposed = true; // Prevent duplicate dispose. + base.Dispose(disposing); // Call base class Dispose(). + } + } + + /// + /// Clears the entire contents and releases any allocated memory blocks. + /// + public void Clear() + { + m_position = 0; + m_length = 0; + m_capacity = 0; + + // In the event that an exception occurs, we don't want to have released blocks that are still in this memory stream. + List blocks = m_blocks; + + m_blocks = new List(); + + foreach (byte[] block in blocks) + s_memoryBlockPool.Enqueue(block); + } + + /// + /// Sets the within the current stream to the specified value relative the . + /// + /// + /// The new position within the stream, calculated by combining the initial reference point and the offset. + /// + /// The new position within the stream. This is relative to the parameter, and can be positive or negative. + /// A value of type , which acts as the seek reference point. + /// Seeking was attempted before the beginning of the stream. + /// The stream is closed. + public override long Seek(long offset, SeekOrigin origin) + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + switch (origin) + { + case SeekOrigin.Begin: + if (offset < 0L) + throw new IOException("Seek was attempted before the beginning of the stream."); + + m_position = offset; + break; + case SeekOrigin.Current: + if (m_position + offset < 0L) + throw new IOException("Seek was attempted before the beginning of the stream."); + + m_position += offset; + break; + case SeekOrigin.End: + if (m_length + offset < 0L) + throw new IOException("Seek was attempted before the beginning of the stream."); + + m_position = m_length + offset; + break; + } + + // Note: the length is not adjusted after this seek to reflect what MemoryStream.Seek does + return m_position; + } + + /// + /// Sets the length of the current stream to the specified value. + /// + /// The value at which to set the length. + /// + /// If this length is larger than the previous length, the data is initialized to 0's between the previous length and the current length. + /// + public override void SetLength(long value) + { + if (value > m_capacity) + EnsureCapacity(value); + + if (m_length < value) + InitializeToPosition(value); + + m_length = value; + + if (m_position > m_length) + m_position = m_length; + } + + /// + /// Reads a block of bytes from the current stream and writes the data to . + /// + /// When this method returns, contains the specified byte array with the values between and ( + - 1) replaced by the characters read from the current stream. + /// The byte offset in at which to begin reading. + /// The maximum number of bytes to read. + /// + /// The total number of bytes written into the buffer. This can be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached before any bytes are read. + /// + /// is null. + /// + /// or is less than 0 -or- + /// and will exceed length. + /// + /// The stream is closed. + public override int Read(byte[] buffer, int startIndex, int length) + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + buffer.ValidateParameters(startIndex, length); + + // Do not read beyond the end of the stream + long remainingBytes = m_length - m_position; + + if (remainingBytes <= 0) + return 0; + + if (length > remainingBytes) + length = (int)remainingBytes; + + int bytesRead = length; + + // Must read 1 block at a time + do + { + int blockOffset = (int)(m_position & BlockMask); + int bytesToRead = Math.Min(length, BlockSize - blockOffset); + + Buffer.BlockCopy(m_blocks[(int)(m_position >> ShiftBits)], blockOffset, buffer, startIndex, bytesToRead); + + length -= bytesToRead; + startIndex += bytesToRead; + m_position += bytesToRead; + } + while (length > 0); + + return bytesRead; + } + + /// + /// Reads a byte from the current stream. + /// + /// + /// The current byte cast to an , or -1 if the end of the stream has been reached. + /// + /// The stream is closed. + public override int ReadByte() + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + if (m_position >= m_length) + return -1; + + byte value = m_blocks[(int)(m_position >> ShiftBits)][(int)(m_position & BlockMask)]; + m_position++; + + return value; + } + + /// + /// Writes a block of bytes to the current stream using data read from . + /// + /// The buffer to write data from. + /// The byte offset in at which to begin writing from. + /// The maximum number of bytes to write. + /// is null. + /// + /// or is less than 0 -or- + /// and will exceed length. + /// + /// The stream is closed. + public override void Write(byte[] buffer, int startIndex, int length) + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + buffer.ValidateParameters(startIndex, length); + + if (m_position + length > m_capacity) + EnsureCapacity(m_position + length); + + if (m_position > m_length) + InitializeToPosition(m_position); + + if (m_length < m_position + length) + m_length = m_position + length; + + if (length == 0) + return; + + do + { + int blockOffset = (int)(m_position & BlockMask); + int bytesToWrite = Math.Min(length, BlockSize - blockOffset); + + Buffer.BlockCopy(buffer, startIndex, m_blocks[(int)(m_position >> ShiftBits)], blockOffset, bytesToWrite); + + length -= bytesToWrite; + startIndex += bytesToWrite; + m_position += bytesToWrite; + } + while (length > 0); + } + + /// + /// Writes a byte to the current stream at the current position. + /// + /// The byte to write. + /// The stream is closed. + public override void WriteByte(byte value) + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + if (m_position + 1 > m_capacity) + EnsureCapacity(m_position + 1); + + if (m_position > m_length) + InitializeToPosition(m_position); + + if (m_length < m_position + 1) + m_length = m_position + 1; + + m_blocks[(int)(m_position >> ShiftBits)][m_position & BlockMask] = value; + m_position++; + } + + /// + /// Writes the stream contents to a byte array, regardless of the property. + /// + /// A [] containing the current data in the stream + /// + /// This may fail if there is not enough contiguous memory available to hold current size of stream. + /// When possible use methods which operate on streams directly instead. + /// + /// Cannot create a byte array with more than 2,147,483,591 elements. + /// The stream is closed. + public byte[] ToArray() + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + if (m_length > 0x7FFFFFC7L) + throw new InvalidOperationException($"Cannot create a byte array of size {m_length}"); + + byte[] destination = new byte[m_length]; + long originalPosition = m_position; + + m_position = 0; + Read(destination, 0, (int)m_length); + m_position = originalPosition; + + return destination; + } + + /// + /// Reads specified number of bytes from source stream into this + /// starting at the current position. + /// + /// The stream containing the data to copy + /// The number of bytes to copy + /// The stream is closed. + public void ReadFrom(Stream source, long length) + { + // Note: A faster way would be to write directly to the BlockAllocatedMemoryStream + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + byte[] buffer = s_memoryBlockPool.Dequeue(); + + do + { + int bytesRead = source.Read(buffer, 0, (int)Math.Min(BlockSize, length)); + + if (bytesRead == 0) + throw new EndOfStreamException(); + + length -= bytesRead; + Write(buffer, 0, bytesRead); + } + while (length > 0); + + s_memoryBlockPool.Enqueue(buffer); + } + + /// + /// Writes the entire stream into destination, regardless of , which remains unchanged. + /// + /// The stream onto which to write the current contents. + /// The stream is closed. + public void WriteTo(Stream destination) + { + if (m_disposed) + throw new ObjectDisposedException(nameof(BlockAllocatedMemoryStream), "The stream is closed."); + + long originalPosition = m_position; + m_position = 0; + + CopyTo(destination); + + m_position = originalPosition; + } + + /// + /// Overrides the method so that no action is performed. + /// + /// + /// + /// This method overrides the method. + /// + /// + /// Because any data written to a object is + /// written into RAM, this method is superfluous. + /// + /// + public override void Flush() + { + // Nothing to flush... + } + + /// + /// Makes sure desired can be accommodated by future data accesses. + /// + /// Minimum desired stream capacity. + private void EnsureCapacity(long length) + { + while (m_capacity < length) + { + m_blocks.Add(s_memoryBlockPool.Dequeue()); + m_capacity += BlockSize; + } + } + + /// + /// Initializes all of the bytes to zero. + /// + private void InitializeToPosition(long position) + { + long bytesToClear = position - m_length; + + while (bytesToClear > 0) + { + int bytesToClearInBlock = (int)Math.Min(bytesToClear, BlockSize - (m_length & BlockMask)); + Array.Clear(m_blocks[(int)(m_length >> ShiftBits)], (int)(m_length & BlockMask), bytesToClearInBlock); + m_length += bytesToClearInBlock; + bytesToClear = position - m_length; + } + } + + #endregion + + #region [ Static ] + + // Static Fields + + // Allow up to 100 items of 8KB items to remain on the buffer pool. This might need to be increased if the buffer pool becomes more + // extensively used. Allocation Statistics will be logged in the Logger. + private static readonly BufferPool s_memoryBlockPool = new(BlockSize, 100); + + #endregion + } + + #endregion + + #region [ Buffer Pool ] + + /// + /// Provides a thread safe queue that acts as a buffer pool. + /// + internal class BufferPool + { + private readonly int m_bufferSize; + private readonly ConcurrentQueue m_buffers; + private readonly Queue m_countHistory; + private readonly int m_targetCount; + private int m_objectsCreated; + + /// + /// Creates a new . + /// + /// The size of buffers in the pool. + /// the ideal number of buffers that are always pending on the queue. + public BufferPool(int bufferSize, int targetCount) + { + m_bufferSize = bufferSize; + m_targetCount = targetCount; + m_countHistory = new Queue(100); + m_buffers = new ConcurrentQueue(); + + new Action(RunCollection).DelayAndExecute(1000); + } + + private void RunCollection() + { + try + { + m_countHistory.Enqueue(m_buffers.Count); + + if (m_countHistory.Count < 60) + return; + + int objectsCreated = Interlocked.Exchange(ref m_objectsCreated, 0); + + // If there were ever more than the target items in the queue over the past 60 seconds remove some items. + // However, don't remove items if the pool ever got to 0 and had objects that had to be created. + int min = m_countHistory.Min(); + m_countHistory.Clear(); + + if (objectsCreated != 0) + return; + + while (min > m_targetCount) + { + if (!m_buffers.TryDequeue(out _)) + return; + + min--; + } + } + finally + { + new Action(RunCollection).DelayAndExecute(1000); + } + } + + /// + /// Removes a buffer from the queue. If one does not exist, one is created. + /// + /// + public byte[] Dequeue() + { + if (m_buffers.TryDequeue(out byte[]? item)) + return item; + + Interlocked.Increment(ref m_objectsCreated); + return new byte[m_bufferSize]; + } + + /// + /// Adds a buffer back to the queue. + /// + /// The buffer to queue. + public void Enqueue(byte[] buffer) => m_buffers.Enqueue(buffer); + } + + #endregion + +} diff --git a/VG Music Studio - Core/Util/DialogUtils.cs b/VG Music Studio - Core/Util/DialogUtils.cs new file mode 100644 index 0000000..0018d33 --- /dev/null +++ b/VG Music Studio - Core/Util/DialogUtils.cs @@ -0,0 +1,27 @@ +using System; + +namespace Kermalis.VGMusicStudio.Core.Util +{ + public abstract class DialogUtils + { + public abstract string CreateLoadDialog( + string title, string filterName = "", + string fileExtensions = "", bool isFile = false, + bool allowAllFiles = false, object? parent = null); + public abstract string CreateLoadDialog( + string title, string filterName, + Span fileExtensions, bool isFile = false, + bool allowAllFiles = false, object? parent = null); + + public abstract string CreateSaveDialog( + string fileName, string title, + string filterName = "", string fileExtension = "", + bool isFile = false, bool allowAllFiles = false, + object? parent = null); + public abstract string CreateSaveDialog( + string fileName, string title, + string filterName, Span fileExtensions, + bool isFile = false, bool allowAllFiles = false, + object? parent = null); + } +} diff --git a/VG Music Studio - Core/Util/GUIUtils.cs b/VG Music Studio - Core/Util/GUIUtils.cs new file mode 100644 index 0000000..8cdd39a --- /dev/null +++ b/VG Music Studio - Core/Util/GUIUtils.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Kermalis.VGMusicStudio.Core.Util; + +public static class GUIUtils +{ + private static readonly Random _rng = new(); + + public static string Print(this IEnumerable source, bool parenthesis = true) + { + string str = parenthesis ? "( " : ""; + str += string.Join(", ", source); + str += parenthesis ? " )" : ""; + return str; + } + /// Fisher-Yates Shuffle + public static void Shuffle(this IList source) + { + for (int a = 0; a < source.Count - 1; a++) + { + int b = _rng.Next(a, source.Count); + (source[b], source[a]) = (source[a], source[b]); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static float Lerp(float progress, float from, float to) + { + return from + ((to - from) * progress); + } + /// Maps a value in the range [a1, a2] to [b1, b2]. Divide by zero occurs if a1 and a2 are equal + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static float Lerp(float value, float a1, float a2, float b1, float b2) + { + return b1 + ((value - a1) / (a2 - a1) * (b2 - b1)); + } +} diff --git a/VG Music Studio - Core/Util/Int24.cs b/VG Music Studio - Core/Util/Int24.cs new file mode 100644 index 0000000..28f9492 --- /dev/null +++ b/VG Music Studio - Core/Util/Int24.cs @@ -0,0 +1,1515 @@ +//****************************************************************************************************** +// Int24.cs - Gbtc +// +// Copyright © 2012, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 11/12/2004 - J. Ritchie Carroll +// Initial version of source generated. +// 08/3/2009 - Josh L. Patterson +// Updated comments. +// 08/11/2009 - Josh L. Patterson +// Updated comments. +// 09/14/2009 - Stephen C. Wills +// Added new header and license agreement. +// 12/14/2012 - Starlynn Danyelle Gilliam +// Modified Header. +// +//****************************************************************************************************** + +#region [ Contributor License Agreements ] + +/**************************************************************************\ + Copyright © 2009 - J. Ritchie Carroll + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +\**************************************************************************/ + +#endregion + +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace System; + +/// Represents a 3-byte, 24-bit signed integer. +/// +/// +/// This class behaves like most other intrinsic signed integers but allows a 3-byte, 24-bit integer implementation +/// that is often found in many digital-signal processing arenas and different kinds of protocol parsing. A signed +/// 24-bit integer is typically used to save storage space on disk where its value range of -8388608 to 8388607 is +/// sufficient, but the signed Int16 value range of -32768 to 32767 is too small. +/// +/// +/// This structure uses an Int32 internally for storage and most other common expected integer functionality, so using +/// a 24-bit integer will not save memory. However, if the 24-bit signed integer range (-8388608 to 8388607) suits your +/// data needs you can save disk space by only storing the three bytes that this integer actually consumes. You can do +/// this by calling the Int24.GetBytes function to return a three byte binary array that can be serialized to the desired +/// destination and then calling the Int24.GetValue function to restore the Int24 value from those three bytes. +/// +/// +/// All the standard operators for the Int24 have been fully defined for use with both Int24 and Int32 signed integers; +/// you should find that without the exception Int24 can be compared and numerically calculated with an Int24 or Int32. +/// Necessary casting should be minimal and typical use should be very simple - just as if you are using any other native +/// signed integer. +/// +/// +[Serializable] +public struct Int24 : IComparable, IFormattable, IConvertible, IComparable, IComparable, IEquatable, IEquatable +{ + #region [ Members ] + + // Constants + private const int MaxValue32 = 8388607; // Represents the largest possible value of an Int24 as an Int32. + private const int MinValue32 = -8388608; // Represents the smallest possible value of an Int24 as an Int32. + + /// High byte bit-mask used when a 24-bit integer is stored within a 32-bit integer. This field is constant. + public const int BitMask = -16777216; + + // Fields + private readonly int m_value; // We internally store the Int24 value in a 4-byte integer for convenience + + #endregion + + #region [ Constructors ] + + /// Creates 24-bit signed integer from an existing 24-bit signed integer. + /// 24-but signed integer to create new Int24 from. + public Int24(Int24 value) + { + m_value = ApplyBitMask(value); + } + + /// Creates 24-bit signed integer from a 32-bit signed integer. + /// 32-bit signed integer to use as new 24-bit signed integer value. + /// Source values outside 24-bit min/max range will cause an overflow exception. + public Int24(int value) + { + ValidateNumericRange(value); + m_value = ApplyBitMask(value); + } + + /// Creates 24-bit signed integer from three bytes at a specified position in a byte array. + /// An array of bytes. + /// The starting position within . + /// + /// You can use this constructor in-lieu of a System.BitConverter.ToInt24 function. + /// Bytes endian order assumed to match that of currently executing process architecture (little-endian on Intel platforms). + /// + /// cannot be null. + /// is greater than length. + /// length from is too small to represent a . + public Int24(byte[] value, int startIndex) + { + m_value = GetValue(value, startIndex).m_value; + } + + #endregion + + #region [ Methods ] + + /// Returns the Int24 value as an array of three bytes. + /// An array of bytes with length 3. + /// + /// You can use this function in-lieu of a System.BitConverter.GetBytes function. + /// Bytes will be returned in endian order of currently executing process architecture (little-endian on Intel platforms). + /// + public byte[] GetBytes() + { + // Return serialized 3-byte representation of Int24 + return GetBytes(this); + } + + /// + /// Compares this instance to a specified object and returns an indication of their relative values. + /// + /// An object to compare, or null. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + /// value is not an Int32 or Int24. + public int CompareTo(object? value) + { + if (value is null) + return 1; + + if (value is not int && value is not Int24) + throw new ArgumentException("Argument must be an Int32 or an Int24"); + + int num = (int)value; + + return m_value < num ? -1 : m_value > num ? 1 : 0; + } + + /// + /// Compares this instance to a specified 24-bit signed integer and returns an indication of their + /// relative values. + /// + /// An integer to compare. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + public int CompareTo(Int24 value) + { + return CompareTo((int)value); + } + + /// + /// Compares this instance to a specified 32-bit signed integer and returns an indication of their + /// relative values. + /// + /// An integer to compare. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + public int CompareTo(int value) + { + return m_value < value ? -1 : m_value > value ? 1 : 0; + } + + /// + /// Returns a value indicating whether this instance is equal to a specified object. + /// + /// An object to compare, or null. + /// + /// True if obj is an instance of Int32 or Int24 and equals the value of this instance; + /// otherwise, False. + /// + public override bool Equals(object? obj) + { + if (obj is int or Int24) + return Equals((int)obj); + + return false; + } + + /// + /// Returns a value indicating whether this instance is equal to a specified Int24 value. + /// + /// An Int24 value to compare to this instance. + /// + /// True if obj has the same value as this instance; otherwise, False. + /// + public bool Equals(Int24 obj) + { + return Equals((int)obj); + } + + /// + /// Returns a value indicating whether this instance is equal to a specified Int32 value. + /// + /// An Int32 value to compare to this instance. + /// + /// True if obj has the same value as this instance; otherwise, False. + /// + public bool Equals(int obj) + { + return m_value == obj; + } + + /// + /// Returns the hash code for this instance. + /// + /// + /// A 32-bit signed integer hash code. + /// + public override int GetHashCode() + { + return m_value; + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation. + /// + /// + /// The string representation of the value of this instance, consisting of a minus sign if + /// the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes. + /// + public override string ToString() + { + return m_value.ToString(); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation, using + /// the specified format. + /// + /// A format string. + /// + /// The string representation of the value of this instance as specified by format. + /// + public string ToString(string? format) + { + return m_value.ToString(format); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation using the + /// specified culture-specific format information. + /// + /// + /// A that supplies culture-specific formatting information. + /// + /// + /// The string representation of the value of this instance as specified by provider. + /// + public string ToString(IFormatProvider? provider) + { + return m_value.ToString(provider); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation using the + /// specified format and culture-specific format information. + /// + /// A format specification. + /// + /// A that supplies culture-specific formatting information. + /// + /// + /// The string representation of the value of this instance as specified by format and provider. + /// + public string ToString(string? format, IFormatProvider? provider) + { + return m_value.ToString(format, provider); + } + + /// + /// Converts the string representation of a number to its 24-bit signed integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A 24-bit signed integer equivalent to the number contained in s. + /// + /// s is null. + /// + /// s represents a number less than Int24.MinValue or greater than Int24.MaxValue. + /// + /// s is not in the correct format. + public static Int24 Parse(string s) + { + return (Int24)int.Parse(s); + } + + /// + /// Converts the string representation of a number in a specified style to its 24-bit signed integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// A 24-bit signed integer equivalent to the number contained in s. + /// + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + /// s is null. + /// + /// s represents a number less than Int24.MinValue or greater than Int24.MaxValue. + /// + /// s is not in a format compliant with style. + public static Int24 Parse(string s, NumberStyles style) + { + return (Int24)int.Parse(s, style); + } + + /// + /// Converts the string representation of a number in a specified culture-specific format to its 24-bit + /// signed integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A that supplies culture-specific formatting information about s. + /// + /// + /// A 24-bit signed integer equivalent to the number contained in s. + /// + /// s is null. + /// + /// s represents a number less than Int24.MinValue or greater than Int24.MaxValue. + /// + /// s is not in the correct format. + public static Int24 Parse(string s, IFormatProvider? provider) + { + return (Int24)int.Parse(s, provider); + } + + /// + /// Converts the string representation of a number in a specified style and culture-specific format to its 24-bit + /// signed integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// A that supplies culture-specific formatting information about s. + /// + /// + /// A 24-bit signed integer equivalent to the number contained in s. + /// + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + /// s is null. + /// + /// s represents a number less than Int24.MinValue or greater than Int24.MaxValue. + /// + /// s is not in a format compliant with style. + public static Int24 Parse(string s, NumberStyles style, IFormatProvider? provider) + { + return (Int24)int.Parse(s, style, provider); + } + + /// + /// Converts the string representation of a number to its 24-bit signed integer equivalent. A return value + /// indicates whether the conversion succeeded or failed. + /// + /// A string containing a number to convert. + /// + /// When this method returns, contains the 24-bit signed integer value equivalent to the number contained in s, + /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, + /// is not of the correct format, or represents a number less than Int24.MinValue or greater than Int24.MaxValue. + /// This parameter is passed uninitialized. + /// + /// true if s was converted successfully; otherwise, false. + public static bool TryParse(string s, out Int24 result) + { + bool parseResponse = int.TryParse(s, out int parseResult); + + try + { + result = (Int24)parseResult; + } + catch + { + result = (Int24)0; + parseResponse = false; + } + + return parseResponse; + } + + + /// + /// Converts the string representation of a number in a specified style and culture-specific format to its + /// 24-bit signed integer equivalent. A return value indicates whether the conversion succeeded or failed. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// When this method returns, contains the 24-bit signed integer value equivalent to the number contained in s, + /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, + /// is not in a format compliant with style, or represents a number less than Int24.MinValue or greater than + /// Int24.MaxValue. This parameter is passed uninitialized. + /// + /// + /// A object that supplies culture-specific formatting information about s. + /// + /// true if s was converted successfully; otherwise, false. + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out Int24 result) + { + bool parseResponse = int.TryParse(s, style, provider, out int parseResult); + + try + { + result = (Int24)parseResult; + } + catch + { + result = (Int24)0; + parseResponse = false; + } + + return parseResponse; + } + + /// + /// Returns the System.TypeCode for value type System.Int32 (there is no defined type code for an Int24). + /// + /// The enumerated constant, System.TypeCode.Int32. + /// + /// There is no defined Int24 type code and since an Int24 will easily fit inside an Int32, the + /// Int32 type code is returned. + /// + public TypeCode GetTypeCode() + { + return TypeCode.Int32; + } + + #region [ Explicit IConvertible Implementation ] + + // These are explicitly implemented on the native integer implementations, so we do the same... + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + return Convert.ToBoolean(m_value, provider); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + return Convert.ToChar(m_value, provider); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(m_value, provider); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(m_value, provider); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(m_value, provider); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(m_value, provider); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return m_value; + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(m_value, provider); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(m_value, provider); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(m_value, provider); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(m_value, provider); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(m_value, provider); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(m_value, provider); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + return Convert.ToDateTime(m_value, provider); + } + + object IConvertible.ToType(Type type, IFormatProvider? provider) + { + return Convert.ChangeType(m_value, type, provider); + } + + #endregion + + #endregion + + #region [ Operators ] + + // Every effort has been made to make Int24 as cleanly interoperable with Int32 as possible... + + #region [ Comparison Operators ] + + /// + /// Compares the two values for equality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean value indicating equality. + public static bool operator ==(Int24 value1, Int24 value2) + { + return value1.Equals(value2); + } + + /// + /// Compares the two values for equality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean value indicating equality. + public static bool operator ==(int value1, Int24 value2) + { + return value1.Equals(value2); + } + + /// + /// Compares the two values for equality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean value indicating equality. + public static bool operator ==(Int24 value1, int value2) + { + return ((int)value1).Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating the result of the inequality. + public static bool operator !=(Int24 value1, Int24 value2) + { + return !value1.Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating the result of the inequality. + public static bool operator !=(int value1, Int24 value2) + { + return !value1.Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating the result of the inequality. + public static bool operator !=(Int24 value1, int value2) + { + return !((int)value1).Equals(value2); + } + + /// + /// Returns true if left value is less than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <(Int24 value1, Int24 value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <(int value1, Int24 value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <(Int24 value1, int value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <=(Int24 value1, Int24 value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <=(int value1, Int24 value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was less than the right value. + public static bool operator <=(Int24 value1, int value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than the right value. + public static bool operator >(Int24 value1, Int24 value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than the right value. + public static bool operator >(int value1, Int24 value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than the right value. + public static bool operator >(Int24 value1, int value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than or equal to the right value. + public static bool operator >=(Int24 value1, Int24 value2) + { + return value1.CompareTo(value2) >= 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than or equal to the right value. + public static bool operator >=(int value1, Int24 value2) + { + return value1.CompareTo(value2) >= 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// Left hand operand. + /// Right hand operand. + /// Boolean indicating whether the left value was greater than or equal to the right value. + public static bool operator >=(Int24 value1, int value2) + { + return value1.CompareTo(value2) >= 0; + } + + #endregion + + #region [ Type Conversion Operators ] + + #region [ Explicit Narrowing Conversions ] + + /// + /// Explicitly converts value to an . + /// + /// Enum value that is converted. + /// Int24 + public static explicit operator Int24(Enum value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// String value that is converted. + /// Int24 + public static explicit operator Int24(string value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// Decimal value that is converted. + /// Int24 + public static explicit operator Int24(decimal value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// Double value that is converted. + /// Int24 + public static explicit operator Int24(double value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// Float value that is converted. + /// Int24 + public static explicit operator Int24(float value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// Long value that is converted. + /// Int24 + public static explicit operator Int24(long value) + { + return new Int24(Convert.ToInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// Integer value that is converted. + /// Int24 + public static explicit operator Int24(int value) + { + return new Int24(value); + } + + /// + /// Explicitly converts to . + /// + /// Int24 value that is converted. + /// Short + public static explicit operator short(Int24 value) + { + return (short)(int)value; + } + + /// + /// Explicitly converts to . + /// + /// Int24 value that is converted. + /// Unsigned Short + public static explicit operator ushort(Int24 value) + { + return (ushort)(uint)value; + } + + /// + /// Explicitly converts to . + /// + /// Int24 value that is converted. + /// Byte + public static explicit operator byte(Int24 value) + { + return (byte)(int)value; + } + + #endregion + + #region [ Implicit Widening Conversions ] + + /// + /// Implicitly converts value to an . + /// + /// Byte value that is converted to an . + /// An value. + public static implicit operator Int24(byte value) + { + return new Int24((int)value); + } + + /// + /// Implicitly converts value to an . + /// + /// Char value that is converted to an . + /// An value. + public static implicit operator Int24(char value) + { + return new Int24((int)value); + } + + /// + /// Implicitly converts value to an . + /// + /// Short value that is converted to an . + /// An value. + public static implicit operator Int24(short value) + { + return new Int24((int)value); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// An value. + public static implicit operator int(Int24 value) + { + return ((IConvertible)value).ToInt32(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an unsigned integer. + /// Unsigned integer + public static implicit operator uint(Int24 value) + { + return ((IConvertible)value).ToUInt32(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// An value. + public static implicit operator long(Int24 value) + { + return ((IConvertible)value).ToInt64(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// An value. + public static implicit operator ulong(Int24 value) + { + return ((IConvertible)value).ToUInt64(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// A value. + public static implicit operator double(Int24 value) + { + return ((IConvertible)value).ToDouble(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// A value. + public static implicit operator float(Int24 value) + { + return ((IConvertible)value).ToSingle(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// A value. + public static implicit operator decimal(Int24 value) + { + return ((IConvertible)value).ToDecimal(null); + } + + /// + /// Implicitly converts to . + /// + /// value that is converted to an . + /// A value. + public static implicit operator string(Int24 value) + { + return value.ToString(CultureInfo.InvariantCulture); + } + + #endregion + + #endregion + + #region [ Boolean and Bitwise Operators ] + + /// + /// Returns true if value is not zero. + /// + /// Int24 value to test. + /// Boolean to indicate whether the value was not equal to zero. + public static bool operator true(Int24 value) + { + return value != 0; + } + + /// + /// Returns true if value is equal to zero. + /// + /// Int24 value to test. + /// Boolean to indicate whether the value was equal to zero. + public static bool operator false(Int24 value) + { + return value == 0; + } + + /// + /// Returns bitwise complement of value. + /// + /// value as operand. + /// as result. + public static Int24 operator ~(Int24 value) + { + return (Int24)ApplyBitMask(~(int)value); + } + + /// + /// Returns logical bitwise AND of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Int24 as result of operation. + public static Int24 operator &(Int24 value1, Int24 value2) + { + return (Int24)ApplyBitMask((int)value1 & (int)value2); + } + + /// + /// Returns logical bitwise AND of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer as result of operation. + public static int operator &(int value1, Int24 value2) + { + return value1 & (int)value2; + } + + /// + /// Returns logical bitwise AND of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer as result of operation. + public static int operator &(Int24 value1, int value2) + { + return (int)value1 & value2; + } + + /// + /// Returns logical bitwise OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Int24 as result of operation. + public static Int24 operator |(Int24 value1, Int24 value2) + { + return (Int24)ApplyBitMask((int)value1 | (int)value2); + } + + /// + /// Returns logical bitwise OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer as result of operation. + public static int operator |(int value1, Int24 value2) + { + return value1 | (int)value2; + } + + /// + /// Returns logical bitwise OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer as result of operation. + public static int operator |(Int24 value1, int value2) + { + return (int)value1 | value2; + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer value of the resulting exclusive-OR operation. + public static Int24 operator ^(Int24 value1, Int24 value2) + { + return (Int24)ApplyBitMask((int)value1 ^ (int)value2); + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer value of the resulting exclusive-OR operation. + public static int operator ^(int value1, Int24 value2) + { + return value1 ^ (int)value2; + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer value of the resulting exclusive-OR operation. + public static int operator ^(Int24 value1, int value2) + { + return (int)value1 ^ value2; + } + + /// + /// Returns value after right shifts of first value by the number of bits specified by second value. + /// + /// value to shift. + /// shifts indicates how many places to shift. + /// An value. + public static Int24 operator >>(Int24 value, int shifts) + { + return (Int24)ApplyBitMask((int)value >> shifts); + } + + /// + /// Returns value after left shifts of first value by the number of bits specified by second value. + /// + /// value to shift. + /// shifts indicates how many places to shift. + /// An value. + public static Int24 operator <<(Int24 value, int shifts) + { + return (Int24)ApplyBitMask((int)value << shifts); + } + + #endregion + + #region [ Arithmetic Operators ] + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// value as numerator. + /// value as denominator. + /// as remainder + public static Int24 operator %(Int24 value1, Int24 value2) + { + return (Int24)((int)value1 % (int)value2); + } + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// value as numerator. + /// value as denominator. + /// as remainder + public static int operator %(int value1, Int24 value2) + { + return value1 % (int)value2; + } + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// value as numerator. + /// value as denominator. + /// as remainder + public static int operator %(Int24 value1, int value2) + { + return (int)value1 % value2; + } + + /// + /// Returns computed sum of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Int24 result of addition. + public static Int24 operator +(Int24 value1, Int24 value2) + { + return (Int24)((int)value1 + (int)value2); + } + + /// + /// Returns computed sum of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of addition. + public static int operator +(int value1, Int24 value2) + { + return value1 + (int)value2; + } + + /// + /// Returns computed sum of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of addition. + public static int operator +(Int24 value1, int value2) + { + return (int)value1 + value2; + } + + /// + /// Returns computed difference of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Int24 result of subtraction. + public static Int24 operator -(Int24 value1, Int24 value2) + { + return (Int24)((int)value1 - (int)value2); + } + + /// + /// Returns computed difference of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of subtraction. + public static int operator -(int value1, Int24 value2) + { + return value1 - (int)value2; + } + + /// + /// Returns computed difference of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of subtraction. + public static int operator -(Int24 value1, int value2) + { + return (int)value1 - value2; + } + + /// + /// Returns incremented value. + /// + /// The operand. + /// Int24 result of increment. + public static Int24 operator ++(Int24 value) + { + return (Int24)(value + 1); + } + + /// + /// Returns decremented value. + /// + /// The operand. + /// Int24 result of decrement. + public static Int24 operator --(Int24 value) + { + return (Int24)(value - 1); + } + + /// + /// Returns computed product of values. + /// + /// value as left hand operand. + /// value as right hand operand. + /// as result + public static Int24 operator *(Int24 value1, Int24 value2) + { + return (Int24)((int)value1 * (int)value2); + } + + /// + /// Returns computed product of values. + /// + /// value as left hand operand. + /// value as right hand operand. + /// as result + public static int operator *(int value1, Int24 value2) + { + return value1 * (int)value2; + } + + /// + /// Returns computed product of values. + /// + /// value as left hand operand. + /// value as right hand operand. + /// as result + public static int operator *(Int24 value1, int value2) + { + return (int)value1 * value2; + } + + // Integer division operators + + /// + /// Returns computed division of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Int24 result of operation. + public static Int24 operator /(Int24 value1, Int24 value2) + { + return (Int24)((int)value1 / (int)value2); + } + + /// + /// Returns computed division of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of operation. + public static int operator /(int value1, Int24 value2) + { + return value1 / (int)value2; + } + + /// + /// Returns computed division of values. + /// + /// Left hand operand. + /// Right hand operand. + /// Integer result of operation. + public static int operator /(Int24 value1, int value2) + { + return (int)value1 / value2; + } + + //// Standard division operators + //public static double operator /(Int24 value1, Int24 value2) + //{ + // return ((double)value1 / (double)value2); + //} + + //public static double operator /(int value1, Int24 value2) + //{ + // return ((double)value1 / (double)value2); + //} + + //public static double operator /(Int24 value1, int value2) + //{ + // return ((double)value1 / (double)value2); + //} + + // C# doesn't expose an exponent operator but some other .NET languages do, + // so we expose the operator via its native special IL function name + + /// + /// Returns result of first value raised to power of second value. + /// + /// Left hand operand. + /// Right hand operand. + /// Double that is the result of the operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(Int24 value1, Int24 value2) + { + return Math.Pow(value1, value2); + } + + /// + /// Returns result of first value raised to power of second value. + /// + /// Left hand operand. + /// Right hand operand. + /// Double that is the result of the operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(int value1, Int24 value2) + { + return Math.Pow(value1, value2); + } + + /// + /// Returns result of first value raised to power of second value. + /// + /// Left hand operand. + /// Right hand operand. + /// Double that is the result of the operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(Int24 value1, int value2) + { + return Math.Pow(value1, value2); + } + + #endregion + + #endregion + + #region [ Static ] + + /// + /// Represents the largest possible value of an Int24. This field is constant. + /// + public static readonly Int24 MaxValue = (Int24)MaxValue32; + + /// + /// Represents the smallest possible value of an Int24. This field is constant. + /// + public static readonly Int24 MinValue = (Int24)MinValue32; + + /// Returns the specified Int24 value as an array of three bytes. + /// Int24 value to convert to bytes. + /// An array of bytes with length 3. + /// + /// You can use this function in-lieu of a System.BitConverter.GetBytes(Int24) function. + /// Bytes will be returned in endian order of currently executing process architecture (little-endian on Intel platforms). + /// + public static byte[] GetBytes(Int24 value) + { + // We use a 32-bit integer to store 24-bit integer internally + byte[] data = new byte[3]; + int valueInt = value; + + if (BitConverter.IsLittleEndian) + { + data[0] = (byte)valueInt; + data[1] = (byte)(valueInt >> 8); + data[2] = (byte)(valueInt >> 16); + } + else + { + data[0] = (byte)(valueInt >> 16); + data[1] = (byte)(valueInt >> 8); + data[2] = (byte)valueInt; + } + + // Return serialized 3-byte representation of Int24 + return data; + } + + /// Returns a 24-bit signed integer from three bytes at a specified position in a byte array. + /// An array of bytes. + /// The starting position within value. + /// A 24-bit signed integer formed by three bytes beginning at startIndex. + /// + /// You can use this function in-lieu of a System.BitConverter.ToInt24 function. + /// Bytes endian order assumed to match that of currently executing process architecture (little-endian on Intel platforms). + /// + /// cannot be null. + /// is greater than length. + /// length from is too small to represent an . + public static Int24 GetValue(byte[] value, int startIndex) + { + value.ValidateParameters(startIndex, 3); + int valueInt; + + if (BitConverter.IsLittleEndian) + { + valueInt = value[startIndex] | + value[startIndex + 1] << 8 | + value[startIndex + 2] << 16; + } + else + { + valueInt = value[startIndex] << 16 | + value[startIndex + 1] << 8 | + value[startIndex + 2]; + } + + // Deserialize value + return (Int24)ApplyBitMask(valueInt); + } + + private static void ValidateNumericRange(int value) + { + if (value is > MaxValue32 + 1 or < MinValue32) + throw new OverflowException($"Value of {value} will not fit in a 24-bit signed integer"); + } + + private static int ApplyBitMask(int value) + { + // Check bit 23, the sign bit in a signed 24-bit integer + if ((value & 0x00800000) > 0) + { + // If the sign-bit is set, this number will be negative - set all high-byte bits (keeps 32-bit number in 24-bit range) + value |= BitMask; + } + else + { + // If the sign-bit is not set, this number will be positive - clear all high-byte bits (keeps 32-bit number in 24-bit range) + value &= ~BitMask; + } + + return value; + } + + #endregion +} diff --git a/VG Music Studio - Core/Util/SampleUtils.cs b/VG Music Studio - Core/Util/SampleUtils.cs index cbce3fb..56e8e81 100644 --- a/VG Music Studio - Core/Util/SampleUtils.cs +++ b/VG Music Studio - Core/Util/SampleUtils.cs @@ -4,12 +4,36 @@ namespace Kermalis.VGMusicStudio.Core.Util; internal static class SampleUtils { - public static void PCMU8ToPCM16(ReadOnlySpan src, Span dest) - { - for (int i = 0; i < src.Length; i++) - { - byte b = src[i]; - dest[i] = (short)((b - 0x80) << 8); - } - } + public static void PCMU8ToPCM16(ReadOnlySpan src, Span dest) + { + for (int i = 0; i < src.Length; i++) + { + byte b = src[i]; + dest[i] = (short)((b - 0x80) << 8); + } + } + public static void PCM16ToPCMU8(ReadOnlySpan src, Span dest) + { + for (int i = 0; i < src.Length; i++) + { + short b = src[i]; + dest[i] = (byte)((b + 0x8000) >> 8); + } + } + public static void PCM16ToPCM24(ReadOnlySpan src, Span dest) + { + for (int i = 0; i < src.Length; i++) + { + short b = src[i]; + dest[i] = (Int24)(b << 8); + } + } + public static void PCM24ToPCM16(ReadOnlySpan src, Span dest) + { + for (int i = 0; i < src.Length; i++) + { + Int24 b = src[i]; + dest[i] = (short)(b >> 8); + } + } } diff --git a/VG Music Studio - Core/Util/UInt24.cs b/VG Music Studio - Core/Util/UInt24.cs new file mode 100644 index 0000000..428ab6c --- /dev/null +++ b/VG Music Studio - Core/Util/UInt24.cs @@ -0,0 +1,1517 @@ +//****************************************************************************************************** +// UInt24.cs - Gbtc +// +// Copyright © 2012, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 11/12/2004 - J. Ritchie Carroll +// Initial version of source generated. +// 08/4/2009 - Josh L. Patterson +// Edited Code Comments. +// 09/14/2009 - Stephen C. Wills +// Added new header and license agreement. +// 12/14/2012 - Starlynn Danyelle Gilliam +// Modified Header. +// +//****************************************************************************************************** + +#region [ Contributor License Agreements ] + +/**************************************************************************\ + Copyright © 2009 - J. Ritchie Carroll + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +\**************************************************************************/ + +#endregion + +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace System; + +/// Represents a 3-byte, 24-bit unsigned integer. +/// +/// +/// This class behaves like most other intrinsic unsigned integers but allows a 3-byte, 24-bit integer implementation +/// that is often found in many digital-signal processing arenas and different kinds of protocol parsing. An unsigned +/// 24-bit integer is typically used to save storage space on disk where its value range of 0 to 16777215 is sufficient, +/// but the unsigned Int16 value range of 0 to 65535 is too small. +/// +/// +/// This structure uses an UInt32 internally for storage and most other common expected integer functionality, so using +/// a 24-bit integer will not save memory. However, if the 24-bit unsigned integer range (0 to 16777215) suits your +/// data needs you can save disk space by only storing the three bytes that this integer actually consumes. You can do +/// this by calling the UInt24.GetBytes function to return a three byte binary array that can be serialized to the desired +/// destination and then calling the UInt24.GetValue function to restore the UInt24 value from those three bytes. +/// +/// +/// All the standard operators for the UInt24 have been fully defined for use with both UInt24 and UInt32 unsigned integers; +/// you should find that without the exception UInt24 can be compared and numerically calculated with an UInt24 or UInt32. +/// Necessary casting should be minimal and typical use should be very simple - just as if you are using any other native +/// unsigned integer. +/// +/// +[Serializable] +public struct UInt24 : IComparable, IFormattable, IConvertible, IComparable, IComparable, IEquatable, IEquatable +{ + #region [ Members ] + + // Constants + private const uint MaxValue32 = 0x00ffffff; // Represents the largest possible value of an UInt24 as an UInt32. + private const uint MinValue32 = 0x00000000; // Represents the smallest possible value of an UInt24 as an UInt32. + + /// High byte bit-mask used when a 24-bit integer is stored within a 32-bit integer. This field is constant. + public const uint BitMask = 0xff000000; + + // Fields + private readonly uint m_value; // We internally store the UInt24 value in a 4-byte unsigned integer for convenience + + #endregion + + #region [ Constructors ] + + /// Creates 24-bit unsigned integer from an existing 24-bit unsigned integer. + /// A to create the new value from. + public UInt24(UInt24 value) + { + m_value = ApplyBitMask(value); + } + + /// Creates 24-bit unsigned integer from a 32-bit unsigned integer. + /// 32-bit unsigned integer to use as new 24-bit unsigned integer value. + /// Source values over 24-bit max range will cause an overflow exception. + public UInt24(uint value) + { + ValidateNumericRange(value); + m_value = ApplyBitMask(value); + } + + /// Creates 24-bit unsigned integer from three bytes at a specified position in a byte array. + /// An array of bytes. + /// The starting position within . + /// + /// You can use this constructor in-lieu of a System.BitConverter.ToUInt24 function. + /// Bytes endian order assumed to match that of currently executing process architecture (little-endian on Intel platforms). + /// + /// cannot be null. + /// is greater than length. + /// length from is too small to represent a . + public UInt24(byte[] value, int startIndex) + { + m_value = GetValue(value, startIndex).m_value; + } + + #endregion + + #region [ Methods ] + + /// Returns the UInt24 value as an array of three bytes. + /// An array of bytes with length 3. + /// + /// You can use this function in-lieu of a System.BitConverter.GetBytes function. + /// Bytes will be returned in endian order of currently executing process architecture (little-endian on Intel platforms). + /// + public byte[] GetBytes() + { + // Return serialized 3-byte representation of UInt24 + return GetBytes(this); + } + + /// + /// Compares this instance to a specified object and returns an indication of their relative values. + /// + /// An object to compare, or null. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + /// value is not an UInt32 or UInt24. + public int CompareTo(object? value) + { + if (value is null) + return 1; + + if (value is not uint && value is not UInt24) + throw new ArgumentException("Argument must be an UInt32 or an UInt24"); + + uint num = (uint)value; + + return m_value < num ? -1 : m_value > num ? 1 : 0; + } + + /// + /// Compares this instance to a specified 24-bit unsigned integer and returns an indication of their + /// relative values. + /// + /// An integer to compare. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + public int CompareTo(UInt24 value) + { + return CompareTo((uint)value); + } + + /// + /// Compares this instance to a specified 32-bit unsigned integer and returns an indication of their + /// relative values. + /// + /// An integer to compare. + /// + /// A signed number indicating the relative values of this instance and value. Returns less than zero + /// if this instance is less than value, zero if this instance is equal to value, or greater than zero + /// if this instance is greater than value. + /// + public int CompareTo(uint value) + { + return m_value < value ? -1 : m_value > value ? 1 : 0; + } + + /// + /// Returns a value indicating whether this instance is equal to a specified object. + /// + /// An object to compare, or null. + /// + /// True if obj is an instance of UInt32 or UInt24 and equals the value of this instance; + /// otherwise, False. + /// + public override bool Equals(object? obj) + { + if (obj is uint or UInt24) + return Equals((uint)obj); + + return false; + } + + /// + /// Returns a value indicating whether this instance is equal to a specified UInt24 value. + /// + /// An UInt24 value to compare to this instance. + /// + /// True if obj has the same value as this instance; otherwise, False. + /// + public bool Equals(UInt24 obj) + { + return Equals((uint)obj); + } + + /// + /// Returns a value indicating whether this instance is equal to a specified uint value. + /// + /// An UInt32 value to compare to this instance. + /// + /// True if obj has the same value as this instance; otherwise, False. + /// + public bool Equals(uint obj) + { + return m_value == obj; + } + + /// + /// Returns the hash code for this instance. + /// + /// + /// A 32-bit unsigned integer hash code. + /// + public override int GetHashCode() + { + unchecked + { + return (int)m_value; + } + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation. + /// + /// + /// The string representation of the value of this instance, consisting of a minus sign if + /// the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes. + /// + public override string ToString() + { + return m_value.ToString(); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation, using + /// the specified format. + /// + /// A format string. + /// + /// The string representation of the value of this instance as specified by format. + /// + public string ToString(string? format) + { + return m_value.ToString(format); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation using the + /// specified culture-specific format information. + /// + /// + /// A that supplies culture-specific formatting information. + /// + /// + /// The string representation of the value of this instance as specified by provider. + /// + public string ToString(IFormatProvider? provider) + { + return m_value.ToString(provider); + } + + /// + /// Converts the numeric value of this instance to its equivalent string representation using the + /// specified format and culture-specific format information. + /// + /// A format specification. + /// + /// A that supplies culture-specific formatting information. + /// + /// + /// The string representation of the value of this instance as specified by format and provider. + /// + public string ToString(string? format, IFormatProvider? provider) + { + return m_value.ToString(format, provider); + } + + /// + /// Converts the string representation of a number to its 24-bit unsigned integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A 24-bit unsigned integer equivalent to the number contained in s. + /// + /// s is null. + /// + /// s represents a number less than UInt24.MinValue or greater than UInt24.MaxValue. + /// + /// s is not in the correct format. + public static UInt24 Parse(string s) + { + return (UInt24)uint.Parse(s); + } + + /// + /// Converts the string representation of a number in a specified style to its 24-bit unsigned integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// A 24-bit unsigned integer equivalent to the number contained in s. + /// + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + /// s is null. + /// + /// s represents a number less than UInt24.MinValue or greater than UInt24.MaxValue. + /// + /// s is not in a format compliant with style. + public static UInt24 Parse(string s, NumberStyles style) + { + return (UInt24)uint.Parse(s, style); + } + + /// + /// Converts the string representation of a number in a specified culture-specific format to its 24-bit + /// unsigned integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A that supplies culture-specific formatting information about s. + /// + /// + /// A 24-bit unsigned integer equivalent to the number contained in s. + /// + /// s is null. + /// + /// s represents a number less than UInt24.MinValue or greater than UInt24.MaxValue. + /// + /// s is not in the correct format. + public static UInt24 Parse(string s, IFormatProvider? provider) + { + return (UInt24)uint.Parse(s, provider); + } + + /// + /// Converts the string representation of a number in a specified style and culture-specific format to its 24-bit + /// unsigned integer equivalent. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// A that supplies culture-specific formatting information about s. + /// + /// + /// A 24-bit unsigned integer equivalent to the number contained in s. + /// + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + /// s is null. + /// + /// s represents a number less than UInt24.MinValue or greater than UInt24.MaxValue. + /// + /// s is not in a format compliant with style. + public static UInt24 Parse(string s, NumberStyles style, IFormatProvider? provider) + { + return (UInt24)uint.Parse(s, style, provider); + } + + /// + /// Converts the string representation of a number to its 24-bit unsigned integer equivalent. A return value + /// indicates whether the conversion succeeded or failed. + /// + /// A string containing a number to convert. + /// + /// When this method returns, contains the 24-bit unsigned integer value equivalent to the number contained in s, + /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, + /// is not of the correct format, or represents a number less than UInt24.MinValue or greater than UInt24.MaxValue. + /// This parameter is passed uninitialized. + /// + /// true if s was converted successfully; otherwise, false. + public static bool TryParse(string s, out UInt24 result) + { + bool parseResponse = uint.TryParse(s, out uint parseResult); + + try + { + result = (UInt24)parseResult; + } + catch + { + result = 0; + parseResponse = false; + } + + return parseResponse; + } + + /// + /// Converts the string representation of a number in a specified style and culture-specific format to its + /// 24-bit unsigned integer equivalent. A return value indicates whether the conversion succeeded or failed. + /// + /// A string containing a number to convert. + /// + /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s. + /// A typical value to specify is System.Globalization.NumberStyles.Integer. + /// + /// + /// When this method returns, contains the 24-bit unsigned integer value equivalent to the number contained in s, + /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, + /// is not in a format compliant with style, or represents a number less than UInt24.MinValue or greater than + /// UInt24.MaxValue. This parameter is passed uninitialized. + /// + /// + /// A object that supplies culture-specific formatting information about s. + /// + /// true if s was converted successfully; otherwise, false. + /// + /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of + /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values. + /// + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out UInt24 result) + { + bool parseResponse = uint.TryParse(s, style, provider, out uint parseResult); + + try + { + result = (UInt24)parseResult; + } + catch + { + result = 0; + parseResponse = false; + } + + return parseResponse; + } + + /// + /// Returns the System.TypeCode for value type System.UInt32 (there is no defined type code for an UInt24). + /// + /// The enumerated constant, System.TypeCode.UInt32. + /// + /// There is no defined UInt24 type code and since an UInt24 will easily fit inside an UInt32, the + /// UInt32 type code is returned. + /// + public TypeCode GetTypeCode() + { + return TypeCode.UInt32; + } + + #region [ Explicit IConvertible Implementation ] + + // These are explicitly implemented on the native integer implementations, so we do the same... + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + return Convert.ToBoolean(m_value, provider); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + return Convert.ToChar(m_value, provider); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(m_value, provider); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(m_value, provider); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(m_value, provider); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(m_value, provider); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(m_value, provider); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return m_value; + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(m_value, provider); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(m_value, provider); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(m_value, provider); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(m_value, provider); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(m_value, provider); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + return Convert.ToDateTime(m_value, provider); + } + + object IConvertible.ToType(Type type, IFormatProvider? provider) + { + return Convert.ChangeType(m_value, type, provider); + } + + #endregion + + #endregion + + #region [ Operators ] + + // Every effort has been made to make UInt24 as cleanly interoperable with UInt32 as possible... + + #region [ Comparison Operators ] + + /// + /// Compares the two values for equality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator ==(UInt24 value1, UInt24 value2) + { + return value1.Equals(value2); + } + + /// + /// Compares the two values for equality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator ==(uint value1, UInt24 value2) + { + return value1.Equals(value2); + } + + /// + /// Compares the two values for equality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator ==(UInt24 value1, uint value2) + { + return ((uint)value1).Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator !=(UInt24 value1, UInt24 value2) + { + return !value1.Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator !=(uint value1, UInt24 value2) + { + return !value1.Equals(value2); + } + + /// + /// Compares the two values for inequality. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator !=(UInt24 value1, uint value2) + { + return !((uint)value1).Equals(value2); + } + + /// + /// Returns true if left value is less than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <(UInt24 value1, UInt24 value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <(uint value1, UInt24 value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <(UInt24 value1, uint value2) + { + return value1.CompareTo(value2) < 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <=(UInt24 value1, UInt24 value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <=(uint value1, UInt24 value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is less or equal to than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator <=(UInt24 value1, uint value2) + { + return value1.CompareTo(value2) <= 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >(UInt24 value1, UInt24 value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >(uint value1, UInt24 value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >(UInt24 value1, uint value2) + { + return value1.CompareTo(value2) > 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >=(UInt24 value1, UInt24 value2) + { + return value1.CompareTo(value2) >= 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >=(uint value1, UInt24 value2) + { + return value1.CompareTo(value2) >= 0; + } + + /// + /// Returns true if left value is greater than or equal to right value. + /// + /// left hand operand. + /// right hand operand. + /// value representing the result. + public static bool operator >=(UInt24 value1, uint value2) + { + return value1.CompareTo(value2) >= 0; + } + + #endregion + + #region [ Type Conversion Operators ] + + #region [ Explicit Narrowing Conversions ] + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(Enum value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(string value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(decimal value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(double value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(float value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(ulong value) + { + return new UInt24(Convert.ToUInt32(value)); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(uint value) + { + return new UInt24(value); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator UInt24(Int24 value) + { + return new UInt24(value); + } + + /// + /// Explicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator Int24(UInt24 value) + { + return new Int24(value); + } + + /// + /// Explicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator short(UInt24 value) + { + return (short)(uint)value; + } + + /// + /// Explicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator ushort(UInt24 value) + { + return (ushort)(uint)value; + } + + /// + /// Explicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static explicit operator byte(UInt24 value) + { + return (byte)(uint)value; + } + + #endregion + + #region [ Implicit Widening Conversions ] + + /// + /// Implicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator UInt24(byte value) + { + return new UInt24((uint)value); + } + + /// + /// Implicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator UInt24(char value) + { + return new UInt24((uint)value); + } + + /// + /// Implicitly converts value to an . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator UInt24(ushort value) + { + return new UInt24((uint)value); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator int(UInt24 value) + { + return ((IConvertible)value).ToInt32(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator uint(UInt24 value) + { + return ((IConvertible)value).ToUInt32(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator long(UInt24 value) + { + return ((IConvertible)value).ToInt64(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator ulong(UInt24 value) + { + return ((IConvertible)value).ToUInt64(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator double(UInt24 value) + { + return ((IConvertible)value).ToDouble(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator float(UInt24 value) + { + return ((IConvertible)value).ToSingle(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator decimal(UInt24 value) + { + return ((IConvertible)value).ToDecimal(null); + } + + /// + /// Implicitly converts to . + /// + /// value to be converted. + /// value that is the result of the conversion. + public static implicit operator string(UInt24 value) + { + return value.ToString(CultureInfo.InvariantCulture); + } + + #endregion + + #endregion + + #region [ Boolean and Bitwise Operators ] + + /// + /// Returns true if value is greater than zero. + /// + /// value to evaluate. + /// value indicating whether the value is greater than zero. + public static bool operator true(UInt24 value) + { + return value > 0; + } + + /// + /// Returns true if value is equal to zero. + /// + /// value to evaluate. + /// value indicating whether the value is equal than zero. + public static bool operator false(UInt24 value) + { + return value == 0; + } + + /// + /// Returns bitwise complement of value. + /// + /// value to evaluate. + /// value representing the complement of the input value. + public static UInt24 operator ~(UInt24 value) + { + return (UInt24)ApplyBitMask(~(uint)value); + } + + /// + /// Returns logical bitwise AND of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise AND of the values. + public static UInt24 operator &(UInt24 value1, UInt24 value2) + { + return (UInt24)ApplyBitMask((uint)value1 & (uint)value2); + } + + /// + /// Returns logical bitwise AND of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise AND of the values. + public static uint operator &(uint value1, UInt24 value2) + { + return value1 & (uint)value2; + } + + /// + /// Returns logical bitwise AND of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise AND of the values. + public static uint operator &(UInt24 value1, uint value2) + { + return (uint)value1 & value2; + } + + /// + /// Returns logical bitwise OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise OR of the values. + public static UInt24 operator |(UInt24 value1, UInt24 value2) + { + return (UInt24)ApplyBitMask((uint)value1 | (uint)value2); + } + + /// + /// Returns logical bitwise OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise OR of the values. + public static uint operator |(uint value1, UInt24 value2) + { + return value1 | (uint)value2; + } + + /// + /// Returns logical bitwise OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise OR of the values. + public static uint operator |(UInt24 value1, uint value2) + { + return (uint)value1 | value2; + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise exclusive-OR of the values. + public static UInt24 operator ^(UInt24 value1, UInt24 value2) + { + return (UInt24)ApplyBitMask((uint)value1 ^ (uint)value2); + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise exclusive-OR of the values. + public static uint operator ^(uint value1, UInt24 value2) + { + return value1 ^ (uint)value2; + } + + /// + /// Returns logical bitwise exclusive-OR of values. + /// + /// left hand operand. + /// right hand operand. + /// value representing the logical bitwise exclusive-OR of the values. + public static uint operator ^(UInt24 value1, uint value2) + { + return (uint)value1 ^ value2; + } + + /// + /// Returns value after right shifts of first value by the number of bits specified by second value. + /// + /// value to right shift. + /// value indicating the number of bits to right shift by. + /// value as result of right shift operation. + public static UInt24 operator >>(UInt24 value, int shifts) + { + return (UInt24)ApplyBitMask((uint)value >> shifts); + } + + /// + /// Returns value after left shifts of first value by the number of bits specified by second value. + /// + /// value to left shift. + /// value indicating the number of bits to left shift by. + /// value as result of left shift operation. + public static UInt24 operator <<(UInt24 value, int shifts) + { + return (UInt24)ApplyBitMask((uint)value << shifts); + } + + #endregion + + #region [ Arithmetic Operators ] + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// left hand operand. + /// right hand operand. + /// value as result of modulus operation. + public static UInt24 operator %(UInt24 value1, UInt24 value2) + { + return (UInt24)((uint)value1 % (uint)value2); + } + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// left hand operand. + /// right hand operand. + /// value as result of modulus operation. + public static uint operator %(uint value1, UInt24 value2) + { + return value1 % (uint)value2; + } + + /// + /// Returns computed remainder after dividing first value by the second. + /// + /// left hand operand. + /// right hand operand. + /// value as result of modulus operation. + public static uint operator %(UInt24 value1, uint value2) + { + return (uint)value1 % value2; + } + + /// + /// Returns computed sum of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of addition operation. + public static UInt24 operator +(UInt24 value1, UInt24 value2) + { + return (UInt24)((uint)value1 + (uint)value2); + } + + /// + /// Returns computed sum of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of addition operation. + public static uint operator +(uint value1, UInt24 value2) + { + return value1 + (uint)value2; + } + + /// + /// Returns computed sum of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of addition operation. + public static uint operator +(UInt24 value1, uint value2) + { + return (uint)value1 + value2; + } + + /// + /// Returns computed difference of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of subtraction operation. + public static UInt24 operator -(UInt24 value1, UInt24 value2) + { + return (UInt24)((uint)value1 - (uint)value2); + } + + /// + /// Returns computed difference of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of subtraction operation. + public static uint operator -(uint value1, UInt24 value2) + { + return value1 - (uint)value2; + } + + /// + /// Returns computed difference of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of subtraction operation. + public static uint operator -(UInt24 value1, uint value2) + { + return (uint)value1 - value2; + } + + /// + /// Returns incremented value. + /// + /// The operand. + /// result of increment. + public static UInt24 operator ++(UInt24 value) + { + return value + 1; + } + + /// + /// Returns decremented value. + /// + /// The operand. + /// result of decrement. + public static UInt24 operator --(UInt24 value) + { + return value - 1; + } + + /// + /// Returns computed product of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of multiplication operation. + public static UInt24 operator *(UInt24 value1, UInt24 value2) + { + return (UInt24)((uint)value1 * (uint)value2); + } + + /// + /// Returns computed product of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of multiplication operation. + public static uint operator *(uint value1, UInt24 value2) + { + return value1 * (uint)value2; + } + + /// + /// Returns computed product of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of multiplication operation. + public static uint operator *(UInt24 value1, uint value2) + { + return (uint)value1 * value2; + } + + // Integer division operators + + /// + /// Returns computed division of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of division operation. + public static UInt24 operator /(UInt24 value1, UInt24 value2) + { + return (UInt24)((uint)value1 / (uint)value2); + } + + /// + /// Returns computed division of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of division operation. + public static uint operator /(uint value1, UInt24 value2) + { + return value1 / (uint)value2; + } + + /// + /// Returns computed division of values. + /// + /// left hand operand. + /// right hand operand. + /// value as result of division operation. + public static uint operator /(UInt24 value1, uint value2) + { + return (uint)value1 / value2; + } + + //// Standard division operators + //public static double operator /(UInt24 value1, UInt24 value2) + //{ + // return ((double)value1 / (double)value2); + //} + + //public static double operator /(uint value1, UInt24 value2) + //{ + // return ((double)value1 / (double)value2); + //} + + //public static double operator /(UInt24 value1, uint value2) + //{ + // return ((double)value1 / (double)value2); + //} + + // C# doesn't expose an exponent operator but some other .NET languages do, + // so we expose the operator via its native special IL function name + + /// + /// Returns result of first value raised to power of second value. + /// + /// left hand operand. + /// right hand operand. + /// value as result of operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(UInt24 value1, UInt24 value2) + { + return Math.Pow(value1, value2); + } + + /// + /// Returns result of first value raised to power of second value. + /// + /// left hand operand. + /// right hand operand. + /// value as result of operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(int value1, UInt24 value2) + { + return Math.Pow(value1, value2); + } + + /// + /// Returns result of first value raised to power of second value. + /// + /// left hand operand. + /// right hand operand. + /// value as result of operation. + [EditorBrowsable(EditorBrowsableState.Advanced), SpecialName] + public static double op_Exponent(UInt24 value1, int value2) + { + return Math.Pow(value1, value2); + } + + #endregion + + #endregion + + #region [ Static ] + + /// + /// Represents the largest possible value of an Int24. This field is constant. + /// + public static readonly UInt24 MaxValue = (UInt24)MaxValue32; + + /// + /// Represents the smallest possible value of an Int24. This field is constant. + /// + public static readonly UInt24 MinValue = (UInt24)MinValue32; + + /// Returns the specified UInt24 value as an array of three bytes. + /// UInt24 value to convert to bytes. + /// An array of bytes with length 3. + /// + /// You can use this function in-lieu of a System.BitConverter.GetBytes(UInt24) function. + /// Bytes will be returned in endian order of currently executing process architecture (little-endian on Intel platforms). + /// + public static byte[] GetBytes(UInt24 value) + { + // We use a 32-bit integer to store 24-bit integer internally + byte[] data = new byte[3]; + uint valueInt = value; + + if (BitConverter.IsLittleEndian) + { + data[0] = (byte)valueInt; + data[1] = (byte)(valueInt >> 8); + data[2] = (byte)(valueInt >> 16); + } + else + { + data[0] = (byte)(valueInt >> 16); + data[1] = (byte)(valueInt >> 8); + data[2] = (byte)valueInt; + } + + // Return serialized 3-byte representation of Int24 + return data; + } + + /// Returns a 24-bit unsigned integer from three bytes at a specified position in a byte array. + /// An array of bytes. + /// The starting position within value. + /// A 24-bit unsigned integer formed by three bytes beginning at startIndex. + /// + /// You can use this function in-lieu of a System.BitConverter.ToUInt24 function. + /// Bytes endian order assumed to match that of currently executing process architecture (little-endian on Intel platforms). + /// + /// cannot be null. + /// is greater than length. + /// length from is too small to represent an . + public static UInt24 GetValue(byte[] value, int startIndex) + { + value.ValidateParameters(startIndex, 3); + int valueInt; + + if (BitConverter.IsLittleEndian) + { + valueInt = value[startIndex] | + value[startIndex + 1] << 8 | + value[startIndex + 2] << 16; + } + else + { + valueInt = value[startIndex] << 16 | + value[startIndex + 1] << 8 | + value[startIndex + 2]; + } + + // Deserialize value + return (UInt24)ApplyBitMask((uint)valueInt); + } + + private static void ValidateNumericRange(uint value) + { + if (value > MaxValue32) + throw new OverflowException($"Value of {value} will not fit in a 24-bit unsigned integer"); + } + + private static uint ApplyBitMask(uint value) + { + // For unsigned values, all we do is clear all the high bits (keeps 32-bit unsigned number in 24-bit unsigned range)... + return value & ~BitMask; + } + + #endregion +} \ No newline at end of file diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index 1d8bb4e..555ddb3 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -12,9 +12,12 @@ - - - + + + + + + Dependencies\DLS2.dll diff --git a/VG Music Studio - GTK3/MainWindow.cs b/VG Music Studio - GTK3/MainWindow.cs new file mode 100644 index 0000000..e1b973d --- /dev/null +++ b/VG Music Studio - GTK3/MainWindow.cs @@ -0,0 +1,875 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal sealed class MainWindow : Window + { + private bool _playlistPlaying; + private Config.Playlist _curPlaylist; + private long _curSong = -1; + private readonly List _playedSequences; + private readonly List _remainingSequences; + + private bool _stopUI = false; + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Menu Bar + private readonly MenuBar _mainMenu; + + // Menus + private readonly Menu _fileMenu, _dataMenu, _soundtableMenu; + + // Menu Items + private readonly MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _soundtableItem, _endSoundtableItem; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private readonly Scale _volumeScale, _positionScale; + + // Adjustments are for indicating the numbers and the position of the scale + private Adjustment _volumeAdjustment, _positionAdjustment, _sequenceNumberAdjustment; + + // Tree View + private readonly TreeView _sequencesListView; + private readonly TreeViewColumn _sequencesColumn; + + // List Store + private ListStore _sequencesListStore; + + #endregion + + public MainWindow() : base(ConfigUtils.PROGRAM_NAME) + { + // Main Window + // Sets the default size of the Window + SetDefaultSize(500, 300); + + + // Sets the _playedSequences and _remainingSequences with a List() function to be ready for use + _playedSequences = new List(); + _remainingSequences = new List(); + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer_NAudio.MixerVolumeChanged += SetVolumeScale; + + // Main Menu + _mainMenu = new MenuBar(); + + // File Menu + _fileMenu = new Menu(); + + _fileItem = new MenuItem() { Label = Strings.MenuFile, UseUnderline = true }; + _fileItem.Submenu = _fileMenu; + + _openDSEItem = new MenuItem() { Label = Strings.MenuOpenDSE, UseUnderline = true }; + _openDSEItem.Activated += OpenDSE; + _fileMenu.Append(_openDSEItem); + + _openSDATItem = new MenuItem() { Label = Strings.MenuOpenSDAT, UseUnderline = true }; + _openSDATItem.Activated += OpenSDAT; + _fileMenu.Append(_openSDATItem); + + _openAlphaDreamItem = new MenuItem() { Label = Strings.MenuOpenAlphaDream, UseUnderline = true }; + _openAlphaDreamItem.Activated += OpenAlphaDream; + _fileMenu.Append(_openAlphaDreamItem); + + _openMP2KItem = new MenuItem() { Label = Strings.MenuOpenMP2K, UseUnderline = true }; + _openMP2KItem.Activated += OpenMP2K; + _fileMenu.Append(_openMP2KItem); + + _mainMenu.Append(_fileItem); // Note: It must append the menu item, not the file menu itself + + // Data Menu + _dataMenu = new Menu(); + + _dataItem = new MenuItem() { Label = Strings.MenuData, UseUnderline = true }; + _dataItem.Submenu = _dataMenu; + + _exportDLSItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveDLS, UseUnderline = true }; // Sensitive is identical to 'Enabled', so if you're disabling the control, Sensitive must be set to false + _exportDLSItem.Activated += ExportDLS; + _dataMenu.Append(_exportDLSItem); + + _exportSF2Item = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveSF2, UseUnderline = true }; + _exportSF2Item.Activated += ExportSF2; + _dataMenu.Append(_exportSF2Item); + + _exportMIDIItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveMIDI, UseUnderline = true }; + _exportMIDIItem.Activated += ExportMIDI; + _dataMenu.Append(_exportMIDIItem); + + _exportWAVItem = new MenuItem() { Sensitive = false, Label = Strings.MenuSaveWAV, UseUnderline = true }; + _exportWAVItem.Activated += ExportWAV; + _dataMenu.Append(_exportWAVItem); + + _mainMenu.Append(_dataItem); + + // Soundtable Menu + _soundtableMenu = new Menu(); + + _soundtableItem = new MenuItem() { Label = Strings.MenuPlaylist, UseUnderline = true }; + _soundtableItem.Submenu = _soundtableMenu; + + _endSoundtableItem = new MenuItem() { Label = Strings.MenuEndPlaylist, UseUnderline = true }; + _endSoundtableItem.Activated += EndCurrentPlaylist; + _soundtableMenu.Append(_endSoundtableItem); + + _mainMenu.Append(_soundtableItem); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.Clicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.Clicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.Clicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = new SpinButton(_sequenceNumberAdjustment, 1, 0) { Sensitive = false, Value = 0, NoShowAll = true, Visible = false }; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += UpdateUI; + + // Volume Scale + _volumeAdjustment = new Adjustment(0, 0, 100, 1, 1, 1); + _volumeScale = new Scale(Orientation.Horizontal, _volumeAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + + // Position Scale + _positionAdjustment = new Adjustment(0, 0, -1, 1, 1, 1); + _positionScale = new Scale(Orientation.Horizontal, _positionAdjustment) { Sensitive = false, ShowFillLevel = true, DrawValue = false, WidthRequest = 250 }; + _positionScale.ButtonReleaseEvent += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + _positionScale.ButtonPressEvent += PositionScale_MouseButtonPress; + + // Sequences List View + _sequencesListView = new TreeView(); + _sequencesListStore = new ListStore(typeof(string), typeof(string)); + _sequencesColumn = new TreeViewColumn("Name", new CellRendererText(), "text", 1); + _sequencesListView.AppendColumn("#", new CellRendererText(), "text", 0); + _sequencesListView.AppendColumn(_sequencesColumn); + _sequencesListView.Model = _sequencesListStore; + + // Main display + _mainBox = new Box(Orientation.Vertical, 4); + _configButtonBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + _configPlayerButtonBox = new Box(Orientation.Horizontal, 3) { Halign = Align.Center }; + _configSpinButtonBox = new Box(Orientation.Horizontal, 1) { Halign = Align.Center, WidthRequest = 100 }; + _configScaleBox = new Box(Orientation.Horizontal, 2) { Halign = Align.Center }; + + _mainBox.PackStart(_mainMenu, false, false, 0); + _mainBox.PackStart(_configButtonBox, false, false, 0); + _mainBox.PackStart(_configScaleBox, false, false, 0); + _mainBox.PackStart(_sequencesListView, false, false, 0); + + _configButtonBox.PackStart(_configPlayerButtonBox, false, false, 40); + _configButtonBox.PackStart(_configSpinButtonBox, false, false, 100); + + _configPlayerButtonBox.PackStart(_buttonPlay, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonPause, false, false, 0); + _configPlayerButtonBox.PackStart(_buttonStop, false, false, 0); + + _configSpinButtonBox.PackStart(_sequenceNumberSpinButton, false, false, 0); + + _configScaleBox.PackStart(_volumeScale, false, false, 20); + _configScaleBox.PackStart(_positionScale, false, false, 20); + + Add(_mainBox); + + ShowAll(); + + // Ensures the entire application closes when the window is closed + DeleteEvent += delegate { Application.Quit(); }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object? sender, EventArgs? e) + { + Engine.Instance.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeAdjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.ValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeAdjustment.Upper); + _volumeScale.ValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object? sender, ButtonReleaseEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance.Player.SetCurrentPosition((long)_positionScale.Value); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object? sender, ButtonPressEventArgs args) + { + if (args.Event.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private bool _autoplay = false; + private void SequenceNumberSpinButton_ValueChanged(object? sender, EventArgs? e) + { + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + + long index = (long)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + _sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index)), ex); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + Config.Song? song = songs.SingleOrDefault(s => s.Index == index); + if (song is not null) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {song.Name}"; // TODO: Make this a func + _sequencesColumn.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + _positionAdjustment.Upper = Engine.Instance!.Player.LoadedSong!.MaxTicks; + _positionAdjustment.Value = _positionAdjustment.Upper / 10; + _positionAdjustment.Value = _positionAdjustment.Value / 4; + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVItem.Sensitive = success; + _exportMIDIItem.Sensitive = success && MP2KEngine.MP2KInstance is not null; + _exportDLSItem.Sensitive = _exportSF2Item.Sensitive = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + } + private void SequencesListView_SelectionGet(object? sender, EventArgs? e) + { + var item = _sequencesListView.Selection; + if (item.SelectFunction.Target is Config.Song song) + { + SetAndLoadSequence(song.Index); + } + else if (item.SelectFunction.Target is Config.Playlist playlist) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist, Strings.MenuPlaylist)); + if (playlist.Songs.Count > 0 + && md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(false); + _curPlaylist = playlist; + Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + _endSoundtableItem.Sensitive = true; + SetAndLoadNextPlaylistSong(); + } + } + } + private void SetAndLoadSequence(long index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + private void SetAndLoadNextPlaylistSong() + { + if (_remainingSequences.Count == 0) + { + _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSequences.Any(); + } + } + long nextSequence = _remainingSequences[0]; + _remainingSequences.RemoveAt(0); + SetAndLoadSequence(nextSequence); + } + private void ResetPlaylistStuff(bool enableds) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _playlistPlaying = false; + _curPlaylist = null; + _curSong = -1; + _remainingSequences.Clear(); + _playedSequences.Clear(); + _endSoundtableItem.Sensitive = false; + _sequenceNumberSpinButton.Sensitive = _sequencesListView.Sensitive = enableds; + } + private void EndCurrentPlaylist(object? sender, EventArgs? e) + { + var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.YesNo, string.Format(Strings.EndPlaylistBody, Strings.MenuPlaylist)); + if (md.Run() == (int)ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(object? sender, EventArgs? e) + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = new FileChooserNative( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, "Open", "Cancel"); // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction, followed by the accept and cancel button names + + if (d.Run() != (int)ResponseType.Accept) + { + return; + } + + DisposeEngine(); + try + { + _ = new DSEEngine(d.CurrentFolder); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenDSE, ex); + return; + } + + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.NoShowAll = true; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); // Ensures disposal of the dialog when closed + } + private void OpenAlphaDream(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenAlphaDream, ex); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = true; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = true; + + d.Destroy(); + } + private void OpenMP2K(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterGBA = new FileFilter() + { + Name = Strings.GTKFilterOpenGBA + }; + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + if (Engine.Instance != null) + { + DisposeEngine(); + } + try + { + _ = new MP2KEngine(File.ReadAllBytes(d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenMP2K, ex); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = true; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + private void OpenSDAT(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, "Open", "Cancel"); + + FileFilter filterSDAT = new FileFilter() + { + Name = Strings.GTKFilterOpenSDAT + }; + filterSDAT.AddPattern("*.sdat"); + FileFilter allFiles = new FileFilter() + { + Name = Strings.GTKAllFiles + }; + allFiles.AddPattern("*.*"); + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + DisposeEngine(); + try + { + _ = new SDATEngine(new SDAT(File.ReadAllBytes(d.Filename))); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorOpenSDAT, ex); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.NoShowAll = false; + _exportDLSItem.Visible = false; + _exportMIDIItem.Visible = false; + _exportSF2Item.Visible = false; + + d.Destroy(); + } + + private void ExportDLS(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveDLS + }; + ff.AddPattern("*.dls"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_DLS.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveDLS, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveDLS, ex); + } + + d.Destroy(); + } + private void ExportMIDI(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, "Save", "Cancel"); + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveMIDI + }; + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs + { + SaveCommandsBeforeTranspose = true, + ReverseVolume = false, + TimeSignatures = new List<(int AbsoluteTick, (byte Numerator, byte Denominator))> + { + (0, (4, 4)), + }, + }; + + try + { + p.SaveAsMIDI(d.Filename, args); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveMIDI, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveMIDI, ex); + } + } + private void ExportSF2(object? sender, EventArgs? e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + var d = new FileChooserNative( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(cfg.GetGameName()); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveSF2 + }; + ff.AddPattern("*.sf2"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + try + { + AlphaDreamSoundFontSaver_SF2.Save(cfg, d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveSF2, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveSF2, ex); + } + } + private void ExportWAV(object? sender, EventArgs? e) + { + var d = new FileChooserNative( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, "Save", "Cancel"); + + d.SetFilename(Engine.Instance!.Config.GetSongName((long)_sequenceNumberSpinButton.Value)); + + FileFilter ff = new FileFilter() + { + Name = Strings.GTKFilterSaveWAV + }; + ff.AddPattern("*.wav"); + d.AddFilter(ff); + + if (d.Run() != (int)ResponseType.Accept) + { + d.Destroy(); + return; + } + + Stop(); + + IPlayer player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(d.Filename); + new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, string.Format(Strings.SuccessSaveWAV, d.Filename)); + } + catch (Exception ex) + { + new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Strings.ErrorSaveWAV, ex); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + //bool timerValue; // Used for updating _positionAdjustment to be in sync with _timer + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; + _buttonPause.Label = Strings.PlayerPause; + GlobalConfig.Init(); + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance.RefreshRate); + + // Experimental attempt for _positionAdjustment to be synchronized with _timer + //timerValue = _timer.Equals(_positionAdjustment); + //timerValue.CompareTo(_timer); + + _timer.Start(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.Pause(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + } + private void TogglePlayback(object? sender, EventArgs? e) + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence(object? sender, EventArgs? e) + { + long prevSequence; + if (_playlistPlaying) + { + int index = _playedSequences.Count - 1; + prevSequence = _playedSequences[index]; + _playedSequences.RemoveAt(index); + _playedSequences.Insert(0, _curSong); + } + else + { + prevSequence = (long)_sequenceNumberSpinButton.Value - 1; + } + SetAndLoadSequence(prevSequence); + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + SetAndLoadNextPlaylistSong(); + } + else + { + SetAndLoadSequence((long)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + { + _sequencesListStore.AppendValues(playlist); + //_sequencesListStore.AppendValues(playlist.Songs.Select(s => new TreeView(_sequencesListStore)).ToArray()); + } + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this UI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + ShowAll(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + _sequencesListView.SelectionGet -= SequencesListView_SelectionGet; + _sequenceNumberAdjustment.ValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + _sequencesListView.Selection.SelectFunction = null; + _sequencesListView.Data.Clear(); + _sequencesListView.SelectionGet += SequencesListView_SelectionGet; + _sequenceNumberSpinButton.ValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void UpdateUI(object? sender, EventArgs? e) + { + if (_stopUI) + { + _stopUI = false; + if (_playlistPlaying) + { + _playedSequences.Add(_curSong); + } + else + { + Stop(); + } + } + else + { + UpdatePositionIndicators(Engine.Instance!.Player.LoadedSong!.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + _positionAdjustment.Value = ticks; // A Gtk.Adjustment field must be used here to avoid issues + } + } + } +} diff --git a/VG Music Studio - GTK3/Program.cs b/VG Music Studio - GTK3/Program.cs new file mode 100644 index 0000000..0f13fcc --- /dev/null +++ b/VG Music Studio - GTK3/Program.cs @@ -0,0 +1,23 @@ +using Gtk; +using System; + +namespace Kermalis.VGMusicStudio.GTK3 +{ + internal class Program + { + [STAThread] + public static void Main(string[] args) + { + Application.Init(); + + var app = new Application("org.Kermalis.VGMusicStudio.GTK3", GLib.ApplicationFlags.None); + app.Register(GLib.Cancellable.Current); + + var win = new MainWindow(); + app.AddWindow(win); + + win.Show(); + Application.Run(); + } + } +} diff --git a/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj new file mode 100644 index 0000000..f78e051 --- /dev/null +++ b/VG Music Studio - GTK3/VG Music Studio - GTK3.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0 + + + + + + + + + + + diff --git a/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs new file mode 100644 index 0000000..ebd2741 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/Gtk.cs @@ -0,0 +1,199 @@ +//using System; +//using System.IO; +//using System.Reflection; +//using System.Runtime.InteropServices; +//using Gtk.Internal; + +//namespace Gtk; + +//internal partial class AlertDialog : GObject.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// [DllImport("Gtk", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint InternalNew(string format); + +// private static IntPtr ObjPtr; + +// internal static AlertDialog New(string format) +// { +// ObjPtr = InternalNew(format); +// return new AlertDialog(ObjPtr, true); +// } +//} + +//internal partial class FileDialog : GObject.Object +//{ +// [DllImport("GObject", EntryPoint = "g_object_unref")] +// private static extern void InternalUnref(nint obj); + +// [DllImport("Gio", EntryPoint = "g_task_return_value")] +// private static extern void InternalReturnValue(nint task, nint result); + +// [DllImport("Gio", EntryPoint = "g_file_get_path")] +// private static extern nint InternalGetPath(nint file); + +// [DllImport("Gtk", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void InternalLoadFromData(nint provider, string data, int length); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint InternalNew(); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint InternalGetInitialFile(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint InternalGetInitialFolder(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string InternalGetInitialName(nint dialog); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void InternalSetTitle(nint dialog, string title); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void InternalSetFilters(nint dialog, nint filters); + +// internal delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open")] +// private static extern void InternalOpen(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint InternalOpenFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save")] +// private static extern void InternalSave(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint InternalSaveFinish(nint dialog, nint result, nint error); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void InternalSelectFolder(nint dialog, nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data); + +// [DllImport("Gtk", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint InternalSelectFolderFinish(nint dialog, nint result, nint error); + + +// private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +// private static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +// private static bool IsFreeBSD() => RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); +// private static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + +// private static IntPtr ObjPtr; + +// // Based on the code from the Nickvision Application template https://github.com/NickvisionApps/Application +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L50 +// private static void ImportNativeLibrary() => NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), LibraryImportResolver); + +// // Code reference: https://github.com/NickvisionApps/Application/blob/28e3307b8242b2d335f8f65394a03afaf213363a/NickvisionApplication.GNOME/Program.cs#L136 +// private static IntPtr LibraryImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) +// { +// string fileName; +// if (IsWindows()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0-0.dll", +// "Gio" => "libgio-2.0-0.dll", +// "Gtk" => "libgtk-4-1.dll", +// _ => libraryName +// }; +// } +// else if (IsMacOS()) +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.0.dylib", +// "Gio" => "libgio-2.0.0.dylib", +// "Gtk" => "libgtk-4.1.dylib", +// _ => libraryName +// }; +// } +// else +// { +// fileName = libraryName switch +// { +// "GObject" => "libgobject-2.0.so.0", +// "Gio" => "libgio-2.0.so.0", +// "Gtk" => "libgtk-4.so.1", +// _ => libraryName +// }; +// } +// return NativeLibrary.Load(fileName, assembly, searchPath); +// } + +// private FileDialog(IntPtr handle, bool ownedRef) : base(handle, ownedRef) +// { +// } + +// // GtkFileDialog* gtk_file_dialog_new (void) +// internal static FileDialog New() +// { +// ImportNativeLibrary(); +// ObjPtr = InternalNew(); +// return new FileDialog(ObjPtr, true); +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Open(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalOpen(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint OpenFinish(nint result, nint error) +// { +// return InternalOpenFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void Save(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSave(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SaveFinish(nint result, nint error) +// { +// return InternalSaveFinish(ObjPtr, result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// internal void SelectFolder(nint parent, nint cancellable, GAsyncReadyCallback callback, nint user_data) => InternalSelectFolder(ObjPtr, parent, cancellable, callback, user_data); + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// internal nint SelectFolderFinish(nint result, nint error) +// { +// return InternalSelectFolderFinish(ObjPtr, result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// internal nint GetInitialFile() +// { +// return InternalGetInitialFile(ObjPtr); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// internal nint GetInitialFolder() +// { +// return InternalGetInitialFolder(ObjPtr); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// internal string GetInitialName() +// { +// return InternalGetInitialName(ObjPtr); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// internal void SetTitle(string title) => InternalSetTitle(ObjPtr, title); + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// internal void SetFilters(Gio.ListModel filters) => InternalSetFilters(ObjPtr, filters.Handle); + + + + + +// internal static nint GetPath(nint path) +// { +// return InternalGetPath(path); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs new file mode 100644 index 0000000..125c4f7 --- /dev/null +++ b/VG Music Studio - GTK4/ExtraLibBindings/GtkInternal.cs @@ -0,0 +1,425 @@ +//using System; +//using System.Runtime.InteropServices; + +//namespace Gtk.Internal; + +//public partial class AlertDialog : GObject.Internal.Object +//{ +// protected AlertDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint linux_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint macos_gtk_alert_dialog_new(string format); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_alert_dialog_new")] +// private static extern nint windows_gtk_alert_dialog_new(string format); + +// private static IntPtr ObjPtr; + +// public static AlertDialog New(string format) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// ObjPtr = linux_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// ObjPtr = macos_gtk_alert_dialog_new(format); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// ObjPtr = windows_gtk_alert_dialog_new(format); +// } +// return new AlertDialog(ObjPtr, true); +// } +//} + +//public partial class FileDialog : GObject.Internal.Object +//{ +// [DllImport("libgobject-2.0.so.0", EntryPoint = "g_object_unref")] +// private static extern void LinuxUnref(nint obj); + +// [DllImport("libgobject-2.0.0.dylib", EntryPoint = "g_object_unref")] +// private static extern void MacOSUnref(nint obj); + +// [DllImport("libgobject-2.0-0.dll", EntryPoint = "g_object_unref")] +// private static extern void WindowsUnref(nint obj); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_task_return_value")] +// private static extern void LinuxReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_task_return_value")] +// private static extern void MacOSReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_task_return_value")] +// private static extern void WindowsReturnValue(nint task, nint result); + +// [DllImport("libgio-2.0.so.0", EntryPoint = "g_file_get_path")] +// private static extern string LinuxGetPath(nint file); + +// [DllImport("libgio-2.0.0.dylib", EntryPoint = "g_file_get_path")] +// private static extern string MacOSGetPath(nint file); + +// [DllImport("libgio-2.0-0.dll", EntryPoint = "g_file_get_path")] +// private static extern string WindowsGetPath(nint file); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void LinuxLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void MacOSLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_css_provider_load_from_data")] +// private static extern void WindowsLoadFromData(nint provider, string data, int length); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint LinuxNew(); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint MacOSNew(); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_new")] +// private static extern nint WindowsNew(); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint LinuxGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint MacOSGetInitialFile(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_file")] +// private static extern nint WindowsGetInitialFile(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint LinuxGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint MacOSGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_folder")] +// private static extern nint WindowsGetInitialFolder(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string LinuxGetInitialName(nint dialog); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string MacOSGetInitialName(nint dialog); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_get_initial_name")] +// private static extern string WindowsGetInitialName(nint dialog); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void LinuxSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void MacOSSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_title")] +// private static extern void WindowsSetTitle(nint dialog, string title); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void LinuxSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void MacOSSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_set_filters")] +// private static extern void WindowsSetFilters(nint dialog, Gio.Internal.ListModel filters); + +// public delegate void GAsyncReadyCallback(nint source, nint res, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open")] +// private static extern void LinuxOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open")] +// private static extern void MacOSOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open")] +// private static extern void WindowsOpen(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint LinuxOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint MacOSOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_open_finish")] +// private static extern nint WindowsOpenFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save")] +// private static extern void LinuxSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save")] +// private static extern void MacOSSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save")] +// private static extern void WindowsSave(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint LinuxSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint MacOSSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_save_finish")] +// private static extern nint WindowsSaveFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void LinuxSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void MacOSSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder")] +// private static extern void WindowsSelectFolder(nint dialog, Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, nint user_data); + +// [DllImport("libgtk-4.so.1", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint LinuxSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4.1.dylib", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint MacOSSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// [DllImport("libgtk-4-1.dll", EntryPoint = "gtk_file_dialog_select_folder_finish")] +// private static extern nint WindowsSelectFolderFinish(nint dialog, Gio.Internal.AsyncResult result, GLib.Internal.Error error); + +// private static IntPtr ObjPtr; +// private static IntPtr UserData; +// private GAsyncReadyCallback callbackHandle { get; set; } +// private static IntPtr FilePath; + +// private FileDialog(IntPtr handle, bool ownedRef) : base() +// { +// } + +// // void gtk_file_dialog_open (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Open(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpen(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_open_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File OpenFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSOpenFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsOpenFinish(ObjPtr, result, error); +// } +// return OpenFinish(result, error); +// } + +// // void gtk_file_dialog_save (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void Save(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSave(ObjPtr, parent, cancellable, callback, user_data); +// } +// } + +// // GFile* gtk_file_dialog_save_finish (GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SaveFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSaveFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSaveFinish(ObjPtr, result, error); +// } +// return SaveFinish(result, error); +// } + +// // void gtk_file_dialog_select_folder (GtkFileDialog* self, GtkWindow* parent, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) +// public void SelectFolder(Gtk.Internal.Window parent, Gio.Internal.Cancellable cancellable, Gio.Internal.AsyncReadyCallback callback, int user_data) +// { +// // if (cancellable is null) +// // { +// // cancellable = Gio.Internal.Cancellable.New(); +// // cancellable.Handle.Equals(IntPtr.Zero); +// // cancellable.Cancel(); +// // UserData = IntPtr.Zero; +// // } + + +// // callback = (source, res) => +// // { +// // var data = new nint(); +// // callbackHandle.BeginInvoke(source.Handle, res.Handle, data, callback, callback); +// // }; +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolder(ObjPtr, parent, cancellable, callback, user_data); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolder(ObjPtr, parent, cancellable, callback, UserData); +// } +// } + +// // GFile* gtk_file_dialog_select_folder_finish(GtkFileDialog* self, GAsyncResult* result, GError** error) +// public Gio.Internal.File SelectFolderFinish(Gio.Internal.AsyncResult result, GLib.Internal.Error error) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSelectFolderFinish(ObjPtr, result, error); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSelectFolderFinish(ObjPtr, result, error); +// } +// return SelectFolderFinish(result, error); +// } + +// // GFile* gtk_file_dialog_get_initial_file (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFile() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFile(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFile(ObjPtr); +// } +// return GetInitialFile(); +// } + +// // GFile* gtk_file_dialog_get_initial_folder (GtkFileDialog* self) +// public Gio.Internal.File GetInitialFolder() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetInitialFolder(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetInitialFolder(ObjPtr); +// } +// return GetInitialFolder(); +// } + +// // const char* gtk_file_dialog_get_initial_name (GtkFileDialog* self) +// public string GetInitialName() +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// return MacOSGetInitialName(ObjPtr); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// return WindowsGetInitialName(ObjPtr); +// } +// return GetInitialName(); +// } + +// // void gtk_file_dialog_set_title (GtkFileDialog* self, const char* title) +// public void SetTitle(string title) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetTitle(ObjPtr, title); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetTitle(ObjPtr, title); +// } +// } + +// // void gtk_file_dialog_set_filters (GtkFileDialog* self, GListModel* filters) +// public void SetFilters(Gio.Internal.ListModel filters) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// LinuxSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSSetFilters(ObjPtr, filters); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsSetFilters(ObjPtr, filters); +// } +// } + + + + + +// public string GetPath(nint path) +// { +// if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) +// { +// return LinuxGetPath(path); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) +// { +// MacOSGetPath(FilePath); +// } +// else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +// { +// WindowsGetPath(FilePath); +// } +// return FilePath.ToString(); +// } +//} \ No newline at end of file diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs new file mode 100644 index 0000000..0d5de31 --- /dev/null +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -0,0 +1,1365 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.GBA.AlphaDream; +using Kermalis.VGMusicStudio.Core.GBA.MP2K; +using Kermalis.VGMusicStudio.Core.NDS.DSE; +using Kermalis.VGMusicStudio.Core.NDS.SDAT; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using GObject; +using Adw; +using Gtk; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Timers; +using System.Runtime.InteropServices; +using System.Diagnostics; + +using Application = Adw.Application; +using Window = Adw.Window; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class MainWindow : Window +{ + private int _duration = 0; + private int _position = 0; + + private PlayingPlaylist? _playlist; + private int _curSong = -1; + + private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. + + private bool _songEnded = false; + private bool _stopUI = false; + private bool _autoplay = false; + + public static Window Instance { get; private set; } + + #region Widgets + + // Buttons + private readonly Button _buttonPlay, _buttonPause, _buttonStop; + + // A Box specifically made to contain two contents inside + private readonly Box _splitContainerBox; + + // Spin Button for the numbered tracks + private readonly SpinButton _sequenceNumberSpinButton; + + // Timer + private readonly Timer _timer; + + // Popover Menu Bar + private readonly PopoverMenuBar _popoverMenuBar; + + // LibAdwaita Header Bar + private readonly Adw.HeaderBar _headerBar; + + // LibAdwaita Application + private readonly Adw.Application _app; + + // LibAdwaita Message Dialog + private Adw.MessageDialog _dialog; + + // Menu Model + //private readonly Gio.MenuModel _mainMenu; + + // Menus + private readonly Gio.Menu _mainMenu, _fileMenu, _dataMenu, _playlistMenu; + + // Menu Labels + private readonly Label _fileLabel, _dataLabel, _playlistLabel; + + // Menu Items + private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + + // Menu Actions + private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, + _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, + _soundSequenceAction; + + private Signal _openDSESignal; + + private SignalHandler _openDSEHandler; + + // Main Box + private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; + + // Volume Button to indicate volume status + private readonly VolumeButton _volumeButton; + + // One Scale controling volume and one Scale for the sequenced track + private Scale _volumeScale, _positionScale; + + // Mouse Click Gesture + private GestureClick _positionGestureClick, _sequencesGestureClick; + + // Event Controller + private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, + _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, + _sequencesEventController; + + // Adjustments are for indicating the numbers and the position of the scale + private readonly Adjustment _sequenceNumberAdjustment; + //private ScaleControl _positionAdjustment; + + // Sound Sequence List + //private SignalListItemFactory _soundSequenceFactory; + //private SoundSequenceList _soundSequenceList; + //private SoundSequenceListItem _soundSequenceListItem; + //private SortListModel _soundSequenceSortListModel; + //private ListBox _soundSequenceListBox; + //private DropDown _soundSequenceDropDown; + + // Error Handle + private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + + // Signal + private Signal _signal; + + // Callback + private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _openCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _selectFolderCallback { get; set; } + private Gio.Internal.AsyncReadyCallback _exceptionCallback { get; set; } + + #endregion + + public MainWindow(Application app) + { + // Main Window + SetDefaultSize(500, 300); // Sets the default size of the Window + Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" + _app = app; + + // Configures SetVolumeScale method with the MixerVolumeChanged Event action + Mixer_NAudio.VolumeChanged += SetVolumeScale; + + // LibAdwaita Header Bar + _headerBar = Adw.HeaderBar.New(); + _headerBar.SetShowEndTitleButtons(true); + + // Main Menu + _mainMenu = Gio.Menu.New(); + + // Popover Menu Bar + _popoverMenuBar = PopoverMenuBar.NewFromModel(_mainMenu); // This will ensure that the menu model is used inside of the PopoverMenuBar widget + _popoverMenuBar.MenuModel = _mainMenu; + _popoverMenuBar.MnemonicActivate(true); + + // File Menu + _fileMenu = Gio.Menu.New(); + + _fileLabel = Label.NewWithMnemonic(Strings.MenuFile); + _fileLabel.GetMnemonicKeyval(); + _fileLabel.SetUseUnderline(true); + _fileItem = Gio.MenuItem.New(_fileLabel.GetLabel(), null); + _fileLabel.SetMnemonicWidget(_popoverMenuBar); + _popoverMenuBar.AddMnemonicLabel(_fileLabel); + _fileItem.SetSubmenu(_fileMenu); + + _openDSEItem = Gio.MenuItem.New(Strings.MenuOpenDSE, "app.openDSE"); + _openDSEAction = Gio.SimpleAction.New("openDSE", null); + _openDSEItem.SetActionAndTargetValue("app.openDSE", null); + _app.AddAction(_openDSEAction); + _openDSEAction.OnActivate += OpenDSE; + _fileMenu.AppendItem(_openDSEItem); + _openDSEItem.Unref(); + + _openSDATItem = Gio.MenuItem.New(Strings.MenuOpenSDAT, "app.openSDAT"); + _openSDATAction = Gio.SimpleAction.New("openSDAT", null); + _openSDATItem.SetActionAndTargetValue("app.openSDAT", null); + _app.AddAction(_openSDATAction); + _openSDATAction.OnActivate += OpenSDAT; + _fileMenu.AppendItem(_openSDATItem); + _openSDATItem.Unref(); + + _openAlphaDreamItem = Gio.MenuItem.New(Strings.MenuOpenAlphaDream, "app.openAlphaDream"); + _openAlphaDreamAction = Gio.SimpleAction.New("openAlphaDream", null); + _app.AddAction(_openAlphaDreamAction); + _openAlphaDreamAction.OnActivate += OpenAlphaDream; + _fileMenu.AppendItem(_openAlphaDreamItem); + _openAlphaDreamItem.Unref(); + + _openMP2KItem = Gio.MenuItem.New(Strings.MenuOpenMP2K, "app.openMP2K"); + _openMP2KAction = Gio.SimpleAction.New("openMP2K", null); + _app.AddAction(_openMP2KAction); + _openMP2KAction.OnActivate += OpenMP2K; + _fileMenu.AppendItem(_openMP2KItem); + _openMP2KItem.Unref(); + + _mainMenu.AppendItem(_fileItem); // Note: It must append the menu item variable (_fileItem), not the file menu variable (_fileMenu) itself + _fileItem.Unref(); + + // Data Menu + _dataMenu = Gio.Menu.New(); + + _dataLabel = Label.NewWithMnemonic(Strings.MenuData); + _dataLabel.GetMnemonicKeyval(); + _dataLabel.SetUseUnderline(true); + _dataItem = Gio.MenuItem.New(_dataLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_dataLabel); + _dataItem.SetSubmenu(_dataMenu); + + _exportDLSItem = Gio.MenuItem.New(Strings.MenuSaveDLS, "app.exportDLS"); + _exportDLSAction = Gio.SimpleAction.New("exportDLS", null); + _app.AddAction(_exportDLSAction); + _exportDLSAction.Enabled = false; + _exportDLSAction.OnActivate += ExportDLS; + _dataMenu.AppendItem(_exportDLSItem); + _exportDLSItem.Unref(); + + _exportSF2Item = Gio.MenuItem.New(Strings.MenuSaveSF2, "app.exportSF2"); + _exportSF2Action = Gio.SimpleAction.New("exportSF2", null); + _app.AddAction(_exportSF2Action); + _exportSF2Action.Enabled = false; + _exportSF2Action.OnActivate += ExportSF2; + _dataMenu.AppendItem(_exportSF2Item); + _exportSF2Item.Unref(); + + _exportMIDIItem = Gio.MenuItem.New(Strings.MenuSaveMIDI, "app.exportMIDI"); + _exportMIDIAction = Gio.SimpleAction.New("exportMIDI", null); + _app.AddAction(_exportMIDIAction); + _exportMIDIAction.Enabled = false; + _exportMIDIAction.OnActivate += ExportMIDI; + _dataMenu.AppendItem(_exportMIDIItem); + _exportMIDIItem.Unref(); + + _exportWAVItem = Gio.MenuItem.New(Strings.MenuSaveWAV, "app.exportWAV"); + _exportWAVAction = Gio.SimpleAction.New("exportWAV", null); + _app.AddAction(_exportWAVAction); + _exportWAVAction.Enabled = false; + _exportWAVAction.OnActivate += ExportWAV; + _dataMenu.AppendItem(_exportWAVItem); + _exportWAVItem.Unref(); + + _mainMenu.AppendItem(_dataItem); + _dataItem.Unref(); + + // Playlist Menu + _playlistMenu = Gio.Menu.New(); + + _playlistLabel = Label.NewWithMnemonic(Strings.MenuPlaylist); + _playlistLabel.GetMnemonicKeyval(); + _playlistLabel.SetUseUnderline(true); + _playlistItem = Gio.MenuItem.New(_playlistLabel.GetLabel(), null); + _popoverMenuBar.AddMnemonicLabel(_playlistLabel); + _playlistItem.SetSubmenu(_playlistMenu); + + _endPlaylistItem = Gio.MenuItem.New(Strings.MenuEndPlaylist, "app.endPlaylist"); + _endPlaylistAction = Gio.SimpleAction.New("endPlaylist", null); + _app.AddAction(_endPlaylistAction); + _endPlaylistAction.Enabled = false; + _endPlaylistAction.OnActivate += EndCurrentPlaylist; + _playlistMenu.AppendItem(_endPlaylistItem); + _endPlaylistItem.Unref(); + + _mainMenu.AppendItem(_playlistItem); + _playlistItem.Unref(); + + // Buttons + _buttonPlay = new Button() { Sensitive = false, Label = Strings.PlayerPlay }; + _buttonPlay.OnClicked += (o, e) => Play(); + _buttonPause = new Button() { Sensitive = false, Label = Strings.PlayerPause }; + _buttonPause.OnClicked += (o, e) => Pause(); + _buttonStop = new Button() { Sensitive = false, Label = Strings.PlayerStop }; + _buttonStop.OnClicked += (o, e) => Stop(); + + // Spin Button + _sequenceNumberAdjustment = Adjustment.New(0, 0, -1, 1, 1, 1); + _sequenceNumberSpinButton = SpinButton.New(_sequenceNumberAdjustment, 1, 0); + _sequenceNumberSpinButton.Sensitive = false; + _sequenceNumberSpinButton.Value = 0; + //_sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + + // Timer + _timer = new Timer(); + _timer.Elapsed += Timer_Tick; + + // Volume Scale + _volumeScale = Scale.NewWithRange(Orientation.Horizontal, 0, 100, 1); + _volumeScale.Sensitive = false; + _volumeScale.ShowFillLevel = true; + _volumeScale.DrawValue = false; + _volumeScale.WidthRequest = 250; + + // Position Scale + _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup + _positionScale.Sensitive = false; + _positionScale.ShowFillLevel = true; + _positionScale.DrawValue = false; + _positionScale.WidthRequest = 250; + _positionScale.RestrictToFillLevel = false; + _positionScale.SetRange(1, double.MaxValue); + _positionGestureClick = GestureClick.New(); + if (_positionGestureClick.Button == 1) + { + _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; + _positionScale.OnValueChanged -= PositionScale_MouseButtonRelease; + _positionScale.OnValueChanged += PositionScale_MouseButtonPress; + _positionScale.OnValueChanged -= PositionScale_MouseButtonPress; + } + //_positionScale.Focusable = true; + //_positionScale.HasOrigin = true; + //_positionScale.Visible = true; + //_positionScale.FillLevel = _positionAdjustment.Upper; + //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading + //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + + // Sound Sequence List + //_soundSequenceList = new SoundSequenceList { Sensitive = false }; + //_soundSequenceFactory = SignalListItemFactory.New(); + //_soundSequenceListBox = ListBox.New(); + //_soundSequenceDropDown = DropDown.New(Gio.ListStore.New(DropDown.GetGType()), new ConstantExpression(IntPtr.Zero)); + //_soundSequenceDropDown.OnActivate += SequencesListView_SelectionGet; + //_soundSequenceDropDown.ListFactory = _soundSequenceFactory; + //_soundSequenceAction = Gio.SimpleAction.New("soundSequenceList", null); + //_soundSequenceAction.OnActivate += SequencesListView_SelectionGet; + + // Main display + _mainBox = Box.New(Orientation.Vertical, 4); + _configButtonBox = Box.New(Orientation.Horizontal, 2); + _configButtonBox.Halign = Align.Center; + _configPlayerButtonBox = Box.New(Orientation.Horizontal, 3); + _configPlayerButtonBox.Halign = Align.Center; + _configSpinButtonBox = Box.New(Orientation.Horizontal, 1); + _configSpinButtonBox.Halign = Align.Center; + _configSpinButtonBox.WidthRequest = 100; + _configScaleBox = Box.New(Orientation.Horizontal, 2); + _configScaleBox.Halign = Align.Center; + + _configPlayerButtonBox.MarginStart = 40; + _configPlayerButtonBox.MarginEnd = 40; + _configButtonBox.Append(_configPlayerButtonBox); + _configSpinButtonBox.MarginStart = 100; + _configSpinButtonBox.MarginEnd = 100; + _configButtonBox.Append(_configSpinButtonBox); + + _configPlayerButtonBox.Append(_buttonPlay); + _configPlayerButtonBox.Append(_buttonPause); + _configPlayerButtonBox.Append(_buttonStop); + + if (_configSpinButtonBox.GetFirstChild() == null) + { + _sequenceNumberSpinButton.Hide(); + _configSpinButtonBox.Append(_sequenceNumberSpinButton); + } + + _volumeScale.MarginStart = 20; + _volumeScale.MarginEnd = 20; + _configScaleBox.Append(_volumeScale); + _positionScale.MarginStart = 20; + _positionScale.MarginEnd = 20; + _configScaleBox.Append(_positionScale); + + _mainBox.Append(_headerBar); + _mainBox.Append(_popoverMenuBar); + _mainBox.Append(_configButtonBox); + _mainBox.Append(_configScaleBox); + //_mainBox.Append(_soundSequenceListBox); + + SetContent(_mainBox); + + Instance = this; + + Show(); + + // Ensures the entire application gets closed when the main window is closed + OnCloseRequest += (sender, args) => + { + DisposeEngine(); // Engine must be disposed first, otherwise the window will softlock when closing + _app.Quit(); + return true; + }; + } + + // When the value is changed on the volume scale + private void VolumeScale_ValueChanged(object sender, EventArgs e) + { + Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeScale.Adjustment.Upper)); + } + + // Sets the volume scale to the specified position + public void SetVolumeScale(float volume) + { + _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; + _volumeScale.Adjustment!.Value = (int)(volume * _volumeScale.Adjustment.Upper); + _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + } + + private bool _positionScaleFree = true; + private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + Engine.Instance!.Player.SetSongPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released + _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + } + private void PositionScale_MouseButtonPress(object sender, EventArgs args) + { + if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button + { + _positionScaleFree = false; + } + } + + private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) + { + //_sequencesGestureClick.OnBegin -= SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + + int index = (int)_sequenceNumberAdjustment.Value; + Stop(); + this.Title = ConfigUtils.PROGRAM_NAME; + //_sequencesListView.Margin = 0; + //_songInfo.Reset(); + bool success; + try + { + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Engine.Instance!.Player.LoadSong(index); + success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, string.Format(Strings.ErrorLoadSong, Engine.Instance!.Config.GetSongName(index))); + success = false; + } + + //_trackViewer?.UpdateTracks(); + if (success) + { + Config config = Engine.Instance.Config; + List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + int songIndex = songs.FindIndex(s => s.Index == index); + if (songIndex != -1) + { + this.Title = $"{ConfigUtils.PROGRAM_NAME} - {songs[songIndex].Name}"; // TODO: Make this a func + //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox + } + //_positionScale.Adjustment!.Upper = double.MaxValue; + _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); + _positionScale.SetRange(0, _duration); + //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; + //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; + _positionScale.Show(); + //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); + if (_autoplay) + { + Play(); + } + } + else + { + //_songInfo.SetNumTracks(0); + } + _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; + _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; + + _autoplay = true; + //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + } + //private void SequencesListView_SelectionGet(object sender, EventArgs e) + //{ + // var item = _soundSequenceList.SelectedItem; + // if (item is Config.Song song) + // { + // SetAndLoadSequence(song.Index); + // } + // else if (item is Config.Playlist playlist) + // { + // if (playlist.Songs.Count > 0 + // && FlexibleMessageBox.Show(string.Format(Strings.PlayPlaylistBody, Environment.NewLine + playlist), Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + // { + // ResetPlaylistStuff(false); + // _curPlaylist = playlist; + // Engine.Instance.Player.ShouldFadeOut = _playlistPlaying = true; + // Engine.Instance.Player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + // _endPlaylistAction.Enabled = true; + // SetAndLoadNextPlaylistSong(); + // } + // } + //} + public void SetAndLoadSequence(int index) + { + _curSong = index; + if (_sequenceNumberSpinButton.Value == index) + { + SequenceNumberSpinButton_ValueChanged(null, null); + } + else + { + _sequenceNumberSpinButton.Value = index; + } + } + + //private void SetAndLoadNextPlaylistSong() + //{ + // if (_remainingSequences.Count == 0) + // { + // _remainingSequences.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + // if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + // { + // _remainingSequences.Any(); + // } + // } + // long nextSequence = _remainingSequences[0]; + // _remainingSequences.RemoveAt(0); + // SetAndLoadSequence(nextSequence); + //} + private void ResetPlaylistStuff(bool spinButtonAndListBoxEnabled) + { + if (Engine.Instance != null) + { + Engine.Instance.Player.ShouldFadeOut = false; + } + _curSong = -1; + _endPlaylistAction.Enabled = false; + _sequenceNumberSpinButton.Sensitive = /* _soundSequenceListBox.Sensitive = */ spinButtonAndListBoxEnabled; + } + private void EndCurrentPlaylist(object sender, EventArgs e) + { + if (FlexibleMessageBox.Show(Strings.EndPlaylistBody, Strings.MenuPlaylist, ButtonsType.YesNo) == ResponseType.Yes) + { + ResetPlaylistStuff(true); + } + } + + private void OpenDSE(Gio.SimpleAction sender, EventArgs e) + { + if (Gtk.Functions.GetMinorVersion() <= 8) // There's a bug in Gtk 4.09 and later that has broken FileChooserNative functionality, causing icons and thumbnails to appear broken + { + // To allow the dialog to display in native windowing format, FileChooserNative is used instead of FileChooserDialog + var d = FileChooserNative.New( + Strings.MenuOpenDSE, // The title shown in the folder select dialog window + this, // The parent of the dialog window, is the MainWindow itself + FileChooserAction.SelectFolder, // To ensure it becomes a folder select dialog window, SelectFolder is used as the FileChooserAction + "Select Folder", // Followed by the accept + "Cancel"); // and cancel button names. + + d.SetModal(true); + + // Note: Blocking APIs were removed in GTK4, which means the code will proceed to run and return to the main loop, even when a dialog is displayed. + // Instead, it's handled by the OnResponse event function when it re-enters upon selection. + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) // In GTK4, the 'Gtk.FileChooserNative.Action' property is used for determining the button selection on the dialog. The 'Gtk.Dialog.Run' method was removed in GTK4, due to it being a non-GUI function and going against GTK's main objectives. + { + d.Unref(); + return; + } + var path = d.GetCurrentFolder()!.GetPath() ?? ""; + d.GetData(path); + OpenDSEFinish(path); + d.Unref(); // Ensures disposal of the dialog when closed + return; + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenDSE); + + _selectFolderCallback = (source, res, data) => + { + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out ErrorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + OpenDSEFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + //d.SelectFolder(Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + } + private void OpenDSEFinish(string path) + { + DisposeEngine(); + try + { + _ = new DSEEngine(path); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); + return; + } + DSEConfig config = DSEEngine.DSEInstance!.Config; + FinishLoading(config.BGMFiles.Length); + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Hide(); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenSDAT(Gio.SimpleAction sender, EventArgs e) + { + var filterSDAT = FileFilter.New(); + filterSDAT.SetName(Strings.FilterOpenSDAT); + filterSDAT.AddPattern("*.sdat"); + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.FilterAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenSDAT, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + d.SetModal(true); + + d.AddFilter(filterSDAT); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenSDATFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenSDAT); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterSDAT); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenSDATFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenSDATFinish(string path) + { + DisposeEngine(); + try + { + using (FileStream stream = File.OpenRead(path)) + { + _ = new SDATEngine(new SDAT(stream)); + } + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenSDAT); + return; + } + + SDATConfig config = SDATEngine.SDATInstance!.Config; + FinishLoading(config.SDAT.INFOBlock.SequenceInfos.NumEntries); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = false; + } + private void OpenAlphaDream(Gio.SimpleAction sender, EventArgs e) + { + var filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.FilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + var allFiles = FileFilter.New(); + allFiles.SetName(Name = Strings.FilterAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenAlphaDream, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + d.SetModal(true); + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + d.GetData(path); + OpenAlphaDreamFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenAlphaDream); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenAlphaDreamFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + } + private void OpenAlphaDreamFinish(string path) + { + DisposeEngine(); + try + { + _ = new AlphaDreamEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorOpenAlphaDream); + return; + } + + AlphaDreamConfig config = AlphaDreamEngine.AlphaDreamInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + _mainMenu.AppendItem(_dataItem); + _mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = true; + _exportMIDIAction.Enabled = false; + _exportSF2Action.Enabled = true; + } + private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) + { + var inFile = GTK4Utils.CreateLoadDialog(["*.gba", "*.srl"], Strings.MenuOpenMP2K, Strings.FilterOpenGBA); + if (inFile is null) + { + return; + } + OpenMP2KFinish(inFile); + //FileFilter filterGBA = FileFilter.New(); + //filterGBA.SetName(Strings.FilterOpenGBA); + //filterGBA.AddPattern("*.gba"); + //filterGBA.AddPattern("*.srl"); + //FileFilter allFiles = FileFilter.New(); + //allFiles.SetName(Strings.FilterAllFiles); + //allFiles.AddPattern("*.*"); + + //if (Gtk.Functions.GetMinorVersion() <= 8) + //{ + // var d = FileChooserNative.New( + // Strings.MenuOpenMP2K, + // this, + // FileChooserAction.Open, + // "Open", + // "Cancel"); + + + // d.AddFilter(filterGBA); + // d.AddFilter(allFiles); + + // d.OnResponse += (sender, e) => + // { + // if (e.ResponseId != (int)ResponseType.Accept) + // { + // d.Unref(); + // return; + // } + // var path = d.GetFile()!.GetPath() ?? ""; + // OpenMP2KFinish(path); + // d.Unref(); + // }; + // d.Show(); + //} + //else + //{ + // var d = FileDialog.New(); + // d.SetTitle(Strings.MenuOpenMP2K); + // var filters = Gio.ListStore.New(FileFilter.GetGType()); + // filters.Append(filterGBA); + // filters.Append(allFiles); + // d.SetFilters(filters); + // _openCallback = (source, res, data) => + // { + // var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + // if (fileHandle != IntPtr.Zero) + // { + // var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + // OpenMP2KFinish(path!); + // filterGBA.Unref(); + // allFiles.Unref(); + // filters.Unref(); + // GObject.Internal.Object.Unref(fileHandle); + // d.Unref(); + // return; + // } + // d.Unref(); + // }; + // Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + // //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //} + } + private void OpenMP2KFinish(string path) + { + if (Engine.Instance is not null) + { + DisposeEngine(); + } + + if (IsWindows()) + { + try + { + _ = new MP2KEngine(File.ReadAllBytes(path)); + } + catch (Exception ex) + { + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + } + else + { + var ex = new PlatformNotSupportedException(); + ExceptionDialog(ex, Strings.ErrorOpenMP2K); + return; + } + + MP2KConfig config = MP2KEngine.MP2KInstance!.Config; + FinishLoading(config.SongTableSizes[0]); + _sequenceNumberSpinButton.Visible = true; + _sequenceNumberSpinButton.Show(); + //_mainMenu.AppendItem(_dataItem); + //_mainMenu.AppendItem(_playlistItem); + _exportDLSAction.Enabled = false; + _exportMIDIAction.Enabled = true; + _exportSF2Action.Enabled = false; + } + private void ExportDLS(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.FilterSaveDLS); + ff.AddPattern("*.dls"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveDLS, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportDLSFinish(cfg, path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveDLS); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportDLSFinish(cfg, path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportDLSFinish(AlphaDreamConfig config, string path) + { + try + { + AlphaDreamSoundFontSaver_DLS.Save(config, path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveDLS, path), Strings.SuccessSaveDLS); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveDLS); + } + } + private void ExportMIDI(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.FilterSaveMIDI); + ff.AddPattern("*.mid"); + ff.AddPattern("*.midi"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveMIDI, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + d.SetCurrentName(Engine.Instance!.Config.GetSongName((int)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportMIDIFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveMIDI); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportMIDIFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportMIDIFinish(string path) + { + MP2KPlayer p = MP2KEngine.MP2KInstance!.Player; + var args = new MIDISaveArgs(true, false, new (int AbsoluteTick, (byte Numerator, byte Denominator))[] + { + (0, (4, 4)), + }); + + try + { + p.SaveAsMIDI(path, args); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveMIDI, path), Strings.SuccessSaveMIDI); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveMIDI); + } + } + private void ExportSF2(Gio.SimpleAction sender, EventArgs e) + { + AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; + + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.FilterSaveSF2); + ff.AddPattern("*.sf2"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveSF2, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(cfg.GetGameName()); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportSF2Finish(path, cfg); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveSF2); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportSF2Finish(path!, cfg); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportSF2Finish(string path, AlphaDreamConfig config) + { + try + { + AlphaDreamSoundFontSaver_SF2.Save(path, config); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveSF2, path), Strings.SuccessSaveSF2); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveSF2); + } + } + private void ExportWAV(Gio.SimpleAction sender, EventArgs e) + { + FileFilter ff = FileFilter.New(); + ff.SetName(Strings.FilterSaveWAV); + ff.AddPattern("*.wav"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuSaveWAV, + this, + FileChooserAction.Save, + "Save", + "Cancel"); + + d.SetCurrentName(Engine.Instance!.Config.GetSongName((int)_sequenceNumberSpinButton.Value)); + d.AddFilter(ff); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + + var path = d.GetFile()!.GetPath() ?? ""; + ExportWAVFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuSaveWAV); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + d.SetFilters(filters); + _saveCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + ExportWAVFinish(path!); + d.Unref(); + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Save(d.Handle, Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + //d.Save(Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + } + private void ExportWAVFinish(string path) + { + Stop(); + + Player player = Engine.Instance.Player; + bool oldFade = player.ShouldFadeOut; + long oldLoops = player.NumLoops; + player.ShouldFadeOut = true; + player.NumLoops = GlobalConfig.Instance.PlaylistSongLoops; + + try + { + player.Record(path); + FlexibleMessageBox.Show(string.Format(Strings.SuccessSaveWAV, path), Strings.SuccessSaveWAV); + } + catch (Exception ex) + { + FlexibleMessageBox.Show(ex, Strings.ErrorSaveWAV); + } + + player.ShouldFadeOut = oldFade; + player.NumLoops = oldLoops; + _stopUI = false; + } + + public void ExceptionDialog(Exception error, string heading) + { + Debug.WriteLine(error.Message); + var md = Adw.MessageDialog.New(this, heading, error.Message); + md.SetModal(true); + md.AddResponse("ok", ("_OK")); + md.SetResponseAppearance("ok", ResponseAppearance.Default); + md.SetDefaultResponse("ok"); + md.SetCloseResponse("ok"); + _exceptionCallback = (source, res, data) => + { + md.Destroy(); + }; + md.Activate(); + md.Show(); + } + + public void LetUIKnowPlayerIsPlaying() + { + // Prevents method from being used if timer is already active + if (_timer.Enabled) + { + return; + } + + // Ensures a GlobalConfig Instance is created if one doesn't exist + if (GlobalConfig.Instance == null) + { + GlobalConfig.Init(); // A new instance needs to be initialized before it can do anything + } + + // Configures the buttons when player is playing a sequenced track + _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them + _buttonPause.Label = Strings.PlayerPause; + _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + _timer.Start(); + Show(); + } + + private void Play() + { + Engine.Instance!.Player.Play(); + LetUIKnowPlayerIsPlaying(); + } + private void Pause() + { + Engine.Instance!.Player.TogglePlaying(); + if (Engine.Instance.Player.State == PlayerState.Paused) + { + _buttonPause.Label = Strings.PlayerUnpause; + _timer.Stop(); + } + else + { + _buttonPause.Label = Strings.PlayerPause; + _timer.Start(); + } + } + private void Stop() + { + if (Engine.Instance == null) + { + return; // This is here to ensure that it returns if the Engine.Instance is null while closing the main window + } + Engine.Instance!.Player.Stop(); + _buttonPause.Sensitive = _buttonStop.Sensitive = false; + _buttonPause.Label = Strings.PlayerPause; + _timer.Stop(); + UpdatePositionIndicators(0L); + Show(); + } + private void TogglePlayback() + { + switch (Engine.Instance!.Player.State) + { + case PlayerState.Stopped: Play(); break; + case PlayerState.Paused: + case PlayerState.Playing: Pause(); break; + } + } + private void PlayPreviousSequence() + { + + if (_playlist is not null) + { + _playlist.UndoThenSetAndLoadPrevSong(this, _curSong); + } + else + { + SetAndLoadSequence((int)_sequenceNumberSpinButton.Value - 1); + } + } + private void PlayNextSong(object? sender, EventArgs? e) + { + if (_playlist is not null) + { + _playlist.AdvanceThenSetAndLoadNextSong(this, _curSong); + } + else + { + SetAndLoadSequence((int)_sequenceNumberSpinButton.Value + 1); + } + } + + private void FinishLoading(long numSongs) + { + Engine.Instance!.Player.SongEnded += SongEnded; + //foreach (Config.Playlist playlist in Engine.Instance.Config.Playlists) + //{ + // _soundSequenceListBox.Insert(Label.New(playlist.Name), playlist.Songs.Count); + // _soundSequenceList.Add(new SoundSequenceListItem(playlist)); + // _soundSequenceList.AddRange(playlist.Songs.Select(s => new SoundSequenceListItem(s)).ToArray()); + //} + _sequenceNumberAdjustment.Upper = numSongs - 1; +#if DEBUG + // [Debug methods specific to this GUI will go in here] +#endif + _autoplay = false; + SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + Show(); + } + private void DisposeEngine() + { + if (Engine.Instance is not null) + { + Stop(); + Engine.Instance.Dispose(); + } + + //_trackViewer?.UpdateTracks(); + Name = ConfigUtils.PROGRAM_NAME; + //_songInfo.SetNumTracks(0); + //_songInfo.ResetMutes(); + ResetPlaylistStuff(false); + UpdatePositionIndicators(0L); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, false, null); + _sequenceNumberAdjustment.OnValueChanged -= SequenceNumberSpinButton_ValueChanged; + _sequenceNumberSpinButton.Visible = false; + _sequenceNumberSpinButton.Value = _sequenceNumberAdjustment.Upper = 0; + //_sequencesListView.Selection.SelectFunction = null; + //_sequencesColumnView.Unref(); + //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; + } + + private void Timer_Tick(object? sender, EventArgs e) + { + if (_songEnded) + { + _songEnded = false; + if (_playlist is not null) + { + _playlist.AdvanceThenSetAndLoadNextSong(this, _curSong); + } + else + { + Stop(); + } + } + else + { + Player player = Engine.Instance!.Player; + UpdatePositionIndicators(player.ElapsedTicks); + } + } + private void SongEnded() + { + _stopUI = true; + } + + // This updates _positionScale and _positionAdjustment to the value specified + // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead + private void UpdatePositionIndicators(long ticks) + { + if (_positionScaleFree) + { + if (ticks < _duration) + { + // TODO: Implement GStreamer functions to replace Gtk.Adjustment + _positionScale.SetRange(1, _duration); + _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues + } + else + { + return; + } + } + } +} diff --git a/VG Music Studio - GTK4/PlayingPlaylist.cs b/VG Music Studio - GTK4/PlayingPlaylist.cs new file mode 100644 index 0000000..e1b1d0d --- /dev/null +++ b/VG Music Studio - GTK4/PlayingPlaylist.cs @@ -0,0 +1,53 @@ +using Kermalis.VGMusicStudio.Core; +using Kermalis.VGMusicStudio.Core.Util; +using Kermalis.VGMusicStudio.GTK4.Util; +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4; + +internal sealed class PlayingPlaylist +{ + public readonly List _playedSongs; + public readonly List _remainingSongs; + public readonly Config.Playlist _curPlaylist; + + public PlayingPlaylist(Config.Playlist play) + { + _playedSongs = new List(); + _remainingSongs = new List(); + _curPlaylist = play; + } + + public void AdvanceThenSetAndLoadNextSong(MainWindow parent, int curSong) + { + _playedSongs.Add(curSong); + SetAndLoadNextSong(parent); + } + public void UndoThenSetAndLoadPrevSong(MainWindow parent, int curSong) + { + int prevIndex = _playedSongs.Count - 1; + int prevSong = _playedSongs[prevIndex]; + _playedSongs.RemoveAt(prevIndex); + _remainingSongs.Insert(0, curSong); + parent.SetAndLoadSequence(prevSong); + } + public void SetAndLoadNextSong(MainWindow parent) + { + if (_remainingSongs.Count == 0) + { + _remainingSongs.AddRange(_curPlaylist.Songs.Select(s => s.Index)); + if (GlobalConfig.Instance.PlaylistMode == PlaylistMode.Random) + { + _remainingSongs.Shuffle(); + } + } + int nextSong = _remainingSongs[0]; + _remainingSongs.RemoveAt(0); + parent.SetAndLoadSequence(nextSong); + } +} diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs new file mode 100644 index 0000000..a99da5f --- /dev/null +++ b/VG Music Studio - GTK4/Program.cs @@ -0,0 +1,48 @@ +using Adw; +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4 +{ + internal class Program + { + private readonly Adw.Application app; + + // public Theme Theme => Theme.ThemeType; + + [STAThread] + public static int Main(string[] args) => new Program().Run(args); + public Program() + { + app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + + // var theme = new ThemeType(); + // // Set LibAdwaita Themes + // app.StyleManager!.ColorScheme = theme switch + // { + // ThemeType.System => ColorScheme.PreferDark, + // ThemeType.Light => ColorScheme.ForceLight, + // ThemeType.Dark => ColorScheme.ForceDark, + // _ => ColorScheme.PreferDark + // }; + var win = new MainWindow(app); + + app.OnActivate += OnActivate; + + void OnActivate(Gio.Application sender, EventArgs e) + { + // Add Main Window + app.AddWindow(win); + } + } + + public int Run(string[] args) + { + var argv = new string[args.Length + 1]; + argv[0] = "Kermalis.VGMusicStudio.GTK4"; + args.CopyTo(argv, 1); + return app.Run(args.Length + 1, argv); + } + } +} diff --git a/VG Music Studio - GTK4/Theme.cs b/VG Music Studio - GTK4/Theme.cs new file mode 100644 index 0000000..1fd8cf1 --- /dev/null +++ b/VG Music Studio - GTK4/Theme.cs @@ -0,0 +1,224 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Util; +using Cairo; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System; +using Pango; +using Window = Gtk.Window; +using Context = Cairo.Context; + +namespace Kermalis.VGMusicStudio.GTK4; + +/// +/// LibAdwaita theme selection enumerations. +/// +public enum ThemeType +{ + Light = 0, // Light Theme + Dark, // Dark Theme + System // System Default Theme +} + +internal class Theme +{ + + public Theme ThemeType { get; set; } + + //[StructLayout(LayoutKind.Sequential)] + //public struct Color + //{ + // public float Red; + // public float Green; + // public float Blue; + // public float Alpha; + //} + + //[DllImport("libadwaita-1.so.0")] + //[return: MarshalAs(UnmanagedType.I1)] + //private static extern bool gdk_rgba_parse(ref Color rgba, string spec); + + //[DllImport("libadwaita-1.so.0")] + //private static extern string gdk_rgba_to_string(ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_get_rgba(nint chooser, ref Color rgba); + + //[DllImport("libadwaita-1.so.0")] + //private static extern void gtk_color_chooser_set_rgba(nint chooser, ref Color rgba); + + //public static Color FromArgb(int r, int g, int b) + //{ + // Color color = new Color(); + // r = (int)color.Red; + // g = (int)color.Green; + // b = (int)color.Blue; + + // return color; + //} + + //public static readonly Font Font = new("Segoe UI", 8f, FontStyle.Bold); + //public static readonly Color + // BackColor = Color.FromArgb(33, 33, 39), + // BackColorDisabled = Color.FromArgb(35, 42, 47), + // BackColorMouseOver = Color.FromArgb(32, 37, 47), + // BorderColor = Color.FromArgb(25, 120, 186), + // BorderColorDisabled = Color.FromArgb(47, 55, 60), + // ForeColor = Color.FromArgb(94, 159, 230), + // PlayerColor = Color.FromArgb(8, 8, 8), + // SelectionColor = Color.FromArgb(7, 51, 141), + // TitleBar = Color.FromArgb(16, 40, 63); + + + + //public static Color DrainColor(Color c) + //{ + // var hsl = new HSLColor(c); + // return HSLColor.ToColor(hsl.H, (byte)(hsl.S / 2.5), hsl.L); + //} +} + +internal sealed class ThemedButton : Button +{ + public ResponseType ResponseType; + public ThemedButton() + { + //FlatAppearance.MouseOverBackColor = Theme.BackColorMouseOver; + //FlatStyle = FlatStyle.Flat; + //Font = Theme.FontType; + //ForeColor = Theme.ForeColor; + } + protected void OnEnabledChanged(EventArgs e) + { + //base.OnEnabledChanged(e); + //BackColor = Enabled ? Theme.BackColor : Theme.BackColorDisabled; + //FlatAppearance.BorderColor = Enabled ? Theme.BorderColor : Theme.BorderColorDisabled; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //if (!Enabled) + //{ + // TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Theme.DrainColor(ForeColor), BackColor); + //} + } + //protected override bool ShowFocusCues => false; +} +internal sealed class ThemedLabel : Label +{ + public ThemedLabel() + { + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + } +} +internal class ThemedWindow : Window +{ + public ThemedWindow() + { + //BackColor = Theme.BackColor; + //Icon = Resources.Icon; + } +} +internal class ThemedBox : Box +{ + public ThemedBox() + { + //SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //using (var b = new SolidBrush(BackColor)) + //{ + // e.Graphics.FillRectangle(b, e.ClipRectangle); + //} + //using (var b = new SolidBrush(Theme.BorderColor)) + //using (var p = new Pen(b, 2)) + //{ + // e.Graphics.DrawRectangle(p, e.ClipRectangle); + //} + } + private const int WM_PAINT = 0xF; + //protected void WndProc(ref Message m) + //{ + // if (m.Msg == WM_PAINT) + // { + // Invalidate(); + // } + // base.WndProc(ref m); + //} +} +internal class ThemedTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } + //[DllImport("user32.dll")] + //private static extern IntPtr GetWindowDC(IntPtr hWnd); + //[DllImport("user32.dll")] + //private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + //[DllImport("user32.dll")] + //private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags); + //private const int WM_NCPAINT = 0x85; + //private const uint RDW_INVALIDATE = 0x1; + //private const uint RDW_IUPDATENOW = 0x100; + //private const uint RDW_FRAME = 0x400; + //protected override void WndProc(ref Message m) + //{ + // base.WndProc(ref m); + // if (m.Msg == WM_NCPAINT && BorderStyle == BorderStyle.Fixed3D) + // { + // IntPtr hdc = GetWindowDC(Handle); + // using (var g = Graphics.FromHdcInternal(hdc)) + // using (var p = new Pen(Theme.BorderColor)) + // { + // g.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + // } + // ReleaseDC(Handle, hdc); + // } + //} + protected void OnSizeChanged(EventArgs e) + { + //base.OnSizeChanged(e); + //RedrawWindow(Handle, IntPtr.Zero, IntPtr.Zero, RDW_FRAME | RDW_IUPDATENOW | RDW_INVALIDATE); + } +} +internal sealed class ThemedRichTextBox : Adw.Window +{ + public Box Box; + public Text Text; + public ThemedRichTextBox() + { + //BackColor = Theme.BackColor; + //Font = Theme.Font; + //ForeColor = Theme.ForeColor; + //SelectionColor = Theme.SelectionColor; + Box = Box.New(Orientation.Horizontal, 0); + Text = Text.New(); + Box.Append(Text); + } +} +internal sealed class ThemedNumeric : SpinButton +{ + public ThemedNumeric() + { + //BackColor = Theme.BackColor; + //Font = new Font(Theme.Font.FontFamily, 7.5f, Theme.Font.Style); + //ForeColor = Theme.ForeColor; + //TextAlign = HorizontalAlignment.Center; + } + protected void OnDraw(Context c) + { + //base.OnPaint(e); + //ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Enabled ? Theme.BorderColor : Theme.BorderColorDisabled, ButtonBorderStyle.Solid); + } +} \ No newline at end of file diff --git a/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs new file mode 100644 index 0000000..621175f --- /dev/null +++ b/VG Music Studio - GTK4/Util/FlexibleMessageBox.cs @@ -0,0 +1,763 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using Adw; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * FlexibleMessageBox + * + * A Message Box completely rewritten by Davin (Platinum Lucario) for use with Gir.Core (GTK4 and LibAdwaita) + * on VG Music Studio, modified from the WinForms-based FlexibleMessageBox originally made by Jörg Reichert. + * + * This uses Adw.Window to create a window similar to MessageDialog, since + * MessageDialog and many Gtk.Dialog functions are deprecated since GTK version 4.10, + * Adw.Window and Gtk.Window are better supported (and probably won't be deprecated until several major versions later). + * + * Features include: + * - Extra options for a dialog box style Adw.Window with the Show() function + * - Displays a vertical scrollbar, just like the original one did + * - Only one source file is used + * - Much less lines of code than the original, due to built-in GTK4 and LibAdwaita functions + * - All WinForms functions removed and replaced with GObject library functions via Gir.Core + * + * GitHub: https://github.com/PlatinumLucario + * Repository: https://github.com/PlatinumLucario/VGMusicStudio/ + * + * | Original Author can be found below: | + * v v + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#region Original Author +/* FlexibleMessageBox – A flexible replacement for the .NET MessageBox + * + * Author: Jörg Reichert (public@jreichert.de) + * Contributors: Thanks to: David Hall, Roink + * Version: 1.3 + * Published at: http://www.codeproject.com/Articles/601900/FlexibleMessageBox + * + ************************************************************************************************************ + * Features: + * - It can be simply used instead of MessageBox since all important static "Show"-Functions are supported + * - It is small, only one source file, which could be added easily to each solution + * - It can be resized and the content is correctly word-wrapped + * - It tries to auto-size the width to show the longest text row + * - It never exceeds the current desktop working area + * - It displays a vertical scrollbar when needed + * - It does support hyperlinks in text + * + * Because the interface is identical to MessageBox, you can add this single source file to your project + * and use the FlexibleMessageBox almost everywhere you use a standard MessageBox. + * The goal was NOT to produce as many features as possible but to provide a simple replacement to fit my + * own needs. Feel free to add additional features on your own, but please left my credits in this class. + * + ************************************************************************************************************ + * Usage examples: + * + * FlexibleMessageBox.Show("Just a text"); + * + * FlexibleMessageBox.Show("A text", + * "A caption"); + * + * FlexibleMessageBox.Show("Some text with a link: www.google.com", + * "Some caption", + * MessageBoxButtons.AbortRetryIgnore, + * MessageBoxIcon.Information, + * MessageBoxDefaultButton.Button2); + * + * var dialogResult = FlexibleMessageBox.Show("Do you know the answer to life the universe and everything?", + * "One short question", + * MessageBoxButtons.YesNo); + * + ************************************************************************************************************ + * THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY + * OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS + * SOFTWARE. + * + ************************************************************************************************************ + * History: + * Version 1.3 - 19.Dezember 2014 + * - Added refactoring function GetButtonText() + * - Used CurrentUICulture instead of InstalledUICulture + * - Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN + * - Added standard MessageBox handling for "copy to clipboard" with + and + + * - Tab handling is now corrected (only tabbing over the visible buttons) + * - Added standard MessageBox handling for ALT-Keyboard shortcuts + * - SetDialogSizes: Refactored completely: Corrected sizing and added caption driven sizing + * + * Version 1.2 - 10.August 2013 + * - Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar) + * - Added handling for Escape-Button + * - Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated) + * + * Version 1.1 - 14.June 2013 + * - Some Refactoring + * - Added internal form class + * - Added missing code comments, etc. + * + * Version 1.0 - 15.April 2013 + * - Initial Version + */ +#endregion + +internal class FlexibleMessageBox +{ + #region Public statics + + /// + /// Defines the maximum width for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area. + /// 1.0 means: The FlexibleMessageBox can be as wide as the working area. + /// + /// Default is: 70% of the working area width. + /// + //public static double MAX_WIDTH_FACTOR = 0.7; + + /// + /// Defines the maximum height for all FlexibleMessageBox instances in percent of the working area. + /// + /// Allowed values are 0.2 - 1.0 where: + /// 0.2 means: The FlexibleMessageBox can be at most half as high as the working area. + /// 1.0 means: The FlexibleMessageBox can be as high as the working area. + /// + /// Default is: 90% of the working area height. + /// + //public static double MAX_HEIGHT_FACTOR = 0.9; + + /// + /// Defines the font for all FlexibleMessageBox instances. + /// + /// Default is: Theme.Font + /// + //public static Font FONT = Theme.Font; + + #endregion + + #region Public show functions + + public static Gtk.ResponseType Show(string text) + { + return FlexibleMessageBoxWindow.Show(null, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text) + { + return FlexibleMessageBoxWindow.Show(owner, text, string.Empty, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Exception ex, string caption) + { + return FlexibleMessageBoxWindow.Show(null, string.Format("Error Details:{1}{1}{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, Gtk.ButtonsType.Ok, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, Gtk.MessageType.Other, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, Gtk.ResponseType.Ok); + } + public static Gtk.ResponseType Show(string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(null, text, caption, buttons, icon, defaultButton); + } + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + return FlexibleMessageBoxWindow.Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + + #region Internal form classes + + internal sealed class FlexibleButton : Gtk.Button + { + public Gtk.ButtonsType ButtonsType; + public Gtk.ResponseType ResponseType; + + private FlexibleButton() + { + ResponseType = new Gtk.ResponseType(); + } + } + + internal sealed class FlexibleContentBox : Gtk.Box + { + public Gtk.Text Text; + + private FlexibleContentBox() + { + Text = Gtk.Text.New(); + } + } + + class FlexibleMessageBoxWindow : Window + { + //IContainer components = null; + + protected void Dispose(bool disposing) + { + if (disposing && richTextBoxMessage != null) + { + richTextBoxMessage.Dispose(); + } + base.Dispose(); + } + void InitializeComponent() + { + //components = new Container(); + richTextBoxMessage = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + button1 = (FlexibleButton)Gtk.Button.New(); + //FlexibleMessageBoxFormBindingSource = new BindingSource(components); + panel1 = (FlexibleContentBox)Gtk.Box.New(Gtk.Orientation.Vertical, 0); + pictureBoxForIcon = Gtk.Image.New(); + button2 = (FlexibleButton)Gtk.Button.New(); + button3 = (FlexibleButton)Gtk.Button.New(); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit(); + //panel1.SuspendLayout(); + //((ISupportInitialize)pictureBoxForIcon).BeginInit(); + //SuspendLayout(); + // + // button1 + // + //button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button1.AutoSize = true; + button1.ResponseType = Gtk.ResponseType.Ok; + //button1.Location = new Point(11, 67); + //button1.MinimumSize = new Size(0, 24); + button1.Name = "button1"; + //button1.Size = new Size(75, 24); + button1.WidthRequest = 75; + button1.HeightRequest = 24; + //button1.TabIndex = 2; + button1.Label = "OK"; + //button1.UseVisualStyleBackColor = true; + button1.Visible = false; + // + // richTextBoxMessage + // + //richTextBoxMessage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //richTextBoxMessage.BorderStyle = BorderStyle.None; + richTextBoxMessage.BindProperty("Text", FlexibleMessageBoxFormBindingSource, "MessageText", GObject.BindingFlags.Default); + //richTextBoxMessage.Font = new Font(Theme.Font.FontFamily, 9); + //richTextBoxMessage.Location = new Point(50, 26); + //richTextBoxMessage.Margin = new Padding(0); + richTextBoxMessage.Name = "richTextBoxMessage"; + //richTextBoxMessage.ReadOnly = true; + richTextBoxMessage.Text.Editable = false; + //richTextBoxMessage.ScrollBars = RichTextBoxScrollBars.Vertical; + scrollbar = Gtk.Scrollbar.New(Gtk.Orientation.Vertical, null); + scrollbar.SetParent(richTextBoxMessage); + //richTextBoxMessage.Size = new Size(200, 20); + richTextBoxMessage.WidthRequest = 200; + richTextBoxMessage.HeightRequest = 20; + //richTextBoxMessage.TabIndex = 0; + //richTextBoxMessage.TabStop = false; + richTextBoxMessage.Text.SetText(""); + //richTextBoxMessage.LinkClicked += new LinkClickedEventHandler(LinkClicked); + // + // panel1 + // + //panel1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + //| AnchorStyles.Left + //| AnchorStyles.Right; + //panel1.Controls.Add(pictureBoxForIcon); + panel1.Append(pictureBoxForIcon); + //panel1.Controls.Add(richTextBoxMessage); + panel1.Append(richTextBoxMessage); + //panel1.Location = new Point(-3, -4); + panel1.Name = "panel1"; + //panel1.Size = new Size(268, 59); + panel1.WidthRequest = 268; + panel1.HeightRequest = 59; + //panel1.TabIndex = 1; + // + // pictureBoxForIcon + // + //pictureBoxForIcon.BackColor = Color.Transparent; + //pictureBoxForIcon.Location = new Point(15, 19); + pictureBoxForIcon.Name = "pictureBoxForIcon"; + //pictureBoxForIcon.Size = new Size(32, 32); + pictureBoxForIcon.WidthRequest = 32; + pictureBoxForIcon.HeightRequest = 32; + //pictureBoxForIcon.TabIndex = 8; + //pictureBoxForIcon.TabStop = false; + // + // button2 + // + //button2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + button2.ResponseType = Gtk.ResponseType.Ok; + //button2.Location = new Point(92, 67); + //button2.MinimumSize = new Size(0, 24); + button2.Name = "button2"; + //button2.Size = new Size(75, 24); + button2.WidthRequest = 75; + button2.HeightRequest = 24; + //button2.TabIndex = 3; + button2.Label = "OK"; + //button2.UseVisualStyleBackColor = true; + button2.Visible = false; + // + // button3 + // + //button3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + //button3.AutoSize = true; + button3.ResponseType = Gtk.ResponseType.Ok; + //button3.Location = new Point(173, 67); + //button3.MinimumSize = new Size(0, 24); + button3.Name = "button3"; + //button3.Size = new Size(75, 24); + button3.WidthRequest = 75; + button3.HeightRequest = 24; + //button3.TabIndex = 0; + button3.Label = "OK"; + //button3.UseVisualStyleBackColor = true; + button3.Visible = false; + // + // FlexibleMessageBoxForm + // + //AutoScaleDimensions = new SizeF(6F, 13F); + //AutoScaleMode = AutoScaleMode.Font; + //ClientSize = new Size(260, 102); + //Controls.Add(button3); + SetChild(button3); + //Controls.Add(button2); + SetChild(button2); + //Controls.Add(panel1); + SetChild(panel1); + //Controls.Add(button1); + SetChild(button1); + //DataBindings.Add(new Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true)); + //Icon = Properties.Resources.Icon; + //MaximizeBox = false; + //MinimizeBox = false; + //MinimumSize = new Size(276, 140); + //Name = "FlexibleMessageBoxForm"; + //SizeGripStyle = SizeGripStyle.Show; + //StartPosition = FormStartPosition.CenterParent; + //Text = ""; + //Shown += new EventHandler(FlexibleMessageBoxForm_Shown); + //((ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit(); + //panel1.ResumeLayout(false); + //((ISupportInitialize)pictureBoxForIcon).EndInit(); + //ResumeLayout(false); + //PerformLayout(); + } + + private FlexibleButton button1, button2, button3; + private GObject.Object FlexibleMessageBoxFormBindingSource; + private FlexibleContentBox richTextBoxMessage, panel1; + private Gtk.Scrollbar scrollbar; + private Gtk.Image pictureBoxForIcon; + + #region Private constants + + //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + + //These are the possible buttons (in a standard MessageBox) + private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE }; + + //These are the buttons texts for different languages. + //If you want to add a new language, add it here and in the GetButtonText-Function + private enum TwoLetterISOLanguageID { en, de, es, it }; + static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language + static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" }; + static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" }; + static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" }; + + #endregion + + #region Private members + + Gtk.ResponseType defaultButton; + int visibleButtonsCount; + readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + + #endregion + + #region Private constructors + + private FlexibleMessageBoxWindow() + { + InitializeComponent(); + + //Try to evaluate the language. If this fails, the fallback language English will be used + Enum.TryParse(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID); + + //KeyPreview = true; + //KeyUp += FlexibleMessageBoxForm_KeyUp; + } + + #endregion + + #region Private helper functions + + static string[] GetStringRows(string message) + { + if (string.IsNullOrEmpty(message)) + { + return null; + } + + string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None); + return messageRows; + } + + string GetButtonText(ButtonID buttonID) + { + int buttonTextArrayIndex = Convert.ToInt32(buttonID); + + switch (languageID) + { + case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex]; + case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex]; + + default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex]; + } + } + + static double GetCorrectedWorkingAreaFactor(double workingAreaFactor) + { + const double MIN_FACTOR = 0.2; + const double MAX_FACTOR = 1.0; + + if (workingAreaFactor < MIN_FACTOR) + { + return MIN_FACTOR; + } + + if (workingAreaFactor > MAX_FACTOR) + { + return MAX_FACTOR; + } + + return workingAreaFactor; + } + + static void SetDialogStartPosition(FlexibleMessageBoxWindow flexibleMessageBoxForm, Window owner) + { + //If no owner given: Center on current screen + if (owner == null) + { + //var screen = Screen.FromPoint(Cursor.Position); + //flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual; + //flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2; + //flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2; + } + } + + static void SetDialogSizes(FlexibleMessageBoxWindow flexibleMessageBoxForm, string text, string caption) + { + //First set the bounds for the maximum dialog size + //flexibleMessageBoxForm.MaximumSize = new Size(Convert.ToInt32(SystemInformation.WorkingArea.Width * GetCorrectedWorkingAreaFactor(MAX_WIDTH_FACTOR)), + // Convert.ToInt32(SystemInformation.WorkingArea.Height * GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR))); + + //Get rows. Exit if there are no rows to render... + string[] stringRows = GetStringRows(text); + if (stringRows == null) + { + return; + } + + //Calculate whole text height + //int textHeight = TextRenderer.MeasureText(text, FONT).Height; + + //Calculate width for longest text line + //const int SCROLLBAR_WIDTH_OFFSET = 15; + //int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width); + //int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width; + //int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth); + + //Calculate margins + int marginWidth = flexibleMessageBoxForm.WidthRequest - flexibleMessageBoxForm.richTextBoxMessage.WidthRequest; + int marginHeight = flexibleMessageBoxForm.HeightRequest - flexibleMessageBoxForm.richTextBoxMessage.HeightRequest; + + //Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically) + //flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth, + // textHeight + marginHeight); + } + + static void SetDialogIcon(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.MessageType icon) + { + switch (icon) + { + case Gtk.MessageType.Info: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-information-symbolic"); + break; + case Gtk.MessageType.Warning: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-warning-symbolic"); + break; + case Gtk.MessageType.Error: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-error-symbolic"); + break; + case Gtk.MessageType.Question: + flexibleMessageBoxForm.pictureBoxForIcon.SetFromIconName("dialog-question-symbolic"); + break; + default: + //When no icon is used: Correct placement and width of rich text box. + flexibleMessageBoxForm.pictureBoxForIcon.Visible = false; + //flexibleMessageBoxForm.richTextBoxMessage.Left -= flexibleMessageBoxForm.pictureBoxForIcon.Width; + //flexibleMessageBoxForm.richTextBoxMessage.Width += flexibleMessageBoxForm.pictureBoxForIcon.Width; + break; + } + } + + static void SetDialogButtons(FlexibleMessageBoxWindow flexibleMessageBoxForm, Gtk.ButtonsType buttons, Gtk.ResponseType defaultButton) + { + //Set the buttons visibilities and texts + switch (buttons) + { + case 0: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.ABORT); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Reject; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)1: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)2: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.RETRY); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Ok; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)3: + flexibleMessageBoxForm.visibleButtonsCount = 2; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.No; + + //flexibleMessageBoxForm.ControlBox = false; + break; + + case (Gtk.ButtonsType)4: + flexibleMessageBoxForm.visibleButtonsCount = 3; + + flexibleMessageBoxForm.button1.Visible = true; + flexibleMessageBoxForm.button1.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.YES); + flexibleMessageBoxForm.button1.ResponseType = Gtk.ResponseType.Yes; + + flexibleMessageBoxForm.button2.Visible = true; + flexibleMessageBoxForm.button2.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.NO); + flexibleMessageBoxForm.button2.ResponseType = Gtk.ResponseType.No; + + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.CANCEL); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Cancel; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + + case (Gtk.ButtonsType)5: + default: + flexibleMessageBoxForm.visibleButtonsCount = 1; + flexibleMessageBoxForm.button3.Visible = true; + flexibleMessageBoxForm.button3.Label = flexibleMessageBoxForm.GetButtonText(ButtonID.OK); + flexibleMessageBoxForm.button3.ResponseType = Gtk.ResponseType.Ok; + + //flexibleMessageBoxForm.CancelButton = flexibleMessageBoxForm.button3; + break; + } + + //Set default button (used in FlexibleMessageBoxWindow_Shown) + flexibleMessageBoxForm.defaultButton = defaultButton; + } + + #endregion + + #region Private event handlers + + void FlexibleMessageBoxWindow_Shown(object sender, EventArgs e) + { + int buttonIndexToFocus = 1; + Gtk.Widget buttonToFocus; + + //Set the default button... + //switch (defaultButton) + //{ + // case MessageBoxDefaultButton.Button1: + // default: + // buttonIndexToFocus = 1; + // break; + // case MessageBoxDefaultButton.Button2: + // buttonIndexToFocus = 2; + // break; + // case MessageBoxDefaultButton.Button3: + // buttonIndexToFocus = 3; + // break; + //} + + if (buttonIndexToFocus > visibleButtonsCount) + { + buttonIndexToFocus = visibleButtonsCount; + } + + if (buttonIndexToFocus == 3) + { + buttonToFocus = button3; + } + else if (buttonIndexToFocus == 2) + { + buttonToFocus = button2; + } + else + { + buttonToFocus = button1; + } + + buttonToFocus.IsFocus(); + } + + //void LinkClicked(object sender, LinkClickedEventArgs e) + //{ + // try + // { + // Cursor.Current = Cursors.WaitCursor; + // Process.Start(e.LinkText); + // } + // catch (Exception) + // { + // //Let the caller of FlexibleMessageBoxWindow decide what to do with this exception... + // throw; + // } + // finally + // { + // Cursor.Current = Cursors.Default; + // } + //} + + //void FlexibleMessageBoxWindow_KeyUp(object sender, KeyEventArgs e) + //{ + // //Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert" + // if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert)) + // { + // string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty) + // + (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty); + + // //Build same clipboard text like the standard .Net MessageBox + // string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + richTextBoxMessage.Text + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES + // + buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine + // + STANDARD_MESSAGEBOX_SEPARATOR_LINES; + + // //Set text in clipboard + // Clipboard.SetText(textForClipboard); + // } + //} + + #endregion + + #region Properties (only used for binding) + + public string CaptionText { get; set; } + public string MessageText { get; set; } + + #endregion + + #region Public show function + + public static Gtk.ResponseType Show(Window owner, string text, string caption, Gtk.ButtonsType buttons, Gtk.MessageType icon, Gtk.ResponseType defaultButton) + { + //Create a new instance of the FlexibleMessageBox form + var flexibleMessageBoxForm = new FlexibleMessageBoxWindow + { + //ShowInTaskbar = false, + + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; + //flexibleMessageBoxForm.FlexibleMessageBoxWindowBindingSource.DataSource = flexibleMessageBoxForm; + + //Set the buttons visibilities and texts. Also set a default button. + SetDialogButtons(flexibleMessageBoxForm, buttons, defaultButton); + + //Set the dialogs icon. When no icon is used: Correct placement and width of rich text box. + SetDialogIcon(flexibleMessageBoxForm, icon); + + //Set the font for all controls + //flexibleMessageBoxForm.Font = FONT; + //flexibleMessageBoxForm.richTextBoxMessage.Font = FONT; + + //Calculate the dialogs start size (Try to auto-size width to show longest text row). Also set the maximum dialog size. + SetDialogSizes(flexibleMessageBoxForm, text, caption); + + //Set the dialogs start position when given. Otherwise center the dialog on the current screen. + SetDialogStartPosition(flexibleMessageBoxForm, owner); + + //Show the dialog + return Show(owner, text, caption, buttons, icon, defaultButton); + } + + #endregion + } //class FlexibleMessageBoxForm + + #endregion +} diff --git a/VG Music Studio - GTK4/Util/GTK4Utils.cs b/VG Music Studio - GTK4/Util/GTK4Utils.cs new file mode 100644 index 0000000..760f9b8 --- /dev/null +++ b/VG Music Studio - GTK4/Util/GTK4Utils.cs @@ -0,0 +1,214 @@ +using Gtk; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using System; +using System.Runtime.InteropServices; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class GTK4Utils : DialogUtils +{ + // Callback + private static Gio.Internal.AsyncReadyCallback? _saveCallback { get; set; } + private static Gio.Internal.AsyncReadyCallback? _openCallback { get; set; } + private static Gio.Internal.AsyncReadyCallback? _selectFolderCallback { get; set; } + + + + private static void Convert(string filterName, Span fileExtensions, FileFilter fileFilter) + { + if (fileExtensions.IsEmpty | filterName.Contains('|')) + { + for (int i = 0; i < filterName.Length; i++) + { + _ = new string[filterName.Split('|').Length]; + Span fn = filterName.Split('|'); + fileFilter.SetName(fn[0]); + if (fn[1].Contains(';')) + { + _ = new string[fn[1].Split(';').Length]; + Span fe = fn[1].Split(';'); + for (int k = 0; k < fe.Length; k++) + { + //fe[k] = fe[k].Trim('*', '.'); + fileFilter.AddPattern(fe[k]); + } + } + else + { + fileFilter.AddPattern(fn[1]); + } + } + } + else + { + fileFilter.SetName(filterName); + for (int i = 0; i < fileExtensions.Length; i++) + { + fileFilter.AddPattern(fileExtensions[i]); + } + } + } + public static string CreateLoadDialog(string title, object parent = null!) => + new GTK4Utils().CreateLoadDialog(title, "", [""], false, false, parent); + public static string CreateLoadDialog(string extension, string title, string filter, object parent = null!) => + new GTK4Utils().CreateLoadDialog(title, filter, [extension], true, true, parent); + public static string CreateLoadDialog(Span extensions, string title, string filter, object parent = null!) => + new GTK4Utils().CreateLoadDialog(title, filter, extensions, true, true, parent); + public override string CreateLoadDialog(string title, string filterName = "", string fileExtension = "", bool isFile = false, bool allowAllFiles = false, object? parent = null) => + CreateLoadDialog(title, filterName, [fileExtension], isFile, allowAllFiles, parent!); + public override string CreateLoadDialog(string title, string filterName, Span fileExtensions, bool isFile, bool allowAllFiles, object? parent) + { + if (isFile) + { + + var ff = FileFilter.New(); + Convert(filterName, fileExtensions, ff); + + var d = FileDialog.New(); + d.SetTitle(title); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + if (allowAllFiles) + { + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.FilterAllFiles); + allFiles.AddPattern("*.*"); + filters.Append(allFiles); + } + d.SetFilters(filters); + string? path = null; + _openCallback = (source, res, data) => + { + var errorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out errorHandle); + if (fileHandle != IntPtr.Zero) + { + path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + if (parent == Adw.Window.New()) + { + var p = (Adw.Window)parent; + // SelectFolder, Open and Save methods are currently missing from GirCore, but are available in the Gtk.Internal namespace, + // so we're using this until GirCore updates with the method bindings. See here: https://github.com/gircore/gir.core/issues/900 + Gtk.Internal.FileDialog.Open(d.Handle, p.Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + else if (parent == Gtk.Window.New()) + { + var p = (Gtk.Window)parent; + Gtk.Internal.FileDialog.Open(d.Handle, p.Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + else + { + var p = Gtk.Window.New(); + Gtk.Internal.FileDialog.Open(d.Handle, p.Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + return null!; + } + else + { + var d = FileDialog.New(); + d.SetTitle(title); + + string? path = null; + _selectFolderCallback = (source, res, data) => + { + var errorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + var folderHandle = Gtk.Internal.FileDialog.SelectFolderFinish(d.Handle, res, out errorHandle); + if (folderHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(folderHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + if (parent == Adw.Window.New()) + { + var p = (Adw.Window)parent; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, p.Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + else if (parent == Gtk.Window.New()) + { + var p = (Gtk.Window)parent; + Gtk.Internal.FileDialog.SelectFolder(d.Handle, p.Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + else + { + var p = Gtk.Window.New(); + Gtk.Internal.FileDialog.SelectFolder(d.Handle, p.Handle, IntPtr.Zero, _selectFolderCallback, IntPtr.Zero); + } + return null!; + } + } + + public static string CreateSaveDialog(string fileName, string extension, string title, string filter, object parent = null!) => + new GTK4Utils().CreateSaveDialog(fileName, title, filter, [extension], false, false, parent); + public static string CreateSaveDialog(string fileName, Span extensions, string title, string filter, object parent = null!) => + new GTK4Utils().CreateSaveDialog(fileName, title, filter, extensions, false, false, parent); + public override string CreateSaveDialog(string fileName, string title, string filterName, string fileExtension = "", bool isFile = false, bool allowAllFiles = false, object? parent = null) => + CreateSaveDialog(fileName, title, filterName, [fileExtension], false); + public override string CreateSaveDialog(string fileName, string title, string filterName, Span fileExtensions, bool isFile = false, bool allowAllFiles = false, object? parent = null) + { + var ff = FileFilter.New(); + Convert(filterName, fileExtensions, ff); + + var d = FileDialog.New(); + d.SetTitle(title); + d.SetInitialName(fileName); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(ff); + if (allowAllFiles) + { + var allFiles = FileFilter.New(); + allFiles.SetName(Strings.FilterAllFiles); + allFiles.AddPattern("*.*"); + filters.Append(allFiles); + } + d.SetFilters(filters); + string? path = null; + _saveCallback = (source, res, data) => + { + var errorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); + var fileHandle = Gtk.Internal.FileDialog.SaveFinish(d.Handle, res, out errorHandle); + if (fileHandle != IntPtr.Zero) + { + path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + } + d.Unref(); + }; + if (path != null) + { + d.Unref(); + return path; + } + if (parent == Adw.Window.New()) + { + var p = (Adw.Window)parent; + Gtk.Internal.FileDialog.Save(d.Handle, p.Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + else if (parent == Gtk.Window.New()) + { + var p = (Gtk.Window)parent; + Gtk.Internal.FileDialog.Save(d.Handle, p.Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + else + { + var p = Gtk.Window.New(); + Gtk.Internal.FileDialog.Save(d.Handle, p.Handle, IntPtr.Zero, _saveCallback, IntPtr.Zero); + } + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + return null!; + } +} diff --git a/VG Music Studio - GTK4/Util/ScaleControl.cs b/VG Music Studio - GTK4/Util/ScaleControl.cs new file mode 100644 index 0000000..6d21dc2 --- /dev/null +++ b/VG Music Studio - GTK4/Util/ScaleControl.cs @@ -0,0 +1,86 @@ +/* + * Modified by Davin Ockerby (Platinum Lucario) for use with GTK4 + * and VG Music Studio. Originally made by Fabrice Lacharme for use + * on WinForms. Modified since 2023-08-04 at 00:32. + */ + +#region Original License + +/* Copyright (c) 2017 Fabrice Lacharme + * This code is inspired from Michal Brylka + * https://www.codeproject.com/Articles/17395/Owner-drawn-trackbar-slider + * + * 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. + */ + +#endregion + + +using Gtk; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class ScaleControl : Adjustment +{ + internal Adjustment Instance { get; } + + internal ScaleControl(double value, double lower, double upper, double stepIncrement, double pageIncrement, double pageSize) + { + Instance = New(value, lower, upper, stepIncrement, pageIncrement, pageSize); + } + + private double _smallChange = 1L; + public double SmallChange + { + get => _smallChange; + set + { + if (value >= 0) + { + _smallChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(SmallChange), $"{nameof(SmallChange)} must be greater than or equal to 0."); + } + } + } + private double _largeChange = 5L; + public double LargeChange + { + get => _largeChange; + set + { + if (value >= 0) + { + _largeChange = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(LargeChange), $"{nameof(LargeChange)} must be greater than or equal to 0."); + } + } + } + +} diff --git a/VG Music Studio - GTK4/Util/SoundSequenceList.cs b/VG Music Studio - GTK4/Util/SoundSequenceList.cs new file mode 100644 index 0000000..6077bf9 --- /dev/null +++ b/VG Music Studio - GTK4/Util/SoundSequenceList.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Gtk; +using Kermalis.VGMusicStudio.Core; +using Pango; + +namespace Kermalis.VGMusicStudio.GTK4.Util; + +internal class SoundSequenceList : Widget, IDisposable +{ + internal static ListItem? ListItem { get; set; } + internal static long? Index { get; set; } + internal static new string? Name { get; set; } + internal static List? Songs { get; set; } + //internal SingleSelection Selection { get; set; } + //private SignalListItemFactory Factory; + + internal SoundSequenceList() + { + var box = Box.New(Orientation.Horizontal, 0); + var label = Label.New(""); + label.SetWidthChars(2); + label.SetHexpand(true); + box.Append(label); + + var sw = ScrolledWindow.New(); + sw.SetPropagateNaturalWidth(true); + var listView = Create(label); + sw.SetChild(listView); + box.Prepend(sw); + } + + private static void SetupLabel(SignalListItemFactory factory, EventArgs e) + { + var label = Label.New(""); + label.SetXalign(0); + ListItem!.SetChild(label); + //e.Equals(label); + } + private static void BindName(SignalListItemFactory factory, EventArgs e) + { + var label = ListItem!.GetChild(); + var item = ListItem!.GetItem(); + var name = item.Equals(Name); + + label!.SetName(name.ToString()); + } + + private static Widget Create(object item) + { + if (item is Config.Song song) + { + Index = song.Index; + Name = song.Name; + } + else if (item is Config.Playlist playlist) + { + Songs = playlist.Songs; + Name = playlist.Name; + } + var model = Gio.ListStore.New(ColumnView.GetGType()); + + var selection = SingleSelection.New(model); + selection.SetAutoselect(true); + selection.SetCanUnselect(false); + + + var cv = ColumnView.New(selection); + cv.SetShowColumnSeparators(true); + cv.SetShowRowSeparators(true); + + var factory = SignalListItemFactory.New(); + factory.OnSetup += SetupLabel; + factory.OnBind += BindName; + var column = ColumnViewColumn.New("Name", factory); + column.SetResizable(true); + cv.AppendColumn(column); + column.Unref(); + + return cv; + } + + internal int Add(object item) + { + return Add(item); + } + internal int AddRange(Span items) + { + foreach (object item in items) + { + Create(item); + } + return AddRange(items); + } + + //internal SignalListItemFactory Items + //{ + // get + // { + // if (Factory is null) + // { + // Factory = SignalListItemFactory.New(); + // } + + // return Factory; + // } + //} + + internal object SelectedItem + { + get + { + int index = (int)Index!; + return (index == -1) ? null : ListItem.Item.Equals(index); + } + set + { + int x = -1; + + if (ListItem is not null) + { + // + if (value is not null) + { + x = ListItem.GetPosition().CompareTo(value); + } + else + { + Index = -1; + } + } + + if (x != -1) + { + Index = x; + } + } + } +} + +internal class SoundSequenceListItem +{ + internal object Item { get; } + internal SoundSequenceListItem(object item) + { + Item = item; + } + + public override string ToString() + { + return Item.ToString(); + } +} diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj new file mode 100644 index 0000000..b3d37e9 --- /dev/null +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -0,0 +1,285 @@ + + + + Exe + net8.0 + enable + true + + + + + + + + + + + + + Always + %(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ../../../share/glib-2.0/%(RecursiveDir)/%(Filename)%(Extension) + + + Always + ..\..\..\share\glib-2.0\%(RecursiveDir)\%(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + + diff --git a/VG Music Studio - WinForms/PlayingPlaylist.cs b/VG Music Studio - WinForms/PlayingPlaylist.cs index 100f88f..2719753 100644 --- a/VG Music Studio - WinForms/PlayingPlaylist.cs +++ b/VG Music Studio - WinForms/PlayingPlaylist.cs @@ -1,6 +1,5 @@ using Kermalis.VGMusicStudio.Core; using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Util; using System.Collections.Generic; using System.Linq; diff --git a/VG Music Studio - WinForms/SongInfoControl.cs b/VG Music Studio - WinForms/SongInfoControl.cs index 36cfe49..f177d83 100644 --- a/VG Music Studio - WinForms/SongInfoControl.cs +++ b/VG Music Studio - WinForms/SongInfoControl.cs @@ -1,7 +1,6 @@ using Kermalis.VGMusicStudio.Core; using Kermalis.VGMusicStudio.Core.Properties; using Kermalis.VGMusicStudio.Core.Util; -using Kermalis.VGMusicStudio.WinForms.Util; using System; using System.ComponentModel; using System.Drawing; @@ -298,7 +297,7 @@ private void DrawVerticalBars(Graphics g, SongState.Track track, int vBarY1, int else { const int DELTA = 125; - alpha = (int)WinFormsUtils.Lerp(velocity * 0.5f, 0f, DELTA); + alpha = (int)GUIUtils.Lerp(velocity * 0.5f, 0f, DELTA); alpha += 255 - DELTA; } _solidBrush.Color = Color.FromArgb(alpha, color); diff --git a/VG Music Studio - WinForms/Util/WinFormsUtils.cs b/VG Music Studio - WinForms/Util/WinFormsUtils.cs index 33a0766..9b79cc4 100644 --- a/VG Music Studio - WinForms/Util/WinFormsUtils.cs +++ b/VG Music Studio - WinForms/Util/WinFormsUtils.cs @@ -1,76 +1,140 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; +using Kermalis.VGMusicStudio.Core.Properties; +using Kermalis.VGMusicStudio.Core.Util; +using System; using System.Windows.Forms; namespace Kermalis.VGMusicStudio.WinForms.Util; -internal static class WinFormsUtils +internal class WinFormsUtils : DialogUtils { - private static readonly Random _rng = new(); + private static void Convert(string filterName, Span fileExtensions) + { + string extensions; + if (fileExtensions == null) fileExtensions = new string[1]; + if (fileExtensions.Length > 1) + { + extensions = $"|"; + foreach (string ext in fileExtensions) + { + extensions += $"*.{ext}"; + if (ext != fileExtensions[fileExtensions.Length]) + { + extensions += $";"; + } + } + } + else + { + if (filterName.Contains('|')) + { + var filters = filterName.Split('|'); + fileExtensions[0] = filters[1]; + } + extensions = fileExtensions[0]; + if (extensions.StartsWith('.')) + { + if (extensions.Contains(';')) + { + var ext = extensions.Split(';'); + fileExtensions[0] = ext[0]; + } + } + else if (extensions.StartsWith('*')) + { + var modifiedExt = extensions.Trim('*'); + if (modifiedExt.Contains(';')) + { + var ext = modifiedExt.Split(';'); + fileExtensions[0] = ext[0]; + } + else + { + fileExtensions[0] = modifiedExt; + } + } + else + { + if (extensions.Contains(';')) + { + var ext = extensions.Split(';'); + fileExtensions[0] = $".{ext[0]}"; + } + else + { + fileExtensions[0] = extensions; + } + } + } + } - public static string Print(this IEnumerable source, bool parenthesis = true) - { - string str = parenthesis ? "( " : ""; - str += string.Join(", ", source); - str += parenthesis ? " )" : ""; - return str; - } - /// Fisher-Yates Shuffle - public static void Shuffle(this IList source) - { - for (int a = 0; a < source.Count - 1; a++) - { - int b = _rng.Next(a, source.Count); - (source[b], source[a]) = (source[a], source[b]); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public static float Lerp(float progress, float from, float to) - { - return from + ((to - from) * progress); - } - /// Maps a value in the range [a1, a2] to [b1, b2]. Divide by zero occurs if a1 and a2 are equal - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public static float Lerp(float value, float a1, float a2, float b1, float b2) - { - return b1 + ((value - a1) / (a2 - a1) * (b2 - b1)); - } - - public static string? CreateLoadDialog(string extension, string title, string filter) - { - var d = new OpenFileDialog - { - DefaultExt = extension, - ValidateNames = true, - CheckFileExists = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } - public static string? CreateSaveDialog(string fileName, string extension, string title, string filter) - { - var d = new SaveFileDialog - { - FileName = fileName, - DefaultExt = extension, - AddExtension = true, - ValidateNames = true, - CheckPathExists = true, - Title = title, - Filter = $"{filter}|All files (*.*)|*.*", - }; - if (d.ShowDialog() == DialogResult.OK) - { - return d.FileName; - } - return null; - } + public static string CreateLoadDialog(string title, object parent = null!) => + new WinFormsUtils().CreateLoadDialog(title, "", "", false, false, parent); + public static string CreateLoadDialog(string extension, string title, string filter, object parent = null!) => + new WinFormsUtils().CreateLoadDialog(title, filter, [extension], true, true, parent); + public static string CreateLoadDialog(Span extensions, string title, string filter, object parent = null!) => + new WinFormsUtils().CreateLoadDialog(title, filter, extensions, true, true, parent); + public override string CreateLoadDialog(string title, string filterName = "", string fileExtension = "", bool isFile = false, bool allowAllFiles = false, object? parent = null) => + CreateLoadDialog(title, filterName, [fileExtension], isFile, allowAllFiles); + public override string CreateLoadDialog(string title, string filterName, Span fileExtensions, bool isFile = false, bool allowAllFiles = false, object? parent = null) + { + if (isFile) + { + Convert(filterName, fileExtensions); + var allFiles = ""; + if (allowAllFiles) allFiles = $"|{Strings.FilterAllFiles}|*.*"; + var d = new OpenFileDialog + { + DefaultExt = fileExtensions[0], + ValidateNames = true, + CheckFileExists = true, + CheckPathExists = true, + Title = title, + Filter = $"{filterName}{allFiles}", + }; + if (d.ShowDialog() == DialogResult.OK) + { + return d.FileName; + } + } + else + { + var d = new FolderBrowserDialog + { + Description = Strings.MenuOpenDSE, + UseDescriptionForTitle = true, + }; + if (d.ShowDialog() == DialogResult.OK) + { + return d.SelectedPath; + } + } + return null!; + } + public static string CreateSaveDialog(string fileName, string extension, string title, string filter, object parent = null!) => + new WinFormsUtils().CreateSaveDialog(fileName, title, filter, [extension], false, false, parent); + public static string CreateSaveDialog(string fileName, Span extensions, string title, string filter, object parent = null!) => + new WinFormsUtils().CreateSaveDialog(fileName, title, filter, extensions, false, false, parent); + public override string CreateSaveDialog(string fileName, string title, string filterName, string fileExtension = "", bool isFile = false, bool allowAllFiles = false, object? parent = null) => + CreateSaveDialog(fileName, title, filterName, [fileExtension], false); + public override string CreateSaveDialog(string fileName, string title, string filterName, Span fileExtensions, bool isFile = false, bool allowAllFiles = false, object? parent = null) + { + Convert(filterName, fileExtensions); + var allFiles = ""; + if (allowAllFiles) allFiles = $"|{Strings.FilterAllFiles}|*.*"; + var d = new SaveFileDialog + { + FileName = fileName, + DefaultExt = fileExtensions[0], + AddExtension = true, + ValidateNames = true, + CheckPathExists = true, + Title = title, + Filter = $"{filterName}{allFiles}", + }; + if (d.ShowDialog() == DialogResult.OK) + { + return d.FileName; + } + return null!; + } } diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 31bb2a2..6d9df17 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -7,20 +7,68 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - WinForms" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - Core", "VG Music Studio - Core\VG Music Studio - Core.csproj", "{5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK3", "VG Music Studio - GTK3\VG Music Studio - GTK3.csproj", "{A9471061-10D2-41AE-86C9-1D927D7B33B8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio - GTK4", "VG Music Studio - GTK4\VG Music Studio - GTK4.csproj", "{AB599ACD-26E0-4925-B91E-E25D41CB05E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|ARM64.Build.0 = Debug|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|x64.ActiveCfg = Debug|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Debug|x64.Build.0 = Debug|Any CPU {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|Any CPU.Build.0 = Release|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|ARM64.ActiveCfg = Release|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|ARM64.Build.0 = Release|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|x64.ActiveCfg = Release|Any CPU + {646D3254-F214-4F33-991F-5D5DEB7219AA}.Release|x64.Build.0 = Release|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|ARM64.Build.0 = Debug|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|x64.ActiveCfg = Debug|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Debug|x64.Build.0 = Debug|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|Any CPU.Build.0 = Release|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|ARM64.ActiveCfg = Release|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|ARM64.Build.0 = Release|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|x64.ActiveCfg = Release|Any CPU + {5DC1E437-AEA1-4C0E-A57F-09D3DC9F4E7D}.Release|x64.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|ARM64.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|x64.ActiveCfg = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Debug|x64.Build.0 = Debug|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|Any CPU.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|ARM64.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|ARM64.Build.0 = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|x64.ActiveCfg = Release|Any CPU + {A9471061-10D2-41AE-86C9-1D927D7B33B8}.Release|x64.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|ARM64.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|x64.ActiveCfg = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Debug|x64.Build.0 = Debug|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|Any CPU.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|ARM64.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|ARM64.Build.0 = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|x64.ActiveCfg = Release|Any CPU + {AB599ACD-26E0-4925-B91E-E25D41CB05E8}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 33b2443600f3183141ef001b3b838e95fa1ff759 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Fri, 12 Jul 2024 21:27:43 +1000 Subject: [PATCH 17/20] PortAudio buffers are now functional --- VG Music Studio - Core/Engine.cs | 1 + VG Music Studio - Core/Formats/Wave.cs | 29 +- .../GBA/AlphaDream/AlphaDreamEngine.cs | 2 +- .../GBA/AlphaDream/AlphaDreamMixer.cs | 6 +- VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs | 3 +- VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 9 +- VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs | 25 +- VG Music Studio - Core/Mixer.cs | 840 ++++++++++-------- VG Music Studio - Core/NDS/DSE/DSEEngine.cs | 2 +- VG Music Studio - Core/NDS/SDAT/SDATEngine.cs | 2 +- .../VG Music Studio - GTK4.csproj | 2 +- VG Music Studio - WinForms/MainForm.cs | 2 +- .../VG Music Studio - WinForms.csproj | 2 +- 13 files changed, 509 insertions(+), 416 deletions(-) diff --git a/VG Music Studio - Core/Engine.cs b/VG Music Studio - Core/Engine.cs index d5c4b33..29554e0 100644 --- a/VG Music Studio - Core/Engine.cs +++ b/VG Music Studio - Core/Engine.cs @@ -8,6 +8,7 @@ public abstract class Engine : IDisposable public abstract Config Config { get; } public abstract Mixer Mixer { get; } + public abstract Mixer_NAudio Mixer_NAudio { get; } public abstract Player Player { get; } public abstract bool UseNewMixer { get; } diff --git a/VG Music Studio - Core/Formats/Wave.cs b/VG Music Studio - Core/Formats/Wave.cs index 5be041f..636070b 100644 --- a/VG Music Studio - Core/Formats/Wave.cs +++ b/VG Music Studio - Core/Formats/Wave.cs @@ -1,4 +1,5 @@ using Kermalis.EndianBinaryIO; +using NAudio.Utils; using System; using System.IO; @@ -50,6 +51,30 @@ public long Position } } + public int BufferedBytes + { + get + { + if (this != null) + { + return Count; + } + + return 0; + } + } + + public int Count + { + get + { + lock (LockObject!) + { + return ByteCount; + } + } + } + public Wave() { InStream = new MemoryStream(); @@ -72,8 +97,8 @@ public Wave CreateFormat(uint sampleRate, ushort channels, ushort blockAlign, ui ExtraSize = 0; return new Wave(); } - public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate* BlockAlign, 32); - public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels, ushort bits) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate * BlockAlign, bits); + public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate * (ushort)(4 * channels), 32); + public Wave CreateIeeeFloatWave(uint sampleRate, ushort channels, ushort bits) => CreateFormat(sampleRate, channels, (ushort)(4 * channels), sampleRate * (ushort)(4 * channels), bits); public void AddSamples(Span buffer, int offset, int count) { diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs index c5966b7..a59e28e 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamEngine.cs @@ -8,7 +8,7 @@ public sealed class AlphaDreamEngine : Engine public override AlphaDreamConfig Config { get; } public override AlphaDreamMixer Mixer { get; } - public AlphaDreamMixer_NAudio Mixer_NAudio { get; } + public override AlphaDreamMixer_NAudio Mixer_NAudio { get; } public override AlphaDreamPlayer Player { get; } public override bool UseNewMixer { get => false; } diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs index 04a02df..f601a14 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs @@ -28,7 +28,7 @@ internal AlphaDreamMixer(AlphaDreamConfig config) _samplesReciprocal = 1f / SamplesPerBuffer; int amt = SamplesPerBuffer * 2; - _audio = new Audio(amt) { FloatBufferCount = amt }; + _audio = new Audio(amt) { Float32BufferCount = amt }; for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) { _trackBuffers[i] = new float[amt]; @@ -110,8 +110,8 @@ internal void Process(AlphaDreamTrack[] tracks, bool output, bool recording) track.Channel.Process(buf); for (int j = 0; j < SamplesPerBuffer; j++) { - _audio.FloatBuffer![j * 2] += buf[j * 2] * level; - _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + _audio.Float32Buffer![j * 2] += buf[j * 2] * level; + _audio.Float32Buffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; level += masterStep; } } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs index f832aad..0f8c5ab 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KEngine.cs @@ -8,7 +8,7 @@ public sealed class MP2KEngine : Engine public override MP2KConfig Config { get; } public override MP2KMixer Mixer { get; } - public MP2KMixer_NAudio Mixer_NAudio { get; } + public override MP2KMixer_NAudio Mixer_NAudio { get; } public override MP2KPlayer Player { get; } public override bool UseNewMixer { get => true; } @@ -27,6 +27,7 @@ public MP2KEngine(byte[] rom) } else { + Mixer = new MP2KMixer(); Mixer_NAudio = new MP2KMixer_NAudio(Config); Player = new MP2KPlayer(Config, Mixer_NAudio); } diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index 9e725e4..3d2f030 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -28,6 +28,8 @@ public sealed class MP2KMixer : Mixer private readonly MP2KPSGChannel[] _psgChannels; private readonly Wave _buffer; + internal MP2KMixer() { } + internal MP2KMixer(MP2KConfig config) { Config = config; @@ -45,7 +47,7 @@ internal MP2KMixer(MP2KConfig config) int amt = SamplesPerBuffer * 2; Instance = this; - _audio = new Audio(amt) { FloatBufferCount = amt }; + _audio = new Audio(amt * sizeof(float)) { Float32BufferCount = amt }; _trackBuffers = new float[0x10][]; for (int i = 0; i < _trackBuffers.Length; i++) { @@ -249,14 +251,15 @@ internal void Process(bool output, bool recording) float[] buf = _trackBuffers[i]; for (int j = 0; j < SamplesPerBuffer; j++) { - _audio.FloatBuffer![j * 2] += buf[j * 2] * level; - _audio.FloatBuffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + _audio.Float32Buffer![j * 2] += buf[j * 2] * level; + _audio.Float32Buffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; level += masterStep; } } if (output) { _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + Instance!.Buffer = _audio.Float32Buffer!; } if (recording) { diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs b/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs index e612465..0ec7376 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KTrack.cs @@ -202,18 +202,21 @@ public void UpdateSongState(SongState.Track tin, MP2KLoadedSong loadedSong, stri for (int j = 0; j < channels.Length; j++) { MP2KChannel c = channels[j]; - if (c.State < EnvelopeState.Releasing) + if (c is not null) { - tin.Keys[numKeys++] = c.Note.OriginalNote; - } - ChannelVolume vol = c.GetVolume(); - if (vol.LeftVol > left) - { - left = vol.LeftVol; - } - if (vol.RightVol > right) - { - right = vol.RightVol; + if (c.State < EnvelopeState.Releasing) + { + tin.Keys[numKeys++] = c.Note.OriginalNote; + } + ChannelVolume vol = c.GetVolume(); + if (vol.LeftVol > left) + { + left = vol.LeftVol; + } + if (vol.RightVol > right) + { + right = vol.RightVol; + } } } tin.Keys[numKeys] = byte.MaxValue; // There's no way for numKeys to be after the last index in the array diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index e059b8b..676d3fe 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -10,410 +10,470 @@ namespace Kermalis.VGMusicStudio.Core; public abstract class Mixer : IDisposable { - public static event Action? VolumeChanged; + public static event Action? VolumeChanged; - public Wave? WaveData; - public EndianBinaryReader? Reader; - public byte[] Buffer; + public Wave? WaveData; + public EndianBinaryReader? Reader; + public float[] Buffer; - public readonly bool[] Mutes; - public int SizeInBytes; - public uint CombinedSamplesPerBuffer; - public int SizeToAllocateInBytes; - public long FinalFrameSize; - public long TotalFrames; - internal long Pos = 0; - internal float Vol = 1; + public readonly bool[] Mutes; + public int SizeInBytes; + public uint FramesPerBuffer; + public uint CombinedSamplesPerBuffer; + public int SizeToAllocateInBytes; + public long FinalFrameSize; + public long TotalFrames; + internal long Pos = 0; + internal float Vol = 1; - public int freePos = 0; - public int dataPos = 0; - public int freeCount; - public int dataCount = 0; + public int freePos = 0; + public int dataPos = 0; + public int freeCount; + public int dataCount = 0; - public readonly object CountLock = new object(); + public readonly object CountLock = new object(); - private bool _shouldSendVolUpdateEvent = true; + private bool _shouldSendVolUpdateEvent = true; - protected Wave? _waveWriter; + protected Wave? _waveWriter; - internal bool PlayingBack = false; - public StreamParameters OParams; - public StreamParameters DefaultOutputParams { get; private set; } + internal bool PlayingBack = false; + public StreamParameters OParams; + public StreamParameters DefaultOutputParams { get; private set; } - private Stream? Stream; - private bool IsDisposed = false; + private Stream? Stream; + private bool IsDisposed = false; - public static Mixer? Instance { get; set; } + public static Mixer? Instance { get; set; } - protected Mixer() - { - Mutes = new bool[SongState.MAX_TRACKS]; - } + protected Mixer() + { + Mutes = new bool[SongState.MAX_TRACKS]; + Buffer = null!; + } - protected void Init(Wave waveData) - { - // First, check if the instance contains something - if (WaveData == null) - { - IsDisposed = false; + protected void Init(Wave waveData) + { + // First, check if the instance contains something + if (WaveData == null) + { + IsDisposed = false; - Pa.Initialize(); - WaveData = waveData; - Reader = new EndianBinaryReader(new MemoryStream(Buffer!)); + Pa.Initialize(); + WaveData = waveData; //Instance = this; // Try setting up an output device OParams.device = Pa.DefaultOutputDevice; - if (OParams.device == Pa.NoDevice) - throw new Exception("No default audio output device is available."); - - OParams.channelCount = 2; - OParams.sampleFormat = SampleFormat.Float32; - OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; - OParams.hostApiSpecificStreamInfo = IntPtr.Zero; - - // Set it as a the default - DefaultOutputParams = OParams; - } - - Sound(); - - Play(); - } - - private void Sound() - { - Stream = new Stream( - null, - OParams, - WaveData!.SampleRate, - CombinedSamplesPerBuffer, - StreamFlags.ClipOff, - PlayCallback, - this - ); - - FinalFrameSize = CombinedSamplesPerBuffer; - TotalFrames = WaveData.Channels * WaveData.BufferLength; - } - - private static StreamCallbackResult PlayCallback( - nint input, nint output, - uint frameCount, - ref StreamCallbackTimeInfo timeInfo, - StreamCallbackFlags statusFlags, - nint data - ) - { - // Ensure there's no memory allocated in this block to prevent issues - Mixer d = Stream.GetUserData(data); - - long numRead = 0; - unsafe - { - // Do a zero-out memset - float* buffer = (float*)output; - for (uint i = 0; i < d.FinalFrameSize; i++) - *buffer++ = 0; - - // If we're reading data, play it back - if (d.PlayingBack) - { - // Read the data - numRead = 8192; - //numRead = d.ReadFloat(output, d.FinalFrameSize); - - // Apply volume - buffer = (float*)output; - for (int i = 0; i < numRead; i++) - *buffer++ *= d.Volume; - } - } - - // Increment counter - d.Pos += numRead; - - // If it's at end of the data - if (d.PlayingBack && (numRead < frameCount)) - { - if (d.WaveData!.IsLooped) - d.Cursor = d.WaveData.LoopStart; - else - d.Cursor = 0; - d.PlayingBack = false; - } - - // Continue on - return StreamCallbackResult.Continue; - } - - private long ReadFloat(nint outData, long nElements) - { - if (Reader == null) - { - Reader = new EndianBinaryReader(new MemoryStream(WaveData!.Buffer!)); - } - if (outData > nElements) - { - Reader.Stream.Position = outData = (nint)WaveData!.LoopStart; - return WaveData.LoopStart; - } - else - { - Reader.Stream.Position = outData; - return Reader!.ReadInt16(); - } - //if (dataCount < nElements) - //{ - // // underrun - // std::fill(outData, outData + nElements, sample{ 0.0f, 0.0f}); - //} - //else - //{ - // // output - // std::unique_lock < std::mutex > lock (CountLock) ; - // while (nElements > 0) - // { - // int count = takeChunk(outData, nElements); - // outData += count; - // nElements -= count; - // } - // sig.notify_one(); - //} - } - - public float Volume - { - get => Vol; - set => Vol = Math.Max(Math.Min(value, 0), 1); - } - - public bool IsPlaying - { - get => PlayingBack; - } - - public float Cursor - { - get => (float)(Pos) / (float)(TotalFrames) * (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; - set - { - // Do math - float per = value / (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; - long frame = (long)(per * TotalFrames); - - // Clamp - frame = Math.Max(Math.Min(frame, 0), TotalFrames); - - // Set (stop playback for a very short while, to stop some back skipping noises) - bool wasPlaying = IsPlaying; - if (Pos != TotalFrames) // this check stops a segfault when the audio has reached the end of playback - Pause(); - - Pos = frame; - Reader!.Stream.Seek(Pos / WaveData!.Channels, SeekOrigin.Begin); - - if (wasPlaying) - Play(); - } - } - - public void Play() - { - PlayingBack = true; - - if (Stream!.IsStopped) - Stream.Start(); - } - - public void Pause() - { - PlayingBack = false; - - if (Stream!.IsActive) - Stream.Stop(); - } - - public float GetVolume() - { - return Vol; - } - - public void SetVolume(float volume) - { - Vol = Math.Max(Math.Min(volume, 0), 1); - } - - public void CreateWaveWriter(string fileName) - { - _waveWriter = new Wave(fileName); - } - public void CloseWaveWriter() - { - - } - - public virtual void Dispose() - { - if (IsDisposed) return; - - Stream!.Dispose(); - Reader!.Stream.Dispose(); - GC.SuppressFinalize(this); - - IsDisposed = true; - } - - public interface IAudio - { - byte[] ByteBuffer { get; } - float[] FloatBuffer { get; } - short[] ShortBuffer { get; } - int[] IntBuffer { get; } - } - - [StructLayout(LayoutKind.Explicit, Pack = 2)] - public class Audio : IAudio - { - [FieldOffset(0)] - public int NumberOfBytes; - [FieldOffset(8)] - public byte[] ByteBuffer; - [FieldOffset(8)] - public float[]? FloatBuffer; - [FieldOffset(8)] - public short[]? ShortBuffer; - [FieldOffset(8)] - public int[]? IntBuffer; - - byte[] IAudio.ByteBuffer => ByteBuffer; - float[] IAudio.FloatBuffer => FloatBuffer!; - short[] IAudio.ShortBuffer => ShortBuffer!; - int[] IAudio.IntBuffer => IntBuffer!; - - public int ByteBufferCount - { - get - { - return NumberOfBytes; - } - set - { - NumberOfBytes = CheckValidityCount("ByteBufferCount", value, 1); - } - } - - public int ShortBufferCount - { - get - { - return NumberOfBytes / 2; - } - set - { - NumberOfBytes = CheckValidityCount("ShortBufferCount", value, 2); - } - } - - public int IntBufferCount - { - get - { - return NumberOfBytes / 4; - } - set - { - NumberOfBytes = CheckValidityCount("IntBufferCount", value, 4); - } - } - - public int LongBufferCount - { - get - { - return NumberOfBytes / 8; - } - set - { - NumberOfBytes = CheckValidityCount("LongBufferCount", value, 8); - } - } - - public int HalfBufferCount - { - get - { - return NumberOfBytes / 2; - } - set - { - NumberOfBytes = CheckValidityCount("HalfBufferCount", value, 2); - } - } - - public int FloatBufferCount - { - get - { - return NumberOfBytes / 4; - } - set - { - NumberOfBytes = CheckValidityCount("FloatBufferCount", value, 4); - } - } - - public int DoubleBufferCount - { - get - { - return NumberOfBytes / 8; - } - set - { - NumberOfBytes = CheckValidityCount("DoubleBufferCount", value, 8); - } - } - - public Audio(int combinedSamplesPerBuffer) - { - Instance!.CombinedSamplesPerBuffer = (uint)combinedSamplesPerBuffer; - Instance.SizeInBytes = combinedSamplesPerBuffer * sizeof(float); - int num = Instance.SizeInBytes % 4; - Instance.SizeToAllocateInBytes = (num == 0) ? Instance.SizeInBytes : (Instance.SizeInBytes + 4 - num); - Instance.Buffer = ByteBuffer = new byte[Instance.SizeToAllocateInBytes]; - NumberOfBytes = 0; - } - - public static implicit operator byte[](Audio waveBuffer) - { - return waveBuffer.ByteBuffer; - } - - private int CheckValidityCount(string argName, int value, int sizeOfValue) - { - int num = value * sizeOfValue; - if (num % 4 != 0) - { - throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); - } - - if (value < 0 || value > ByteBuffer.Length / sizeOfValue) - { - throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceed max count {ByteBuffer.Length / sizeOfValue}"); - } - - return num; - } - - public void Clear() - { - Array.Clear(ByteBuffer, 0, ByteBuffer.Length); - } - - public void Copy(Array destinationArray) - { - Array.Copy(ByteBuffer, destinationArray, NumberOfBytes); - } - } + if (OParams.device == Pa.NoDevice) + throw new Exception("No default audio output device is available."); + + OParams.channelCount = 2; + OParams.sampleFormat = SampleFormat.Float32; + OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; + OParams.hostApiSpecificStreamInfo = IntPtr.Zero; + + // Set it as a the default + DefaultOutputParams = OParams; + } + + Sound(); + + Play(); + } + + private void Sound() + { + Stream = new Stream( + null, + OParams, + WaveData!.SampleRate, + FramesPerBuffer, + StreamFlags.ClipOff, + PlayCallback, + this + ); + + FinalFrameSize = FramesPerBuffer * 2; + TotalFrames = WaveData.Channels * WaveData.BufferLength; + } + + private static StreamCallbackResult PlayCallback( + nint input, nint output, + uint frameCount, + ref StreamCallbackTimeInfo timeInfo, + StreamCallbackFlags statusFlags, + nint data + ) + { + // Ensure there's no memory allocated in this block to prevent issues + Mixer d = Stream.GetUserData(data); + + long numRead = 0; + Span buffer; + unsafe + { + buffer = new Span(output.ToPointer(), (int)d.FinalFrameSize); + } + + // Do a zero-out memset + //float* buffer = (float*)output; + //for (uint i = 0; i < d.FinalFrameSize; i++) + // buffer[i] = 0; + + // If we're reading data, play it back + if (d.PlayingBack) + { + // Read the data + numRead = d.FinalFrameSize; + + //for (int i = 0; i < numRead; i++) + // buffer[i] = d.Buffer[i] >> 7; + + // Apply volume with buffer value + for (int i = 0; i < numRead; i++) + buffer[i] = d.Buffer[i] * d.Vol; + //numRead = d.ReadFloat(output, d.FinalFrameSize); + + // Apply volume + //buffer = (float*)output; + //for (int i = 0; i < numRead; i++) + // buffer[i] *= d.Volume; + } + + //// Increment counter + //d.Pos += numRead; + + //// If it's at end of the data + //if (d.PlayingBack && (numRead < frameCount)) + //{ + // if (d.WaveData!.IsLooped) + // d.Cursor = d.WaveData.LoopStart; + // else + // d.Cursor = 0; + // d.PlayingBack = false; + // return StreamCallbackResult.Complete; + //} + + // Continue on + return StreamCallbackResult.Continue; + } + + private long ReadFloat(nint outData, long nElements) + { + if (Reader == null) + { + Reader = new EndianBinaryReader(new MemoryStream(WaveData!.Buffer!)); + } + if (outData > nElements) + { + Reader.Stream.Position = outData = (nint)WaveData!.LoopStart; + return WaveData.LoopStart; + } + else + { + Reader.Stream.Position = outData; + return Reader!.ReadInt16(); + } + //if (dataCount < nElements) + //{ + // // underrun + // std::fill(outData, outData + nElements, sample{ 0.0f, 0.0f}); + //} + //else + //{ + // // output + // std::unique_lock < std::mutex > lock (CountLock) ; + // while (nElements > 0) + // { + // int count = takeChunk(outData, nElements); + // outData += count; + // nElements -= count; + // } + // sig.notify_one(); + //} + } + + public float Volume + { + get => Vol; + set => Vol = Math.Clamp(value, 0, 1); + } + + public bool IsPlaying + { + get => PlayingBack; + } + + public float Cursor + { + get => (float)(Pos) / (float)(TotalFrames) * (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; + set + { + // Do math + float per = value / (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; + long frame = (long)(per * TotalFrames); + + // Clamp + frame = Math.Max(Math.Min(frame, 0), TotalFrames); + + // Set (stop playback for a very short while, to stop some back skipping noises) + bool wasPlaying = IsPlaying; + if (Pos != TotalFrames) // this check stops a segfault when the audio has reached the end of playback + Pause(); + + Pos = frame; + Reader!.Stream.Seek(Pos / WaveData!.Channels, SeekOrigin.Begin); + + if (wasPlaying) + Play(); + } + } + + public void Play() + { + PlayingBack = true; + + if (Stream!.IsStopped) + Stream.Start(); + } + + public void Pause() + { + PlayingBack = false; + + if (Stream!.IsActive) + Stream.Stop(); + } + + public float GetVolume() + { + return Vol; + } + + public void SetVolume(float volume) + { + if (!Engine.Instance!.UseNewMixer) + Engine.Instance.Mixer_NAudio.SetVolume(volume); + else + Vol = Math.Clamp(volume, 0, 1); + } + + public void CreateWaveWriter(string fileName) + { + _waveWriter = new Wave(fileName); + } + public void CloseWaveWriter() + { + + } + + public virtual void Dispose() + { + if (IsDisposed || Stream is null) return; + + Stream!.Dispose(); + //Reader!.Stream.Dispose(); + GC.SuppressFinalize(this); + + IsDisposed = true; + } + + public interface IAudio + { + Span ByteBuffer { get; } + Span Int16Buffer { get; } + Span Int32Buffer { get; } + Span Int64Buffer { get; } + Span Int128Buffer { get; } + Span Float16Buffer { get; } + Span Float32Buffer { get; } + Span Float64Buffer { get; } + Span Float128Buffer { get; } + } + + [StructLayout(LayoutKind.Explicit, Pack = 2)] + public class Audio : IAudio + { + [FieldOffset(0)] + public int NumberOfBytes; + [FieldOffset(8)] + public byte[]? ByteBuffer; + [FieldOffset(8)] + public short[]? Int16Buffer; + [FieldOffset(8)] + public int[]? Int32Buffer; + [FieldOffset(8)] + public long[]? Int64Buffer; + [FieldOffset(8)] + public Int128[]? Int128Buffer; + [FieldOffset(8)] + public Half[]? Float16Buffer; + [FieldOffset(8)] + public float[]? Float32Buffer; + [FieldOffset(8)] + public double[]? Float64Buffer; + [FieldOffset(8)] + public decimal[]? Float128Buffer; + + Span IAudio.ByteBuffer => ByteBuffer!; + Span IAudio.Int16Buffer => Int16Buffer!; + Span IAudio.Int32Buffer => Int32Buffer!; + Span IAudio.Int64Buffer => Int64Buffer!; + Span IAudio.Int128Buffer => Int128Buffer!; + Span IAudio.Float16Buffer => Float16Buffer!; + Span IAudio.Float32Buffer => Float32Buffer!; + Span IAudio.Float64Buffer => Float64Buffer!; + Span IAudio.Float128Buffer => Float128Buffer!; + + public int ByteBufferCount + { + get + { + return NumberOfBytes; + } + set + { + NumberOfBytes = CheckValidityCount("ByteBufferCount", value, 1); + } + } + + public int Int16BufferCount + { + get + { + return NumberOfBytes / 2; + } + set + { + NumberOfBytes = CheckValidityCount("Int16BufferCount", value, 2); + } + } + + public int Int32BufferCount + { + get + { + return NumberOfBytes / 4; + } + set + { + NumberOfBytes = CheckValidityCount("Int32BufferCount", value, 4); + } + } + + public int Int64BufferCount + { + get + { + return NumberOfBytes / 8; + } + set + { + NumberOfBytes = CheckValidityCount("Int64BufferCount", value, 8); + } + } + + public int Int128BufferCount + { + get + { + return NumberOfBytes / 16; + } + set + { + NumberOfBytes = CheckValidityCount("Int128BufferCount", value, 16); + } + } + + public int Float16BufferCount + { + get + { + return NumberOfBytes / 2; + } + set + { + NumberOfBytes = CheckValidityCount("Float16BufferCount", value, 2); + } + } + + public int Float32BufferCount + { + get + { + return NumberOfBytes / 4; + } + set + { + NumberOfBytes = CheckValidityCount("Float32BufferCount", value, 4); + } + } + + public int Float64BufferCount + { + get + { + return NumberOfBytes / 8; + } + set + { + NumberOfBytes = CheckValidityCount("Float64BufferCount", value, 8); + } + } + + public int Float128BufferCount + { + get + { + return NumberOfBytes / 16; + } + set + { + NumberOfBytes = CheckValidityCount("Float128BufferCount", value, 16); + } + } + + public Audio(int sizeToAllocateInBytes) + { + Instance!.FramesPerBuffer = (uint)(sizeToAllocateInBytes / sizeof(float)) / 2; + //Instance.CombinedSamplesPerBuffer = (uint)SamplesPerBuffer * 2; + Instance.SizeInBytes = sizeToAllocateInBytes; + int num = Instance.SizeInBytes % 4; + Instance.SizeToAllocateInBytes = (num == 0) ? Instance.SizeInBytes : (Instance.SizeInBytes + 4 - num); + Instance.Buffer = Float32Buffer = new float[Instance.SizeToAllocateInBytes]; + NumberOfBytes = 0; + } + + public static implicit operator byte[](Audio waveBuffer) + { + return waveBuffer.ByteBuffer!; + } + + private int CheckValidityCount(string argName, int value, int sizeOfValue) + { + int num = value * sizeOfValue; + if (num % 4 != 0) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); + } + + if (value < 0 || value > ByteBuffer.Length / sizeOfValue) + { + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceeds max count of {ByteBuffer.Length / sizeOfValue}."); + } + + return num; + } + + public void Clear() + { + Array.Clear(ByteBuffer, 0, ByteBuffer.Length); + } + + public void Copy(Array destinationArray) + { + Array.Copy(ByteBuffer, destinationArray, NumberOfBytes); + } + } } diff --git a/VG Music Studio - Core/NDS/DSE/DSEEngine.cs b/VG Music Studio - Core/NDS/DSE/DSEEngine.cs index 5fe7228..6b1ffdd 100644 --- a/VG Music Studio - Core/NDS/DSE/DSEEngine.cs +++ b/VG Music Studio - Core/NDS/DSE/DSEEngine.cs @@ -6,7 +6,7 @@ public sealed class DSEEngine : Engine public override DSEConfig Config { get; } public override DSEMixer Mixer { get; } - public DSEMixer_NAudio Mixer_NAudio { get; } + public override DSEMixer_NAudio Mixer_NAudio { get; } public override DSEPlayer Player { get; } public override bool UseNewMixer { get => false; } diff --git a/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs b/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs index f2bc349..faea0af 100644 --- a/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs +++ b/VG Music Studio - Core/NDS/SDAT/SDATEngine.cs @@ -6,7 +6,7 @@ public sealed class SDATEngine : Engine public override SDATConfig Config { get; } public override SDATMixer Mixer { get; } - public SDATMixer_NAudio Mixer_NAudio { get; } + public override SDATMixer_NAudio Mixer_NAudio { get; } public override SDATPlayer Player { get; } public override bool UseNewMixer { get => false; } diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj index b3d37e9..60fd97f 100644 --- a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -8,7 +8,7 @@ - + diff --git a/VG Music Studio - WinForms/MainForm.cs b/VG Music Studio - WinForms/MainForm.cs index 8820c08..00c54a0 100644 --- a/VG Music Studio - WinForms/MainForm.cs +++ b/VG Music Studio - WinForms/MainForm.cs @@ -737,7 +737,7 @@ private void Timer_Tick(object? sender, EventArgs e) } private void Mixer_VolumeChanged(float volume) { - _volumeBar.ValueChanged -= VolumeBar_ValueChanged; + //_volumeBar.ValueChanged -= VolumeBar_ValueChanged; _volumeBar.Value = (int)(volume * _volumeBar.Maximum); _volumeBar.ValueChanged += VolumeBar_ValueChanged; } diff --git a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj index cd3552b..b1c5a71 100644 --- a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj +++ b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj @@ -21,7 +21,7 @@ - + From d24593790cfcdc6cf860653763eda18b99b800a0 Mon Sep 17 00:00:00 2001 From: PlatinumLucario Date: Sun, 14 Jul 2024 04:57:28 +1000 Subject: [PATCH 18/20] Repaired GTK4 GUI It should be able to open now. Will test it out on Ubuntu soon. --- .../Dependencies/KMIDI.deps.json | 41 -- VG Music Studio - Core/Dependencies/KMIDI.dll | Bin 49664 -> 0 bytes VG Music Studio - Core/Dependencies/KMIDI.xml | 77 --- VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 492 +++++++++--------- VG Music Studio - Core/Mixer.cs | 145 +----- VG Music Studio - Core/PortAudio/Stream.cs | 4 + .../VG Music Studio - Core.csproj | 10 +- VG Music Studio - GTK4/MainWindow.cs | 133 ++--- VG Music Studio - GTK4/Util/GTK4Utils.cs | 7 +- .../VG Music Studio - GTK4.csproj | 253 +++++++++ VG Music Studio - WinForms/MainForm.cs | 2 +- .../VG Music Studio - WinForms.csproj | 2 +- 12 files changed, 596 insertions(+), 570 deletions(-) delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.deps.json delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.dll delete mode 100644 VG Music Studio - Core/Dependencies/KMIDI.xml diff --git a/VG Music Studio - Core/Dependencies/KMIDI.deps.json b/VG Music Studio - Core/Dependencies/KMIDI.deps.json deleted file mode 100644 index 7feb759..0000000 --- a/VG Music Studio - Core/Dependencies/KMIDI.deps.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "runtimeTarget": { - "name": ".NETCoreApp,Version=v7.0", - "signature": "" - }, - "compilationOptions": {}, - "targets": { - ".NETCoreApp,Version=v7.0": { - "KMIDI/1.0.0": { - "dependencies": { - "EndianBinaryIO": "2.1.0" - }, - "runtime": { - "KMIDI.dll": {} - } - }, - "EndianBinaryIO/2.1.0": { - "runtime": { - "lib/net7.0/EndianBinaryIO.dll": { - "assemblyVersion": "2.1.0.0", - "fileVersion": "2.1.0.0" - } - } - } - } - }, - "libraries": { - "KMIDI/1.0.0": { - "type": "project", - "serviceable": false, - "sha512": "" - }, - "EndianBinaryIO/2.1.0": { - "type": "package", - "serviceable": true, - "sha512": "sha512-OzcYSj5h37lj8PJAcROuYIW+FEO/it3Famh3cduziKQzE2ZKDgirNUJNnDCYkHgBxc2CRc//GV2ChRSqlXhbjQ==", - "path": "endianbinaryio/2.1.0", - "hashPath": "endianbinaryio.2.1.0.nupkg.sha512" - } - } -} \ No newline at end of file diff --git a/VG Music Studio - Core/Dependencies/KMIDI.dll b/VG Music Studio - Core/Dependencies/KMIDI.dll deleted file mode 100644 index 372b9e3267f3ac7910431a340807fa7f02cdc29b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 49664 zcmbq+3t&{$we~va%$#}TITP{%LMA|PBq2f)Bq&ls5+KSWl8B&am?T3oGMR}p69k1C z6e(6zd|YcST70zCYOVHKtJb#oe$-ZLt=D_6ZK2v$TibGb?O)qk{J*vKIr9i$Z7(|C zS$plh*Is+=wby=}8CY@7UNVTtfzL-D5j}z@|5+sX@i2z$!s^Eg=^@V#Y97&+|DdL4 zD3T0}B;tdK&~TtX6pO`Efxd7cF&Ya*VuAKm-GSlwK)9ixz&qU%-PJ*~Tr=pMs)v7X zw|0=G2J*DoM2~@ED(+>k;~Bu`AU;IJLhDLzX0ZP9C!i65&wmWsa0M6T|1(c3$t?V7 zfZSC~93;wTLmc%-qkQmo|AeUJsJxG11c=;O*>0qlWu+TZ;VmhoceBBfCw;Z_MoRt! zh&D7Nl8Jt#M7M(=xTBBbll5m2hN~eFj>b`tbtSTFa6l4iSVXiqov?^Lwk!UyZaO(> z=ecO&Vv!*He-@_d!6`&un%QR&dimA$5La7f?As2t95WZ%8OBj*9?$H2jE7?;QORtb zCO{EX_mLj2hWvN{V8qsX>&Tp0GTWd8@=-lE|A_82>(3;=R$W;UtU(RGmVl6v;8a%8 zuQ`I#6p@&f#dQWzrViPOxmny`Es7>*04`Q481WOh@=WwND8v-~5+^H+C!E%S3}d?x zV7QpUdUiukbjzm)J>uI&g(z7?BzdYajYESvGL(S$94m)yamgbZITT0cu0c-tBn;#uKUL>d z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)7gg z@7qQidW@{f8VQFDRf7{;sg6tk&(6!%r{0wIN6*Qww~e$PJ12_|9hYLUDEgbD-|b%# zwn$}+Ne!_?y`1hh^4eoYItnj|*|k(A>Fs2e|9H*O+sW)(MvA0s?zE9q&dBm7jVyi6 zkQgJu9~p7Jz zVyC=o9+x*BpC40KakH3w|$s4uK7vvRlrbkR z^f$9liXz29p|{~55?@iw`APX6ThQ4__^I<^-XXw|S}`-H#XEdb+E2YLSG{>bR+vA^ zsQHcj*gPf^=67O_uor)SUS`OPVzD6SUZ0Xwsvw!KosfGE9F?atPs_{2DXNZ(GIeyN z%snqsAP;IkG9|};@Ll=l_fJT%P*^y8{-63Eae&{(W6gYe8(&C(mC#gFU7D|O8+qRI z2cfTEP5H-kpp}uGRDX6cY?tkfZK7YMtxT&@<#xvPI39fG1N*S1Yk)ocYpRqA@_G?k zo110`VpXM!s{2$irK%BCCF#+?8O>Q?)n&SoIY7v=4&DODbkHSIkS0~Cslu@LKVW)` zq=2n1|5~Y^;AJK#uoWI0E&Mz>G9Qjx)DM}4v$uTRRHsK=thigv1#3^ zHZ9qE*s^8Sovy5)qb8HY)iDhDf+ZKiU}w;ySu z%33!N)lZYQWeeeZEwr{O&-N%~y;MJqTAD6x&stm8wi29j(BIwgdqY!$#HqZvw9cgE zg|A%R%gqE;BUY%qxQy~Z`L+=D-#Jm?gHVB{JiCp2(oM8M_L!>26C5oIxmPKpJiLsL TQ$jCs{NChEmoX16 - - - KMIDI - - - - Includes the end of track event - - - - - - If there are other events at , will be inserted after them. - - - Length 4 - - - Contains a single multi-channel track - - - Contains one or more simultaneous tracks - - - Contains one or more independent single-track patterns - - - Used with - - - Used with - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Reserved for ASCII treatment - - - Not optional - - - Used with - - - Used with - - - Used with - - - How many ticks are between this event and the previous one. If this is the first event in the track, then it is equal to - - - Returns a value in the range [-8_192, 8_191] - - - - - - Middle C - - - diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index 3d2f030..a3b473f 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -7,263 +7,263 @@ namespace Kermalis.VGMusicStudio.Core.GBA.MP2K; public sealed class MP2KMixer : Mixer { - internal readonly int SampleRate; - internal readonly int SamplesPerBuffer; - internal readonly float SampleRateReciprocal; - private readonly float _samplesReciprocal; - internal readonly float PCM8MasterVolume; - private bool _isFading; - private long _fadeMicroFramesLeft; - private float _fadePos; - private float _fadeStepPerMicroframe; + internal readonly int SampleRate; + internal readonly int SamplesPerBuffer; + internal readonly float SampleRateReciprocal; + private readonly float _samplesReciprocal; + internal readonly float PCM8MasterVolume; + private bool _isFading; + private long _fadeMicroFramesLeft; + private float _fadePos; + private float _fadeStepPerMicroframe; - internal readonly MP2KConfig Config; - private readonly Audio _audio; - private readonly float[][] _trackBuffers; - private readonly MP2KPCM8Channel[] _pcm8Channels; - private readonly MP2KSquareChannel _sq1; - private readonly MP2KSquareChannel _sq2; - private readonly MP2KPCM4Channel _pcm4; - private readonly MP2KNoiseChannel _noise; - private readonly MP2KPSGChannel[] _psgChannels; - private readonly Wave _buffer; + internal readonly MP2KConfig Config; + private readonly Audio _audio; + private readonly float[][] _trackBuffers; + private readonly MP2KPCM8Channel[] _pcm8Channels; + private readonly MP2KSquareChannel _sq1; + private readonly MP2KSquareChannel _sq2; + private readonly MP2KPCM4Channel _pcm4; + private readonly MP2KNoiseChannel _noise; + private readonly MP2KPSGChannel[] _psgChannels; + private readonly Wave _buffer; - internal MP2KMixer() { } + internal MP2KMixer() { } - internal MP2KMixer(MP2KConfig config) - { - Config = config; - (SampleRate, SamplesPerBuffer) = MP2KUtils.FrequencyTable[config.SampleRate]; - SampleRateReciprocal = 1f / SampleRate; - _samplesReciprocal = 1f / SamplesPerBuffer; - PCM8MasterVolume = config.Volume / 15f; + internal MP2KMixer(MP2KConfig config) + { + Config = config; + (SampleRate, SamplesPerBuffer) = MP2KUtils.FrequencyTable[config.SampleRate]; + SampleRateReciprocal = 1f / SampleRate; + _samplesReciprocal = 1f / SamplesPerBuffer; + PCM8MasterVolume = config.Volume / 15f; - _pcm8Channels = new MP2KPCM8Channel[24]; - for (int i = 0; i < _pcm8Channels.Length; i++) - { - _pcm8Channels[i] = new MP2KPCM8Channel(this); - } - _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; + _pcm8Channels = new MP2KPCM8Channel[24]; + for (int i = 0; i < _pcm8Channels.Length; i++) + { + _pcm8Channels[i] = new MP2KPCM8Channel(this); + } + _psgChannels = new MP2KPSGChannel[4] { _sq1 = new MP2KSquareChannel(this), _sq2 = new MP2KSquareChannel(this), _pcm4 = new MP2KPCM4Channel(this), _noise = new MP2KNoiseChannel(this), }; - int amt = SamplesPerBuffer * 2; - Instance = this; - _audio = new Audio(amt * sizeof(float)) { Float32BufferCount = amt }; - _trackBuffers = new float[0x10][]; - for (int i = 0; i < _trackBuffers.Length; i++) - { - _trackBuffers[i] = new float[amt]; - } - _buffer = new Wave() - { - DiscardOnBufferOverflow = true, - BufferLength = SamplesPerBuffer * 64, - }; - _buffer.CreateIeeeFloatWave((uint)SampleRate, 2); + int amt = SamplesPerBuffer * 2; + Instance = this; + _audio = new Audio(amt * sizeof(float)) { Float32BufferCount = amt }; + _trackBuffers = new float[0x10][]; + for (int i = 0; i < _trackBuffers.Length; i++) + { + _trackBuffers[i] = new float[amt]; + } + _buffer = new Wave() + { + DiscardOnBufferOverflow = true, + BufferLength = SamplesPerBuffer * 64, + }; + _buffer.CreateIeeeFloatWave((uint)SampleRate, 2); - Init(_buffer); - } + Init(_buffer); + } - internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) - { - MP2KPCM8Channel? nChn = null; - IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner is null ? 0xFF : c.Owner.Index); - foreach (MP2KPCM8Channel i in byOwner) // Find free - { - if (i.State == EnvelopeState.Dead || i.Owner is null) - { - nChn = i; - break; - } - } - if (nChn is null) // Find releasing - { - foreach (MP2KPCM8Channel i in byOwner) - { - if (i.State == EnvelopeState.Releasing) - { - nChn = i; - break; - } - } - } - if (nChn is null) // Find prioritized - { - foreach (MP2KPCM8Channel i in byOwner) - { - if (owner.Priority > i.Owner!.Priority) - { - nChn = i; - break; - } - } - } - if (nChn is null) // None available - { - MP2KPCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one - if (lowest.Owner!.Index >= owner.Index) - { - nChn = lowest; - } - } - if (nChn is not null) // Could still be null from the above if - { - nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); - } - return nChn; - } - internal MP2KPSGChannel? AllocPSGChannel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) - { - MP2KPSGChannel nChn; - switch (type) - { - case VoiceType.Square1: - { - nChn = _sq1; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) - { - return null; - } - _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } - case VoiceType.Square2: - { - nChn = _sq2; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) - { - return null; - } - _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); - break; - } - case VoiceType.PCM4: - { - nChn = _pcm4; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) - { - return null; - } - _pcm4.Init(owner, note, env, instPan, (int)arg); - break; - } - case VoiceType.Noise: - { - nChn = _noise; - if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) - { - return null; - } - _noise.Init(owner, note, env, instPan, (NoisePattern)arg); - break; - } - default: return null; - } - nChn.SetVolume(vol, pan); - nChn.SetPitch(pitch); - return nChn; - } + internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) + { + MP2KPCM8Channel? nChn = null; + IOrderedEnumerable byOwner = _pcm8Channels.OrderByDescending(c => c.Owner is null ? 0xFF : c.Owner.Index); + foreach (MP2KPCM8Channel i in byOwner) // Find free + { + if (i.State == EnvelopeState.Dead || i.Owner is null) + { + nChn = i; + break; + } + } + if (nChn is null) // Find releasing + { + foreach (MP2KPCM8Channel i in byOwner) + { + if (i.State == EnvelopeState.Releasing) + { + nChn = i; + break; + } + } + } + if (nChn is null) // Find prioritized + { + foreach (MP2KPCM8Channel i in byOwner) + { + if (owner.Priority > i.Owner!.Priority) + { + nChn = i; + break; + } + } + } + if (nChn is null) // None available + { + MP2KPCM8Channel lowest = byOwner.First(); // Kill lowest track's instrument if the track is lower than this one + if (lowest.Owner!.Index >= owner.Index) + { + nChn = lowest; + } + } + if (nChn is not null) // Could still be null from the above if + { + nChn.Init(owner, note, env, sampleOffset, vol, pan, instPan, pitch, bFixed, bCompressed); + } + return nChn; + } + internal MP2KPSGChannel? AllocPSGChannel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, VoiceType type, object arg) + { + MP2KPSGChannel nChn; + switch (type) + { + case VoiceType.Square1: + { + nChn = _sq1; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq1.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.Square2: + { + nChn = _sq2; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _sq2.Init(owner, note, env, instPan, (SquarePattern)arg); + break; + } + case VoiceType.PCM4: + { + nChn = _pcm4; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _pcm4.Init(owner, note, env, instPan, (int)arg); + break; + } + case VoiceType.Noise: + { + nChn = _noise; + if (nChn.State < EnvelopeState.Releasing && nChn.Owner!.Index < owner.Index) + { + return null; + } + _noise.Init(owner, note, env, instPan, (NoisePattern)arg); + break; + } + default: return null; + } + nChn.SetVolume(vol, pan); + nChn.SetPitch(pitch); + return nChn; + } - internal void BeginFadeIn() - { - _fadePos = 0f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); - _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; - _isFading = true; - } - internal void BeginFadeOut() - { - _fadePos = 1f; - _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); - _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; - _isFading = true; - } - internal bool IsFading() - { - return _isFading; - } - internal bool IsFadeDone() - { - return _isFading && _fadeMicroFramesLeft == 0; - } - internal void ResetFade() - { - _isFading = false; - _fadeMicroFramesLeft = 0; - } + internal void BeginFadeIn() + { + _fadePos = 0f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = 1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal void BeginFadeOut() + { + _fadePos = 1f; + _fadeMicroFramesLeft = (long)(GlobalConfig.Instance.PlaylistFadeOutMilliseconds / 1_000.0 * GBAUtils.AGB_FPS); + _fadeStepPerMicroframe = -1f / _fadeMicroFramesLeft; + _isFading = true; + } + internal bool IsFading() + { + return _isFading; + } + internal bool IsFadeDone() + { + return _isFading && _fadeMicroFramesLeft == 0; + } + internal void ResetFade() + { + _isFading = false; + _fadeMicroFramesLeft = 0; + } - internal void Process(bool output, bool recording) - { - for (int i = 0; i < _trackBuffers.Length; i++) - { - float[] buf = _trackBuffers[i]; - Array.Clear(buf, 0, buf.Length); - } - _audio.Clear(); + internal void Process(bool output, bool recording) + { + for (int i = 0; i < _trackBuffers.Length; i++) + { + float[] buf = _trackBuffers[i]; + Array.Clear(buf, 0, buf.Length); + } + _audio.Clear(); - for (int i = 0; i < _pcm8Channels.Length; i++) - { - MP2KPCM8Channel c = _pcm8Channels[i]; - if (c.Owner is not null) - { - c.Process(_trackBuffers[c.Owner.Index]); - } - } + for (int i = 0; i < _pcm8Channels.Length; i++) + { + MP2KPCM8Channel c = _pcm8Channels[i]; + if (c.Owner is not null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } - for (int i = 0; i < _psgChannels.Length; i++) - { - MP2KPSGChannel c = _psgChannels[i]; - if (c.Owner is not null) - { - c.Process(_trackBuffers[c.Owner.Index]); - } - } + for (int i = 0; i < _psgChannels.Length; i++) + { + MP2KPSGChannel c = _psgChannels[i]; + if (c.Owner is not null) + { + c.Process(_trackBuffers[c.Owner.Index]); + } + } - float masterStep; - float masterLevel; - if (_isFading && _fadeMicroFramesLeft == 0) - { - masterStep = 0; - masterLevel = 0; - } - else - { - float fromMaster = 1f; - float toMaster = 1f; - if (_fadeMicroFramesLeft > 0) - { - const float scale = 10f / 6f; - fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); - _fadePos += _fadeStepPerMicroframe; - toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); - _fadeMicroFramesLeft--; - } - masterStep = (toMaster - fromMaster) * _samplesReciprocal; - masterLevel = fromMaster; - } - for (int i = 0; i < _trackBuffers.Length; i++) - { - if (Mutes[i]) - { - continue; - } + float masterStep; + float masterLevel; + if (_isFading && _fadeMicroFramesLeft == 0) + { + masterStep = 0; + masterLevel = 0; + } + else + { + float fromMaster = 1f; + float toMaster = 1f; + if (_fadeMicroFramesLeft > 0) + { + const float scale = 10f / 6f; + fromMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadePos += _fadeStepPerMicroframe; + toMaster *= (_fadePos < 0f) ? 0f : MathF.Pow(_fadePos, scale); + _fadeMicroFramesLeft--; + } + masterStep = (toMaster - fromMaster) * _samplesReciprocal; + masterLevel = fromMaster; + } + for (int i = 0; i < _trackBuffers.Length; i++) + { + if (Mutes[i]) + { + continue; + } - float level = masterLevel; - float[] buf = _trackBuffers[i]; - for (int j = 0; j < SamplesPerBuffer; j++) - { - _audio.Float32Buffer![j * 2] += buf[j * 2] * level; - _audio.Float32Buffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; - level += masterStep; - } - } - if (output) - { - _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); - Instance!.Buffer = _audio.Float32Buffer!; - } - if (recording) - { - _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); - } - } + float level = masterLevel; + float[] buf = _trackBuffers[i]; + for (int j = 0; j < SamplesPerBuffer; j++) + { + _audio.Float32Buffer![j * 2] += buf[j * 2] * level; + _audio.Float32Buffer[(j * 2) + 1] += buf[(j * 2) + 1] * level; + level += masterStep; + } + } + if (output) + { + _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + Instance!.Buffer = new Span(_audio.Float32Buffer!).ToArray(); + } + if (recording) + { + _waveWriter!.Write(_audio.ByteBuffer, 0, _audio.ByteBufferCount); + } + } } diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 676d3fe..8b7dd21 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -19,12 +19,10 @@ public abstract class Mixer : IDisposable public readonly bool[] Mutes; public int SizeInBytes; public uint FramesPerBuffer; - public uint CombinedSamplesPerBuffer; public int SizeToAllocateInBytes; public long FinalFrameSize; - public long TotalFrames; internal long Pos = 0; - internal float Vol = 1; + internal float Vol = 1.0f; public int freePos = 0; public int dataPos = 0; @@ -37,7 +35,6 @@ public abstract class Mixer : IDisposable protected Wave? _waveWriter; - internal bool PlayingBack = false; public StreamParameters OParams; public StreamParameters DefaultOutputParams { get; private set; } @@ -52,7 +49,9 @@ protected Mixer() Buffer = null!; } - protected void Init(Wave waveData) + protected void Init(Wave waveData) => Init(waveData, SampleFormat.Float32); + + protected void Init(Wave waveData, SampleFormat sampleFormat) { // First, check if the instance contains something if (WaveData == null) @@ -69,7 +68,7 @@ protected void Init(Wave waveData) throw new Exception("No default audio output device is available."); OParams.channelCount = 2; - OParams.sampleFormat = SampleFormat.Float32; + OParams.sampleFormat = sampleFormat; OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; OParams.hostApiSpecificStreamInfo = IntPtr.Zero; @@ -79,7 +78,7 @@ protected void Init(Wave waveData) Sound(); - Play(); + Stream!.Start(); } private void Sound() @@ -94,8 +93,8 @@ private void Sound() this ); - FinalFrameSize = FramesPerBuffer * 2; - TotalFrames = WaveData.Channels * WaveData.BufferLength; + FinalFrameSize = FramesPerBuffer * WaveData.Channels; + Buffer = new Span(new float[SizeToAllocateInBytes]).ToArray(); } private static StreamCallbackResult PlayCallback( @@ -109,7 +108,6 @@ nint data // Ensure there's no memory allocated in this block to prevent issues Mixer d = Stream.GetUserData(data); - long numRead = 0; Span buffer; unsafe { @@ -117,135 +115,27 @@ nint data } // Do a zero-out memset - //float* buffer = (float*)output; - //for (uint i = 0; i < d.FinalFrameSize; i++) - // buffer[i] = 0; + for (int i = 0; i < d.FinalFrameSize; i++) + buffer[i] = 0; // If we're reading data, play it back - if (d.PlayingBack) + if (Engine.Instance!.Player.State == PlayerState.Playing) { - // Read the data - numRead = d.FinalFrameSize; - - //for (int i = 0; i < numRead; i++) - // buffer[i] = d.Buffer[i] >> 7; - // Apply volume with buffer value - for (int i = 0; i < numRead; i++) + for (int i = 0; i < d.FinalFrameSize; i++) buffer[i] = d.Buffer[i] * d.Vol; - //numRead = d.ReadFloat(output, d.FinalFrameSize); - - // Apply volume - //buffer = (float*)output; - //for (int i = 0; i < numRead; i++) - // buffer[i] *= d.Volume; } - //// Increment counter - //d.Pos += numRead; - - //// If it's at end of the data - //if (d.PlayingBack && (numRead < frameCount)) - //{ - // if (d.WaveData!.IsLooped) - // d.Cursor = d.WaveData.LoopStart; - // else - // d.Cursor = 0; - // d.PlayingBack = false; - // return StreamCallbackResult.Complete; - //} - // Continue on return StreamCallbackResult.Continue; } - private long ReadFloat(nint outData, long nElements) - { - if (Reader == null) - { - Reader = new EndianBinaryReader(new MemoryStream(WaveData!.Buffer!)); - } - if (outData > nElements) - { - Reader.Stream.Position = outData = (nint)WaveData!.LoopStart; - return WaveData.LoopStart; - } - else - { - Reader.Stream.Position = outData; - return Reader!.ReadInt16(); - } - //if (dataCount < nElements) - //{ - // // underrun - // std::fill(outData, outData + nElements, sample{ 0.0f, 0.0f}); - //} - //else - //{ - // // output - // std::unique_lock < std::mutex > lock (CountLock) ; - // while (nElements > 0) - // { - // int count = takeChunk(outData, nElements); - // outData += count; - // nElements -= count; - // } - // sig.notify_one(); - //} - } - public float Volume { get => Vol; set => Vol = Math.Clamp(value, 0, 1); } - public bool IsPlaying - { - get => PlayingBack; - } - - public float Cursor - { - get => (float)(Pos) / (float)(TotalFrames) * (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; - set - { - // Do math - float per = value / (float)TimeSpan.FromSeconds(Buffer!.LongLength).TotalSeconds; - long frame = (long)(per * TotalFrames); - - // Clamp - frame = Math.Max(Math.Min(frame, 0), TotalFrames); - - // Set (stop playback for a very short while, to stop some back skipping noises) - bool wasPlaying = IsPlaying; - if (Pos != TotalFrames) // this check stops a segfault when the audio has reached the end of playback - Pause(); - - Pos = frame; - Reader!.Stream.Seek(Pos / WaveData!.Channels, SeekOrigin.Begin); - - if (wasPlaying) - Play(); - } - } - - public void Play() - { - PlayingBack = true; - - if (Stream!.IsStopped) - Stream.Start(); - } - - public void Pause() - { - PlayingBack = false; - - if (Stream!.IsActive) - Stream.Stop(); - } - public float GetVolume() { return Vol; @@ -437,11 +327,10 @@ public int Float128BufferCount public Audio(int sizeToAllocateInBytes) { Instance!.FramesPerBuffer = (uint)(sizeToAllocateInBytes / sizeof(float)) / 2; - //Instance.CombinedSamplesPerBuffer = (uint)SamplesPerBuffer * 2; Instance.SizeInBytes = sizeToAllocateInBytes; int num = Instance.SizeInBytes % 4; Instance.SizeToAllocateInBytes = (num == 0) ? Instance.SizeInBytes : (Instance.SizeInBytes + 4 - num); - Instance.Buffer = Float32Buffer = new float[Instance.SizeToAllocateInBytes]; + ByteBuffer = new Span(new byte[Instance.SizeToAllocateInBytes]).ToArray(); NumberOfBytes = 0; } @@ -458,9 +347,9 @@ private int CheckValidityCount(string argName, int value, int sizeOfValue) throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); } - if (value < 0 || value > ByteBuffer.Length / sizeOfValue) + if (value < 0 || value > ByteBuffer!.Length / sizeOfValue) { - throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceeds max count of {ByteBuffer.Length / sizeOfValue}."); + throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceeds max count of {ByteBuffer!.Length / sizeOfValue}."); } return num; @@ -468,12 +357,12 @@ private int CheckValidityCount(string argName, int value, int sizeOfValue) public void Clear() { - Array.Clear(ByteBuffer, 0, ByteBuffer.Length); + Array.Clear(ByteBuffer!, 0, ByteBuffer!.Length); } public void Copy(Array destinationArray) { - Array.Copy(ByteBuffer, destinationArray, NumberOfBytes); + Array.Copy(ByteBuffer!, destinationArray, NumberOfBytes); } } } diff --git a/VG Music Studio - Core/PortAudio/Stream.cs b/VG Music Studio - Core/PortAudio/Stream.cs index 28aed76..fc94266 100644 --- a/VG Music Studio - Core/PortAudio/Stream.cs +++ b/VG Music Studio - Core/PortAudio/Stream.cs @@ -313,6 +313,10 @@ public void Stop() { ErrorCode ec = Native.Pa_StopStream(streamPtr); if (ec != ErrorCode.NoError) + if (ec == ErrorCode.TimedOut) + throw new PortAudioException(ec, "Unable to stop PortAudio stream due to an active callback loop.\n" + + "A StreamCallbackResult must be set to 'Complete' or 'Abort' before a stream can be stopped.\n" + + "Error Code: " + ec.ToString()); throw new PortAudioException(ec, "Error stopping PortAudio Stream.\nError Code: " + ec.ToString()); } diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index 555ddb3..b7dded9 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 Library latest Kermalis.VGMusicStudio.Core @@ -11,19 +11,17 @@ - + + - + Dependencies\DLS2.dll - - Dependencies\KMIDI.dll - Dependencies\SoundFont2.dll diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index c2e1117..467d49c 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -37,7 +37,7 @@ internal sealed class MainWindow : Window private bool _stopUI = false; private bool _autoplay = false; - public static Window Instance { get; private set; } + public static Window? Instance { get; private set; } #region Widgets @@ -780,73 +780,74 @@ private void OpenAlphaDreamFinish(string path) } private void OpenMP2K(Gio.SimpleAction sender, EventArgs e) { - var inFile = GTK4Utils.CreateLoadDialog(["*.gba", "*.srl"], Strings.MenuOpenMP2K, Strings.FilterOpenGBA); - if (inFile is null) - { - return; - } - OpenMP2KFinish(inFile); - //FileFilter filterGBA = FileFilter.New(); - //filterGBA.SetName(Strings.FilterOpenGBA); - //filterGBA.AddPattern("*.gba"); - //filterGBA.AddPattern("*.srl"); - //FileFilter allFiles = FileFilter.New(); - //allFiles.SetName(Strings.FilterAllFiles); - //allFiles.AddPattern("*.*"); - - //if (Gtk.Functions.GetMinorVersion() <= 8) - //{ - // var d = FileChooserNative.New( - // Strings.MenuOpenMP2K, - // this, - // FileChooserAction.Open, - // "Open", - // "Cancel"); - - - // d.AddFilter(filterGBA); - // d.AddFilter(allFiles); - - // d.OnResponse += (sender, e) => - // { - // if (e.ResponseId != (int)ResponseType.Accept) - // { - // d.Unref(); - // return; - // } - // var path = d.GetFile()!.GetPath() ?? ""; - // OpenMP2KFinish(path); - // d.Unref(); - // }; - // d.Show(); - //} - //else + //var inFile = GTK4Utils.CreateLoadDialog(["*.gba", "*.srl"], Strings.MenuOpenMP2K, Strings.FilterOpenGBA); + //if (inFile is not null) //{ - // var d = FileDialog.New(); - // d.SetTitle(Strings.MenuOpenMP2K); - // var filters = Gio.ListStore.New(FileFilter.GetGType()); - // filters.Append(filterGBA); - // filters.Append(allFiles); - // d.SetFilters(filters); - // _openCallback = (source, res, data) => - // { - // var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); - // if (fileHandle != IntPtr.Zero) - // { - // var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); - // OpenMP2KFinish(path!); - // filterGBA.Unref(); - // allFiles.Unref(); - // filters.Unref(); - // GObject.Internal.Object.Unref(fileHandle); - // d.Unref(); - // return; - // } - // d.Unref(); - // }; - // Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); - // //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + // OpenMP2KFinish(inFile); //} + + + FileFilter filterGBA = FileFilter.New(); + filterGBA.SetName(Strings.FilterOpenGBA); + filterGBA.AddPattern("*.gba"); + filterGBA.AddPattern("*.srl"); + FileFilter allFiles = FileFilter.New(); + allFiles.SetName(Strings.FilterAllFiles); + allFiles.AddPattern("*.*"); + + if (Gtk.Functions.GetMinorVersion() <= 8) + { + var d = FileChooserNative.New( + Strings.MenuOpenMP2K, + this, + FileChooserAction.Open, + "Open", + "Cancel"); + + + d.AddFilter(filterGBA); + d.AddFilter(allFiles); + + d.OnResponse += (sender, e) => + { + if (e.ResponseId != (int)ResponseType.Accept) + { + d.Unref(); + return; + } + var path = d.GetFile()!.GetPath() ?? ""; + OpenMP2KFinish(path); + d.Unref(); + }; + d.Show(); + } + else + { + var d = FileDialog.New(); + d.SetTitle(Strings.MenuOpenMP2K); + var filters = Gio.ListStore.New(FileFilter.GetGType()); + filters.Append(filterGBA); + filters.Append(allFiles); + d.SetFilters(filters); + _openCallback = (source, res, data) => + { + var fileHandle = Gtk.Internal.FileDialog.OpenFinish(d.Handle, res, out ErrorHandle); + if (fileHandle != IntPtr.Zero) + { + var path = Marshal.PtrToStringUTF8(Gio.Internal.File.GetPath(fileHandle).DangerousGetHandle()); + OpenMP2KFinish(path!); + filterGBA.Unref(); + allFiles.Unref(); + filters.Unref(); + GObject.Internal.Object.Unref(fileHandle); + d.Unref(); + return; + } + d.Unref(); + }; + Gtk.Internal.FileDialog.Open(d.Handle, Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + //d.Open(Handle, IntPtr.Zero, _openCallback, IntPtr.Zero); + } } private void OpenMP2KFinish(string path) { diff --git a/VG Music Studio - GTK4/Util/GTK4Utils.cs b/VG Music Studio - GTK4/Util/GTK4Utils.cs index 760f9b8..c45cccf 100644 --- a/VG Music Studio - GTK4/Util/GTK4Utils.cs +++ b/VG Music Studio - GTK4/Util/GTK4Utils.cs @@ -61,7 +61,6 @@ public override string CreateLoadDialog(string title, string filterName, SpanAlways %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + + + Always + %(Filename)%(Extension) + diff --git a/VG Music Studio - WinForms/MainForm.cs b/VG Music Studio - WinForms/MainForm.cs index 00c54a0..970ff26 100644 --- a/VG Music Studio - WinForms/MainForm.cs +++ b/VG Music Studio - WinForms/MainForm.cs @@ -218,7 +218,7 @@ private void SongNumerical_ValueChanged(object? sender, EventArgs e) } private void SongsComboBox_SelectedIndexChanged(object? sender, EventArgs e) { - var item = (ImageComboBoxItem)_songsComboBox.SelectedItem; + var item = (ImageComboBoxItem)_songsComboBox.SelectedItem!; switch (item.Item) { case Config.Song song: diff --git a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj index b1c5a71..5a159a1 100644 --- a/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj +++ b/VG Music Studio - WinForms/VG Music Studio - WinForms.csproj @@ -1,7 +1,7 @@  - net7.0-windows + net8.0-windows WinExe latest Kermalis.VGMusicStudio.WinForms From f2a0276767bfb65449bc342d25e1b94cc682cddd Mon Sep 17 00:00:00 2001 From: Platinum Lucario Date: Fri, 19 Jul 2024 23:59:36 +1000 Subject: [PATCH 19/20] Some fixes --- VG Music Studio - Core/Mixer.cs | 7 +- VG Music Studio - Core/Player.cs | 9 + .../VG Music Studio - Core.csproj | 2 +- VG Music Studio - GTK4/MainWindow.cs | 181 ++++++++---------- .../VG Music Studio - GTK4.csproj | 2 +- 5 files changed, 95 insertions(+), 106 deletions(-) diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 8b7dd21..79a2bee 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -77,13 +77,11 @@ protected void Init(Wave waveData, SampleFormat sampleFormat) } Sound(); - - Stream!.Start(); } private void Sound() { - Stream = new Stream( + Instance!.Stream = new Stream( null, OParams, WaveData!.SampleRate, @@ -96,6 +94,9 @@ private void Sound() FinalFrameSize = FramesPerBuffer * WaveData.Channels; Buffer = new Span(new float[SizeToAllocateInBytes]).ToArray(); } + + public void Start() => Instance!.Stream!.Start(); + public void Stop() => Instance!.Stream!.Stop(); private static StreamCallbackResult PlayCallback( nint input, nint output, diff --git a/VG Music Studio - Core/Player.cs b/VG Music Studio - Core/Player.cs index 9d1e0da..caaa167 100644 --- a/VG Music Studio - Core/Player.cs +++ b/VG Music Studio - Core/Player.cs @@ -91,6 +91,10 @@ public void Play() InitEmulation(); State = PlayerState.Playing; CreateThread(); + if (Engine.Instance!.UseNewMixer) + { + Mixer.Instance!.Start(); + } } } public void TogglePlaying() @@ -119,6 +123,11 @@ public void Stop() State = PlayerState.Stopped; WaitThread(); OnStopped(); + if (Engine.Instance!.UseNewMixer) + { + Mixer.Stop(); + ElapsedTicks = 0; + } } } public void Record(string fileName) diff --git a/VG Music Studio - Core/VG Music Studio - Core.csproj b/VG Music Studio - Core/VG Music Studio - Core.csproj index b7dded9..b45bf6a 100644 --- a/VG Music Studio - Core/VG Music Studio - Core.csproj +++ b/VG Music Studio - Core/VG Music Studio - Core.csproj @@ -16,7 +16,7 @@ - + diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index 467d49c..e387d31 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -31,8 +31,6 @@ internal sealed class MainWindow : Window private PlayingPlaylist? _playlist; private int _curSong = -1; - private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // Because WASAPI (via NAudio) is the only audio backend currently. - private bool _songEnded = false; private bool _stopUI = false; private bool _autoplay = false; @@ -76,25 +74,18 @@ internal sealed class MainWindow : Window // Menu Items private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, - _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; // Menu Actions private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, _soundSequenceAction; - private Signal _openDSESignal; - - private SignalHandler _openDSEHandler; - // Main Box private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; - // Volume Button to indicate volume status - private readonly VolumeButton _volumeButton; - // One Scale controling volume and one Scale for the sequenced track - private Scale _volumeScale, _positionScale; + private Scale _volumeBar, _positionBar; // Mouse Click Gesture private GestureClick _positionGestureClick, _sequencesGestureClick; @@ -137,8 +128,8 @@ public MainWindow(Application app) Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" _app = app; - // Configures SetVolumeScale method with the MixerVolumeChanged Event action - Mixer.VolumeChanged += SetVolumeScale; + // Configures SetVolumeBar method with the MixerVolumeChanged Event action + Mixer.VolumeChanged += SetVolumeBar; // LibAdwaita Header Bar _headerBar = Adw.HeaderBar.New(); @@ -282,35 +273,32 @@ public MainWindow(Application app) _timer = new Timer(); _timer.Elapsed += Timer_Tick; - // Volume Scale - _volumeScale = Scale.NewWithRange(Orientation.Horizontal, 0, 100, 1); - _volumeScale.Sensitive = false; - _volumeScale.ShowFillLevel = true; - _volumeScale.DrawValue = false; - _volumeScale.WidthRequest = 250; - - // Position Scale - _positionScale = Scale.NewWithRange(Orientation.Horizontal, 0, 1, 1); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup - _positionScale.Sensitive = false; - _positionScale.ShowFillLevel = true; - _positionScale.DrawValue = false; - _positionScale.WidthRequest = 250; - _positionScale.RestrictToFillLevel = false; - _positionScale.SetRange(1, double.MaxValue); + // Volume Bar + _volumeBar = Scale.New(Orientation.Horizontal, Gtk.Adjustment.New(0, 0, 100, 1, 10, 0)); + _volumeBar.Sensitive = false; + _volumeBar.ShowFillLevel = true; + _volumeBar.DrawValue = false; + _volumeBar.WidthRequest = 250; + + // Position Bar + _positionBar = Scale.New(Orientation.Horizontal, Gtk.Adjustment.New(0, 0, 100, 1, 10, 0)); // The Upper value property must contain a value of 1 or higher for the widget to show upon startup _positionGestureClick = GestureClick.New(); - if (_positionGestureClick.Button == 1) - { - _positionScale.OnValueChanged += PositionScale_MouseButtonRelease; - _positionScale.OnValueChanged -= PositionScale_MouseButtonRelease; - _positionScale.OnValueChanged += PositionScale_MouseButtonPress; - _positionScale.OnValueChanged -= PositionScale_MouseButtonPress; - } - //_positionScale.Focusable = true; - //_positionScale.HasOrigin = true; - //_positionScale.Visible = true; - //_positionScale.FillLevel = _positionAdjustment.Upper; - //_positionGestureClick.OnReleased += PositionScale_MouseButtonRelease; // ButtonRelease must go first, otherwise the scale it will follow the mouse cursor upon loading - //_positionGestureClick.OnPressed += PositionScale_MouseButtonPress; + _positionBar.AddController(_positionGestureClick); + _positionBar.Sensitive = false; + _positionBar.ShowFillLevel = true; + _positionBar.DrawValue = false; + _positionBar.WidthRequest = 250; + _positionBar.RestrictToFillLevel = false; + _positionBar.OnChangeValue += PositionBar_ChangeValue; + _positionBar.OnMoveSlider += PositionBar_MoveSlider; + _positionBar.OnValueChanged += PositionBar_ValueChanged; + _positionGestureClick.OnStopped += PositionBar_MouseButtonRelease; + _positionGestureClick.OnCancel += PositionBar_MouseButtonRelease; + _positionGestureClick.OnPressed += PositionBar_MouseButtonPress; + _positionGestureClick.OnReleased += PositionBar_MouseButtonRelease; + _positionGestureClick.OnUnpairedRelease += PositionBar_MouseButtonRelease; + _positionGestureClick.OnEnd += PositionBar_MouseButtonRelease; + _positionGestureClick.OnBegin += PositionBar_MouseButtonPress; // Sound Sequence List //_soundSequenceList = new SoundSequenceList { Sensitive = false }; @@ -350,13 +338,13 @@ public MainWindow(Application app) _sequenceNumberSpinButton.Hide(); _configSpinButtonBox.Append(_sequenceNumberSpinButton); } - - _volumeScale.MarginStart = 20; - _volumeScale.MarginEnd = 20; - _configScaleBox.Append(_volumeScale); - _positionScale.MarginStart = 20; - _positionScale.MarginEnd = 20; - _configScaleBox.Append(_positionScale); + + // _volumeBar.MarginStart = 20; + // _volumeBar.MarginEnd = 20; + _configScaleBox.Append(_volumeBar); + // _positionBar.MarginStart = 20; + // _positionBar.MarginEnd = 20; + _configScaleBox.Append(_positionBar); _mainBox.Append(_headerBar); _mainBox.Append(_popoverMenuBar); @@ -380,35 +368,43 @@ public MainWindow(Application app) } // When the value is changed on the volume scale - private void VolumeScale_ValueChanged(object sender, EventArgs e) + private void VolumeBar_ValueChanged(object sender, EventArgs e) { - Engine.Instance!.Mixer.SetVolume((float)(_volumeScale.Adjustment!.Value / _volumeScale.Adjustment.Upper)); + Engine.Instance!.Mixer.SetVolume((float)(_volumeBar.Adjustment!.Value / _volumeBar.Adjustment.Upper)); } // Sets the volume scale to the specified position - public void SetVolumeScale(float volume) + public void SetVolumeBar(float volume) { - _volumeScale.OnValueChanged -= VolumeScale_ValueChanged; - _volumeScale.Adjustment!.Value = (int)(volume * _volumeScale.Adjustment.Upper); - _volumeScale.OnValueChanged += VolumeScale_ValueChanged; + _volumeBar.Adjustment!.Value = (int)(volume * _volumeBar.Adjustment.Upper); + _volumeBar.OnValueChanged += VolumeBar_ValueChanged; } - private bool _positionScaleFree = true; - private void PositionScale_MouseButtonRelease(object sender, EventArgs args) + private bool _positionBarFree = true; + private void PositionBar_MouseButtonRelease(object sender, EventArgs args) { - if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button - { - Engine.Instance!.Player.SetSongPosition((long)_positionScale.GetValue()); // Sets the value based on the position when mouse button is released - _positionScaleFree = true; // Sets _positionScaleFree to true when mouse button is released - LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track - } + Engine.Instance!.Player.SetSongPosition((long)_positionBar.ValuePos); // Sets the value based on the position when mouse button is released + _positionBarFree = true; // Sets _positionBarFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track } - private void PositionScale_MouseButtonPress(object sender, EventArgs args) + private bool PositionBar_ChangeValue(object sender, EventArgs args) { - if (_positionGestureClick.Button == 1) // Number 1 is Left Mouse Button - { - _positionScaleFree = false; - } + _positionBarFree = false; + + return false; + } + private void PositionBar_MoveSlider(object sender, EventArgs args) => + _positionBarFree = true; + private void PositionBar_ValueChanged(object sender, EventArgs args) + { + if (Engine.Instance is not null) + _positionBar.SetValue(Engine.Instance!.Player.ElapsedTicks); // Sets the value based on the position when mouse button is released + _positionBarFree = true; // Sets _positionBarFree to true when mouse button is released + LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + } + private void PositionBar_MouseButtonPress(object sender, EventArgs args) + { + _positionBarFree = false; } private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) @@ -448,12 +444,12 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) this.Title = $"{ConfigUtils.PROGRAM_NAME} - {songs[songIndex].Name}"; // TODO: Make this a func //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - //_positionScale.Adjustment!.Upper = double.MaxValue; + //_positionBar.Adjustment!.Upper = double.MaxValue; _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); - _positionScale.SetRange(0, _duration); + _positionBar.SetRange(0, _duration); //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; - _positionScale.Show(); + _positionBar.Show(); //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) { @@ -464,7 +460,7 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) { //_songInfo.SetNumTracks(0); } - _positionScale.Sensitive = _exportWAVAction.Enabled = success; + _positionBar.Sensitive = _exportWAVAction.Enabled = success; _exportMIDIAction.Enabled = success && MP2KEngine.MP2KInstance is not null; _exportDLSAction.Enabled = _exportSF2Action.Enabled = success && AlphaDreamEngine.AlphaDreamInstance is not null; @@ -855,25 +851,16 @@ private void OpenMP2KFinish(string path) { DisposeEngine(); } - - if (IsWindows()) + + try { - try - { - _ = new MP2KEngine(File.ReadAllBytes(path)); - } - catch (Exception ex) - { - //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); - //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); - DisposeEngine(); - ExceptionDialog(ex, Strings.ErrorOpenMP2K); - return; - } + _ = new MP2KEngine(File.ReadAllBytes(path)); } - else + catch (Exception ex) { - var ex = new PlatformNotSupportedException(); + //_dialog = Adw.MessageDialog.New(this, Strings.ErrorOpenMP2K, ex.ToString()); + //FlexibleMessageBox.Show(ex, Strings.ErrorOpenMP2K); + DisposeEngine(); ExceptionDialog(ex, Strings.ErrorOpenMP2K); return; } @@ -1030,7 +1017,7 @@ private void ExportMIDIFinish(string path) private void ExportSF2(Gio.SimpleAction sender, EventArgs e) { AlphaDreamConfig cfg = AlphaDreamEngine.AlphaDreamInstance!.Config; - + FileFilter ff = FileFilter.New(); ff.SetName(Strings.FilterSaveSF2); ff.AddPattern("*.sf2"); @@ -1293,7 +1280,7 @@ private void FinishLoading(long numSongs) #endif _autoplay = false; SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); - _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeScale.Sensitive = true; + _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeBar.Sensitive = true; Show(); } private void DisposeEngine() @@ -1342,25 +1329,17 @@ private void Timer_Tick(object? sender, EventArgs e) } private void SongEnded() { + _songEnded = true; _stopUI = true; } - // This updates _positionScale and _positionAdjustment to the value specified + // This updates _positionBar and _positionAdjustment to the value specified // Note: Gtk.Scale is dependent on Gtk.Adjustment, which is why _positionAdjustment is used instead private void UpdatePositionIndicators(long ticks) { - if (_positionScaleFree) + if (_positionBarFree) { - if (ticks < _duration) - { - // TODO: Implement GStreamer functions to replace Gtk.Adjustment - _positionScale.SetRange(1, _duration); - _positionScale.SetValue(ticks); // A Gtk.Adjustment field must be used here to avoid issues - } - else - { - return; - } + _positionBar.Adjustment!.Value = ticks; } } } diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj index b37a3d6..d711af8 100644 --- a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -16,7 +16,7 @@ - + Always %(Filename)%(Extension) From e220aea53e436e468c090150a019baf4afe6c2e1 Mon Sep 17 00:00:00 2001 From: Platinum Lucario Date: Wed, 11 Sep 2024 02:48:49 +1000 Subject: [PATCH 20/20] Some minor updates and experiments --- VG Music Studio - Core/Backend.cs | 744 ------------------ VG Music Studio - Core/Formats/Wave.cs | 1 - .../GBA/AlphaDream/AlphaDreamMixer.cs | 2 +- VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs | 3 +- .../LowLatencyRingbuffer.cs | 185 +++++ VG Music Studio - Core/Mixer.cs | 73 +- VG Music Studio - Core/Player.cs | 154 +++- VG Music Studio - Core/PortAudio/Stream.cs | 419 +++++++++- VG Music Studio - GTK4/MainWindow.cs | 142 ++-- VG Music Studio - GTK4/PlayingPlaylist.cs | 4 +- VG Music Studio - GTK4/Program.cs | 49 +- .../VG Music Studio - GTK4.csproj | 7 + VG Music Studio - GTK4/mainwindow.xml | 133 ++++ 13 files changed, 972 insertions(+), 944 deletions(-) delete mode 100644 VG Music Studio - Core/Backend.cs create mode 100644 VG Music Studio - Core/LowLatencyRingbuffer.cs create mode 100644 VG Music Studio - GTK4/mainwindow.xml diff --git a/VG Music Studio - Core/Backend.cs b/VG Music Studio - Core/Backend.cs deleted file mode 100644 index 5fda723..0000000 --- a/VG Music Studio - Core/Backend.cs +++ /dev/null @@ -1,744 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using NAudio.CoreAudioApi; -using NAudio.CoreAudioApi.Interfaces; -using NAudio.Wave; -using PortAudio; -using Kermalis.EndianBinaryIO; - -namespace Kermalis.VGMusicStudio.Core; - -public class Backend -{ - /// - /// The output parameters for an output stream - /// - internal static StreamParameters OParams; - - /// - /// The default settings for an output stream - /// - public StreamParameters DefaultOutputParams { get; private set; } - - /// - /// How many frames to give each audio buffer - /// - public int FramesPerBuffer { get; private set; } = 4096; - - /// - /// The sample rate of the audio data - /// - public int SampleRate { get; private set; } - - /// - /// The instance of the backend currently running. - /// - /// `null` if the backend isn't activated. Otherwise, it should contain a value. - public static Backend Instance { get; private set; } = null; - - public Backend() - { - } - - public void Init(BufferedWaveProvider waveProvider) - { - // Check if a backend is already initialized - if (Instance == null) - return; - - Pa.Initialize(); - - // Try setting up an output device - OParams.device = Pa.DefaultOutputDevice; - if (OParams.device == Pa.NoDevice) - throw new Exception("PortAudio Error:\nThere's no default audio device available."); - - OParams.channelCount = 2; - OParams.sampleFormat = SampleFormat.Float32; - OParams.suggestedLatency = Pa.GetDeviceInfo(OParams.device).defaultLowOutputLatency; - OParams.hostApiSpecificStreamInfo = IntPtr.Zero; - - // Set it as the default audio device - DefaultOutputParams = OParams; - - - Instance = this; - } - - public void OnVolumeChanged(float volume, bool isMuted) - { - - } - public void OnDisplayNameChanged(string displayName) - { - throw new NotImplementedException(); - } - public void OnIconPathChanged(string iconPath) - { - throw new NotImplementedException(); - } - public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) - { - throw new NotImplementedException(); - } - public void OnGroupingParamChanged(ref Guid groupingId) - { - throw new NotImplementedException(); - } - // Fires on @out.Play() and @out.Stop() - public void OnStateChanged(uint state) - { - - } - public void OnSessionDisconnected(uint disconnectReason) - { - throw new NotImplementedException(); - } - public void SetVolume(float volume) - { - - } - - public virtual void Dispose() - { - - } - - public class WaveBuffer - { - // - // Summary: - // Number of Bytes - public int numberOfBytes; - - private byte[] byteBuffer; - - private float[] floatBuffer; - - private short[] shortBuffer; - - private int[] intBuffer; - - // - // Summary: - // Gets the byte buffer. - // - // Value: - // The byte buffer. - public byte[] ByteBuffer => byteBuffer; - - // - // Summary: - // Gets the float buffer. - // - // Value: - // The float buffer. - public float[] FloatBuffer => floatBuffer; - - // - // Summary: - // Gets the short buffer. - // - // Value: - // The short buffer. - public short[] ShortBuffer => shortBuffer; - - // - // Summary: - // Gets the int buffer. - // - // Value: - // The int buffer. - public int[] IntBuffer => intBuffer; - - // - // Summary: - // Gets the max size in bytes of the byte buffer.. - // - // Value: - // Maximum number of bytes in the buffer. - public int MaxSize => byteBuffer.Length; - - // - // Summary: - // Gets or sets the byte buffer count. - // - // Value: - // The byte buffer count. - public int ByteBufferCount - { - get - { - return numberOfBytes; - } - set - { - numberOfBytes = CheckValidityCount("ByteBufferCount", value, 1); - } - } - - // - // Summary: - // Gets or sets the float buffer count. - // - // Value: - // The float buffer count. - public int FloatBufferCount - { - get - { - return numberOfBytes / 4; - } - set - { - numberOfBytes = CheckValidityCount("FloatBufferCount", value, 4); - } - } - - // - // Summary: - // Gets or sets the short buffer count. - // - // Value: - // The short buffer count. - public int ShortBufferCount - { - get - { - return numberOfBytes / 2; - } - set - { - numberOfBytes = CheckValidityCount("ShortBufferCount", value, 2); - } - } - - // - // Summary: - // Gets or sets the int buffer count. - // - // Value: - // The int buffer count. - public int IntBufferCount - { - get - { - return numberOfBytes / 4; - } - set - { - numberOfBytes = CheckValidityCount("IntBufferCount", value, 4); - } - } - - // - // Summary: - // Checks the validity of the count parameters. - // - // Parameters: - // argName: - // Name of the arg. - // - // value: - // The value. - // - // sizeOfValue: - // The size of value. - private int CheckValidityCount(string argName, int value, int sizeOfValue) - { - int num = value * sizeOfValue; - if (num % 4 != 0) - { - throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count ({num}) that is not 4 bytes aligned "); - } - - if (value < 0 || value > byteBuffer.Length / sizeOfValue) - { - throw new ArgumentOutOfRangeException(argName, $"{argName} cannot set a count that exceed max count {byteBuffer.Length / sizeOfValue}"); - } - - return num; - } - - // - // Summary: - // Initializes a new instance of the NAudio.Wave.WaveBuffer class. - // - // Parameters: - // sizeToAllocateInBytes: - // The number of bytes. The size of the final buffer will be aligned on 4 Bytes - // (upper bound) - public WaveBuffer(int sizeToAllocateInBytes) - { - Instance.FramesPerBuffer = sizeToAllocateInBytes / sizeof(float); - - int num = sizeToAllocateInBytes % 4; - sizeToAllocateInBytes = ((num == 0) ? sizeToAllocateInBytes : (sizeToAllocateInBytes + 4 - num)); - byteBuffer = new byte[sizeToAllocateInBytes]; - numberOfBytes = 0; - } - } - - public class BufferedWaveProvider - { - private readonly WaveFormat waveFormat; - - // - // Summary: - // If true, always read the amount of data requested, padding with zeroes if necessary - // By default is set to true - public bool ReadFully { get; set; } - - // - // Summary: - // Buffer length in bytes - public int BufferLength { get; set; } - - // - // Summary: - // If true, when the buffer is full, start throwing away data if false, AddSamples - // will throw an exception when buffer is full - public bool DiscardOnBufferOverflow { get; set; } - - public BufferedWaveProvider(WaveFormat waveFormat) - { - //this.waveFormat = waveFormat; - //Instance.FramesPerBuffer = BufferLength = waveFormat.averageBytesPerSecond * 5; - //ReadFully = true; - } - - public void AddSamples(byte[] buffer, int offset, int count) - { - - } - } - - public class WaveFormat - { - // - // Summary: - // number of channels - protected short Channels; - - // - // Summary: - // sample rate - protected int SampleRate; - - // - // Summary: - // for buffer estimation - public int AverageBytesPerSecond; - - // - // Summary: - // block size of data - protected short BlockAlign; - - // - // Summary: - // number of bits per sample of mono data - protected short BitsPerSample; - - // - // Summary: - // number of following bytes - protected short ExtraSize; - - public WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels) - { - WaveFormat waveFormat = new WaveFormat(); - waveFormat.Channels = (short)channels; - waveFormat.BitsPerSample = 32; - Instance.SampleRate = waveFormat.SampleRate = sampleRate; - waveFormat.BlockAlign = (short)(4 * channels); - waveFormat.AverageBytesPerSecond = sampleRate * waveFormat.BlockAlign; - waveFormat.ExtraSize = 0; - return waveFormat; - } - } - - public class WaveFileWriter - { - private Stream outStream; - - private readonly EndianBinaryWriter writer; - - private long dataSizePos; - - private long factSampleCountPos; - - private long dataChunkSize; - - private readonly WaveFormat format; - - private readonly string filename; - - private readonly byte[] value24 = new byte[3]; - - // - // Summary: - // The wave file name or null if not applicable - public string Filename => filename; - - // - // Summary: - // Number of bytes of audio in the data chunk - public long Length => dataChunkSize; - - // - // Summary: - // Total time (calculated from Length and average bytes per second) - public TimeSpan TotalTime => TimeSpan.FromSeconds((double)Length / (double)WaveFormat.AverageBytesPerSecond); - - // - // Summary: - // WaveFormat of this wave file - public WaveFormat WaveFormat => format; - - // - // Summary: - // Returns false: Cannot read from a WaveFileWriter - public bool CanRead => false; - - // - // Summary: - // Returns true: Can write to a WaveFileWriter - public bool CanWrite => true; - - // - // Summary: - // Returns false: Cannot seek within a WaveFileWriter - public bool CanSeek => false; - - // - // Summary: - // Gets the Position in the WaveFile (i.e. number of bytes written so far) - public long Position - { - get - { - return dataChunkSize; - } - set - { - throw new InvalidOperationException("Repositioning a WaveFileWriter is not supported"); - } - } - - public void Write(byte[] data, int offset, int count) - { - - } - } - - public class PortAudio : IDisposable - { - // License: APL 2.0 - // Author: Benjamin N. Summerton - // Based on the code from Bassoon, modified for use in VGMS - - // Flag used for the IDispoable interface - private bool disposed = false; - - /// - /// Audio level, should be between [0.0, 1.0]. - /// 0.0 = silent, 1.0 = full volume - /// - internal float volume = 1; - - /// - /// Where in the audio (in bytes) we are. - /// - internal long Cursor = 0; - - /// - /// If we should be currently playing audio - /// - internal bool playingBack = false; - - private Stream stream; - - /// - /// How much data needs to be read when doing a playback - /// - internal int finalFrameSize; - - /// - /// How many frames of audio are in the loaded file. - /// - private readonly long totalFrames; - - public PortAudio() - { - // Setup the playback stream - // Get the channel count - StreamParameters oParams = Instance.DefaultOutputParams; - oParams.channelCount = OParams.channelCount; - - // Create the stream - stream = new Stream( - null, - oParams, - Instance.SampleRate, - (uint)Instance.FramesPerBuffer, - StreamFlags.ClipOff, - PlayCallback, - this - ); - } - - ~PortAudio() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - protected virtual void Dispose(bool disposing) - { - - } - - #region Math - /// - /// Clamp a value between a range (inclusive). - /// - /// This exists in .NET Core, but not in .NET standard - /// - /// Valume to clamp - /// minimum possible value - /// maximum possible value - /// The orignal value (clamped between the range) - public static float Clamp(float value, float min, float max) => - Math.Max(Math.Min(value, max), min); - - /// - /// Clamp a value between a range (inclusive). - /// - /// This exists in .NET Core, but not in .NET standard - /// - /// Valume to clamp - /// minimum possible value - /// maximum possible value - /// The orignal value (clamped between the range) - public static long Clamp(long value, long min, long max) => - Math.Max(Math.Min(value, max), min); - - #endregion - - #region Properties - /// - /// Level to play back the audio at. default is 100%. - /// - /// When setting, this will be clamped within range in the `value`. - /// - /// [0.0, 1.0] - public float Volume - { - get => volume; - set => volume = Clamp(value, 0, 1); - } - - /// - /// See if the sound is being played back rightnow - /// - /// true if so, false otherwise - public bool IsPlaying - { - get => playingBack; - } - - - #endregion // Properties - - #region Methods - /// - /// Start playing the sound - /// - public void Play() - { - playingBack = true; - - if (stream.IsStopped) - stream.Start(); - } - - /// - /// Stop audio playback - /// - public void Pause() - { - playingBack = false; - - if (stream.IsActive) - stream.Stop(); - } - - /// - /// Pause audio playback - /// - public void Stop() - { - playingBack = false; - - if (stream.IsActive) - Cursor = 0; - stream.Stop(); - } - #endregion // Methods - - #region PortAudio Callbacks - /// - /// Performs the actual audio playback - /// - private static StreamCallbackResult PlayCallback( - IntPtr input, IntPtr output, - uint frameCount, - ref StreamCallbackTimeInfo timeInfo, - StreamCallbackFlags statusFlags, - IntPtr dataPtr - ) - { - // NOTE: make sure there are no malloc in this block, as it can cause issues. - PortAudio data = Stream.GetUserData(dataPtr); - - long numRead = 0; - unsafe - { - // Do a zero-out memset - float* buffer = (float*)output; - for (uint i = 0; i < data.finalFrameSize; i++) - *buffer++ = 0; - - // If we are reading data, then play it back - if (data.playingBack) - { - // Read data - //numRead = data.audioFile.readFloat(output, data.finalFrameSize); - - - // Apply volume - buffer = (float*)output; - for (int i = 0; i < numRead; i++) - *buffer++ *= data.volume; - } - } - - // Increment the counter - data.Cursor += numRead; - - // Did we hit the end? - if (data.playingBack && (numRead < frameCount)) - { - // Stop playback, and reset to the beginning - data.Cursor = 0; - data.playingBack = false; - } - - // Continue on - return StreamCallbackResult.Continue; - } - #endregion // PortAudio Callbacks - } - - public abstract class NAudio : IAudioSessionEventsHandler, IDisposable - { - public static event Action? VolumeChanged; - - public readonly bool[] Mutes; - private IWavePlayer _out; - private AudioSessionControl _appVolume; - - private bool _shouldSendVolUpdateEvent = true; - - protected WaveFileWriter? _waveWriter; - protected abstract WaveFormat WaveFormat { get; } - - - protected NAudio() - { - Mutes = new bool[SongState.MAX_TRACKS]; - _out = null!; - _appVolume = null!; - } - - protected void Init(IWaveProvider waveProvider) - { - _out = new WasapiOut(); - _out.Init(waveProvider); - using (var en = new MMDeviceEnumerator()) - { - SessionCollection sessions = en.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions; - int id = Environment.ProcessId; - for (int i = 0; i < sessions.Count; i++) - { - AudioSessionControl session = sessions[i]; - if (session.GetProcessID == id) - { - _appVolume = session; - _appVolume.RegisterEventClient(this); - break; - } - } - } - _out.Play(); - } - - public void OnVolumeChanged(float volume, bool isMuted) - { - if (_shouldSendVolUpdateEvent) - { - VolumeChanged?.Invoke(volume); - } - _shouldSendVolUpdateEvent = true; - } - public void OnDisplayNameChanged(string displayName) - { - throw new NotImplementedException(); - } - public void OnIconPathChanged(string iconPath) - { - throw new NotImplementedException(); - } - public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) - { - throw new NotImplementedException(); - } - public void OnGroupingParamChanged(ref Guid groupingId) - { - throw new NotImplementedException(); - } - // Fires on @out.Play() and @out.Stop() - public void OnStateChanged(AudioSessionState state) - { - if (state == AudioSessionState.AudioSessionStateActive) - { - OnVolumeChanged(_appVolume.SimpleAudioVolume.Volume, _appVolume.SimpleAudioVolume.Mute); - } - } - public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) - { - throw new NotImplementedException(); - } - public void SetVolume(float volume) - { - _shouldSendVolUpdateEvent = false; - _appVolume.SimpleAudioVolume.Volume = volume; - } - - public virtual void Dispose() - { - GC.SuppressFinalize(this); - _out.Stop(); - _out.Dispose(); - _appVolume.Dispose(); - } - } -} diff --git a/VG Music Studio - Core/Formats/Wave.cs b/VG Music Studio - Core/Formats/Wave.cs index 636070b..5163f55 100644 --- a/VG Music Studio - Core/Formats/Wave.cs +++ b/VG Music Studio - Core/Formats/Wave.cs @@ -1,5 +1,4 @@ using Kermalis.EndianBinaryIO; -using NAudio.Utils; using System; using System.IO; diff --git a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs index f601a14..bda9a0a 100644 --- a/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs +++ b/VG Music Studio - Core/GBA/AlphaDream/AlphaDreamMixer.cs @@ -28,7 +28,7 @@ internal AlphaDreamMixer(AlphaDreamConfig config) _samplesReciprocal = 1f / SamplesPerBuffer; int amt = SamplesPerBuffer * 2; - _audio = new Audio(amt) { Float32BufferCount = amt }; + _audio = new Audio(amt * sizeof(float)) { Float32BufferCount = amt }; for (int i = 0; i < AlphaDreamPlayer.NUM_TRACKS; i++) { _trackBuffers[i] = new float[amt]; diff --git a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs index a3b473f..422d8b0 100644 --- a/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs +++ b/VG Music Studio - Core/GBA/MP2K/MP2KMixer.cs @@ -60,7 +60,7 @@ internal MP2KMixer(MP2KConfig config) }; _buffer.CreateIeeeFloatWave((uint)SampleRate, 2); - Init(_buffer); + Init(_buffer, _audio); } internal MP2KPCM8Channel? AllocPCM8Channel(MP2KTrack owner, ADSR env, NoteInfo note, byte vol, sbyte pan, int instPan, int pitch, bool bFixed, bool bCompressed, int sampleOffset) @@ -259,7 +259,6 @@ internal void Process(bool output, bool recording) if (output) { _buffer.AddSamples(_audio.ByteBuffer, 0, _audio.ByteBufferCount); - Instance!.Buffer = new Span(_audio.Float32Buffer!).ToArray(); } if (recording) { diff --git a/VG Music Studio - Core/LowLatencyRingbuffer.cs b/VG Music Studio - Core/LowLatencyRingbuffer.cs new file mode 100644 index 0000000..0fe2d65 --- /dev/null +++ b/VG Music Studio - Core/LowLatencyRingbuffer.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace Kermalis.VGMusicStudio.Core; + +internal class LowLatencyRingbuffer +{ + internal struct Sample + { + internal float left; + internal float right; + } + + private System.Threading.Mutex? mtx = new(); + private int? mtxOwner; + private readonly object? cv = new(); + private List? buffer; + + // Free variables + private int freePos = 0; + private int freeCount = 0; + + // Data variables + private int dataPos = 0; + private int dataCount = 0; + + // Atomic variable for System.Threading.Interlocked + private int lastTake = 0; + + // Last put value + private int lastPut = 0; + + // Number of buffers (beginning from 1) + private int numBuffers = 1; + + public LowLatencyRingbuffer() + { + Reset(); + } + + public void Reset() + { + lock (mtx!) + { + dataCount = 0; + dataPos = 0; + freeCount = buffer!.Count; + freePos = 0; + } + } + + public void SetNumBuffers(int numBuffers) + { + lock (mtx!) + { + if (numBuffers is 0) + numBuffers = 1; + this.numBuffers = numBuffers; + } + } + + public void Put(Span inBuffer) + { + lastPut = inBuffer.Length; + + lock (mtx!) + { + int bufferedNumBuffers = numBuffers; + int bufferedLastTake = lastTake; + int requiredBufferSize = bufferedNumBuffers * bufferedLastTake + lastPut; + + if (buffer!.Count < requiredBufferSize) + { + List backupBuffer = new(new Sample[dataCount]); + int beforeWraparoundSize = Math.Min(dataCount, buffer.Count - dataPos); + Span beforeWraparound = new Span(new Sample[dataCount], 0 + dataPos, beforeWraparoundSize); + int afterWraparoundSize = dataCount - beforeWraparoundSize; + Span afterWraparound = new Span(new Sample[dataCount], 0, afterWraparoundSize); + Array.Copy(buffer.ToArray(), 0 + dataPos, backupBuffer.ToArray(), 0, beforeWraparoundSize); + Array.Copy(buffer.ToArray(), 0, backupBuffer.ToArray(), 0 + beforeWraparoundSize, afterWraparoundSize); + Debug.Assert(beforeWraparoundSize + afterWraparoundSize == dataCount); + Debug.Assert(dataCount <= requiredBufferSize); + + buffer.EnsureCapacity(requiredBufferSize); + Array.Copy(backupBuffer.ToArray(), 0, buffer.ToArray(), 0, dataCount); + Array.Fill(buffer.ToArray(), new Sample{left = 0.0f, right = 0.0f}, 0 + dataCount, buffer.Count - 1); + + dataPos = 0; + freeCount = buffer.Count - dataCount; + freePos = dataCount; + } + + while (dataCount > bufferedNumBuffers * bufferedLastTake) + { + Monitor.Wait(cv!); + } + + while (inBuffer.Length > 0) + { + int elementsPut = PutSome(inBuffer); + inBuffer = inBuffer.Slice(elementsPut); + } + } + } + + public void Take(Span outBuffer) + { + lastTake = outBuffer.Length; + + lock (mtx!) + { + mtxOwner = Thread.CurrentThread.ManagedThreadId; + + if (mtxOwner == Thread.CurrentThread.ManagedThreadId || outBuffer.Length > dataCount) + { + Array.Fill(outBuffer.ToArray(), new Sample{left = 0.0f, right = 0.0f}, 0, outBuffer.Length - 1); + return; + } + + while (outBuffer.Length > 0) + { + int elementsTaken = TakeSome(outBuffer); + outBuffer = outBuffer.Slice(elementsTaken); + } + + Monitor.Exit(cv!); + } + } + + private int PutSome(Span inBuffer) + { + Debug.Assert(inBuffer.Length <= freeCount); + bool wrap = inBuffer.Length >= (buffer!.Count - freePos); + + int putCount; + int newFreePos; + if (wrap) + { + putCount = buffer.Count - freePos; + newFreePos = 0; + } + else + { + putCount = buffer.Count; + newFreePos = freePos + inBuffer.Length; + } + + Array.Copy(inBuffer.ToArray(), 0, buffer.ToArray(), 0 + freePos, putCount); + + freePos = newFreePos; + Debug.Assert(freeCount >= putCount); + freeCount -= putCount; + dataCount += putCount; + return putCount; + } + + private int TakeSome(Span outBuffer) + { + Debug.Assert(outBuffer.Length <= dataCount); + bool wrap = outBuffer.Length >= (buffer!.Count - dataPos); + + int takeCount; + int newDataPos; + if (wrap) + { + takeCount = buffer.Count - dataPos; + newDataPos = 0; + } + else + { + takeCount = outBuffer.Length; + newDataPos = dataPos + outBuffer.Length; + } + + Array.Copy(buffer.ToArray(), 0 + dataPos, outBuffer.ToArray(), 0, takeCount); + + dataPos = newDataPos; + freeCount += takeCount; + Debug.Assert(dataCount >= takeCount); + dataCount -= takeCount; + return takeCount; + } +} \ No newline at end of file diff --git a/VG Music Studio - Core/Mixer.cs b/VG Music Studio - Core/Mixer.cs index 79a2bee..b3ea375 100644 --- a/VG Music Studio - Core/Mixer.cs +++ b/VG Music Studio - Core/Mixer.cs @@ -3,7 +3,6 @@ using System.Runtime.InteropServices; using Kermalis.EndianBinaryIO; using Kermalis.VGMusicStudio.Core.Formats; -using System.IO; using Stream = PortAudio.Stream; namespace Kermalis.VGMusicStudio.Core; @@ -21,24 +20,16 @@ public abstract class Mixer : IDisposable public uint FramesPerBuffer; public int SizeToAllocateInBytes; public long FinalFrameSize; - internal long Pos = 0; - internal float Vol = 1.0f; - - public int freePos = 0; - public int dataPos = 0; - public int freeCount; - public int dataCount = 0; + private float Vol = 1; public readonly object CountLock = new object(); - private bool _shouldSendVolUpdateEvent = true; - protected Wave? _waveWriter; public StreamParameters OParams; public StreamParameters DefaultOutputParams { get; private set; } - private Stream? Stream; + public Stream? Stream; private bool IsDisposed = false; public static Mixer? Instance { get; set; } @@ -49,9 +40,9 @@ protected Mixer() Buffer = null!; } - protected void Init(Wave waveData) => Init(waveData, SampleFormat.Float32); - - protected void Init(Wave waveData, SampleFormat sampleFormat) + protected void Init(Wave waveData) => Init(waveData, new Audio(SizeToAllocateInBytes), SampleFormat.Float32); + protected void Init(Wave waveData, Audio audioData) => Init(waveData, audioData, SampleFormat.Float32); + protected void Init(Wave waveData, Audio audioData, SampleFormat sampleFormat) { // First, check if the instance contains something if (WaveData == null) @@ -60,7 +51,6 @@ protected void Init(Wave waveData, SampleFormat sampleFormat) Pa.Initialize(); WaveData = waveData; - //Instance = this; // Try setting up an output device OParams.device = Pa.DefaultOutputDevice; @@ -76,59 +66,40 @@ protected void Init(Wave waveData, SampleFormat sampleFormat) DefaultOutputParams = OParams; } - Sound(); - } - - private void Sound() - { Instance!.Stream = new Stream( null, OParams, WaveData!.SampleRate, FramesPerBuffer, StreamFlags.ClipOff, - PlayCallback, - this + Player.PlayCallback, + audioData ); - FinalFrameSize = FramesPerBuffer * WaveData.Channels; - Buffer = new Span(new float[SizeToAllocateInBytes]).ToArray(); + FinalFrameSize = FramesPerBuffer * 2; + Buffer = new Span(audioData.Float32Buffer).ToArray(); } - - public void Start() => Instance!.Stream!.Start(); - public void Stop() => Instance!.Stream!.Stop(); - - private static StreamCallbackResult PlayCallback( - nint input, nint output, - uint frameCount, - ref StreamCallbackTimeInfo timeInfo, - StreamCallbackFlags statusFlags, - nint data - ) + + private int ProcessFrame(Span output, Span buffer, int framesPerBuffer) { - // Ensure there's no memory allocated in this block to prevent issues - Mixer d = Stream.GetUserData(data); + float counter = 0; - Span buffer; - unsafe + counter += framesPerBuffer; + while (counter >= Instance!.FramesPerBuffer) { - buffer = new Span(output.ToPointer(), (int)d.FinalFrameSize); + counter -= Instance.FramesPerBuffer; } - // Do a zero-out memset - for (int i = 0; i < d.FinalFrameSize; i++) - buffer[i] = 0; - - // If we're reading data, play it back - if (Engine.Instance!.Player.State == PlayerState.Playing) + framesPerBuffer = (int)(Instance.FramesPerBuffer * 2); + float[] outBuffer = buffer.ToArray(); + + float[] outBuf = output.ToArray(); + for (int i = 0; i < framesPerBuffer; i++) { - // Apply volume with buffer value - for (int i = 0; i < d.FinalFrameSize; i++) - buffer[i] = d.Buffer[i] * d.Vol; + outBuf[i] = outBuffer[i]; } - // Continue on - return StreamCallbackResult.Continue; + return 1; } public float Volume diff --git a/VG Music Studio - Core/Player.cs b/VG Music Studio - Core/Player.cs index caaa167..55fec7c 100644 --- a/VG Music Studio - Core/Player.cs +++ b/VG Music Studio - Core/Player.cs @@ -1,4 +1,5 @@ -using Kermalis.VGMusicStudio.Core.Util; +using PortAudio; +using Kermalis.VGMusicStudio.Core.Util; using System; using System.Collections.Generic; using System.IO; @@ -37,6 +38,7 @@ public abstract class Player : IDisposable private readonly TimeBarrier _time; private Thread? _thread; + public bool IsStopped = true; protected Player(double ticksPerSecond) { @@ -50,10 +52,81 @@ protected Player(double ticksPerSecond) protected abstract void OnStopped(); protected abstract bool Tick(bool playing, bool recording); + + internal static StreamCallbackResult PlayCallback( + nint input, nint output, + uint frameCount, + ref StreamCallbackTimeInfo timeInfo, + StreamCallbackFlags statusFlags, + nint userData + ) + { + // Marshal.AllocHGlobal() or any related functions cannot and must not be used + // in this callback, otherwise it will cause an OutOfMemoryException. + // + // The memory is already allocated by the output and userData params by + // the native PortAudio library itself. + + var player = Engine.Instance!.Player; + + Mixer.Audio d = Mixer.Instance!.Stream!.GetUserData(userData); + + if (!Mixer.Instance.Stream.UDHandle.IsAllocated) + { + return StreamCallbackResult.Abort; + } + + var frameSize = (int)Mixer.Instance.FinalFrameSize; + float[] frameBuffer = new float[frameSize]; + for (int i = 0; i < frameSize; i++) + frameBuffer[i] = d.Float32Buffer![i]; + + float[] newBuffer = new float[frameSize]; + for (int i = 0; i < frameSize; i++) + { + newBuffer[i] = Math.Clamp(frameBuffer[i], -1f, 1f); + } + // for (int i = 0; i < newBuffer.Length; i++) + // { + // System.Diagnostics.Debug.WriteLine("Buffer value: " + newBuffer[i].ToString()); + // } + + Span buffer; + unsafe + { + buffer = new((float*)output, frameSize); + } + + // Zero out the memory buffer output before applying buffer values + for (int i = 0; i < frameSize; i++) + buffer[i] = 0; + + // If we're reading data, play it back + if (player.State == PlayerState.Playing) + { + // Apply buffer value + for (int i = 0; i < frameSize; i++) + buffer[i] = newBuffer[i]; + + for (int i = 0; i < frameSize; i++) + buffer[i] *= Mixer.Instance.Volume; + } + + if (player.State is PlayerState.Playing or PlayerState.Paused) + { + // Continue if the song isn't finished + return StreamCallbackResult.Continue; + } + else + { + // Complete the callback when song is finished + return StreamCallbackResult.Complete; + } + } protected void CreateThread() { - _thread = new Thread(TimerTick) { Name = Name + " Tick" }; + _thread = new Thread(TimerLoop) { Name = Name + " Tick" }; _thread.Start(); } protected void WaitThread() @@ -90,10 +163,18 @@ public void Play() Stop(); InitEmulation(); State = PlayerState.Playing; - CreateThread(); if (Engine.Instance!.UseNewMixer) { - Mixer.Instance!.Start(); + if (IsStopped) + { + IsStopped = false; + CreateThread(); + Mixer.Instance!.Stream!.Start(); + } + } + else + { + CreateThread(); } } } @@ -102,18 +183,18 @@ public void TogglePlaying() switch (State) { case PlayerState.Playing: - { - State = PlayerState.Paused; - WaitThread(); - break; - } + { + State = PlayerState.Paused; + WaitThread(); + break; + } case PlayerState.Paused: case PlayerState.Stopped: - { - State = PlayerState.Playing; - CreateThread(); - break; - } + { + State = PlayerState.Playing; + CreateThread(); + break; + } } } public void Stop() @@ -125,8 +206,12 @@ public void Stop() OnStopped(); if (Engine.Instance!.UseNewMixer) { - Mixer.Stop(); - ElapsedTicks = 0; + if (!IsStopped) + { + IsStopped = true; + //_time.Stop(); + Mixer.Instance!.Stream!.Stop(); + } } } } @@ -163,35 +248,42 @@ public void SetSongPosition(long ticks) TogglePlaying(); } - private void TimerTick() + private void TimerLoop() { _time.Start(); while (true) { - PlayerState state = State; - bool playing = state == PlayerState.Playing; - bool recording = state == PlayerState.Recording; + var state = State; + var playing = state == PlayerState.Playing; + var recording = state == PlayerState.Recording; if (!playing && !recording) { break; } - - bool allDone = Tick(playing, recording); - if (allDone) + if (TimerTick(_time, playing, recording) is true) { - // TODO: lock state - _time.Stop(); // TODO: Don't need timer if recording - State = PlayerState.Stopped; - SongEnded?.Invoke(); return; } - if (playing) - { - _time.Wait(); - } } _time.Stop(); } + private bool TimerTick(TimeBarrier time, bool playing, bool recording) + { + bool allDone = Tick(playing, recording); + if (allDone) + { + // TODO: lock state + time.Stop(); // TODO: Don't need timer if recording + State = PlayerState.Stopped; + SongEnded?.Invoke(); + return allDone; + } + if (playing) + { + time.Wait(); + } + return false; + } public void Dispose() { diff --git a/VG Music Studio - Core/PortAudio/Stream.cs b/VG Music Studio - Core/PortAudio/Stream.cs index fc94266..2dcf7e6 100644 --- a/VG Music Studio - Core/PortAudio/Stream.cs +++ b/VG Music Studio - Core/PortAudio/Stream.cs @@ -2,6 +2,7 @@ // Author: Benjamin N. Summerton using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace PortAudio @@ -21,6 +22,19 @@ public static extern ErrorCode Pa_OpenStream( IntPtr userData // `void *` ); + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_OpenDefaultStream( + out IntPtr stream, + int numInputChannels, + int numOutputChannels, + SampleFormat sampleFormat, + double sampleRate, + System.UInt32 framesPerBuffer, + IntPtr streamCallback, + IntPtr userData + ); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] [return: MarshalAs(UnmanagedType.I4)] public delegate StreamCallbackResult Callback( @@ -69,6 +83,22 @@ IntPtr userData // Originally `void *` [DllImport(PortAudioDLL)] public static extern double Pa_GetStreamCpuLoad(IntPtr stream); // `PaStream *` + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_ReadStream( + nint stream, // `PaStream *` + nint buffer, // `void *` + ulong frames // `unsigned long` + ); + + [DllImport(PortAudioDLL)] + [return: MarshalAs(UnmanagedType.I4)] + public static extern ErrorCode Pa_WriteStream( + nint stream, // `PaStream *` + nint buffer, // `const void *` + ulong frames // `unsigned long` + ); } /// @@ -95,8 +125,8 @@ public class Stream : IDisposable private GCHandle userDataHandle; // Callback structures - private _NativeInterfacingCallback streamCallback = null; - private _NativeInterfacingCallback finishedCallback = null; + private _NativeInterfacingCallback? streamCallback; + private _NativeInterfacingCallback? finishedCallback; /// /// The input parameters for this stream, if any @@ -170,9 +200,16 @@ public class Stream : IDisposable /// @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream, /// Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable /// + /// + /// + /// + /// + /// + /// + /// public Stream( - StreamParameters? inParams, - StreamParameters? outParams, + StreamParameters? inputParameters, + StreamParameters? outputParameters, double sampleRate, System.UInt32 framesPerBuffer, StreamFlags streamFlags, @@ -187,28 +224,28 @@ object userData userDataHandle = GCHandle.Alloc(userData); // Set the ins and the outs - InputParameters = inParams; - OutputParameters = outParams; + InputParameters = inputParameters; + OutputParameters = outputParameters; // If the in/out params are set, then we need to make some P/Invoke friendly memory - IntPtr inParamsPtr = IntPtr.Zero; - IntPtr outParamsPtr = IntPtr.Zero; - if (inParams.HasValue) + IntPtr inputParametersPtr = IntPtr.Zero; + IntPtr outputParametersPtr = IntPtr.Zero; + if (inputParameters.HasValue) { - inParamsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(inParams.Value)); - Marshal.StructureToPtr(inParams.Value, inParamsPtr, false); + inputParametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(inputParameters.Value)); + Marshal.StructureToPtr(inputParameters.Value, inputParametersPtr, false); } - if (outParams.HasValue) + if (outputParameters.HasValue) { - outParamsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(outParams.Value)); - Marshal.StructureToPtr(outParams.Value, outParamsPtr, false); + outputParametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(outputParameters.Value)); + Marshal.StructureToPtr(outputParameters.Value, outputParametersPtr, false); } // Open the stream ErrorCode ec = Native.Pa_OpenStream( out streamPtr, - inParamsPtr, - outParamsPtr, + inputParametersPtr, + outputParametersPtr, sampleRate, framesPerBuffer, streamFlags, @@ -219,12 +256,80 @@ object userData throw new PortAudioException(ec, "Error opening PortAudio Stream.\nError Code: " + ec.ToString()); // Cleanup the in/out params ptrs - if (inParamsPtr != IntPtr.Zero) - Marshal.FreeHGlobal(inParamsPtr); - if (outParamsPtr != IntPtr.Zero) - Marshal.FreeHGlobal(outParamsPtr); + if (inputParametersPtr != IntPtr.Zero) + Marshal.FreeHGlobal(inputParametersPtr); + if (outputParametersPtr != IntPtr.Zero) + Marshal.FreeHGlobal(outputParametersPtr); } + + /// + /// A simplified version of Pa_OpenStream() that opens the default input + /// and/or output devices. + /// + /// @param stream The address of a PaStream pointer which will receive + /// a pointer to the newly opened stream. + /// + /// @param numInputChannels The number of channels of sound that will be supplied + /// to the stream callback or returned by Pa_ReadStream(). It can range from 1 to + /// the value of maxInputChannels in the PaDeviceInfo record for the default input + /// device. If 0 the stream is opened as an output-only stream. + /// + /// @param numOutputChannels The number of channels of sound to be delivered to the + /// stream callback or passed to Pa_WriteStream. It can range from 1 to the value + /// of maxOutputChannels in the PaDeviceInfo record for the default output device. + /// If 0 the stream is opened as an input-only stream. + /// + /// @param sampleFormat The sample format of both the input and output buffers + /// provided to the callback or passed to and from Pa_ReadStream() and Pa_WriteStream(). + /// sampleFormat may be any of the formats described by the PaSampleFormat + /// enumeration. + /// + /// @param sampleRate Same as Pa_OpenStream parameter of the same name. + /// @param framesPerBuffer Same as Pa_OpenStream parameter of the same name. + /// @param streamCallback Same as Pa_OpenStream parameter of the same name. + /// @param userData Same as Pa_OpenStream parameter of the same name. + /// + /// @return As for Pa_OpenStream + /// + /// @see Pa_OpenStream, PaStreamCallback + /// + /// + /// + /// + /// + /// + /// + /// + public Stream( + System.Int32 numInputChannels, + System.Int32 numOutputChannels, + SampleFormat sampleFormat, + double sampleRate, + System.UInt32 framesPerBuffer, + Callback callback, + object userData + ) + { + // Setup the steam's callback + streamCallback = new _NativeInterfacingCallback(callback); + // Take control of the userdata object + userDataHandle = GCHandle.Alloc(userData); + + // Open the stream + ErrorCode ec = Native.Pa_OpenDefaultStream( + out streamPtr, + numInputChannels, + numOutputChannels, + sampleFormat, + sampleRate, + framesPerBuffer, + streamCallback.Ptr, + GCHandle.ToIntPtr(userDataHandle) + ); + if (ec != ErrorCode.NoError) + throw new PortAudioException(ec, "Error opening PortAudio Stream.\nError Code: " + ec.ToString()); + } ~Stream() { Dispose(false); @@ -255,7 +360,7 @@ protected virtual void Dispose(bool disposing) // Free Unmanaged resources Close(); userDataHandle.Free(); - streamCallback.Free(); + streamCallback!.Free(); if (finishedCallback != null) finishedCallback.Free(); @@ -317,7 +422,8 @@ public void Stop() throw new PortAudioException(ec, "Unable to stop PortAudio stream due to an active callback loop.\n" + "A StreamCallbackResult must be set to 'Complete' or 'Abort' before a stream can be stopped.\n" + "Error Code: " + ec.ToString()); - throw new PortAudioException(ec, "Error stopping PortAudio Stream.\nError Code: " + ec.ToString()); + else + throw new PortAudioException(ec, "Error stopping PortAudio Stream.\nError Code: " + ec.ToString()); } /// @@ -330,6 +436,263 @@ public void Abort() if (ec != ErrorCode.NoError) throw new PortAudioException(ec, "Error aborting PortAudio Stream.\nError Code: " + ec.ToString()); } + + #region ReadInput + /// + /// Reads the audio input when the stream is opened and processing. + /// The stream must be started with `Pa_StartStream()` before using this. + /// + /// @param buffer The audio input buffer that will be read. + /// + /// @param frames The number of frames in the audio input buffer. + /// + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + public void ReadInput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_ReadStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error reading PortAudio Input Stream.\nError Code: " + ec.ToString()); + } + } + #endregion + + #region WriteOutput + /// + /// Writes the audio output when the stream is opened and processing. + /// The stream must be started with `Pa_StartStream()` before using this. + /// + /// @param buffer The audio output buffer that will be written. + /// + /// @param frames The number of frames in the audio output buffer. + /// + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + public void WriteOutput(Span buffer, ulong frames) + { + nint buffPtr; + unsafe + { + buffPtr = (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)); + } + ErrorCode ec = Native.Pa_WriteStream(streamPtr, buffPtr, frames); + if (ec != ErrorCode.NoError) + { + throw new PortAudioException(ec, "Error writing PortAudio Output Stream.\nError Code: " + ec.ToString()); + } + } + #endregion + #endregion // Operations #region Properties @@ -526,9 +889,15 @@ IntPtr userDataPtr // Originally `void *` /// /// The type of data that was put into the stream /// - public static UD GetUserData(IntPtr userDataPtr) => - (UD)GCHandle.FromIntPtr(userDataPtr).Target; - + public UD GetUserData(nint userDataPtr) + { + UDHandle = GCHandle.FromIntPtr(userDataPtr); + return (UD)GCHandle.FromIntPtr(userDataPtr).Target!; + } + internal GCHandle UDHandle + { + get; private set; + } /// /// This is an internal structure to aid with C# Callbacks that interface with P/Invoke functions. diff --git a/VG Music Studio - GTK4/MainWindow.cs b/VG Music Studio - GTK4/MainWindow.cs index e387d31..268a558 100644 --- a/VG Music Studio - GTK4/MainWindow.cs +++ b/VG Music Studio - GTK4/MainWindow.cs @@ -40,16 +40,14 @@ internal sealed class MainWindow : Window #region Widgets // Buttons - private readonly Button _buttonPlay, _buttonPause, _buttonStop; - - // A Box specifically made to contain two contents inside - private readonly Box _splitContainerBox; + private Button _buttonPlay, _buttonPause, _buttonStop; // Spin Button for the numbered tracks private readonly SpinButton _sequenceNumberSpinButton; // Timer - private readonly Timer _timer; + private GLib.Source _source; + private readonly GLib.Timer _timer; // Popover Menu Bar private readonly PopoverMenuBar _popoverMenuBar; @@ -60,9 +58,6 @@ internal sealed class MainWindow : Window // LibAdwaita Application private readonly Adw.Application _app; - // LibAdwaita Message Dialog - private Adw.MessageDialog _dialog; - // Menu Model //private readonly Gio.MenuModel _mainMenu; @@ -74,12 +69,11 @@ internal sealed class MainWindow : Window // Menu Items private readonly Gio.MenuItem _fileItem, _openDSEItem, _openAlphaDreamItem, _openMP2KItem, _openSDATItem, - _dataItem, _trackViewerItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; + _dataItem, _exportDLSItem, _exportSF2Item, _exportMIDIItem, _exportWAVItem, _playlistItem, _endPlaylistItem; // Menu Actions private Gio.SimpleAction _openDSEAction, _openAlphaDreamAction, _openMP2KAction, _openSDATAction, - _dataAction, _trackViewerAction, _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _playlistAction, _endPlaylistAction, - _soundSequenceAction; + _exportDLSAction, _exportSF2Action, _exportMIDIAction, _exportWAVAction, _endPlaylistAction; // Main Box private Box _mainBox, _configButtonBox, _configPlayerButtonBox, _configSpinButtonBox, _configScaleBox; @@ -88,12 +82,7 @@ internal sealed class MainWindow : Window private Scale _volumeBar, _positionBar; // Mouse Click Gesture - private GestureClick _positionGestureClick, _sequencesGestureClick; - - // Event Controller - private EventArgs _openDSEEvent, _openAlphaDreamEvent, _openMP2KEvent, _openSDATEvent, - _dataEvent, _trackViewerEvent, _exportDLSEvent, _exportSF2Event, _exportMIDIEvent, _exportWAVEvent, _playlistEvent, _endPlaylistEvent, - _sequencesEventController; + private GestureClick _positionGestureClick; // Adjustments are for indicating the numbers and the position of the scale private readonly Adjustment _sequenceNumberAdjustment; @@ -111,7 +100,7 @@ internal sealed class MainWindow : Window private GLib.Internal.ErrorOwnedHandle ErrorHandle = new GLib.Internal.ErrorOwnedHandle(IntPtr.Zero); // Signal - private Signal _signal; + //private Signal _signal; // Callback private Gio.Internal.AsyncReadyCallback _saveCallback { get; set; } @@ -128,9 +117,6 @@ public MainWindow(Application app) Title = ConfigUtils.PROGRAM_NAME; // Sets the title to the name of the program, which is "VG Music Studio" _app = app; - // Configures SetVolumeBar method with the MixerVolumeChanged Event action - Mixer.VolumeChanged += SetVolumeBar; - // LibAdwaita Header Bar _headerBar = Adw.HeaderBar.New(); _headerBar.SetShowEndTitleButtons(true); @@ -269,12 +255,14 @@ public MainWindow(Application app) //_sequenceNumberSpinButton.Visible = false; _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; - // Timer - _timer = new Timer(); - _timer.Elapsed += Timer_Tick; + // // Timer + _timer = GLib.Timer.New(); + // _timer = new Timer(); + // _timer.Elapsed += Timer_Tick; // Volume Bar _volumeBar = Scale.New(Orientation.Horizontal, Gtk.Adjustment.New(0, 0, 100, 1, 10, 0)); + _volumeBar.OnValueChanged += VolumeBar_ValueChanged; _volumeBar.Sensitive = false; _volumeBar.ShowFillLevel = true; _volumeBar.DrawValue = false; @@ -285,6 +273,7 @@ public MainWindow(Application app) _positionGestureClick = GestureClick.New(); _positionBar.AddController(_positionGestureClick); _positionBar.Sensitive = false; + _positionBar.Focusable = true; _positionBar.ShowFillLevel = true; _positionBar.DrawValue = false; _positionBar.WidthRequest = 250; @@ -339,11 +328,11 @@ public MainWindow(Application app) _configSpinButtonBox.Append(_sequenceNumberSpinButton); } - // _volumeBar.MarginStart = 20; - // _volumeBar.MarginEnd = 20; + _volumeBar.MarginStart = 20; + _volumeBar.MarginEnd = 20; _configScaleBox.Append(_volumeBar); - // _positionBar.MarginStart = 20; - // _positionBar.MarginEnd = 20; + _positionBar.MarginStart = 20; + _positionBar.MarginEnd = 20; _configScaleBox.Append(_positionBar); _mainBox.Append(_headerBar); @@ -383,7 +372,8 @@ public void SetVolumeBar(float volume) private bool _positionBarFree = true; private void PositionBar_MouseButtonRelease(object sender, EventArgs args) { - Engine.Instance!.Player.SetSongPosition((long)_positionBar.ValuePos); // Sets the value based on the position when mouse button is released + if (!_positionBarFree) + Engine.Instance!.Player.SetSongPosition((long)_positionBar.Adjustment!.Value); // Sets the value based on the position when mouse button is released _positionBarFree = true; // Sets _positionBarFree to true when mouse button is released LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track } @@ -393,14 +383,16 @@ private bool PositionBar_ChangeValue(object sender, EventArgs args) return false; } - private void PositionBar_MoveSlider(object sender, EventArgs args) => - _positionBarFree = true; + private void PositionBar_MoveSlider(object sender, EventArgs args) + { + UpdatePositionIndicators(Engine.Instance!.Player.ElapsedTicks); + _positionBarFree = false; + } private void PositionBar_ValueChanged(object sender, EventArgs args) { if (Engine.Instance is not null) - _positionBar.SetValue(Engine.Instance!.Player.ElapsedTicks); // Sets the value based on the position when mouse button is released - _positionBarFree = true; // Sets _positionBarFree to true when mouse button is released - LetUIKnowPlayerIsPlaying(); // This method will run the void that tells the UI that the player is playing a track + UpdatePositionIndicators(Engine.Instance!.Player.ElapsedTicks); // Sets the value based on the position when mouse button is released + } private void PositionBar_MouseButtonPress(object sender, EventArgs args) { @@ -418,13 +410,15 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) //_sequencesListView.Margin = 0; //_songInfo.Reset(); bool success; + if (Engine.Instance == null) + { + return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed + } + Player player = Engine.Instance!.Player; + Config cfg = Engine.Instance.Config; try { - if (Engine.Instance == null) - { - return; // Prevents referencing a null Engine.Instance when the engine is being disposed, especially while main window is being closed - } - Engine.Instance!.Player.LoadSong(index); + player.LoadSong(index); success = Engine.Instance.Player.LoadedSong is not null; // TODO: Make sure loadedsong is null when there are no tracks (for each engine, only mp2k guarantees it rn) } catch (Exception ex) @@ -434,25 +428,22 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) } //_trackViewer?.UpdateTracks(); + ILoadedSong? loadedSong = player.LoadedSong; // LoadedSong is still null when there are no tracks if (success) { - Config config = Engine.Instance.Config; - List songs = config.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 + List songs = cfg.Playlists[0].Songs; // Complete "Music" playlist is present in all configs at index 0 int songIndex = songs.FindIndex(s => s.Index == index); if (songIndex != -1) { this.Title = $"{ConfigUtils.PROGRAM_NAME} - {songs[songIndex].Name}"; // TODO: Make this a func //_sequencesColumnView.SortColumnId = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } - //_positionBar.Adjustment!.Upper = double.MaxValue; - _duration = (int)(Engine.Instance!.Player.LoadedSong!.MaxTicks + 0.5); - _positionBar.SetRange(0, _duration); - //_positionAdjustment.LargeChange = (long)(_positionAdjustment.Upper / 10) >> 64; - //_positionAdjustment.SmallChange = (long)(_positionAdjustment.LargeChange / 4) >> 64; - _positionBar.Show(); + _positionBar.Adjustment!.Upper = loadedSong!.MaxTicks; + _positionBar.SetRange(0, loadedSong.MaxTicks); //_songInfo.SetNumTracks(Engine.Instance.Player.LoadedSong.Events.Length); if (_autoplay) { + Show(); Play(); } } @@ -467,13 +458,14 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) _autoplay = true; //_sequencesGestureClick.OnEnd += SequencesListView_SelectionGet; //_signal.Connect(_sequencesListFactory, SequencesListView_SelectionGet, true, null); + Show(); } //private void SequencesListView_SelectionGet(object sender, EventArgs e) //{ // var item = _soundSequenceList.SelectedItem; // if (item is Config.Song song) // { - // SetAndLoadSequence(song.Index); + // SetAndLoadSong(song.Index); // } // else if (item is Config.Playlist playlist) // { @@ -489,12 +481,12 @@ private void SequenceNumberSpinButton_ValueChanged(object sender, EventArgs e) // } // } //} - public void SetAndLoadSequence(int index) + public void SetAndLoadSong(int index) { _curSong = index; if (_sequenceNumberSpinButton.Value == index) { - SequenceNumberSpinButton_ValueChanged(null, null); + SequenceNumberSpinButton_ValueChanged(this, EventArgs.Empty); } else { @@ -514,7 +506,7 @@ public void SetAndLoadSequence(int index) // } // long nextSequence = _remainingSequences[0]; // _remainingSequences.RemoveAt(0); - // SetAndLoadSequence(nextSequence); + // SetAndLoadSong(nextSequence); //} private void ResetPlaylistStuff(bool spinButtonAndListBoxEnabled) { @@ -1140,7 +1132,7 @@ private void ExportWAVFinish(string path) { Stop(); - Player player = Engine.Instance.Player; + Player player = Engine.Instance!.Player; bool oldFade = player.ShouldFadeOut; long oldLoops = player.NumLoops; player.ShouldFadeOut = true; @@ -1181,10 +1173,10 @@ public void ExceptionDialog(Exception error, string heading) public void LetUIKnowPlayerIsPlaying() { // Prevents method from being used if timer is already active - if (_timer.Enabled) - { - return; - } + // if (_timer.Enabled) + // { + // return; + // } // Ensures a GlobalConfig Instance is created if one doesn't exist if (GlobalConfig.Instance == null) @@ -1195,7 +1187,14 @@ public void LetUIKnowPlayerIsPlaying() // Configures the buttons when player is playing a sequenced track _buttonPause.Sensitive = _buttonStop.Sensitive = true; // Setting the 'Sensitive' property to 'true' enables the buttons, allowing you to click on them _buttonPause.Label = Strings.PlayerPause; - _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); + var context = GLib.MainContext.GetThreadDefault(); + var source = GLib.Functions.TimeoutSourceNew((uint)(1_000.0 / GlobalConfig.Instance!.RefreshRate)); + source.SetCallback(CheckPlayback); + var microsec = (ulong)source.Attach(context); + _timer.Elapsed(ref microsec); + //GLib.Functions.TimeoutAdd(0, (uint)(1_000.0 / GlobalConfig.Instance!.RefreshRate), new GLib.SourceFunc(CheckPlayback)); + //GLib.Functions.TestTimerStart(); + // _timer.Interval = (int)(1_000.0 / GlobalConfig.Instance!.RefreshRate); _timer.Start(); Show(); } @@ -1250,7 +1249,7 @@ private void PlayPreviousSequence() } else { - SetAndLoadSequence((int)_sequenceNumberSpinButton.Value - 1); + SetAndLoadSong((int)_sequenceNumberSpinButton.Value - 1); } } private void PlayNextSong(object? sender, EventArgs? e) @@ -1261,7 +1260,7 @@ private void PlayNextSong(object? sender, EventArgs? e) } else { - SetAndLoadSequence((int)_sequenceNumberSpinButton.Value + 1); + SetAndLoadSong((int)_sequenceNumberSpinButton.Value + 1); } } @@ -1279,8 +1278,9 @@ private void FinishLoading(long numSongs) // [Debug methods specific to this GUI will go in here] #endif _autoplay = false; - SetAndLoadSequence(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); + SetAndLoadSong(Engine.Instance.Config.Playlists[0].Songs.Count == 0 ? 0 : Engine.Instance.Config.Playlists[0].Songs[0].Index); _sequenceNumberSpinButton.Sensitive = _buttonPlay.Sensitive = _volumeBar.Sensitive = true; + _volumeBar.SetValue(100); Show(); } private void DisposeEngine() @@ -1307,6 +1307,19 @@ private void DisposeEngine() _sequenceNumberSpinButton.OnValueChanged += SequenceNumberSpinButton_ValueChanged; } + private bool CheckPlayback() + { + if (Engine.Instance is not null) + { + if (_positionBarFree) + { + UpdatePositionIndicators(Engine.Instance!.Player.ElapsedTicks); + return true; + } + } + return false; + } + private void Timer_Tick(object? sender, EventArgs e) { if (_songEnded) @@ -1323,8 +1336,11 @@ private void Timer_Tick(object? sender, EventArgs e) } else { - Player player = Engine.Instance!.Player; - UpdatePositionIndicators(player.ElapsedTicks); + if (Engine.Instance is not null) + { + Player player = Engine.Instance!.Player; + UpdatePositionIndicators(player.ElapsedTicks); + } } } private void SongEnded() @@ -1339,7 +1355,7 @@ private void UpdatePositionIndicators(long ticks) { if (_positionBarFree) { - _positionBar.Adjustment!.Value = ticks; + _positionBar.Adjustment!.SetValue(ticks); } } } diff --git a/VG Music Studio - GTK4/PlayingPlaylist.cs b/VG Music Studio - GTK4/PlayingPlaylist.cs index e1b1d0d..14b7bbb 100644 --- a/VG Music Studio - GTK4/PlayingPlaylist.cs +++ b/VG Music Studio - GTK4/PlayingPlaylist.cs @@ -34,7 +34,7 @@ public void UndoThenSetAndLoadPrevSong(MainWindow parent, int curSong) int prevSong = _playedSongs[prevIndex]; _playedSongs.RemoveAt(prevIndex); _remainingSongs.Insert(0, curSong); - parent.SetAndLoadSequence(prevSong); + parent.SetAndLoadSong(prevSong); } public void SetAndLoadNextSong(MainWindow parent) { @@ -48,6 +48,6 @@ public void SetAndLoadNextSong(MainWindow parent) } int nextSong = _remainingSongs[0]; _remainingSongs.RemoveAt(0); - parent.SetAndLoadSequence(nextSong); + parent.SetAndLoadSong(nextSong); } } diff --git a/VG Music Studio - GTK4/Program.cs b/VG Music Studio - GTK4/Program.cs index a99da5f..46ca59f 100644 --- a/VG Music Studio - GTK4/Program.cs +++ b/VG Music Studio - GTK4/Program.cs @@ -1,48 +1,49 @@ using Adw; using System; -using System.Reflection; using System.Runtime.InteropServices; namespace Kermalis.VGMusicStudio.GTK4 { internal class Program { - private readonly Adw.Application app; - - // public Theme Theme => Theme.ThemeType; + private static readonly Adw.Application _app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.FlagsNone); + private static readonly OSPlatform Linux = OSPlatform.Linux; + private static readonly OSPlatform FreeBSD = OSPlatform.FreeBSD; [STAThread] - public static int Main(string[] args) => new Program().Run(args); - public Program() + public static void Main(string[] args) { - app = Application.New("org.Kermalis.VGMusicStudio.GTK4", Gio.ApplicationFlags.NonUnique); + _app.Register(Gio.Cancellable.GetCurrent()); - // var theme = new ThemeType(); - // // Set LibAdwaita Themes - // app.StyleManager!.ColorScheme = theme switch - // { - // ThemeType.System => ColorScheme.PreferDark, - // ThemeType.Light => ColorScheme.ForceLight, - // ThemeType.Dark => ColorScheme.ForceDark, - // _ => ColorScheme.PreferDark - // }; - var win = new MainWindow(app); + if (!RuntimeInformation.IsOSPlatform(Linux) | !RuntimeInformation.IsOSPlatform(FreeBSD)) + { + if (GLib.Functions.Getenv("GDK_BACKEND") is not "wayland") + { + GLib.Functions.Setenv("GSK_RENDERER", "cairo", false); + } + } - app.OnActivate += OnActivate; + _app.OnActivate += OnActivate; void OnActivate(Gio.Application sender, EventArgs e) { - // Add Main Window - app.AddWindow(win); + } - } - public int Run(string[] args) - { var argv = new string[args.Length + 1]; argv[0] = "Kermalis.VGMusicStudio.GTK4"; args.CopyTo(argv, 1); - return app.Run(args.Length + 1, argv); + + // Set an initial? + string initial = ""; + if (args.Length > 0) + initial = args[0].Trim(); + + // Add Main Window + var win = new MainWindow(_app); + _app.AddWindow(win); + win.Show(); + _app.Run(args.Length, args); } } } diff --git a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj index d711af8..08aa569 100644 --- a/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj +++ b/VG Music Studio - GTK4/VG Music Studio - GTK4.csproj @@ -11,6 +11,13 @@ + + + + %(Filename)%(Extension) + + + diff --git a/VG Music Studio - GTK4/mainwindow.xml b/VG Music Studio - GTK4/mainwindow.xml new file mode 100644 index 0000000..0488032 --- /dev/null +++ b/VG Music Studio - GTK4/mainwindow.xml @@ -0,0 +1,133 @@ + + + + + + + + + + + vertical + + + + + Open + + + + + + + + + + + + + 60 + + + vertical + 15 + + + 175 + + + media-playback-start + False + + + + + media-playback-pause + False + + + + + media-playback-stop + False + + + + + + + + + 10.0 + 1.0 + 100.0 + + + False + + + + + + + vertical + 15 + 175 + + + + + 1.0 + 1.0 + 1.0 + -1.0 + + + 1.0 + False + False + + + + + + + 10.0 + 1.0 + 100.0 + + + False + + + + + + + + + + + +
      + + + + +
      +
      + +
      + + + + +
      +
      + +
      + +
      +
      +
      +