diff --git a/DLS2/Chunks/Chunk.cs b/DLS2/Chunks/Chunk.cs new file mode 100644 index 0000000..6b4b775 --- /dev/null +++ b/DLS2/Chunks/Chunk.cs @@ -0,0 +1,98 @@ +using Kermalis.EndianBinaryIO; +using System.Collections.Generic; +using System.IO; + +namespace Kermalis.DLS2 +{ + public abstract class DLSChunk + { + /// Length 4 + public string ChunkName { get; } + /// Size in bytes + protected internal uint Size { get; protected set; } + + protected DLSChunk(string name) + { + ChunkName = name; + } + protected DLSChunk(string name, EndianBinaryReader reader) + { + ChunkName = name; + Size = reader.ReadUInt32(); + } + + protected long GetEndOffset(EndianBinaryReader reader) + { + return reader.BaseStream.Position + Size; + } + protected void EatRemainingBytes(EndianBinaryReader reader, long endOffset) + { + if (reader.BaseStream.Position > endOffset) + { + throw new InvalidDataException(); + } + reader.BaseStream.Position = endOffset; + } + + internal abstract void UpdateSize(); + + internal virtual void Write(EndianBinaryWriter writer) + { + UpdateSize(); + writer.Write(ChunkName, 4); + writer.Write(Size); + } + + internal static List GetAllChunks(EndianBinaryReader reader, long endOffset) + { + var chunks = new List(); + while (reader.BaseStream.Position < endOffset) + { + chunks.Add(SwitchNextChunk(reader)); + } + if (reader.BaseStream.Position > endOffset) + { + throw new InvalidDataException(); + } + return chunks; + } + private static DLSChunk SwitchNextChunk(EndianBinaryReader reader) + { + string str = reader.ReadString(4, false); + switch (str) + { + case "art1": return new Level1ArticulatorChunk(reader); + case "art2": return new Level2ArticulatorChunk(reader); + case "colh": return new CollectionHeaderChunk(reader); + case "data": return new DataChunk(reader); + case "dlid": return new DLSIDChunk(reader); + case "fmt ": return new FormatChunk(reader); + case "insh": return new InstrumentHeaderChunk(reader); + case "LIST": return new ListChunk(reader); + case "ptbl": return new PoolTableChunk(reader); + case "rgnh": return new RegionHeaderChunk(reader); + case "wlnk": return new WaveLinkChunk(reader); + case "wsmp": return new WaveSampleChunk(reader); + // InfoSubChunks + case "IARL": + case "IART": + case "ICMS": + case "ICMD": + case "ICOP": + case "ICRD": + case "IENG": + case "IGNR": + case "IKEY": + case "IMED": + case "INAM": + case "IPRD": + case "ISBJ": + case "ISFT": + case "ISRC": + case "ISRF": + case "ITCH": return new InfoSubChunk(str, reader); + default: return new UnsupportedChunk(str, reader); + } + } + } +} diff --git a/DLS2/Chunks/CollectionHeaderChunk.cs b/DLS2/Chunks/CollectionHeaderChunk.cs new file mode 100644 index 0000000..0f5256e --- /dev/null +++ b/DLS2/Chunks/CollectionHeaderChunk.cs @@ -0,0 +1,29 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + // Collection Header Chunk - Page 40 of spec + public sealed class CollectionHeaderChunk : DLSChunk + { + public uint NumInstruments { get; internal set; } + + internal CollectionHeaderChunk() : base("colh") { } + public CollectionHeaderChunk(EndianBinaryReader reader) : base("colh", reader) + { + long endOffset = GetEndOffset(reader); + NumInstruments = reader.ReadUInt32(); + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4; // NumInstruments + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(NumInstruments); + } + } +} diff --git a/DLS2/Chunks/ConditionalChunk.cs b/DLS2/Chunks/ConditionalChunk.cs new file mode 100644 index 0000000..c96c20e --- /dev/null +++ b/DLS2/Chunks/ConditionalChunk.cs @@ -0,0 +1,36 @@ +namespace Kermalis.DLS2 +{ + // ALL TODO: + + /*public enum DLSConditional : ushort + { + And = 1, + Or = 2, + Xor = 3, + Add = 4, + Subtract = 5, + Multiply = 6, + Divide = 7, + LogicalAnd = 8, + LogicalOr = 9, + Lt = 10, + Le = 11, + Gt = 12, + Ge = 13, + Eq = 14, + Not = 15, + Const = 16, + Query = 17, + QuerySupported = 18 + } + + // Conditional Chunk - Page 42 of spec + internal sealed class ConditionalChunk : DLSChunk + { + public ConditionalChunk(EndianBinaryReader reader) : base("cdl ", reader) + { + DLSConditional cond = reader.ReadEnum(); + + } + }*/ +} diff --git a/DLS2/Chunks/DLSIDChunk.cs b/DLS2/Chunks/DLSIDChunk.cs new file mode 100644 index 0000000..b9b8aab --- /dev/null +++ b/DLS2/Chunks/DLSIDChunk.cs @@ -0,0 +1,45 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.DLS2 +{ + // DLSID Chunk - Page 40 of spec + public sealed class DLSIDChunk : DLSChunk + { + private DLSID _dlsid; + public DLSID DLSID + { + get => _dlsid; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _dlsid = value; + } + } + + public DLSIDChunk(DLSID id) : base("dlid") + { + DLSID = id; + } + public DLSIDChunk(EndianBinaryReader reader) : base("dlid", reader) + { + long endOffset = GetEndOffset(reader); + DLSID = new DLSID(reader); + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 16; // DLSID + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + DLSID.Write(writer); + } + } +} diff --git a/DLS2/Chunks/DataChunk.cs b/DLS2/Chunks/DataChunk.cs new file mode 100644 index 0000000..f924db3 --- /dev/null +++ b/DLS2/Chunks/DataChunk.cs @@ -0,0 +1,10 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + public sealed class DataChunk : RawDataChunk + { + public DataChunk(byte[] data) : base("data", data) { } + internal DataChunk(EndianBinaryReader reader) : base("data", reader) { } + } +} diff --git a/DLS2/Chunks/FormatChunk.cs b/DLS2/Chunks/FormatChunk.cs new file mode 100644 index 0000000..7a7779e --- /dev/null +++ b/DLS2/Chunks/FormatChunk.cs @@ -0,0 +1,105 @@ +using Kermalis.EndianBinaryIO; +using System.IO; + +namespace Kermalis.DLS2 +{ + public abstract class FormatInfo + { + public ushort BitsPerSample { get; set; } + + internal abstract void Write(EndianBinaryWriter writer); + } + public sealed class PCMInfo : FormatInfo + { + internal PCMInfo() { } + internal PCMInfo(EndianBinaryReader reader) + { + BitsPerSample = reader.ReadUInt16(); + } + + internal override void Write(EndianBinaryWriter writer) + { + writer.Write(BitsPerSample); + } + } + // Untested! + public sealed class ExtensibleInfo : FormatInfo + { + public ushort ExtraInfo { get; set; } + public uint ChannelMask { get; set; } + public DLSID SubFormat { get; set; } + + internal ExtensibleInfo() + { + SubFormat = new DLSID(); + } + internal ExtensibleInfo(EndianBinaryReader reader) + { + BitsPerSample = reader.ReadUInt16(); + ushort byteSize = reader.ReadUInt16(); + if (byteSize != 22) + { + throw new InvalidDataException(); + } + ExtraInfo = reader.ReadUInt16(); + ChannelMask = reader.ReadUInt32(); + SubFormat = new DLSID(reader); + } + + internal override void Write(EndianBinaryWriter writer) + { + writer.Write(BitsPerSample); + writer.Write(22u); + writer.Write(ExtraInfo); + writer.Write(ChannelMask); + SubFormat.Write(writer); + } + } + + // Format Chunk - Page 57 of spec + public sealed class FormatChunk : DLSChunk + { + public WaveInfo WaveInfo { get; } + public FormatInfo FormatInfo { get; } + + public FormatChunk(WaveFormat format) : base("fmt ") + { + WaveInfo = new WaveInfo() { FormatTag = format }; + if (format == WaveFormat.Extensible) + { + FormatInfo = new ExtensibleInfo(); + } + else + { + FormatInfo = new PCMInfo(); + } + } + internal FormatChunk(EndianBinaryReader reader) : base("fmt ", reader) + { + long endOffset = GetEndOffset(reader); + WaveInfo = new WaveInfo(reader); + if (WaveInfo.FormatTag == WaveFormat.Extensible) + { + FormatInfo = new ExtensibleInfo(reader); + } + else + { + FormatInfo = new PCMInfo(reader); + } + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 14 // WaveFormat + + (WaveInfo.FormatTag == DLS2.WaveFormat.Extensible ? 26u : 2u); // FormatInfo + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + WaveInfo.Write(writer); + FormatInfo.Write(writer); + } + } +} diff --git a/DLS2/Chunks/InfoSubChunk.cs b/DLS2/Chunks/InfoSubChunk.cs new file mode 100644 index 0000000..71a629a --- /dev/null +++ b/DLS2/Chunks/InfoSubChunk.cs @@ -0,0 +1,53 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Linq; + +namespace Kermalis.DLS2 +{ + public sealed class InfoSubChunk : DLSChunk + { + private string _text; + public string Text + { + get => _text; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (value.Any(c => c > sbyte.MaxValue)) + { + throw new ArgumentException("Text must be ASCII"); + } + _text = value; + } + } + + public InfoSubChunk(string name, string text) : base(name) + { + Text = text; + } + internal InfoSubChunk(string name, EndianBinaryReader reader) : base(name, reader) + { + long endOffset = GetEndOffset(reader); + _text = reader.ReadStringNullTerminated(); + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = (uint)_text.Length + 1; // +1 for \0 + if (Size % 2 != 0) // Align by 2 bytes + { + Size++; + } + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(_text, (int)Size); + } + } +} diff --git a/DLS2/Chunks/InstrumentHeaderChunk.cs b/DLS2/Chunks/InstrumentHeaderChunk.cs new file mode 100644 index 0000000..077070c --- /dev/null +++ b/DLS2/Chunks/InstrumentHeaderChunk.cs @@ -0,0 +1,46 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.DLS2 +{ + // Instrument Header Chunk - Page 45 of spec + public sealed class InstrumentHeaderChunk : DLSChunk + { + public uint NumRegions { get; set; } + private MIDILocale _locale; + public MIDILocale Locale + { + get => _locale; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _locale = value; + } + } + + public InstrumentHeaderChunk() : base("insh") { } + internal InstrumentHeaderChunk(EndianBinaryReader reader) : base("insh", reader) + { + long endOffset = GetEndOffset(reader); + NumRegions = reader.ReadUInt32(); + _locale = new MIDILocale(reader); + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4 // NumRegions + + 8; // Locale + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(NumRegions); + _locale.Write(writer); + } + } +} diff --git a/DLS2/Chunks/Level1ArticulatorChunk.cs b/DLS2/Chunks/Level1ArticulatorChunk.cs new file mode 100644 index 0000000..c6b4f26 --- /dev/null +++ b/DLS2/Chunks/Level1ArticulatorChunk.cs @@ -0,0 +1,119 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace Kermalis.DLS2 +{ + // Level 1 Articulator Chunk - Page 46 of spec + public sealed class Level1ArticulatorChunk : DLSChunk, IList, IReadOnlyList + { + private readonly List _connectionBlocks; + + public Level1ArticulatorConnectionBlock this[int index] + { + get => _connectionBlocks[index]; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _connectionBlocks[index] = value; + } + } + public int Count => _connectionBlocks.Count; + public bool IsReadOnly => false; + + public Level1ArticulatorChunk() : base("art1") + { + _connectionBlocks = new List(); + } + internal Level1ArticulatorChunk(EndianBinaryReader reader) : base("art1", reader) + { + long endOffset = GetEndOffset(reader); + uint byteSize = reader.ReadUInt32(); + if (byteSize != 8) + { + throw new InvalidDataException(); + } + uint numConnectionBlocks = reader.ReadUInt32(); + _connectionBlocks = new List((int)numConnectionBlocks); + for (uint i = 0; i < numConnectionBlocks; i++) + { + _connectionBlocks.Add(new Level1ArticulatorConnectionBlock(reader)); + } + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4 // byteSize + + 4 // _numConnectionBlocks + + (uint)(12 * _connectionBlocks.Count); // _connectionBlocks + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(8u); + writer.Write((uint)_connectionBlocks.Count); + for (int i = 0; i < _connectionBlocks.Count; i++) + { + _connectionBlocks[i].Write(writer); + } + } + + public IEnumerator GetEnumerator() + { + return _connectionBlocks.GetEnumerator(); + } + IEnumerator IEnumerable.GetEnumerator() + { + return _connectionBlocks.GetEnumerator(); + } + + public void Add(Level1ArticulatorConnectionBlock item) + { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + _connectionBlocks.Add(item); + } + public void Clear() + { + _connectionBlocks.Clear(); + } + public void CopyTo(Level1ArticulatorConnectionBlock[] array, int arrayIndex) + { + _connectionBlocks.CopyTo(array, arrayIndex); + } + public bool Contains(Level1ArticulatorConnectionBlock item) + { + return _connectionBlocks.Contains(item); + } + public int IndexOf(Level1ArticulatorConnectionBlock item) + { + return _connectionBlocks.IndexOf(item); + } + public void Insert(int index, Level1ArticulatorConnectionBlock item) + { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + _connectionBlocks.Insert(index, item); + } + public bool Remove(Level1ArticulatorConnectionBlock item) + { + return _connectionBlocks.Remove(item); + } + public void RemoveAt(int index) + { + _connectionBlocks.RemoveAt(index); + } + + } +} diff --git a/DLS2/Chunks/Level2ArticulatorChunk.cs b/DLS2/Chunks/Level2ArticulatorChunk.cs new file mode 100644 index 0000000..71e8b33 --- /dev/null +++ b/DLS2/Chunks/Level2ArticulatorChunk.cs @@ -0,0 +1,119 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace Kermalis.DLS2 +{ + // Level 2 Articulator Chunk - Page 49 of spec + public sealed class Level2ArticulatorChunk : DLSChunk, IList, IReadOnlyList + { + private readonly List _connectionBlocks; + + public Level2ArticulatorConnectionBlock this[int index] + { + get => _connectionBlocks[index]; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _connectionBlocks[index] = value; + } + } + public int Count => _connectionBlocks.Count; + public bool IsReadOnly => false; + + public Level2ArticulatorChunk() : base("art2") + { + _connectionBlocks = new List(); + } + internal Level2ArticulatorChunk(EndianBinaryReader reader) : base("art2", reader) + { + long endOffset = GetEndOffset(reader); + uint byteSize = reader.ReadUInt32(); + if (byteSize != 8) + { + throw new InvalidDataException(); + } + uint numConnectionBlocks = reader.ReadUInt32(); + _connectionBlocks = new List((int)numConnectionBlocks); + for (uint i = 0; i < numConnectionBlocks; i++) + { + _connectionBlocks.Add(new Level2ArticulatorConnectionBlock(reader)); + } + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4 // byteSize + + 4 // _numConnectionBlocks + + (uint)(12 * _connectionBlocks.Count); // _connectionBlocks + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(8u); + writer.Write((uint)_connectionBlocks.Count); + for (int i = 0; i < _connectionBlocks.Count; i++) + { + _connectionBlocks[i].Write(writer); + } + } + + public IEnumerator GetEnumerator() + { + return _connectionBlocks.GetEnumerator(); + } + IEnumerator IEnumerable.GetEnumerator() + { + return _connectionBlocks.GetEnumerator(); + } + + public void Add(Level2ArticulatorConnectionBlock item) + { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + _connectionBlocks.Add(item); + } + public void Clear() + { + _connectionBlocks.Clear(); + } + public void CopyTo(Level2ArticulatorConnectionBlock[] array, int arrayIndex) + { + _connectionBlocks.CopyTo(array, arrayIndex); + } + public bool Contains(Level2ArticulatorConnectionBlock item) + { + return _connectionBlocks.Contains(item); + } + public int IndexOf(Level2ArticulatorConnectionBlock item) + { + return _connectionBlocks.IndexOf(item); + } + public void Insert(int index, Level2ArticulatorConnectionBlock item) + { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + _connectionBlocks.Insert(index, item); + } + public bool Remove(Level2ArticulatorConnectionBlock item) + { + return _connectionBlocks.Remove(item); + } + public void RemoveAt(int index) + { + _connectionBlocks.RemoveAt(index); + } + + } +} diff --git a/DLS2/Chunks/ListChunk.cs b/DLS2/Chunks/ListChunk.cs new file mode 100644 index 0000000..1c4107e --- /dev/null +++ b/DLS2/Chunks/ListChunk.cs @@ -0,0 +1,112 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Kermalis.DLS2 +{ + // LIST Chunk - Page 40 of spec + public sealed class ListChunk : DLSChunk, IList, IReadOnlyList + { + /// Length 4 + public string Identifier { get; set; } + private readonly List _children; + + public int Count => _children.Count; + public bool IsReadOnly => false; + public DLSChunk this[int index] + { + get => _children[index]; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _children[index] = value; + } + } + + public ListChunk(string identifier) : base("LIST") + { + Identifier = identifier; + _children = new List(); + } + internal ListChunk(EndianBinaryReader reader) : base("LIST", reader) + { + long endOffset = GetEndOffset(reader); + Identifier = reader.ReadString(4, false); + _children = GetAllChunks(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4; // Identifier + foreach (DLSChunk c in _children) + { + c.UpdateSize(); + Size += c.Size + 8; + } + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(Identifier, 4); + foreach (DLSChunk c in _children) + { + c.Write(writer); + } + } + + public void Add(DLSChunk chunk) + { + if (chunk is null) + { + throw new ArgumentNullException(nameof(chunk)); + } + _children.Add(chunk); + } + public void Clear() + { + _children.Clear(); + } + public bool Contains(DLSChunk chunk) + { + return _children.Contains(chunk); + } + public void CopyTo(DLSChunk[] array, int arrayIndex) + { + _children.CopyTo(array, arrayIndex); + } + public int IndexOf(DLSChunk chunk) + { + return _children.IndexOf(chunk); + } + public void Insert(int index, DLSChunk chunk) + { + if (chunk is null) + { + throw new ArgumentNullException(nameof(chunk)); + } + _children.Insert(index, chunk); + } + public bool Remove(DLSChunk chunk) + { + return _children.Remove(chunk); + } + public void RemoveAt(int index) + { + _children.RemoveAt(index); + } + + public IEnumerator GetEnumerator() + { + return _children.GetEnumerator(); + } + IEnumerator IEnumerable.GetEnumerator() + { + return _children.GetEnumerator(); + } + } +} diff --git a/DLS2/Chunks/PoolTableChunk.cs b/DLS2/Chunks/PoolTableChunk.cs new file mode 100644 index 0000000..07d698c --- /dev/null +++ b/DLS2/Chunks/PoolTableChunk.cs @@ -0,0 +1,71 @@ +using Kermalis.EndianBinaryIO; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace Kermalis.DLS2 +{ + // Pool Table Chunk - Page 54 of spec + public sealed class PoolTableChunk : DLSChunk, IReadOnlyList + { + private uint _numCues; + private List _poolCues; + + public uint this[int index] => _poolCues[index]; + public int Count => (int)_numCues; + + internal PoolTableChunk() : base("ptbl") + { + _poolCues = new List(); + } + internal PoolTableChunk(EndianBinaryReader reader) : base("ptbl", reader) + { + long endOffset = GetEndOffset(reader); + uint byteSize = reader.ReadUInt32(); + if (byteSize != 8) + { + throw new InvalidDataException(); + } + _numCues = reader.ReadUInt32(); + _poolCues = new List((int)_numCues); + for (uint i = 0; i < _numCues; i++) + { + _poolCues.Add(reader.ReadUInt32()); + } + EatRemainingBytes(reader, endOffset); + } + + internal void UpdateCues(List newCues) + { + _numCues = (uint)newCues.Count; + _poolCues = newCues; + } + + internal override void UpdateSize() + { + Size = 4 // byteSize + + 4 // _numCues + + (4 * _numCues); // _poolCues + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(8u); + writer.Write(_numCues); + for (int i = 0; i < _numCues; i++) + { + writer.Write(_poolCues[i]); + } + } + + public IEnumerator GetEnumerator() + { + return _poolCues.GetEnumerator(); + } + IEnumerator IEnumerable.GetEnumerator() + { + return _poolCues.GetEnumerator(); + } + } +} diff --git a/DLS2/Chunks/RawDataChunk.cs b/DLS2/Chunks/RawDataChunk.cs new file mode 100644 index 0000000..117d24f --- /dev/null +++ b/DLS2/Chunks/RawDataChunk.cs @@ -0,0 +1,50 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.DLS2 +{ + public abstract class RawDataChunk : DLSChunk + { + private byte[] _data; + public byte[] Data + { + get => _data; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _data = value; + } + } + + protected RawDataChunk(string name, byte[] data) : base(name) + { + Data = data; + } + protected RawDataChunk(string name, EndianBinaryReader reader) : base(name, reader) + { + _data = reader.ReadBytes((int)Size); + } + + internal override void UpdateSize() + { + Size = (uint)_data.Length; + if (Size % 2 != 0) // Align by 2 bytes + { + Size++; + } + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(_data); + for (int i = _data.Length; i < Size; i++) + { + writer.Write((byte)0); + } + } + } +} diff --git a/DLS2/Chunks/RegionHeaderChunk.cs b/DLS2/Chunks/RegionHeaderChunk.cs new file mode 100644 index 0000000..aaabd0b --- /dev/null +++ b/DLS2/Chunks/RegionHeaderChunk.cs @@ -0,0 +1,52 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + // Region Header Chunk - Page 45 of spec + public sealed class RegionHeaderChunk : DLSChunk + { + public Range KeyRange { get; set; } + public Range VelocityRange { get; set; } + public ushort Options { get; set; } + public ushort KeyGroup { get; set; } + public ushort Layer { get; set; } + + public RegionHeaderChunk() : base("rgnh") + { + KeyRange = new Range(0, 127); + VelocityRange = new Range(0, 127); + } + internal RegionHeaderChunk(EndianBinaryReader reader) : base("rgnh", reader) + { + long endOffset = GetEndOffset(reader); + KeyRange = new Range(reader); + VelocityRange = new Range(reader); + Options = reader.ReadUInt16(); + KeyGroup = reader.ReadUInt16(); + if (Size >= 14) // Size of 12 is also valid + { + Layer = reader.ReadUInt16(); + } + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4 // KeyRange + + 4 // VelocityRange + + 2 // Options + + 2 // KeyGroup + + 2; // Layer + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + KeyRange.Write(writer); + VelocityRange.Write(writer); + writer.Write(Options); + writer.Write(KeyGroup); + writer.Write(Layer); + } + } +} diff --git a/DLS2/Chunks/UnsupportedChunk.cs b/DLS2/Chunks/UnsupportedChunk.cs new file mode 100644 index 0000000..acdccb1 --- /dev/null +++ b/DLS2/Chunks/UnsupportedChunk.cs @@ -0,0 +1,10 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + public sealed class UnsupportedChunk : RawDataChunk + { + public UnsupportedChunk(string name, byte[] data) : base(name, data) { } + internal UnsupportedChunk(string name, EndianBinaryReader reader) : base(name, reader) { } + } +} diff --git a/DLS2/Chunks/VersionChunk.cs b/DLS2/Chunks/VersionChunk.cs new file mode 100644 index 0000000..42302bf --- /dev/null +++ b/DLS2/Chunks/VersionChunk.cs @@ -0,0 +1,14 @@ +namespace Kermalis.DLS2 +{ + // TODO: + + /*public sealed class VersionChunk : DLSChunk + { + + + internal VersionChunk(EndianBinaryReader reader) : base("vers", reader) + { + + } + }*/ +} diff --git a/DLS2/Chunks/WaveLinkChunk.cs b/DLS2/Chunks/WaveLinkChunk.cs new file mode 100644 index 0000000..37cb660 --- /dev/null +++ b/DLS2/Chunks/WaveLinkChunk.cs @@ -0,0 +1,43 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + public sealed class WaveLinkChunk : DLSChunk + { + public WaveLinkOptions Options { get; set; } + public ushort PhaseGroup { get; set; } + public WaveLinkChannels Channels { get; set; } + public uint TableIndex { get; set; } + + public WaveLinkChunk() : base("wlnk") + { + Channels = WaveLinkChannels.Left; + } + internal WaveLinkChunk(EndianBinaryReader reader) : base("wlnk", reader) + { + long endOffset = GetEndOffset(reader); + Options = reader.ReadEnum(); + PhaseGroup = reader.ReadUInt16(); + Channels = reader.ReadEnum(); + TableIndex = reader.ReadUInt32(); + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 2 // Options + + 2 // PhaseGroup + + 4 // Channel + + 4; // TableIndex + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(Options); + writer.Write(PhaseGroup); + writer.Write(Channels); + writer.Write(TableIndex); + } + } +} diff --git a/DLS2/Chunks/WaveSampleChunk.cs b/DLS2/Chunks/WaveSampleChunk.cs new file mode 100644 index 0000000..d005392 --- /dev/null +++ b/DLS2/Chunks/WaveSampleChunk.cs @@ -0,0 +1,69 @@ +using Kermalis.EndianBinaryIO; +using System.IO; + +namespace Kermalis.DLS2 +{ + public sealed class WaveSampleChunk : DLSChunk + { + public ushort UnityNote { get; set; } + public short FineTune { get; set; } + public int Gain { get; set; } + public WaveSampleOptions Options { get; set; } + + public WaveSampleLoop Loop { get; set; } // Combining "SampleLoops" and the loop list + + public WaveSampleChunk() : base("wsmp") + { + UnityNote = 60; + Loop = null; + } + internal WaveSampleChunk(EndianBinaryReader reader) : base("wsmp", reader) + { + long endOffset = GetEndOffset(reader); + uint byteSize = reader.ReadUInt32(); + if (byteSize != 20) + { + throw new InvalidDataException(); + } + UnityNote = reader.ReadUInt16(); + FineTune = reader.ReadInt16(); + Gain = reader.ReadInt32(); + Options = reader.ReadEnum(); + if (reader.ReadUInt32() == 1) + { + Loop = new WaveSampleLoop(reader); + } + EatRemainingBytes(reader, endOffset); + } + + internal override void UpdateSize() + { + Size = 4 // byteSize + + 2 // UnityNote + + 2 // FineTune + + 4 // Gain + + 4 // Options + + 4 // DoesLoop + + (Loop is null ? 0u : 16u); // Loop + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(20u); + writer.Write(UnityNote); + writer.Write(FineTune); + writer.Write(Gain); + writer.Write(Options); + if (Loop is null) + { + writer.Write(0u); + } + else + { + writer.Write(1u); + Loop.Write(writer); + } + } + } +} diff --git a/DLS2/DLS.cs b/DLS2/DLS.cs new file mode 100644 index 0000000..d785aca --- /dev/null +++ b/DLS2/DLS.cs @@ -0,0 +1,235 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace Kermalis.DLS2 +{ + public sealed class DLS : IList, IReadOnlyList + { + private readonly List _chunks; + + public int Count => _chunks.Count; + public bool IsReadOnly => false; + public DLSChunk this[int index] + { + get => _chunks[index]; + set + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _chunks[index] = value; + } + } + + public CollectionHeaderChunk CollectionHeader => GetChunk(); + public ListChunk InstrumentList => GetListChunk("lins"); + public PoolTableChunk PoolTable => GetChunk(); + public ListChunk WavePool => GetListChunk("wvpl"); + + private T GetChunk() where T : DLSChunk + { + return (T)_chunks.Find(c => c is T); + } + private ListChunk GetListChunk(string str) + { + return (ListChunk)_chunks.Find(c => c is ListChunk lc && lc.Identifier == str); + } + +#if DEBUG + public static void Main() + { + //new DLS(@"C:\Users\Kermalis\Documents\Emulation\GBA\Games\M\test.dls"); + //new DLS(@"C:\Users\Kermalis\Documents\Emulation\GBA\Games\M\test2.dls"); + //new DLS(@"C:\Users\Kermalis\Music\Samples, Presets, Soundfonts, VSTs, etc\Soundfonts\Arachno SoundFont - Version 1.0.dls"); + //new DLS(@"C:\Users\Kermalis\Music\Samples, Presets, Soundfonts, VSTs, etc\Soundfonts\Musyng Kite.dls"); + new DLS(@"C:\Users\Kermalis\Music\Samples, Presets, Soundfonts, VSTs, etc\Soundfonts\RSE Corrected Soundfont Revision 17.dls"); + } +#endif + + /// For creating. + public DLS() + { + _chunks = new List() + { + new CollectionHeaderChunk(), + new ListChunk("lins"), + new PoolTableChunk(), + new ListChunk("wvpl"), + }; + } + public DLS(string path) + { + var reader = new EndianBinaryReader(File.Open(path, FileMode.Open)); + { + _chunks = Init(reader); + } + } + public DLS(Stream stream) + { + _chunks = Init(new EndianBinaryReader(stream)); + } + private List Init(EndianBinaryReader reader) + { + string str = reader.ReadString(4, false); + if (str != "RIFF") + { + throw new InvalidDataException("RIFF header was not found at the start of the file."); + } + uint size = reader.ReadUInt32(); + long endOffset = reader.BaseStream.Position + size; + str = reader.ReadString(4, false); + if (str != "DLS ") + { + throw new InvalidDataException("DLS header was not found at the expected offset."); + } + return DLSChunk.GetAllChunks(reader, endOffset); + } + + public void UpdateCollectionHeader() + { + CollectionHeader.NumInstruments = (uint)InstrumentList.Count; + } + /// Updates the pointers in the . Should be called after modifying . + public void UpdatePoolTable() + { + ListChunk wvpl = WavePool; + var newCues = new List(wvpl.Count); + uint cur = 0; + for (int i = 0; i < wvpl.Count; i++) + { + newCues.Add(cur); + DLSChunk c = wvpl[i]; + c.UpdateSize(); + cur += c.Size + 8; + } + PoolTable.UpdateCues(newCues); + } + public void Save(string path) + { + UpdateCollectionHeader(); + UpdatePoolTable(); + + var writer = new EndianBinaryWriter(File.Open(path, FileMode.Create)); + { + writer.Write("RIFF", 4); + writer.Write(UpdateSize()); + writer.Write("DLS ", 4); + foreach (DLSChunk c in _chunks) + { + c.Write(writer); + } + } + } + + public string GetHierarchy() + { + var str = new StringBuilder(); + int tabLevel = 0; + void ApplyTabLevel() + { + for (int t = 0; t < tabLevel; t++) + { + str.Append('\t'); + } + } + void Recursion(IReadOnlyList parent, string listName) + { + ApplyTabLevel(); + str.Append($"{listName} ({parent.Count})"); + tabLevel++; + foreach (DLSChunk c in parent) + { + str.AppendLine(); + if (c is ListChunk lc) + { + Recursion(lc, $"{lc.ChunkName} '{lc.Identifier}'"); + } + else + { + ApplyTabLevel(); + str.Append($"<{c.ChunkName}>"); + if (c is InfoSubChunk ic) + { + str.Append($" [\"{ic.Text}\"]"); + } + else if (c is RawDataChunk dc) + { + str.Append($" [{dc.Data.Length} bytes]"); + } + } + } +#pragma warning disable IDE0059 // Unnecessary assignment of a value + tabLevel--; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + } + Recursion(this, "RIFF 'DLS '"); + return str.ToString(); + } + + private uint UpdateSize() + { + uint size = 4; + foreach (DLSChunk c in _chunks) + { + c.UpdateSize(); + size += c.Size + 8; + } + return size; + } + + public void Add(DLSChunk chunk) + { + if (chunk is null) + { + throw new ArgumentNullException(nameof(chunk)); + } + _chunks.Add(chunk); + } + public void Clear() + { + _chunks.Clear(); + } + public bool Contains(DLSChunk chunk) + { + return _chunks.Contains(chunk); + } + public void CopyTo(DLSChunk[] array, int arrayIndex) + { + _chunks.CopyTo(array, arrayIndex); + } + public int IndexOf(DLSChunk chunk) + { + return _chunks.IndexOf(chunk); + } + public void Insert(int index, DLSChunk chunk) + { + if (chunk is null) + { + throw new ArgumentNullException(nameof(chunk)); + } + _chunks.Insert(index, chunk); + } + public bool Remove(DLSChunk chunk) + { + return _chunks.Remove(chunk); + } + public void RemoveAt(int index) + { + _chunks.RemoveAt(index); + } + + public IEnumerator GetEnumerator() + { + return _chunks.GetEnumerator(); + } + IEnumerator IEnumerable.GetEnumerator() + { + return _chunks.GetEnumerator(); + } + } +} diff --git a/DLS2/DLS2.csproj b/DLS2/DLS2.csproj new file mode 100644 index 0000000..4da739f --- /dev/null +++ b/DLS2/DLS2.csproj @@ -0,0 +1,30 @@ + + + + Kermalis + + DLS2 + DLS2 + DLS2 + Kermalis.DLS2 + 1.0.0.0 + ..\Build + + + + netcoreapp3.1 + Exe + + + + netcoreapp3.1 + Auto + none + false + + + + + + + diff --git a/DLS2/Enums/Level1ArticulatorEnums.cs b/DLS2/Enums/Level1ArticulatorEnums.cs new file mode 100644 index 0000000..0cbe822 --- /dev/null +++ b/DLS2/Enums/Level1ArticulatorEnums.cs @@ -0,0 +1,44 @@ +namespace Kermalis.DLS2 +{ + public enum Level1ArticulatorSource : ushort + { + None = 0x0, + LFO = 0x1, + KeyOnVelocity = 0x2, + KeyNumber = 0x3, + EG1 = 0x4, + EG2 = 0x5, + PitchWheel = 0x6, + Modulation_CC1 = 0x81, + ChannelVolume_CC7 = 0x87, + Pan_CC10 = 0x8A, + Expression_CC11 = 0x8B, + PitchBendRange_RPN0 = 0x100, + FineTune_RPN1 = 0x101, + CoarseTune_RPN2 = 0x102 + } + + public enum Level1ArticulatorDestination : ushort + { + None = 0x0, + Gain = 0x1, + Pitch = 0x3, + Pan = 0x4, + LFOFrequency = 0x104, + LFOStartDelay = 0x105, + EG1AttackTime = 0x206, + EG1DecayTime = 0x207, + EG1ReleaseTime = 0x209, + EG1SustainLevel = 0x20A, + EG2AttackTime = 0x30A, + EG2DecayTime = 0x30B, + EG2ReleaseTime = 0x30D, + EG2SustainLevel = 0x30E + } + + public enum Level1ArticulatorTransform : byte + { + None = 0x0, + Concave = 0x1 + } +} diff --git a/DLS2/Enums/Level2ArticulatorEnums.cs b/DLS2/Enums/Level2ArticulatorEnums.cs new file mode 100644 index 0000000..4437952 --- /dev/null +++ b/DLS2/Enums/Level2ArticulatorEnums.cs @@ -0,0 +1,69 @@ +namespace Kermalis.DLS2 +{ + public enum Level2ArticulatorSource : ushort + { + None = 0x0, + LFO = 0x1, + KeyOnVelocity = 0x2, + KeyNumber = 0x3, + EG1 = 0x4, + EG2 = 0x5, + PitchWheel = 0x6, + PolyPressure = 0x7, + ChannelPressure = 0x8, + Vibrato = 0x9, + Modulation_CC1 = 0x81, + ChannelVolume_CC7 = 0x87, + Pan_CC10 = 0x8A, + Expression_CC11 = 0x8B, + ChorusSend_CC91 = 0xDB, + Reverb_SendCC93 = 0xDD, + PitchBendRange_RPN0 = 0x100, + FineTune_RPN1 = 0x101, + CoarseTune_RPN2 = 0x102 + } + + public enum Level2ArticulatorDestination : ushort + { + None = 0x0, + Gain = 0x1, + Pitch = 0x3, + Pan = 0x4, + KeyNumber = 0x5, + Left = 0x10, + Right = 0x11, + Center = 0x12, + LFEChannel = 0x13, + LeftRear = 0x14, + RightRear = 0x15, + Chorus = 0x80, + Reverb = 0x81, + LFOFrequency = 0x104, + LFOStartDelay = 0x105, + VIBFrequency = 0x114, + VIBStartDelay = 0x115, + EG1AttackTime = 0x206, + EG1DecayTime = 0x207, + EG1ReleaseTime = 0x209, + EG1SustainLevel = 0x20A, + EG1DelayTime = 0x20B, + EG1HoldTime = 0x20C, + EG1ShutdownTime = 0x20D, + EG2AttackTime = 0x30A, + EG2DecayTime = 0x30B, + EG2ReleaseTime = 0x30D, + EG2SustainLevel = 0x30E, + EG2DelayTime = 0x30F, + EG2HoldTime = 0x310, + FilterCutoff = 0x500, + FilterResonance = 0x501 + } + + public enum Level2ArticulatorTransform : byte + { + None = 0x0, + Concave = 0x1, + Convex = 0x2, + Switch = 0x3 + } +} diff --git a/DLS2/Enums/WaveFormat.cs b/DLS2/Enums/WaveFormat.cs new file mode 100644 index 0000000..4cab797 --- /dev/null +++ b/DLS2/Enums/WaveFormat.cs @@ -0,0 +1,15 @@ +namespace Kermalis.DLS2 +{ + public enum WaveFormat : ushort + { + Unknown = 0, + PCM = 1, + MSADPCM = 2, + Float = 3, + ALaw = 6, + MuLaw = 7, + DVIADPCM = 17, + IMAADPCM = 17, + Extensible = 0xFFFE + } +} diff --git a/DLS2/Enums/WaveLinkChannels.cs b/DLS2/Enums/WaveLinkChannels.cs new file mode 100644 index 0000000..678bd25 --- /dev/null +++ b/DLS2/Enums/WaveLinkChannels.cs @@ -0,0 +1,28 @@ +using System; + +namespace Kermalis.DLS2 +{ + [Flags] + public enum WaveLinkChannels : uint + { + None = 0, + Left = 1 << 0, + Right = 1 << 1, + Center = 1 << 2, + LowFrequencyEnergy = 1 << 3, + SurroundLeft = 1 << 4, + SurroundRight = 1 << 5, + LeftOfCenter = 1 << 6, + RightOfCenter = 1 << 7, + SurroundCenter = 1 << 8, + SideLeft = 1 << 9, + SideRight = 1 << 10, + Top = 1 << 11, + TopFrontLeft = 1 << 12, + TopFrontCenter = 1 << 13, + TopFrontRight = 1 << 14, + TopRearLeft = 1 << 15, + TopRearCenter = 1 << 16, + TopRearRight = 1 << 17 + } +} diff --git a/DLS2/Enums/WaveLinkOptions.cs b/DLS2/Enums/WaveLinkOptions.cs new file mode 100644 index 0000000..7f47d8c --- /dev/null +++ b/DLS2/Enums/WaveLinkOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Kermalis.DLS2 +{ + [Flags] + public enum WaveLinkOptions : ushort + { + None = 0, + PhaseMaster = 1 << 0, + MultiChannel = 1 << 1 + } +} diff --git a/DLS2/Enums/WaveSampleLoop.cs b/DLS2/Enums/WaveSampleLoop.cs new file mode 100644 index 0000000..68b6313 --- /dev/null +++ b/DLS2/Enums/WaveSampleLoop.cs @@ -0,0 +1,8 @@ +namespace Kermalis.DLS2 +{ + public enum LoopType : uint + { + Forward = 0, + Release = 1 + } +} diff --git a/DLS2/Enums/WaveSampleOptions.cs b/DLS2/Enums/WaveSampleOptions.cs new file mode 100644 index 0000000..ef87bab --- /dev/null +++ b/DLS2/Enums/WaveSampleOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Kermalis.DLS2 +{ + [Flags] + public enum WaveSampleOptions : uint + { + None = 0, + NoTruncation = 1 << 0, + NoCompression = 1 << 1 + } +} diff --git a/DLS2/Structs/ConnectionBlock.cs b/DLS2/Structs/ConnectionBlock.cs new file mode 100644 index 0000000..d8a9f75 --- /dev/null +++ b/DLS2/Structs/ConnectionBlock.cs @@ -0,0 +1,163 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.DLS2 +{ + public sealed class Level1ArticulatorConnectionBlock + { + public Level1ArticulatorSource Source { get; set; } + public Level1ArticulatorSource Control { get; set; } + public Level1ArticulatorDestination Destination { get; set; } + public Level1ArticulatorTransform Transform { get; set; } + public int Scale { get; set; } + + public Level1ArticulatorConnectionBlock() { } + internal Level1ArticulatorConnectionBlock(EndianBinaryReader reader) + { + Source = reader.ReadEnum(); + Control = reader.ReadEnum(); + Destination = reader.ReadEnum(); + Transform = reader.ReadEnum(); + Scale = reader.ReadInt32(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(Source); + writer.Write(Control); + writer.Write(Destination); + writer.Write(Transform); + writer.Write(Scale); + } + } + + public sealed class Level2ArticulatorConnectionBlock + { + public Level2ArticulatorSource Source { get; set; } + public Level2ArticulatorSource Control { get; set; } + public Level2ArticulatorDestination Destination { get; set; } + public ushort Transform_Raw { get; set; } + public int Scale { get; set; } + + public bool InvertSource + { + get => (Transform_Raw >> 15) != 0; + set + { + if (value) + { + Transform_Raw |= 1 << 15; + } + else + { + Transform_Raw &= unchecked((ushort)~(1 << 15)); + } + } + } + public bool BipolarSource + { + get => ((Transform_Raw >> 14) & 1) != 0; + set + { + if (value) + { + Transform_Raw |= 1 << 14; + } + else + { + Transform_Raw &= unchecked((ushort)~(1 << 14)); + } + } + } + public Level2ArticulatorTransform TransformSource + { + get => (Level2ArticulatorTransform)((Transform_Raw >> 10) & 0xF); + set + { + if (value > (Level2ArticulatorTransform)0xF) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Transform_Raw &= unchecked((ushort)~(0xF << 10)); + Transform_Raw |= (ushort)((ushort)value << 10); + } + } + + public bool InvertDestination + { + get => ((Transform_Raw >> 9) & 1) != 0; + set + { + if (value) + { + Transform_Raw |= 1 << 9; + } + else + { + Transform_Raw &= unchecked((ushort)~(1 << 9)); + } + } + } + public bool BipolarDestination + { + get => ((Transform_Raw >> 8) & 1) != 0; + set + { + if (value) + { + Transform_Raw |= 1 << 8; + } + else + { + Transform_Raw &= unchecked((ushort)~(1 << 8)); + } + } + } + public Level2ArticulatorTransform TransformDestination + { + get => (Level2ArticulatorTransform)((Transform_Raw >> 4) & 0xF); + set + { + if (value > (Level2ArticulatorTransform)0xF) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Transform_Raw &= unchecked((ushort)~(0xF << 4)); + Transform_Raw |= (ushort)((ushort)value << 4); + } + } + + public Level2ArticulatorTransform TransformOutput + { + get => (Level2ArticulatorTransform)(Transform_Raw & 0xF); + set + { + if (value > (Level2ArticulatorTransform)0xF) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Transform_Raw &= unchecked((ushort)~0xF); + Transform_Raw |= (ushort)value; + } + } + + public Level2ArticulatorConnectionBlock() { } + internal Level2ArticulatorConnectionBlock(EndianBinaryReader reader) + { + Source = reader.ReadEnum(); + Control = reader.ReadEnum(); + Destination = reader.ReadEnum(); + Transform_Raw = reader.ReadUInt16(); + Scale = reader.ReadInt32(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(Source); + writer.Write(Control); + writer.Write(Destination); + writer.Write(Transform_Raw); + writer.Write(Scale); + } + } +} diff --git a/DLS2/Structs/DLSID.cs b/DLS2/Structs/DLSID.cs new file mode 100644 index 0000000..d955ef7 --- /dev/null +++ b/DLS2/Structs/DLSID.cs @@ -0,0 +1,122 @@ +using Kermalis.EndianBinaryIO; +using System; +#if !DEBUG +using System.Collections.Generic; +#endif +using System.Linq; + +namespace Kermalis.DLS2 +{ + public sealed class DLSID + { + public uint Data1 { get; set; } + public ushort Data2 { get; set; } + public ushort Data3 { get; set; } + public byte[] Data4 { get; } + + public static DLSID Query_GMInHardware { get; } = new DLSID(0x178F2F24, 0xC364, 0x11D1, new byte[] { 0xA7, 0x60, 0x00, 0x00, 0xF8, 0x75, 0xAC, 0x12 }); + public static DLSID Query_GSInHardware { get; } = new DLSID(0x178F2F25, 0xC364, 0x11D1, new byte[] { 0xA7, 0x60, 0x00, 0x00, 0xF8, 0x75, 0xAC, 0x12 }); + public static DLSID Query_XGInHardware { get; } = new DLSID(0x178F2F26, 0xC364, 0x11D1, new byte[] { 0xA7, 0x60, 0x00, 0x00, 0xF8, 0x75, 0xAC, 0x12 }); + public static DLSID Query_SupportsDLS1 { get; } = new DLSID(0x178F2F27, 0xC364, 0x11D1, new byte[] { 0xA7, 0x60, 0x00, 0x00, 0xF8, 0x75, 0xAC, 0x12 }); + public static DLSID Query_SampleMemorySize { get; } = new DLSID(0x178F2F28, 0xC364, 0x11D1, new byte[] { 0xA7, 0x60, 0x00, 0x00, 0xF8, 0x75, 0xAC, 0x12 }); + public static DLSID Query_SamplePlaybackRate { get; } = new DLSID(0x2A91F713, 0xA4BF, 0x11D2, new byte[] { 0xBB, 0xDF, 0x00, 0x60, 0x08, 0x33, 0xDB, 0xD8 }); + public static DLSID Query_ManufacturersID { get; } = new DLSID(0xB03E1181, 0x8095, 0x11D2, new byte[] { 0xA1, 0xEF, 0x00, 0x60, 0x08, 0x33, 0xDB, 0xD8 }); + public static DLSID Query_ProductID { get; } = new DLSID(0xB03E1182, 0x8095, 0x11D2, new byte[] { 0xA1, 0xEF, 0x00, 0x60, 0x08, 0x33, 0xDB, 0xD8 }); + public static DLSID Query_SupportsDLS2 { get; } = new DLSID(0xF14599E5, 0x4689, 0x11D2, new byte[] { 0xAF, 0xA6, 0x00, 0xAA, 0x00, 0x24, 0xD8, 0xB6 }); + + public DLSID() + { + Data4 = new byte[8]; + } + internal DLSID(EndianBinaryReader reader) + { + Data1 = reader.ReadUInt32(); + Data2 = reader.ReadUInt16(); + Data3 = reader.ReadUInt16(); + Data4 = reader.ReadBytes(8); + } + public DLSID(uint data1, ushort data2, ushort data3, byte[] data4) + { + if (data4 is null) + { + throw new ArgumentNullException(nameof(data4)); + } + if (data4.Length != 8) + { + throw new ArgumentOutOfRangeException(nameof(data4.Length)); + } + Data1 = data1; + Data2 = data2; + Data3 = data3; + Data4 = data4; + } + public DLSID(byte[] data) + { + if (data is null) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Length != 16) + { + throw new ArgumentOutOfRangeException(nameof(data.Length)); + } + Data1 = (uint)EndianBitConverter.BytesToInt32(data, 0, Endianness.LittleEndian); + Data2 = (ushort)EndianBitConverter.BytesToInt16(data, 4, Endianness.LittleEndian); + Data3 = (ushort)EndianBitConverter.BytesToInt16(data, 6, Endianness.LittleEndian); + Data4 = new byte[8]; + for (int i = 0; i < 8; i++) + { + Data4[i] = data[8 + i]; + } + } + + public void Write(EndianBinaryWriter writer) + { + writer.Write(Data1); + writer.Write(Data2); + writer.Write(Data3); + writer.Write(Data4); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(obj, this)) + { + return true; + } + if (obj is DLSID id) + { + return id.Data1 == Data1 && id.Data2 == Data2 && id.Data3 == Data3 && id.Data4.SequenceEqual(Data4); + } + return false; + } + public override int GetHashCode() + { + // .NET Standard does not have this method +#if DEBUG + return HashCode.Combine(Data1, Data2, Data3, Data4); +#else + int hashCode = -0x8CAC62A; + hashCode = hashCode * -0x5AAAAAD7 + Data1.GetHashCode(); + hashCode = hashCode * -0x5AAAAAD7 + Data2.GetHashCode(); + hashCode = hashCode * -0x5AAAAAD7 + Data3.GetHashCode(); + hashCode = hashCode * -0x5AAAAAD7 + EqualityComparer.Default.GetHashCode(Data4); + return hashCode; +#endif + } + public override string ToString() + { + string str = Data1.ToString("X8") + '-' + Data2.ToString("X4") + '-' + Data3.ToString("X4") + '-'; + for (int i = 0; i < 2; i++) + { + str += Data4[i].ToString("X2"); + } + str += '-'; + for (int i = 2; i < 8; i++) + { + str += Data4[i].ToString("X2"); + } + return str; + } + } +} diff --git a/DLS2/Structs/MIDILocale.cs b/DLS2/Structs/MIDILocale.cs new file mode 100644 index 0000000..49cd325 --- /dev/null +++ b/DLS2/Structs/MIDILocale.cs @@ -0,0 +1,87 @@ +using Kermalis.EndianBinaryIO; +using System; + +namespace Kermalis.DLS2 +{ + // MIDILOCALE - Page 45 of spec + public sealed class MIDILocale + { + public uint Bank_Raw { get; set; } + public uint Instrument_Raw { get; set; } + + public byte CC32 + { + get => (byte)(Bank_Raw & 0x7F); + set + { + if (value > 0x7F) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Bank_Raw &= unchecked((uint)~0x7F); + Bank_Raw |= value; + } + } + public byte CC0 + { + get => (byte)((Bank_Raw >> 7) & 0x7F); + set + { + if (value > 0x7F) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Bank_Raw &= unchecked((uint)~(0x7F << 7)); + Bank_Raw |= (uint)(value << 7); + } + } + public bool IsDrum + { + get => (Bank_Raw >> 31) != 0; + set + { + if (value) + { + Bank_Raw |= 1u << 31; + } + else + { + Bank_Raw &= ~(1 << 31); + } + } + } + public byte Instrument + { + get => (byte)(Instrument_Raw & 0x7F); + set + { + if (value > 0x7F) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + Instrument_Raw &= unchecked((uint)~0x7F); + Instrument_Raw |= value; + } + } + + public MIDILocale() { } + public MIDILocale(byte cc32, byte cc0, bool isDrum, byte instrument) + { + CC32 = cc32; + CC0 = cc0; + IsDrum = isDrum; + Instrument = instrument; + } + internal MIDILocale(EndianBinaryReader reader) + { + Bank_Raw = reader.ReadUInt32(); + Instrument_Raw = reader.ReadUInt32(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(Bank_Raw); + writer.Write(Instrument_Raw); + } + } +} diff --git a/DLS2/Structs/Range.cs b/DLS2/Structs/Range.cs new file mode 100644 index 0000000..7248bf8 --- /dev/null +++ b/DLS2/Structs/Range.cs @@ -0,0 +1,28 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + public sealed class Range + { + public ushort Low { get; set; } + public ushort High { get; set; } + + public Range() { } + public Range(ushort low, ushort high) + { + Low = low; + High = high; + } + internal Range(EndianBinaryReader reader) + { + Low = reader.ReadUInt16(); + High = reader.ReadUInt16(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(Low); + writer.Write(High); + } + } +} diff --git a/DLS2/Structs/WaveInfo.cs b/DLS2/Structs/WaveInfo.cs new file mode 100644 index 0000000..2f1cb25 --- /dev/null +++ b/DLS2/Structs/WaveInfo.cs @@ -0,0 +1,32 @@ +using Kermalis.EndianBinaryIO; + +namespace Kermalis.DLS2 +{ + public sealed class WaveInfo + { + public WaveFormat FormatTag { get; set; } + public ushort Channels { get; set; } + public uint SamplesPerSec { get; set; } + public uint AvgBytesPerSec { get; set; } + public ushort BlockAlign { get; set; } + + internal WaveInfo() { } + internal WaveInfo(EndianBinaryReader reader) + { + FormatTag = reader.ReadEnum(); + Channels = reader.ReadUInt16(); + SamplesPerSec = reader.ReadUInt32(); + AvgBytesPerSec = reader.ReadUInt32(); + BlockAlign = reader.ReadUInt16(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(FormatTag); + writer.Write(Channels); + writer.Write(SamplesPerSec); + writer.Write(AvgBytesPerSec); + writer.Write(BlockAlign); + } + } +} diff --git a/DLS2/Structs/WaveSampleLoop.cs b/DLS2/Structs/WaveSampleLoop.cs new file mode 100644 index 0000000..8e98a54 --- /dev/null +++ b/DLS2/Structs/WaveSampleLoop.cs @@ -0,0 +1,33 @@ +using Kermalis.EndianBinaryIO; +using System.IO; + +namespace Kermalis.DLS2 +{ + public sealed class WaveSampleLoop + { + public LoopType LoopType { get; set; } + public uint LoopStart { get; set; } + public uint LoopLength { get; set; } + + public WaveSampleLoop() { } + internal WaveSampleLoop(EndianBinaryReader reader) + { + uint byteSize = reader.ReadUInt32(); + if (byteSize != 16) + { + throw new InvalidDataException(); + } + LoopType = reader.ReadEnum(); + LoopStart = reader.ReadUInt32(); + LoopLength = reader.ReadUInt32(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(16u); + writer.Write(LoopType); + writer.Write(LoopStart); + writer.Write(LoopLength); + } + } +} diff --git a/EndianBinaryIO/Attributes.cs b/EndianBinaryIO/Attributes.cs new file mode 100644 index 0000000..8e3e98f --- /dev/null +++ b/EndianBinaryIO/Attributes.cs @@ -0,0 +1,117 @@ +using System; +using System.Text; + +namespace Kermalis.EndianBinaryIO +{ + public interface IBinaryAttribute + { + T Value { get; } + } + + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryIgnoreAttribute : Attribute, IBinaryAttribute + { + public bool Value { get; } + + public BinaryIgnoreAttribute(bool ignore = true) + { + Value = ignore; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryBooleanSizeAttribute : Attribute, IBinaryAttribute + { + public BooleanSize Value { get; } + + public BinaryBooleanSizeAttribute(BooleanSize booleanSize) + { + if (booleanSize >= BooleanSize.MAX) + { + throw new ArgumentOutOfRangeException($"{nameof(BinaryBooleanSizeAttribute)} cannot be created with a size of {booleanSize}."); + } + Value = booleanSize; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryEncodingAttribute : Attribute, IBinaryAttribute + { + public Encoding Value { get; } + + public BinaryEncodingAttribute(string encodingName) + { + Value = Encoding.GetEncoding(encodingName); + } + public BinaryEncodingAttribute(int encodingCodepage) + { + Value = Encoding.GetEncoding(encodingCodepage); + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryStringNullTerminatedAttribute : Attribute, IBinaryAttribute + { + public bool Value { get; } + + public BinaryStringNullTerminatedAttribute(bool nullTerminated = true) + { + Value = nullTerminated; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryArrayFixedLengthAttribute : Attribute, IBinaryAttribute + { + public int Value { get; } + + public BinaryArrayFixedLengthAttribute(int length) + { + if (length < 0) + { + throw new ArgumentOutOfRangeException($"{nameof(BinaryArrayFixedLengthAttribute)} cannot be created with a length of {length}. Length must be 0 or greater."); + } + Value = length; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryArrayVariableLengthAttribute : Attribute, IBinaryAttribute + { + public string Value { get; } + + public BinaryArrayVariableLengthAttribute(string anchor) + { + Value = anchor; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryStringFixedLengthAttribute : Attribute, IBinaryAttribute + { + public int Value { get; } + + public BinaryStringFixedLengthAttribute(int length) + { + if (length <= 0) + { + throw new ArgumentOutOfRangeException($"{nameof(BinaryStringFixedLengthAttribute)} cannot be created with a length of {length}. Length must be 0 or greater."); + } + Value = length; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryStringVariableLengthAttribute : Attribute, IBinaryAttribute + { + public string Value { get; } + + public BinaryStringVariableLengthAttribute(string anchor) + { + Value = anchor; + } + } + [AttributeUsage(AttributeTargets.Property)] + public sealed class BinaryStringTrimNullTerminatorsAttribute : Attribute, IBinaryAttribute + { + public bool Value { get; } + + public BinaryStringTrimNullTerminatorsAttribute(bool trim = true) + { + Value = trim; + } + } +} diff --git a/EndianBinaryIO/EndianBinaryIO.csproj b/EndianBinaryIO/EndianBinaryIO.csproj new file mode 100644 index 0000000..2aa1ec8 --- /dev/null +++ b/EndianBinaryIO/EndianBinaryIO.csproj @@ -0,0 +1,39 @@ + + + + netcoreapp3.1 + Library + Kermalis.EndianBinaryIO + Kermalis + Kermalis + EndianBinaryIO + EndianBinaryIO + EndianBinaryIO + 1.1.2.0 + https://github.com/Kermalis/EndianBinaryIO + git + + true + + A .NET Core library compatible with any newer .NET SDK versions. This library can read and write primitives, enums, arrays, and strings to streams and byte arrays using specified endianness, string encoding, and boolean sizes. +Objects can also be read from/written to streams via reflection and attributes. +Project URL ― https://github.com/Kermalis/EndianBinaryIO + https://github.com/Kermalis/EndianBinaryIO + en-001 + Serialization;Reflection;Endianness;LittleEndian;BigEndian;EndianBinaryIO + + + + Auto + none + false + + + + false + DEBUG;TRACE + full + true + + + diff --git a/EndianBinaryIO/EndianBinaryReader.cs b/EndianBinaryIO/EndianBinaryReader.cs new file mode 100644 index 0000000..de2ec62 --- /dev/null +++ b/EndianBinaryIO/EndianBinaryReader.cs @@ -0,0 +1,893 @@ +using System; +using System.IO; +using System.Reflection; +using System.Text; + +namespace Kermalis.EndianBinaryIO +{ + public class EndianBinaryReader + { + public Stream BaseStream { get; } + private Endianness _endianness; + public Endianness Endianness + { + get => _endianness; + set + { + if (value >= Endianness.MAX) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + _endianness = value; + } + } + private BooleanSize _booleanSize; + public BooleanSize BooleanSize + { + get => _booleanSize; + set + { + if (value >= BooleanSize.MAX) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + _booleanSize = value; + } + } + public Encoding Encoding { get; set; } + + private byte[] _buffer; + + public EndianBinaryReader(Stream baseStream, Endianness endianness = Endianness.LittleEndian, BooleanSize booleanSize = BooleanSize.U8) + { + if (baseStream is null) + { + throw new ArgumentNullException(nameof(baseStream)); + } + if (!baseStream.CanRead) + { + throw new ArgumentException(nameof(baseStream)); + } + BaseStream = baseStream; + Endianness = endianness; + BooleanSize = booleanSize; + Encoding = Encoding.ASCII; + } + public EndianBinaryReader(Stream baseStream, Encoding encoding, Endianness endianness = Endianness.LittleEndian, BooleanSize booleanSize = BooleanSize.U8) + { + if (baseStream is null) + { + throw new ArgumentNullException(nameof(baseStream)); + } + if (!baseStream.CanRead) + { + throw new ArgumentException(nameof(baseStream)); + } + BaseStream = baseStream; + Endianness = endianness; + BooleanSize = booleanSize; + Encoding = encoding; + } + + private void ReadBytesIntoBuffer(int byteCount) + { + if (_buffer is null || _buffer.Length < byteCount) + { + _buffer = new byte[byteCount]; + } + if (BaseStream.Read(_buffer, 0, byteCount) != byteCount) + { + throw new EndOfStreamException(); + } + } + private char[] DecodeChars(Encoding encoding, int charCount) + { + Utils.ThrowIfCannotUseEncoding(encoding); + int maxBytes = encoding.GetMaxByteCount(charCount); + byte[] buffer = new byte[maxBytes]; + int amtRead = BaseStream.Read(buffer, 0, maxBytes); // Do not throw EndOfStreamException if there aren't enough bytes at the end of the stream + if (amtRead == 0) + { + throw new EndOfStreamException(); + } + // If the maxBytes would be 4, and the string only takes 2, we'd not have enough bytes, but if it's a proper string it doesn't matter + char[] chars = encoding.GetChars(buffer); + if (chars.Length < charCount) + { + throw new InvalidDataException(); // Too few chars means the decoding went wrong + } + // If we read too many chars, we need to shrink the array + // For example, if we want 1 char and the max bytes is 2, but we manage to read 2 1-byte chars, we'd want to shrink back to 1 char + Array.Resize(ref chars, charCount); + int actualBytes = encoding.GetByteCount(chars); + if (amtRead != actualBytes) + { + BaseStream.Position -= amtRead - actualBytes; // Set the stream back to compensate for the extra bytes we read + } + return chars; + } + + public byte PeekByte() + { + long pos = BaseStream.Position; + byte b = ReadByte(); + BaseStream.Position = pos; + return b; + } + public byte PeekByte(long offset) + { + BaseStream.Position = offset; + return PeekByte(); + } + public byte[] PeekBytes(int count) + { + long pos = BaseStream.Position; + byte[] b = ReadBytes(count); + BaseStream.Position = pos; + return b; + } + public byte[] PeekBytes(int count, long offset) + { + BaseStream.Position = offset; + return PeekBytes(count); + } + public char PeekChar() + { + long pos = BaseStream.Position; + char c = ReadChar(); + BaseStream.Position = pos; + return c; + } + public char PeekChar(long offset) + { + BaseStream.Position = offset; + return PeekChar(); + } + public char PeekChar(Encoding encoding) + { + long pos = BaseStream.Position; + char c = ReadChar(encoding); + BaseStream.Position = pos; + return c; + } + public char PeekChar(Encoding encoding, long offset) + { + BaseStream.Position = offset; + return PeekChar(encoding); + } + + public bool ReadBoolean() + { + return ReadBoolean(BooleanSize); + } + public bool ReadBoolean(long offset) + { + BaseStream.Position = offset; + return ReadBoolean(BooleanSize); + } + public bool ReadBoolean(BooleanSize booleanSize) + { + switch (booleanSize) + { + case BooleanSize.U8: + { + ReadBytesIntoBuffer(1); + return _buffer[0] != 0; + } + case BooleanSize.U16: + { + ReadBytesIntoBuffer(2); + return EndianBitConverter.BytesToInt16(_buffer, 0, Endianness) != 0; + } + case BooleanSize.U32: + { + ReadBytesIntoBuffer(4); + return EndianBitConverter.BytesToInt32(_buffer, 0, Endianness) != 0; + } + default: throw new ArgumentOutOfRangeException(nameof(booleanSize)); + } + } + public bool ReadBoolean(BooleanSize booleanSize, long offset) + { + BaseStream.Position = offset; + return ReadBoolean(booleanSize); + } + public bool[] ReadBooleans(int count) + { + return ReadBooleans(count, BooleanSize); + } + public bool[] ReadBooleans(int count, long offset) + { + BaseStream.Position = offset; + return ReadBooleans(count, BooleanSize); + } + public bool[] ReadBooleans(int count, BooleanSize size) + { + if (!Utils.ValidateReadArraySize(count, out bool[] array)) + { + array = new bool[count]; + for (int i = 0; i < count; i++) + { + array[i] = ReadBoolean(size); + } + } + return array; + } + public bool[] ReadBooleans(int count, BooleanSize size, long offset) + { + BaseStream.Position = offset; + return ReadBooleans(count, size); + } + public byte ReadByte() + { + ReadBytesIntoBuffer(1); + return _buffer[0]; + } + public byte ReadByte(long offset) + { + BaseStream.Position = offset; + return ReadByte(); + } + public byte[] ReadBytes(int count) + { + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + ReadBytesIntoBuffer(count); + array = new byte[count]; + for (int i = 0; i < count; i++) + { + array[i] = _buffer[i]; + } + } + return array; + } + public byte[] ReadBytes(int count, long offset) + { + BaseStream.Position = offset; + return ReadBytes(count); + } + public sbyte ReadSByte() + { + ReadBytesIntoBuffer(1); + return (sbyte)_buffer[0]; + } + public sbyte ReadSByte(long offset) + { + BaseStream.Position = offset; + return ReadSByte(); + } + public sbyte[] ReadSBytes(int count) + { + if (!Utils.ValidateReadArraySize(count, out sbyte[] array)) + { + ReadBytesIntoBuffer(count); + array = new sbyte[count]; + for (int i = 0; i < count; i++) + { + array[i] = (sbyte)_buffer[i]; + } + } + return array; + } + public sbyte[] ReadSBytes(int count, long offset) + { + BaseStream.Position = offset; + return ReadSBytes(count); + } + public char ReadChar() + { + return ReadChar(Encoding); + } + public char ReadChar(long offset) + { + BaseStream.Position = offset; + return ReadChar(); + } + public char ReadChar(Encoding encoding) + { + return DecodeChars(encoding, 1)[0]; + } + public char ReadChar(Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadChar(encoding); + } + public char[] ReadChars(int count, bool trimNullTerminators) + { + return ReadChars(count, trimNullTerminators, Encoding); + } + public char[] ReadChars(int count, bool trimNullTerminators, long offset) + { + BaseStream.Position = offset; + return ReadChars(count, trimNullTerminators); + } + public char[] ReadChars(int count, bool trimNullTerminators, Encoding encoding) + { + if (Utils.ValidateReadArraySize(count, out char[] array)) + { + return array; + } + array = DecodeChars(encoding, count); + if (trimNullTerminators) + { + int i = Array.IndexOf(array, '\0'); + if (i != -1) + { + Array.Resize(ref array, i); + } + } + return array; + } + public char[] ReadChars(int count, bool trimNullTerminators, Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadChars(count, trimNullTerminators, encoding); + } + public string ReadStringNullTerminated() + { + return ReadStringNullTerminated(Encoding); + } + public string ReadStringNullTerminated(long offset) + { + BaseStream.Position = offset; + return ReadStringNullTerminated(); + } + public string ReadStringNullTerminated(Encoding encoding) + { + string text = string.Empty; + while (true) + { + char c = ReadChar(encoding); + if (c == '\0') + { + break; + } + text += c; + } + return text; + } + public string ReadStringNullTerminated(Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadStringNullTerminated(encoding); + } + public string ReadString(int charCount, bool trimNullTerminators) + { + return ReadString(charCount, trimNullTerminators, Encoding); + } + public string ReadString(int charCount, bool trimNullTerminators, long offset) + { + BaseStream.Position = offset; + return ReadString(charCount, trimNullTerminators); + } + public string ReadString(int charCount, bool trimNullTerminators, Encoding encoding) + { + return new string(ReadChars(charCount, trimNullTerminators, encoding)); + } + public string ReadString(int charCount, bool trimNullTerminators, Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadString(charCount, trimNullTerminators, encoding); + } + public string[] ReadStringsNullTerminated(int count) + { + return ReadStringsNullTerminated(count, Encoding); + } + public string[] ReadStringsNullTerminated(int count, long offset) + { + BaseStream.Position = offset; + return ReadStringsNullTerminated(count); + } + public string[] ReadStringsNullTerminated(int count, Encoding encoding) + { + if (!Utils.ValidateReadArraySize(count, out string[] array)) + { + array = new string[count]; + for (int i = 0; i < count; i++) + { + array[i] = ReadStringNullTerminated(encoding); + } + } + return array; + } + public string[] ReadStringsNullTerminated(int count, Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadStringsNullTerminated(count, encoding); + } + public string[] ReadStrings(int count, int charCount, bool trimNullTerminators) + { + return ReadStrings(count, charCount, trimNullTerminators, Encoding); + } + public string[] ReadStrings(int count, int charCount, bool trimNullTerminators, long offset) + { + BaseStream.Position = offset; + return ReadStrings(count, charCount, trimNullTerminators); + } + public string[] ReadStrings(int count, int charCount, bool trimNullTerminators, Encoding encoding) + { + if (!Utils.ValidateReadArraySize(count, out string[] array)) + { + array = new string[count]; + for (int i = 0; i < count; i++) + { + array[i] = ReadString(charCount, trimNullTerminators, encoding); + } + } + return array; + } + public string[] ReadStrings(int count, int charCount, bool trimNullTerminators, Encoding encoding, long offset) + { + BaseStream.Position = offset; + return ReadStrings(count, charCount, trimNullTerminators, encoding); + } + public short ReadInt16() + { + ReadBytesIntoBuffer(2); + return EndianBitConverter.BytesToInt16(_buffer, 0, Endianness); + } + public short ReadInt16(long offset) + { + BaseStream.Position = offset; + return ReadInt16(); + } + public short[] ReadInt16s(int count) + { + ReadBytesIntoBuffer(count * 2); + return EndianBitConverter.BytesToInt16s(_buffer, 0, count, Endianness); + } + public short[] ReadInt16s(int count, long offset) + { + BaseStream.Position = offset; + return ReadInt16s(count); + } + public ushort ReadUInt16() + { + ReadBytesIntoBuffer(2); + return (ushort)EndianBitConverter.BytesToInt16(_buffer, 0, Endianness); + } + public ushort ReadUInt16(long offset) + { + BaseStream.Position = offset; + return ReadUInt16(); + } + public ushort[] ReadUInt16s(int count) + { + ReadBytesIntoBuffer(count * 2); + return EndianBitConverter.BytesToUInt16s(_buffer, 0, count, Endianness); + } + public ushort[] ReadUInt16s(int count, long offset) + { + BaseStream.Position = offset; + return ReadUInt16s(count); + } + public int ReadInt32() + { + ReadBytesIntoBuffer(4); + return EndianBitConverter.BytesToInt32(_buffer, 0, Endianness); + } + public int ReadInt32(long offset) + { + BaseStream.Position = offset; + return ReadInt32(); + } + public int[] ReadInt32s(int count) + { + ReadBytesIntoBuffer(count * 4); + return EndianBitConverter.BytesToInt32s(_buffer, 0, count, Endianness); + } + public int[] ReadInt32s(int count, long offset) + { + BaseStream.Position = offset; + return ReadInt32s(count); + } + public uint ReadUInt32() + { + ReadBytesIntoBuffer(4); + return (uint)EndianBitConverter.BytesToInt32(_buffer, 0, Endianness); + } + public uint ReadUInt32(long offset) + { + BaseStream.Position = offset; + return ReadUInt32(); + } + public uint[] ReadUInt32s(int count) + { + ReadBytesIntoBuffer(count * 4); + return EndianBitConverter.BytesToUInt32s(_buffer, 0, count, Endianness); + } + public uint[] ReadUInt32s(int count, long offset) + { + BaseStream.Position = offset; + return ReadUInt32s(count); + } + public long ReadInt64() + { + ReadBytesIntoBuffer(8); + return EndianBitConverter.BytesToInt64(_buffer, 0, Endianness); + } + public long ReadInt64(long offset) + { + BaseStream.Position = offset; + return ReadInt64(); + } + public long[] ReadInt64s(int count) + { + ReadBytesIntoBuffer(count * 8); + return EndianBitConverter.BytesToInt64s(_buffer, 0, count, Endianness); + } + public long[] ReadInt64s(int count, long offset) + { + BaseStream.Position = offset; + return ReadInt64s(count); + } + public ulong ReadUInt64() + { + ReadBytesIntoBuffer(8); + return (ulong)EndianBitConverter.BytesToInt64(_buffer, 0, Endianness); + } + public ulong ReadUInt64(long offset) + { + BaseStream.Position = offset; + return ReadUInt64(); + } + public ulong[] ReadUInt64s(int count) + { + ReadBytesIntoBuffer(count * 8); + return EndianBitConverter.BytesToUInt64s(_buffer, 0, count, Endianness); + } + public ulong[] ReadUInt64s(int count, long offset) + { + BaseStream.Position = offset; + return ReadUInt64s(count); + } + public float ReadSingle() + { + ReadBytesIntoBuffer(4); + return EndianBitConverter.BytesToSingle(_buffer, 0, Endianness); + } + public float ReadSingle(long offset) + { + BaseStream.Position = offset; + return ReadSingle(); + } + public float[] ReadSingles(int count) + { + ReadBytesIntoBuffer(count * 4); + return EndianBitConverter.BytesToSingles(_buffer, 0, count, Endianness); + } + public float[] ReadSingles(int count, long offset) + { + BaseStream.Position = offset; + return ReadSingles(count); + } + public double ReadDouble() + { + ReadBytesIntoBuffer(8); + return EndianBitConverter.BytesToDouble(_buffer, 0, Endianness); + } + public double ReadDouble(long offset) + { + BaseStream.Position = offset; + return ReadDouble(); + } + public double[] ReadDoubles(int count) + { + ReadBytesIntoBuffer(count * 8); + return EndianBitConverter.BytesToDoubles(_buffer, 0, count, Endianness); + } + public double[] ReadDoubles(int count, long offset) + { + BaseStream.Position = offset; + return ReadDoubles(count); + } + public decimal ReadDecimal() + { + ReadBytesIntoBuffer(16); + return EndianBitConverter.BytesToDecimal(_buffer, 0, Endianness); + } + public decimal ReadDecimal(long offset) + { + BaseStream.Position = offset; + return ReadDecimal(); + } + public decimal[] ReadDecimals(int count) + { + ReadBytesIntoBuffer(count * 16); + return EndianBitConverter.BytesToDecimals(_buffer, 0, count, Endianness); + } + public decimal[] ReadDecimals(int count, long offset) + { + BaseStream.Position = offset; + return ReadDecimals(count); + } + + // Do not allow writing abstract "Enum" because there is no way to know which underlying type to read + // Yes "struct" restriction on reads + public TEnum ReadEnum() where TEnum : struct, Enum + { + Type enumType = typeof(TEnum); + Type underlyingType = Enum.GetUnderlyingType(enumType); + object value; + switch (Type.GetTypeCode(underlyingType)) + { + case TypeCode.Byte: value = ReadByte(); break; + case TypeCode.SByte: value = ReadSByte(); break; + case TypeCode.Int16: value = ReadInt16(); break; + case TypeCode.UInt16: value = ReadUInt16(); break; + case TypeCode.Int32: value = ReadInt32(); break; + case TypeCode.UInt32: value = ReadUInt32(); break; + case TypeCode.Int64: value = ReadInt64(); break; + case TypeCode.UInt64: value = ReadUInt64(); break; + default: throw new ArgumentOutOfRangeException(nameof(underlyingType)); + } + return (TEnum)Enum.ToObject(enumType, value); + } + public TEnum ReadEnum(long offset) where TEnum : struct, Enum + { + BaseStream.Position = offset; + return ReadEnum(); + } + public TEnum[] ReadEnums(int count) where TEnum : struct, Enum + { + if (!Utils.ValidateReadArraySize(count, out TEnum[] array)) + { + array = new TEnum[count]; + for (int i = 0; i < count; i++) + { + array[i] = ReadEnum(); + } + } + return array; + } + public TEnum[] ReadEnums(int count, long offset) where TEnum : struct, Enum + { + BaseStream.Position = offset; + return ReadEnums(count); + } + + public DateTime ReadDateTime() + { + return DateTime.FromBinary(ReadInt64()); + } + public DateTime ReadDateTime(long offset) + { + BaseStream.Position = offset; + return ReadDateTime(); + } + public DateTime[] ReadDateTimes(int count) + { + if (!Utils.ValidateReadArraySize(count, out DateTime[] array)) + { + array = new DateTime[count]; + for (int i = 0; i < count; i++) + { + array[i] = ReadDateTime(); + } + } + return array; + } + public DateTime[] ReadDateTimes(int count, long offset) + { + BaseStream.Position = offset; + return ReadDateTimes(count); + } + + public T ReadObject() where T : new() + { + return (T)ReadObject(typeof(T)); + } + public object ReadObject(Type objType) + { + Utils.ThrowIfCannotReadWriteType(objType); + object obj = Activator.CreateInstance(objType); + ReadIntoObject(obj); + return obj; + } + public T ReadObject(long offset) where T : new() + { + BaseStream.Position = offset; + return ReadObject(); + } + public object ReadObject(Type objType, long offset) + { + BaseStream.Position = offset; + return ReadObject(objType); + } + public void ReadIntoObject(IBinarySerializable obj) + { + if (obj is null) + { + throw new ArgumentNullException(nameof(obj)); + } + obj.Read(this); + } + public void ReadIntoObject(IBinarySerializable obj, long offset) + { + BaseStream.Position = offset; + ReadIntoObject(obj); + } + public void ReadIntoObject(object obj) + { + if (obj is null) + { + throw new ArgumentNullException(nameof(obj)); + } + if (obj is IBinarySerializable bs) + { + bs.Read(this); + return; + } + + Type objType = obj.GetType(); + Utils.ThrowIfCannotReadWriteType(objType); + + // Get public non-static properties + foreach (PropertyInfo propertyInfo in objType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + if (Utils.AttributeValueOrDefault(propertyInfo, false)) + { + continue; // Skip properties with BinaryIgnoreAttribute + } + + Type propertyType = propertyInfo.PropertyType; + object value; + + if (propertyType.IsArray) + { + int arrayLength = Utils.GetArrayLength(obj, objType, propertyInfo); + // Get array type + Type elementType = propertyType.GetElementType(); + if (arrayLength == 0) + { + value = Array.CreateInstance(elementType, 0); // Create 0 length array regardless of type + } + else + { + if (elementType.IsEnum) + { + elementType = Enum.GetUnderlyingType(elementType); + } + switch (Type.GetTypeCode(elementType)) + { + case TypeCode.Boolean: + { + BooleanSize booleanSize = Utils.AttributeValueOrDefault(propertyInfo, BooleanSize); + value = ReadBooleans(arrayLength, booleanSize); + break; + } + case TypeCode.Byte: value = ReadBytes(arrayLength); break; + case TypeCode.SByte: value = ReadSBytes(arrayLength); break; + case TypeCode.Char: + { + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + bool trimNullTerminators = Utils.AttributeValueOrDefault(propertyInfo, false); + value = ReadChars(arrayLength, trimNullTerminators, encoding); + break; + } + case TypeCode.Int16: value = ReadInt16s(arrayLength); break; + case TypeCode.UInt16: value = ReadUInt16s(arrayLength); break; + case TypeCode.Int32: value = ReadInt32s(arrayLength); break; + case TypeCode.UInt32: value = ReadUInt32s(arrayLength); break; + case TypeCode.Int64: value = ReadInt64s(arrayLength); break; + case TypeCode.UInt64: value = ReadUInt64s(arrayLength); break; + case TypeCode.Single: value = ReadSingles(arrayLength); break; + case TypeCode.Double: value = ReadDoubles(arrayLength); break; + case TypeCode.Decimal: value = ReadDecimals(arrayLength); break; + case TypeCode.DateTime: value = ReadDateTimes(arrayLength); break; + case TypeCode.String: + { + Utils.GetStringLength(obj, objType, propertyInfo, true, out bool? nullTerminated, out int stringLength); + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + if (nullTerminated == true) + { + value = ReadStringsNullTerminated(arrayLength, encoding); + } + else + { + bool trimNullTerminators = Utils.AttributeValueOrDefault(propertyInfo, false); + value = ReadStrings(arrayLength, stringLength, trimNullTerminators, encoding); + } + break; + } + case TypeCode.Object: + { + value = Array.CreateInstance(elementType, arrayLength); + if (typeof(IBinarySerializable).IsAssignableFrom(elementType)) + { + for (int i = 0; i < arrayLength; i++) + { + var serializable = (IBinarySerializable)Activator.CreateInstance(elementType); + serializable.Read(this); + ((Array)value).SetValue(serializable, i); + } + } + else // Element's type is not supported so try to read the array's objects + { + for (int i = 0; i < arrayLength; i++) + { + object elementObj = ReadObject(elementType); + ((Array)value).SetValue(elementObj, i); + } + } + break; + } + default: throw new ArgumentOutOfRangeException(nameof(elementType)); + } + } + } + else + { + if (propertyType.IsEnum) + { + propertyType = Enum.GetUnderlyingType(propertyType); + } + switch (Type.GetTypeCode(propertyType)) + { + case TypeCode.Boolean: + { + BooleanSize booleanSize = Utils.AttributeValueOrDefault(propertyInfo, BooleanSize); + value = ReadBoolean(booleanSize); + break; + } + case TypeCode.Byte: value = ReadByte(); break; + case TypeCode.SByte: value = ReadSByte(); break; + case TypeCode.Char: + { + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + value = ReadChar(encoding); + break; + } + case TypeCode.Int16: value = ReadInt16(); break; + case TypeCode.UInt16: value = ReadUInt16(); break; + case TypeCode.Int32: value = ReadInt32(); break; + case TypeCode.UInt32: value = ReadUInt32(); break; + case TypeCode.Int64: value = ReadInt64(); break; + case TypeCode.UInt64: value = ReadUInt64(); break; + case TypeCode.Single: value = ReadSingle(); break; + case TypeCode.Double: value = ReadDouble(); break; + case TypeCode.Decimal: value = ReadDecimal(); break; + case TypeCode.DateTime: value = ReadDateTime(); break; + case TypeCode.String: + { + Utils.GetStringLength(obj, objType, propertyInfo, true, out bool? nullTerminated, out int stringLength); + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + if (nullTerminated == true) + { + value = ReadStringNullTerminated(encoding); + } + else + { + bool trimNullTerminators = Utils.AttributeValueOrDefault(propertyInfo, false); + value = ReadString(stringLength, trimNullTerminators, encoding); + } + break; + } + case TypeCode.Object: + { + if (typeof(IBinarySerializable).IsAssignableFrom(propertyType)) + { + value = Activator.CreateInstance(propertyType); + ((IBinarySerializable)value).Read(this); + } + else // The property's type is not supported so try to read the object + { + value = ReadObject(propertyType); + } + break; + } + default: throw new ArgumentOutOfRangeException(nameof(propertyType)); + } + } + + // Set the value into the property + propertyInfo.SetValue(obj, value); + } + } + public void ReadIntoObject(object obj, long offset) + { + BaseStream.Position = offset; + ReadIntoObject(obj); + } + } +} diff --git a/EndianBinaryIO/EndianBinaryWriter.cs b/EndianBinaryIO/EndianBinaryWriter.cs new file mode 100644 index 0000000..7800f28 --- /dev/null +++ b/EndianBinaryIO/EndianBinaryWriter.cs @@ -0,0 +1,926 @@ +using System; +using System.IO; +using System.Reflection; +using System.Text; + +namespace Kermalis.EndianBinaryIO +{ + public class EndianBinaryWriter + { + public Stream BaseStream { get; } + private Endianness _endianness; + public Endianness Endianness + { + get => _endianness; + set + { + if (value >= Endianness.MAX) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + _endianness = value; + } + } + private BooleanSize _booleanSize; + public BooleanSize BooleanSize + { + get => _booleanSize; + set + { + if (value >= BooleanSize.MAX) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + _booleanSize = value; + } + } + public Encoding Encoding { get; set; } + + private byte[] _buffer; + + public EndianBinaryWriter(Stream baseStream, Endianness endianness = Endianness.LittleEndian, BooleanSize booleanSize = BooleanSize.U8) + { + if (baseStream is null) + { + throw new ArgumentNullException(nameof(baseStream)); + } + if (!baseStream.CanWrite) + { + throw new ArgumentException(nameof(baseStream)); + } + BaseStream = baseStream; + Endianness = endianness; + BooleanSize = booleanSize; + Encoding = Encoding.Default; + } + public EndianBinaryWriter(Stream baseStream, Encoding encoding, Endianness endianness = Endianness.LittleEndian, BooleanSize booleanSize = BooleanSize.U8) + { + if (baseStream is null) + { + throw new ArgumentNullException(nameof(baseStream)); + } + if (!baseStream.CanWrite) + { + throw new ArgumentException(nameof(baseStream)); + } + BaseStream = baseStream; + Endianness = endianness; + BooleanSize = booleanSize; + Encoding = encoding; + } + + private void SetBufferSize(int size) + { + if (_buffer is null || _buffer.Length < size) + { + _buffer = new byte[size]; + } + } + private void WriteBytesFromBuffer(int byteCount) + { + BaseStream.Write(_buffer, 0, byteCount); + } + + public void Write(bool value) + { + Write(value, BooleanSize); + } + public void Write(bool value, long offset) + { + BaseStream.Position = offset; + Write(value, BooleanSize); + } + public void Write(bool value, BooleanSize booleanSize) + { + switch (booleanSize) + { + case BooleanSize.U8: + { + SetBufferSize(1); + _buffer[0] = value ? (byte)1 : (byte)0; + WriteBytesFromBuffer(1); + break; + } + case BooleanSize.U16: + { + _buffer = EndianBitConverter.Int16ToBytes(value ? (short)1 : (short)0, Endianness); + WriteBytesFromBuffer(2); + break; + } + case BooleanSize.U32: + { + _buffer = EndianBitConverter.Int32ToBytes(value ? 1 : 0, Endianness); + WriteBytesFromBuffer(4); + break; + } + default: throw new ArgumentOutOfRangeException(nameof(booleanSize)); + } + } + public void Write(bool value, BooleanSize booleanSize, long offset) + { + BaseStream.Position = offset; + Write(value, booleanSize); + } + public void Write(bool[] value) + { + Write(value, 0, value.Length, BooleanSize); + } + public void Write(bool[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length, BooleanSize); + } + public void Write(bool[] value, BooleanSize booleanSize) + { + Write(value, 0, value.Length, booleanSize); + } + public void Write(bool[] value, BooleanSize booleanSize, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length, booleanSize); + } + public void Write(bool[] value, int startIndex, int count) + { + Write(value, startIndex, count, BooleanSize); + } + public void Write(bool[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, BooleanSize); + } + public void Write(bool[] value, int startIndex, int count, BooleanSize booleanSize) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + for (int i = startIndex; i < count; i++) + { + Write(value[i], booleanSize); + } + } + public void Write(bool[] value, int startIndex, int count, BooleanSize booleanSize, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, booleanSize); + } + public void Write(byte value) + { + SetBufferSize(1); + _buffer[0] = value; + WriteBytesFromBuffer(1); + } + public void Write(byte value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(byte[] value) + { + Write(value, 0, value.Length); + } + public void Write(byte[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(byte[] value, int startIndex, int count) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + SetBufferSize(count); + for (int i = 0; i < count; i++) + { + _buffer[i] = value[i + startIndex]; + } + WriteBytesFromBuffer(count); + } + public void Write(byte[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(sbyte value) + { + SetBufferSize(1); + _buffer[0] = (byte)value; + WriteBytesFromBuffer(1); + } + public void Write(sbyte value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(sbyte[] value) + { + Write(value, 0, value.Length); + } + public void Write(sbyte[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(sbyte[] value, int startIndex, int count) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + SetBufferSize(count); + for (int i = 0; i < count; i++) + { + _buffer[i] = (byte)value[i + startIndex]; + } + WriteBytesFromBuffer(count); + } + public void Write(sbyte[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(char value) + { + Write(value, Encoding); + } + public void Write(char value, long offset) + { + BaseStream.Position = offset; + Write(value, Encoding); + } + public void Write(char value, Encoding encoding) + { + Utils.ThrowIfCannotUseEncoding(encoding); + _buffer = encoding.GetBytes(new[] { value }); + WriteBytesFromBuffer(_buffer.Length); + } + public void Write(char value, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, encoding); + } + public void Write(char[] value) + { + Write(value, 0, value.Length, Encoding); + } + public void Write(char[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length, Encoding); + } + public void Write(char[] value, Encoding encoding) + { + Write(value, 0, value.Length, encoding); + } + public void Write(char[] value, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length, encoding); + } + public void Write(char[] value, int startIndex, int count) + { + Write(value, startIndex, count, Encoding); + } + public void Write(char[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, Encoding); + } + public void Write(char[] value, int startIndex, int count, Encoding encoding) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + Utils.ThrowIfCannotUseEncoding(encoding); + _buffer = encoding.GetBytes(value, startIndex, count); + WriteBytesFromBuffer(_buffer.Length); + } + public void Write(char[] value, int startIndex, int count, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, encoding); + } + public void Write(string value, bool nullTerminated) + { + Write(value, nullTerminated, Encoding); + } + public void Write(string value, bool nullTerminated, long offset) + { + BaseStream.Position = offset; + Write(value, nullTerminated, Encoding); + } + public void Write(string value, bool nullTerminated, Encoding encoding) + { + Write(value.ToCharArray(), encoding); + if (nullTerminated) + { + Write('\0', encoding); + } + } + public void Write(string value, bool nullTerminated, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, nullTerminated, encoding); + } + public void Write(string value, int charCount) + { + Write(value, charCount, Encoding); + } + public void Write(string value, int charCount, long offset) + { + BaseStream.Position = offset; + Write(value, charCount, Encoding); + } + public void Write(string value, int charCount, Encoding encoding) + { + Utils.TruncateString(value, charCount, out char[] chars); + Write(chars, encoding); + } + public void Write(string value, int charCount, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, charCount, encoding); + } + public void Write(string[] value, int startIndex, int count, bool nullTerminated) + { + Write(value, startIndex, count, nullTerminated, Encoding); + } + public void Write(string[] value, int startIndex, int count, bool nullTerminated, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, nullTerminated, Encoding); + } + public void Write(string[] value, int startIndex, int count, bool nullTerminated, Encoding encoding) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + for (int i = 0; i < count; i++) + { + Write(value[i + startIndex], nullTerminated, encoding); + } + } + public void Write(string[] value, int startIndex, int count, bool nullTerminated, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, nullTerminated, encoding); + } + public void Write(string[] value, int startIndex, int count, int charCount) + { + Write(value, startIndex, count, charCount, Encoding); + } + public void Write(string[] value, int startIndex, int count, int charCount, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, charCount, Encoding); + } + public void Write(string[] value, int startIndex, int count, int charCount, Encoding encoding) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + for (int i = 0; i < count; i++) + { + Write(value[i + startIndex], charCount, encoding); + } + } + public void Write(string[] value, int startIndex, int count, int charCount, Encoding encoding, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count, charCount, encoding); + } + public void Write(short value) + { + _buffer = EndianBitConverter.Int16ToBytes(value, Endianness); + WriteBytesFromBuffer(2); + } + public void Write(short value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(short[] value) + { + Write(value, 0, value.Length); + } + public void Write(short[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(short[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.Int16sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 2); + } + public void Write(short[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(ushort value) + { + _buffer = EndianBitConverter.Int16ToBytes((short)value, Endianness); + WriteBytesFromBuffer(2); + } + public void Write(ushort value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(ushort[] value) + { + Write(value, 0, value.Length); + } + public void Write(ushort[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(ushort[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.UInt16sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 2); + } + public void Write(ushort[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(int value) + { + _buffer = EndianBitConverter.Int32ToBytes(value, Endianness); + WriteBytesFromBuffer(4); + } + public void Write(int value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(int[] value) + { + Write(value, 0, value.Length); + } + public void Write(int[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(int[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.Int32sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 4); + } + public void Write(int[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(uint value) + { + _buffer = EndianBitConverter.Int32ToBytes((int)value, Endianness); + WriteBytesFromBuffer(4); + } + public void Write(uint value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(uint[] value) + { + Write(value, 0, value.Length); + } + public void Write(uint[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(uint[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.UInt32sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 4); + } + public void Write(uint[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(long value) + { + _buffer = EndianBitConverter.Int64ToBytes(value, Endianness); + WriteBytesFromBuffer(8); + } + public void Write(long value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(long[] value) + { + Write(value, 0, value.Length); + } + public void Write(long[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(long[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.Int64sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 8); + } + public void Write(long[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(ulong value) + { + _buffer = EndianBitConverter.Int64ToBytes((long)value, Endianness); + WriteBytesFromBuffer(8); + } + public void Write(ulong value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(ulong[] value) + { + Write(value, 0, value.Length); + } + public void Write(ulong[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(ulong[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.UInt64sToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 8); + } + public void Write(ulong[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(float value) + { + _buffer = EndianBitConverter.SingleToBytes(value, Endianness); + WriteBytesFromBuffer(4); + } + public void Write(float value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(float[] value) + { + Write(value, 0, value.Length); + } + public void Write(float[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(float[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.SinglesToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 4); + } + public void Write(float[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(double value) + { + _buffer = EndianBitConverter.DoubleToBytes(value, Endianness); + WriteBytesFromBuffer(8); + } + public void Write(double value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(double[] value) + { + Write(value, 0, value.Length); + } + public void Write(double[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(double[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.DoublesToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 8); + } + public void Write(double[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + public void Write(decimal value) + { + _buffer = EndianBitConverter.DecimalToBytes(value, Endianness); + WriteBytesFromBuffer(16); + } + public void Write(decimal value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(decimal[] value) + { + Write(value, 0, value.Length); + } + public void Write(decimal[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(decimal[] value, int startIndex, int count) + { + _buffer = EndianBitConverter.DecimalsToBytes(value, startIndex, count, Endianness); + WriteBytesFromBuffer(count * 16); + } + public void Write(decimal[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + + // #13 - Handle "Enum" abstract type so we get the correct type in that case + // For example, writer.Write((Enum)Enum.Parse(enumType, value)) + // No "struct" restriction on writes + public void Write(TEnum value) where TEnum : Enum + { + Type underlyingType = Enum.GetUnderlyingType(value.GetType()); + switch (Type.GetTypeCode(underlyingType)) + { + case TypeCode.Byte: Write(Convert.ToByte(value)); break; + case TypeCode.SByte: Write(Convert.ToSByte(value)); break; + case TypeCode.Int16: Write(Convert.ToInt16(value)); break; + case TypeCode.UInt16: Write(Convert.ToUInt16(value)); break; + case TypeCode.Int32: Write(Convert.ToInt32(value)); break; + case TypeCode.UInt32: Write(Convert.ToUInt32(value)); break; + case TypeCode.Int64: Write(Convert.ToInt64(value)); break; + case TypeCode.UInt64: Write(Convert.ToUInt64(value)); break; + default: throw new ArgumentOutOfRangeException(nameof(underlyingType)); + } + } + public void Write(TEnum value, long offset) where TEnum : Enum + { + BaseStream.Position = offset; + Write(value); + } + public void Write(TEnum[] value) where TEnum : Enum + { + Write(value, 0, value.Length); + } + public void Write(TEnum[] value, long offset) where TEnum : Enum + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(TEnum[] value, int startIndex, int count) where TEnum : Enum + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + for (int i = 0; i < count; i++) + { + Write(value[i + startIndex]); + } + } + public void Write(TEnum[] value, int startIndex, int count, long offset) where TEnum : Enum + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + + public void Write(DateTime value) + { + Write(value.ToBinary()); + } + public void Write(DateTime value, long offset) + { + BaseStream.Position = offset; + Write(value); + } + public void Write(DateTime[] value) + { + Write(value, 0, value.Length); + } + public void Write(DateTime[] value, long offset) + { + BaseStream.Position = offset; + Write(value, 0, value.Length); + } + public void Write(DateTime[] value, int startIndex, int count) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return; + } + for (int i = 0; i < count; i++) + { + Write(value[i + startIndex]); + } + } + public void Write(DateTime[] value, int startIndex, int count, long offset) + { + BaseStream.Position = offset; + Write(value, startIndex, count); + } + + public void Write(IBinarySerializable obj) + { + if (obj is null) + { + throw new ArgumentNullException(nameof(obj)); + } + obj.Write(this); + } + public void Write(IBinarySerializable obj, long offset) + { + BaseStream.Position = offset; + Write(obj); + } + public void Write(object obj) + { + if (obj is null) + { + throw new ArgumentNullException(nameof(obj)); + } + if (obj is IBinarySerializable bs) + { + bs.Write(this); + return; + } + + Type objType = obj.GetType(); + Utils.ThrowIfCannotReadWriteType(objType); + + // Get public non-static properties + foreach (PropertyInfo propertyInfo in objType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + if (Utils.AttributeValueOrDefault(propertyInfo, false)) + { + continue; // Skip properties with BinaryIgnoreAttribute + } + + Type propertyType = propertyInfo.PropertyType; + object value = propertyInfo.GetValue(obj); + + if (propertyType.IsArray) + { + int arrayLength = Utils.GetArrayLength(obj, objType, propertyInfo); + if (arrayLength != 0) // Do not need to do anything for length 0 + { + // Get array type + Type elementType = propertyType.GetElementType(); + if (elementType.IsEnum) + { + elementType = Enum.GetUnderlyingType(elementType); + } + switch (Type.GetTypeCode(elementType)) + { + case TypeCode.Boolean: + { + BooleanSize booleanSize = Utils.AttributeValueOrDefault(propertyInfo, BooleanSize); + Write((bool[])value, 0, arrayLength, booleanSize); + break; + } + case TypeCode.Byte: Write((byte[])value, 0, arrayLength); break; + case TypeCode.SByte: Write((sbyte[])value, 0, arrayLength); break; + case TypeCode.Char: + { + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + Write((char[])value, 0, arrayLength, encoding); + break; + } + case TypeCode.Int16: Write((short[])value, 0, arrayLength); break; + case TypeCode.UInt16: Write((ushort[])value, 0, arrayLength); break; + case TypeCode.Int32: Write((int[])value, 0, arrayLength); break; + case TypeCode.UInt32: Write((uint[])value, 0, arrayLength); break; + case TypeCode.Int64: Write((long[])value, 0, arrayLength); break; + case TypeCode.UInt64: Write((ulong[])value, 0, arrayLength); break; + case TypeCode.Single: Write((float[])value, 0, arrayLength); break; + case TypeCode.Double: Write((double[])value, 0, arrayLength); break; + case TypeCode.Decimal: Write((decimal[])value, 0, arrayLength); break; + case TypeCode.DateTime: Write((DateTime[])value, 0, arrayLength); break; + case TypeCode.String: + { + Utils.GetStringLength(obj, objType, propertyInfo, false, out bool? nullTerminated, out int stringLength); + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + if (nullTerminated.HasValue) + { + Write((string[])value, 0, arrayLength, nullTerminated.Value, encoding); + } + else + { + Write((string[])value, 0, arrayLength, stringLength, encoding); + } + break; + } + case TypeCode.Object: + { + if (typeof(IBinarySerializable).IsAssignableFrom(elementType)) + { + for (int i = 0; i < arrayLength; i++) + { + var serializable = (IBinarySerializable)((Array)value).GetValue(i); + serializable.Write(this); + } + } + else // Element's type is not supported so try to write the array's objects + { + for (int i = 0; i < arrayLength; i++) + { + object elementObj = ((Array)value).GetValue(i); + Write(elementObj); + } + } + break; + } + default: throw new ArgumentOutOfRangeException(nameof(elementType)); + } + } + } + else + { + if (propertyType.IsEnum) + { + propertyType = Enum.GetUnderlyingType(propertyType); + } + switch (Type.GetTypeCode(propertyType)) + { + case TypeCode.Boolean: + { + BooleanSize booleanSize = Utils.AttributeValueOrDefault(propertyInfo, BooleanSize); + Write((bool)value, booleanSize); + break; + } + case TypeCode.Byte: Write((byte)value); break; + case TypeCode.SByte: Write((sbyte)value); break; + case TypeCode.Char: + { + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + Write((char)value, encoding); + break; + } + case TypeCode.Int16: Write((short)value); break; + case TypeCode.UInt16: Write((ushort)value); break; + case TypeCode.Int32: Write((int)value); break; + case TypeCode.UInt32: Write((uint)value); break; + case TypeCode.Int64: Write((long)value); break; + case TypeCode.UInt64: Write((ulong)value); break; + case TypeCode.Single: Write((float)value); break; + case TypeCode.Double: Write((double)value); break; + case TypeCode.Decimal: Write((decimal)value); break; + case TypeCode.DateTime: Write((DateTime)value); break; + case TypeCode.String: + { + Utils.GetStringLength(obj, objType, propertyInfo, false, out bool? nullTerminated, out int stringLength); + Encoding encoding = Utils.AttributeValueOrDefault(propertyInfo, Encoding); + if (nullTerminated.HasValue) + { + Write((string)value, nullTerminated.Value, encoding); + } + else + { + Write((string)value, stringLength, encoding); + } + break; + } + case TypeCode.Object: + { + if (typeof(IBinarySerializable).IsAssignableFrom(propertyType)) + { + ((IBinarySerializable)value).Write(this); + } + else // property's type is not supported so try to write the object + { + Write(value); + } + break; + } + default: throw new ArgumentOutOfRangeException(nameof(propertyType)); + } + } + } + } + public void Write(object obj, long offset) + { + BaseStream.Position = offset; + Write(obj); + } + } +} diff --git a/EndianBinaryIO/EndianBitConverter.cs b/EndianBinaryIO/EndianBitConverter.cs new file mode 100644 index 0000000..cb00743 --- /dev/null +++ b/EndianBinaryIO/EndianBitConverter.cs @@ -0,0 +1,587 @@ +using System; + +namespace Kermalis.EndianBinaryIO +{ + public static class EndianBitConverter + { + public static Endianness SystemEndianness { get; } = BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian; + + public static unsafe byte[] Int16ToBytes(short value, Endianness targetEndianness) + { + byte[] bytes = new byte[2]; + fixed (byte* b = bytes) + { + *(short*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 2); + } + return bytes; + } + public static unsafe byte[] Int16sToBytes(short[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[2 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((short*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 2); + } + } + return array; + } + public static unsafe byte[] UInt16sToBytes(ushort[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[2 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((ushort*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 2); + } + } + return array; + } + public static unsafe byte[] Int32ToBytes(int value, Endianness targetEndianness) + { + byte[] bytes = new byte[4]; + fixed (byte* b = bytes) + { + *(int*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 4); + } + return bytes; + } + public static unsafe byte[] Int32sToBytes(int[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[4 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((int*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 4); + } + } + return array; + } + public static unsafe byte[] UInt32sToBytes(uint[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[4 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((uint*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 4); + } + } + return array; + } + public static unsafe byte[] Int64ToBytes(long value, Endianness targetEndianness) + { + byte[] bytes = new byte[8]; + fixed (byte* b = bytes) + { + *(long*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 8); + } + return bytes; + } + public static unsafe byte[] Int64sToBytes(long[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[8 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((long*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 8); + } + } + return array; + } + public static unsafe byte[] UInt64sToBytes(ulong[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[8 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((ulong*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 8); + } + } + return array; + } + public static unsafe byte[] SingleToBytes(float value, Endianness targetEndianness) + { + byte[] bytes = new byte[4]; + fixed (byte* b = bytes) + { + *(float*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 4); + } + return bytes; + } + public static unsafe byte[] SinglesToBytes(float[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[4 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((float*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 4); + } + } + return array; + } + public static unsafe byte[] DoubleToBytes(double value, Endianness targetEndianness) + { + byte[] bytes = new byte[8]; + fixed (byte* b = bytes) + { + *(double*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 8); + } + return bytes; + } + public static unsafe byte[] DoublesToBytes(double[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[8 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((double*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 8); + } + } + return array; + } + public static unsafe byte[] DecimalToBytes(decimal value, Endianness targetEndianness) + { + byte[] bytes = new byte[16]; + fixed (byte* b = bytes) + { + *(decimal*)b = value; + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(bytes, 0, 1, 16); + } + return bytes; + } + public static unsafe byte[] DecimalsToBytes(decimal[] value, int startIndex, int count, Endianness targetEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out byte[] array)) + { + array = new byte[16 * count]; + fixed (byte* b = array) + { + for (int i = 0; i < count; i++) + { + ((decimal*)b)[i] = value[startIndex + i]; + } + } + if (SystemEndianness != targetEndianness) + { + FlipPrimitives(array, 0, count, 16); + } + } + return array; + } + + public static unsafe short BytesToInt16(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 2); + } + fixed (byte* b = &value[startIndex]) + { + return *(short*)b; + } + } + public static unsafe short[] BytesToInt16s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 2)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out short[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 2); + } + array = new short[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((short*)b)[i]; + } + } + } + return array; + } + public static unsafe ushort[] BytesToUInt16s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 2)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out ushort[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 2); + } + array = new ushort[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((ushort*)b)[i]; + } + } + } + return array; + } + public static unsafe int BytesToInt32(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 4); + } + fixed (byte* b = &value[startIndex]) + { + return *(int*)b; + } + } + public static unsafe int[] BytesToInt32s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 4)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out int[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 4); + } + array = new int[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((int*)b)[i]; + } + } + } + return array; + } + public static unsafe uint[] BytesToUInt32s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 4)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out uint[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 4); + } + array = new uint[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((uint*)b)[i]; + } + } + } + return array; + } + public static unsafe long BytesToInt64(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 8); + } + fixed (byte* b = &value[startIndex]) + { + return *(long*)b; + } + } + public static unsafe long[] BytesToInt64s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 8)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out long[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 8); + } + array = new long[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((long*)b)[i]; + } + } + } + return array; + } + public static unsafe ulong[] BytesToUInt64s(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 8)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out ulong[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 8); + } + array = new ulong[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((ulong*)b)[i]; + } + } + } + return array; + } + public static unsafe float BytesToSingle(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 4); + } + fixed (byte* b = &value[startIndex]) + { + return *(float*)b; + } + } + public static unsafe float[] BytesToSingles(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 4)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out float[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 4); + } + array = new float[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((float*)b)[i]; + } + } + } + return array; + } + public static unsafe double BytesToDouble(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 8); + } + fixed (byte* b = &value[startIndex]) + { + return *(double*)b; + } + } + public static unsafe double[] BytesToDoubles(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 8)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out double[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 8); + } + array = new double[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((double*)b)[i]; + } + } + } + return array; + } + public static unsafe decimal BytesToDecimal(byte[] value, int startIndex, Endianness sourceEndianness) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, 1, 16); + } + fixed (byte* b = &value[startIndex]) + { + return *(decimal*)b; + } + } + public static unsafe decimal[] BytesToDecimals(byte[] value, int startIndex, int count, Endianness sourceEndianness) + { + if (Utils.ValidateArrayIndexAndCount(value, startIndex, count * 16)) + { + return Array.Empty(); + } + if (!Utils.ValidateReadArraySize(count, out decimal[] array)) + { + if (SystemEndianness != sourceEndianness) + { + FlipPrimitives(value, startIndex, count, 16); + } + array = new decimal[count]; + fixed (byte* b = &value[startIndex]) + { + for (int i = 0; i < count; i++) + { + array[i] = ((decimal*)b)[i]; + } + } + } + return array; + } + + private static void FlipPrimitives(byte[] buffer, int startIndex, int primitiveCount, int primitiveSize) + { + int byteCount = primitiveCount * primitiveSize; + for (int i = startIndex; i < byteCount + startIndex; i += primitiveSize) + { + int a = i; + int b = i + primitiveSize - 1; + while (a < b) + { + byte by = buffer[a]; + buffer[a] = buffer[b]; + buffer[b] = by; + a++; + b--; + } + } + } + } +} diff --git a/EndianBinaryIO/Enums.cs b/EndianBinaryIO/Enums.cs new file mode 100644 index 0000000..5a93b91 --- /dev/null +++ b/EndianBinaryIO/Enums.cs @@ -0,0 +1,18 @@ +namespace Kermalis.EndianBinaryIO +{ + public enum BooleanSize : byte + { + U8, + U16, + U32, + MAX + } + + public enum Endianness : byte + { + LittleEndian, + BigEndian, + MAX + } +} + diff --git a/EndianBinaryIO/IBinarySerializable.cs b/EndianBinaryIO/IBinarySerializable.cs new file mode 100644 index 0000000..69cbfcf --- /dev/null +++ b/EndianBinaryIO/IBinarySerializable.cs @@ -0,0 +1,8 @@ +namespace Kermalis.EndianBinaryIO +{ + public interface IBinarySerializable + { + void Read(EndianBinaryReader r); + void Write(EndianBinaryWriter w); + } +} diff --git a/EndianBinaryIO/Utils.cs b/EndianBinaryIO/Utils.cs new file mode 100644 index 0000000..bdaa7aa --- /dev/null +++ b/EndianBinaryIO/Utils.cs @@ -0,0 +1,178 @@ +using System; +using System.Reflection; +using System.Text; + +namespace Kermalis.EndianBinaryIO +{ + internal sealed class Utils + { + public static void TruncateString(string str, int charCount, out char[] toArray) + { + toArray = new char[charCount]; + int numCharsToCopy = Math.Min(charCount, str.Length); + for (int i = 0; i < numCharsToCopy; i++) + { + toArray[i] = str[i]; + } + } + + public static bool TryGetAttribute(PropertyInfo propertyInfo, out TAttribute attribute) where TAttribute : Attribute + { + object[] attributes = propertyInfo.GetCustomAttributes(typeof(TAttribute), true); + if (attributes.Length == 1) + { + attribute = (TAttribute)attributes[0]; + return true; + } + attribute = null; + return false; + } + public static TValue GetAttributeValue(TAttribute attribute) where TAttribute : Attribute, IBinaryAttribute + { + return (TValue)typeof(TAttribute).GetProperty(nameof(IBinaryAttribute.Value)).GetValue(attribute); + } + public static TValue AttributeValueOrDefault(PropertyInfo propertyInfo, TValue defaultValue) where TAttribute : Attribute, IBinaryAttribute + { + if (TryGetAttribute(propertyInfo, out TAttribute attribute)) + { + return GetAttributeValue(attribute); + } + return defaultValue; + } + + public static void ThrowIfCannotReadWriteType(Type type) + { + if (type.IsArray || type.IsEnum || type.IsInterface || type.IsPointer || type.IsPrimitive) + { + throw new ArgumentException(nameof(type), $"Cannot read/write \"{type.FullName}\" objects."); + } + } + public static void ThrowIfCannotUseEncoding(Encoding encoding) + { + if (encoding is null) + { + throw new ArgumentNullException(nameof(encoding), "EndianBinaryIO could not read/write chars because an encoding was null; make sure you pass one in properly."); + } + } + + // Returns true if count is 0 + public static bool ValidateReadArraySize(int count, out T[] array) + { + if (count < 0) + { + throw new ArgumentOutOfRangeException($"Invalid array length ({count})"); + } + if (count == 0) + { + array = Array.Empty(); + return true; + } + array = null; + return false; + } + // Returns true if count is 0 + public static bool ValidateArrayIndexAndCount(Array array, int startIndex, int count) + { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException($"Invalid array length ({count})"); + } + if (startIndex + count > array.Length) + { + throw new ArgumentOutOfRangeException($"Invalid array index + count (StartIndex: {startIndex}, Count: {count}, Array Length: {array.Length})"); + } + return count == 0; + } + + public static int GetArrayLength(object obj, Type objType, PropertyInfo propertyInfo) + { + int Validate(int value) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException($"An array property in \"{objType.FullName}\" has an invalid length attribute ({value})"); + } + return value; + } + + if (TryGetAttribute(propertyInfo, out BinaryArrayFixedLengthAttribute fixedLenAttribute)) + { + if (propertyInfo.IsDefined(typeof(BinaryArrayVariableLengthAttribute))) + { + throw new ArgumentException($"An array property in \"{objType.FullName}\" has two array length attributes. Only one should be provided."); + } + return Validate(GetAttributeValue(fixedLenAttribute)); + } + if (TryGetAttribute(propertyInfo, out BinaryArrayVariableLengthAttribute varLenAttribute)) + { + string anchorName = GetAttributeValue(varLenAttribute); + PropertyInfo anchor = objType.GetProperty(anchorName, BindingFlags.Instance | BindingFlags.Public); + if (anchor is null) + { + throw new MissingMemberException($"An array property in \"{objType.FullName}\" has an invalid {nameof(BinaryArrayVariableLengthAttribute)} ({anchorName})."); + } + return Validate(Convert.ToInt32(anchor.GetValue(obj))); + } + throw new MissingMemberException($"An array property in \"{objType.FullName}\" is missing an array length attribute. One should be provided."); + } + public static void GetStringLength(object obj, Type objType, PropertyInfo propertyInfo, bool forReads, out bool? nullTerminated, out int stringLength) + { + int Validate(int value) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException($"A string property in \"{objType.FullName}\" has an invalid length attribute ({value})"); + } + return value; + } + + if (TryGetAttribute(propertyInfo, out BinaryStringNullTerminatedAttribute nullTermAttribute)) + { + if (propertyInfo.IsDefined(typeof(BinaryStringFixedLengthAttribute)) || propertyInfo.IsDefined(typeof(BinaryStringVariableLengthAttribute))) + { + throw new ArgumentException($"A string property in \"{objType.FullName}\" has a string length attribute and a {nameof(BinaryStringNullTerminatedAttribute)}; cannot use both."); + } + if (propertyInfo.IsDefined(typeof(BinaryStringTrimNullTerminatorsAttribute))) + { + throw new ArgumentException($"A string property in \"{objType.FullName}\" has a {nameof(BinaryStringNullTerminatedAttribute)} and a {nameof(BinaryStringTrimNullTerminatorsAttribute)}; cannot use both."); + } + bool nt = GetAttributeValue(nullTermAttribute); + if (forReads && !nt) // Not forcing BinaryStringNullTerminatedAttribute to be treated as true since you may only write objects without reading them. + { + throw new ArgumentException($"A string property in \"{objType.FullName}\" has a {nameof(BinaryStringNullTerminatedAttribute)} that's set to false." + + $" Must use null termination or provide a string length when reading."); + } + nullTerminated = nt; + stringLength = -1; + return; + } + if (TryGetAttribute(propertyInfo, out BinaryStringFixedLengthAttribute fixedLenAttribute)) + { + if (propertyInfo.IsDefined(typeof(BinaryStringVariableLengthAttribute))) + { + throw new ArgumentException($"A string property in \"{objType.FullName}\" has two string length attributes. Only one should be provided."); + } + nullTerminated = null; + stringLength = Validate(GetAttributeValue(fixedLenAttribute)); + return; + } + if (TryGetAttribute(propertyInfo, out BinaryStringVariableLengthAttribute varLenAttribute)) + { + string anchorName = GetAttributeValue(varLenAttribute); + PropertyInfo anchor = objType.GetProperty(anchorName, BindingFlags.Instance | BindingFlags.Public); + if (anchor is null) + { + throw new MissingMemberException($"A string property in \"{objType.FullName}\" has an invalid {nameof(BinaryStringVariableLengthAttribute)} ({anchorName})."); + } + nullTerminated = null; + stringLength = Validate(Convert.ToInt32(anchor.GetValue(obj))); + return; + } + throw new MissingMemberException($"A string property in \"{objType.FullName}\" is missing a string length attribute and has no {nameof(BinaryStringNullTerminatedAttribute)}. One should be provided."); + } + } +} 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 don’t 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/ObjectListView2005.csproj b/ObjectListView/ObjectListView2005.csproj new file mode 100644 index 0000000..02c0c00 --- /dev/null +++ b/ObjectListView/ObjectListView2005.csproj @@ -0,0 +1,182 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {18FEDA0C-D147-4286-B39A-01204808106A} + Library + Properties + BrightIdeasSoftware + ObjectListView + true + olv-keyfile.snk + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + pdbonly + true + bin\Release\ + DEBUG;TRACE + prompt + 4 + false + + + + + + + + + + + + + + Component + + + + + + + + + Component + + + + + + + + + Component + + + True + True + Resources.resx + + + + + Component + + + + Component + + + + + + + Component + + + Component + + + + + Component + + + + + + + Component + + + Component + + + Form + + + ColumnSelectionForm.cs + + + + Form + + + + Code + + + + + + + + Component + + + + + + Component + + + Component + + + + Component + + + + + + + Component + + + + + + + Designer + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + ColumnSelectionForm.cs + Designer + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2008.csproj b/ObjectListView/ObjectListView2008.csproj new file mode 100644 index 0000000..fb038d2 --- /dev/null +++ b/ObjectListView/ObjectListView2008.csproj @@ -0,0 +1,188 @@ + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {18FEDA0C-D147-4286-B39A-01204808106A} + Library + Properties + BrightIdeasSoftware + ObjectListView + + + + + 2.0 + v2.0 + true + olv-keyfile.snk + + + true + full + false + bin\Debug\ + TRACE;DEBUG + prompt + 4 + false + + + + + pdbonly + true + bin\Release\ + DEBUG;TRACE + prompt + 4 + false + + + + + + + + + + + + + + + + Component + + + + + + + + + Component + + + + + + + + + Component + + + True + True + Resources.resx + + + + + Component + + + + Component + + + + + + + Component + + + Component + + + + + Component + + + + + + + Component + + + Component + + + Form + + + ColumnSelectionForm.cs + + + + Form + + + + Code + + + + + + + + Component + + + + + + Component + + + Component + + + + Component + + + + + + + Component + + + + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + ColumnSelectionForm.cs + Designer + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2008.ncrunchproject b/ObjectListView/ObjectListView2008.ncrunchproject new file mode 100644 index 0000000..17f8118 --- /dev/null +++ b/ObjectListView/ObjectListView2008.ncrunchproject @@ -0,0 +1,16 @@ + + false + false + false + false + false + true + true + false + true + true + 60000 + + + AutoDetect + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2010.csproj b/ObjectListView/ObjectListView2010.csproj new file mode 100644 index 0000000..f478fa7 --- /dev/null +++ b/ObjectListView/ObjectListView2010.csproj @@ -0,0 +1,188 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {18FEDA0C-D147-4286-B39A-01204808106A} + Library + Properties + BrightIdeasSoftware + ObjectListView + + + + + 3.5 + v2.0 + true + olv-keyfile.snk + + + + true + full + false + bin\Debug\ + TRACE;DEBUG + prompt + 4 + false + bin\Debug\ObjectListView.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + Component + + + + + + + + Component + + + + + + + + + Component + + + True + True + Resources.resx + + + + + Component + + + + Component + + + + + + + Component + + + Component + + + + + + Component + + + + + + + Component + + + Component + + + Form + + + ColumnSelectionForm.cs + + + + Form + + + + Code + + + + + + + + Component + + + + + + Component + + + Component + + + + Component + + + + + + + Component + + + + + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + ColumnSelectionForm.cs + Designer + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2010.ncrunchproject b/ObjectListView/ObjectListView2010.ncrunchproject new file mode 100644 index 0000000..b4ca671 --- /dev/null +++ b/ObjectListView/ObjectListView2010.ncrunchproject @@ -0,0 +1,27 @@ + + false + false + false + true + false + false + false + false + true + true + false + true + true + 60000 + + + + AutoDetect + STA + x86 + + + .* + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2012.csproj b/ObjectListView/ObjectListView2012.csproj new file mode 100644 index 0000000..3ff032a --- /dev/null +++ b/ObjectListView/ObjectListView2012.csproj @@ -0,0 +1,194 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {18FEDA0C-D147-4286-B39A-01204808106A} + Library + Properties + BrightIdeasSoftware + ObjectListView + + + + + 3.5 + v2.0 + true + olv-keyfile.snk + + %24/ObjectListView/trunk/ObjectListView + . + https://grammarian.visualstudio.com + {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} + + + true + full + false + bin\Debug\ + TRACE;DEBUG + prompt + 1 + false + bin\Debug\ObjectListView.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + bin\Release\ObjectListView.XML + + + + + + + + + + + + + + Component + + + + + + + + Component + + + + + + + + + Component + + + True + True + Resources.resx + + + + + + + Component + + + + + + + Component + + + Component + + + + + + Component + + + + + + + Component + + + Component + + + Form + + + ColumnSelectionForm.cs + + + + Form + + + + Code + + + + + + + + Component + + + + + + Component + + + Component + + + + Component + + + + + + + Component + + + + + + + Designer + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + ColumnSelectionForm.cs + Designer + + + + + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2012.ncrunchproject b/ObjectListView/ObjectListView2012.ncrunchproject new file mode 100644 index 0000000..896f219 --- /dev/null +++ b/ObjectListView/ObjectListView2012.ncrunchproject @@ -0,0 +1,22 @@ + + false + false + false + true + false + false + false + false + true + true + false + true + true + 60000 + + + + AutoDetect + STA + x86 + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2012.nuspec b/ObjectListView/ObjectListView2012.nuspec new file mode 100644 index 0000000..3e883c6 --- /dev/null +++ b/ObjectListView/ObjectListView2012.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/ObjectListView2012.sln.DotSettings b/ObjectListView/ObjectListView2012.sln.DotSettings new file mode 100644 index 0000000..a35bee7 --- /dev/null +++ b/ObjectListView/ObjectListView2012.sln.DotSettings @@ -0,0 +1,7 @@ + + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy> \ No newline at end of file diff --git a/ObjectListView/ObjectListView2012.v2.ncrunchproject b/ObjectListView/ObjectListView2012.v2.ncrunchproject new file mode 100644 index 0000000..896f219 --- /dev/null +++ b/ObjectListView/ObjectListView2012.v2.ncrunchproject @@ -0,0 +1,22 @@ + + false + false + false + true + false + false + false + false + true + true + false + true + true + 60000 + + + + AutoDetect + STA + x86 + \ No newline at end of file diff --git a/ObjectListView/ObjectListView2019.csproj b/ObjectListView/ObjectListView2019.csproj new file mode 100644 index 0000000..bc8d730 --- /dev/null +++ b/ObjectListView/ObjectListView2019.csproj @@ -0,0 +1,50 @@ + + + netcoreapp3.1 + 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 + + + + + + + + + + + + + + + + + + + + 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/VG Music Studio/Properties/AssemblyInfo.cs b/ObjectListView/Properties/AssemblyInfo.cs similarity index 57% rename from VG Music Studio/Properties/AssemblyInfo.cs rename to ObjectListView/Properties/AssemblyInfo.cs index 90411a1..515899d 100644 --- a/VG Music Studio/Properties/AssemblyInfo.cs +++ b/ObjectListView/Properties/AssemblyInfo.cs @@ -1,17 +1,15 @@ -using System.Resources; using System.Reflection; -using System.Runtime.CompilerServices; 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("VG Music Studio")] -[assembly: AssemblyDescription("Listen to the music from popular video game formats.")] +[assembly: AssemblyTitle("ObjectListView")] +[assembly: AssemblyDescription("A much easier to use ListView and friends")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Kermalis")] -[assembly: AssemblyProduct("VG Music Studio")] -[assembly: AssemblyCopyright("Copyright © Kermalis 2019")] +[assembly: AssemblyCompany("Bright Ideas Software")] +[assembly: AssemblyProduct("ObjectListView")] +[assembly: AssemblyCopyright("Copyright © 2006-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -21,7 +19,7 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("97c8acf8-66a3-4321-91d6-3e94eaca577f")] +[assembly: Guid("ef28c7a8-77ae-442d-abc3-bb023fa31e57")] // Version information for an assembly consists of the following four values: // @@ -30,10 +28,9 @@ // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.0.0.2")] -[assembly: AssemblyFileVersion("0.0.0.2")] -[assembly: NeutralResourcesLanguage("en-US")] - +[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 0000000..2ddf707 Binary files /dev/null and b/ObjectListView/Resources/clear-filter.png differ diff --git a/ObjectListView/Resources/coffee.jpg b/ObjectListView/Resources/coffee.jpg new file mode 100644 index 0000000..6032d83 Binary files /dev/null and b/ObjectListView/Resources/coffee.jpg differ diff --git a/ObjectListView/Resources/filter-icons3.png b/ObjectListView/Resources/filter-icons3.png new file mode 100644 index 0000000..8017891 Binary files /dev/null and b/ObjectListView/Resources/filter-icons3.png differ diff --git a/ObjectListView/Resources/filter.png b/ObjectListView/Resources/filter.png new file mode 100644 index 0000000..c09c6d0 Binary files /dev/null and b/ObjectListView/Resources/filter.png differ diff --git a/ObjectListView/Resources/sort-ascending.png b/ObjectListView/Resources/sort-ascending.png new file mode 100644 index 0000000..a21be93 Binary files /dev/null and b/ObjectListView/Resources/sort-ascending.png differ diff --git a/ObjectListView/Resources/sort-descending.png b/ObjectListView/Resources/sort-descending.png new file mode 100644 index 0000000..92dbe63 Binary files /dev/null and b/ObjectListView/Resources/sort-descending.png differ 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. Don’t 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 0000000..2658a0a Binary files /dev/null and b/ObjectListView/olv-keyfile.snk differ diff --git a/Sanford.Multimedia.Midi.Core/Icon_-_General_MIDI.png b/Sanford.Multimedia.Midi.Core/Icon_-_General_MIDI.png new file mode 100644 index 0000000..8c91a45 Binary files /dev/null and b/Sanford.Multimedia.Midi.Core/Icon_-_General_MIDI.png differ diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.1.2.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.1.2.nuspec new file mode 100644 index 0000000..baede03 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.1.2.nuspec @@ -0,0 +1,32 @@ + + + + Sanford.Multimedia.Midi + 6.1.2 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Merged github pull request: +Can now load midi files from a stream +Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.0.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.0.nuspec new file mode 100644 index 0000000..457c1aa --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.0.nuspec @@ -0,0 +1,33 @@ + + + + Sanford.Multimedia.Midi + 6.2.0 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Merged github pull request: +Fixed many P/Invoke signatures +Can now load midi files from a stream +Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.1.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.1.nuspec new file mode 100644 index 0000000..691f4fe --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.2.1.nuspec @@ -0,0 +1,33 @@ + + + + Sanford.Multimedia.Midi + 6.2.1 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Merged github pull request: +Fixed many P/Invoke signatures +Can now load midi files from a stream +Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.3.0.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.3.0.nuspec new file mode 100644 index 0000000..f9fb56a --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.3.0.nuspec @@ -0,0 +1,31 @@ + + + + Sanford.Multimedia.Midi + 6.3.0 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Added source/sink interface for events +Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.0.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.0.nuspec new file mode 100644 index 0000000..af998aa --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.0.nuspec @@ -0,0 +1,31 @@ + + + + Sanford.Multimedia.Midi + 6.4.0 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.1.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.1.nuspec new file mode 100644 index 0000000..8700266 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.1.nuspec @@ -0,0 +1,31 @@ + + + + Sanford.Multimedia.Midi + 6.4.1 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Minor dispose fix. Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.2.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.2.nuspec new file mode 100644 index 0000000..c2f74b6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.2.nuspec @@ -0,0 +1,31 @@ + + + + Sanford.Multimedia.Midi + 6.4.2 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Another fix for some drivers that send weird sysex messages on close. Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.3.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.3.nuspec new file mode 100644 index 0000000..200e65d --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.4.3.nuspec @@ -0,0 +1,31 @@ + + + + Sanford.Multimedia.Midi + 6.4.3 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Another fix for some drivers that send weird sysex messages on close. Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.5.0.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.5.0.nuspec new file mode 100644 index 0000000..8a5491b --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.5.0.nuspec @@ -0,0 +1,32 @@ + + + + Sanford.Multimedia.Midi + 6.5.0 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + false + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Fixed PPQM exception, now then only requirement for midi files is PPQM > 24 +Another fix for some drivers that send weird sysex messages on close. Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.6.0.nuspec b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.6.0.nuspec new file mode 100644 index 0000000..86755b3 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Nuget/Sanford.Multimedia.Midi.6.6.0.nuspec @@ -0,0 +1,33 @@ + + + + Sanford.Multimedia.Midi + 6.6.0 + MIDI Toolkit + Leslie Sanford,Tebjan Halm,Andreas Grimme,Andres Fernandez de Prado + Leslie Sanford + false + https://opensource.org/licenses/MIT + http://www.codeproject.com/Articles/6228/C-MIDI-Toolkit + https://raw.githubusercontent.com/tebjan/Sanford.Multimedia.Midi/master/Source/Icon_-_General_MIDI.png + A toolkit for creating MIDI applications with .NET +Source code on github: https://github.com/tebjan/Sanford.Multimedia.Midi + A toolkit for creating MIDI applications with .NET + Midi messages now have the input driver timestamp attached. +Fixed PPQM exception, now then only requirement for midi files is PPQM > 24 +Another fix for some drivers that send weird sysex messages on close. Reworked messages and events a bit. there is now an event for all messages as well as all ShortMessage (was Raw and might break some code if you used it before). +General Improvements: +Now also works on mono +64-bit compatible +Windows 8 and 10 compatible +Does not require additional assemblies +Faster midi file reading in Release build + Leslie Sanford 2006 + en + + + + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Deque.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Deque.cs new file mode 100644 index 0000000..814f8fe --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Deque.cs @@ -0,0 +1,935 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.Diagnostics; + +namespace Sanford.Collections +{ + /// + /// Represents a simple double-ended-queue collection of objects. + /// + [Serializable()] + public class Deque : ICollection, IEnumerable, ICloneable + { + #region Deque Members + + #region Fields + + // The node at the front of the deque. + private Node front = null; + + // The node at the back of the deque. + private Node back = null; + + // The number of elements in the deque. + private int count = 0; + + // The version of the deque. + private long version = 0; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the Deque class. + /// + public Deque() + { + } + + /// + /// Initializes a new instance of the Deque class that contains + /// elements copied from the specified collection. + /// + /// + /// The ICollection to copy elements from. + /// + public Deque(ICollection col) + { + #region Require + + if(col == null) + { + throw new ArgumentNullException("col"); + } + + #endregion + + foreach(object obj in col) + { + PushBack(obj); + } + } + + #endregion + + #region Methods + + /// + /// Removes all objects from the Deque. + /// + public virtual void Clear() + { + count = 0; + + front = back = null; + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Determines whether or not an element is in the Deque. + /// + /// + /// The Object to locate in the Deque. + /// + /// + /// true if obj if found in the Deque; otherwise, + /// false. + /// + public virtual bool Contains(object obj) + { + foreach(object o in this) + { + if(o == null && obj == null) + { + return true; + } + else if(o.Equals(obj)) + { + return true; + } + } + + return false; + } + + /// + /// Inserts an object at the front of the Deque. + /// + /// + /// The object to push onto the deque; + /// + public virtual void PushFront(object obj) + { + // The new node to add to the front of the deque. + Node newNode = new Node(obj); + + // Link the new node to the front node. The current front node at + // the front of the deque is now the second node in the deque. + newNode.Next = front; + + // If the deque isn't empty. + if(Count > 0) + { + // Link the current front to the new node. + front.Previous = newNode; + } + + // Make the new node the front of the deque. + front = newNode; + + // Keep track of the number of elements in the deque. + count++; + + // If this is the first element in the deque. + if(Count == 1) + { + // The front and back nodes are the same. + back = front; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Inserts an object at the back of the Deque. + /// + /// + /// The object to push onto the deque; + /// + public virtual void PushBack(object obj) + { + // The new node to add to the back of the deque. + Node newNode = new Node(obj); + + // Link the new node to the back node. The current back node at + // the back of the deque is now the second to the last node in the + // deque. + newNode.Previous = back; + + // If the deque is not empty. + if(Count > 0) + { + // Link the current back node to the new node. + back.Next = newNode; + } + + // Make the new node the back of the deque. + back = newNode; + + // Keep track of the number of elements in the deque. + count++; + + // If this is the first element in the deque. + if(Count == 1) + { + // The front and back nodes are the same. + front = back; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Removes and returns the object at the front of the Deque. + /// + /// + /// The object at the front of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual object PopFront() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + // Get the object at the front of the deque. + object obj = front.Value; + + // Move the front back one node. + front = front.Next; + + // Keep track of the number of nodes in the deque. + count--; + + // If the deque is not empty. + if(Count > 0) + { + // Tie off the previous link in the front node. + front.Previous = null; + } + // Else the deque is empty. + else + { + // Indicate that there is no back node. + back = null; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + + return obj; + } + + /// + /// Removes and returns the object at the back of the Deque. + /// + /// + /// The object at the back of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual object PopBack() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + // Get the object at the back of the deque. + object obj = back.Value; + + // Move back node forward one node. + back = back.Previous; + + // Keep track of the number of nodes in the deque. + count--; + + // If the deque is not empty. + if(Count > 0) + { + // Tie off the next link in the back node. + back.Next = null; + } + // Else the deque is empty. + else + { + // Indicate that there is no front node. + front = null; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + + return obj; + } + + /// + /// Returns the object at the front of the Deque without removing it. + /// + /// + /// The object at the front of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual object PeekFront() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + return front.Value; + } + + /// + /// Returns the object at the back of the Deque without removing it. + /// + /// + /// The object at the back of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual object PeekBack() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + return back.Value; + } + + /// + /// Copies the Deque to a new array. + /// + /// + /// A new array containing copies of the elements of the Deque. + /// + public virtual object[] ToArray() + { + object[] array = new object[Count]; + int index = 0; + + foreach(object obj in this) + { + array[index] = obj; + index++; + } + + return array; + } + + /// + /// Returns a synchronized (thread-safe) wrapper for the Deque. + /// + /// + /// The Deque to synchronize. + /// + /// + /// A synchronized wrapper around the Deque. + /// + public static Deque Synchronized(Deque deque) + { + #region Require + + if(deque == null) + { + throw new ArgumentNullException("deque"); + } + + #endregion + + return new SynchronizedDeque(deque); + } + + [Conditional("DEBUG")] + private void AssertValid() + { + int n = 0; + Node current = front; + + while(current != null) + { + n++; + current = current.Next; + } + + Debug.Assert(n == Count); + + if(Count > 0) + { + Debug.Assert(front != null && back != null, "Front/Back Null Test - Count > 0"); + + Node f = front; + Node b = back; + + while(f.Next != null && b.Previous != null) + { + f = f.Next; + b = b.Previous; + } + + Debug.Assert(f.Next == null && b.Previous == null, "Front/Back Termination Test"); + Debug.Assert(f == back && b == front, "Front/Back Equality Test"); + } + else + { + Debug.Assert(front == null && back == null, "Front/Back Null Test - Count == 0"); + } + } + + #endregion + + #region Node Class + + // Represents a node in the deque. + [Serializable()] + private class Node + { + private object value; + + private Node previous = null; + + private Node next = null; + + public Node(object value) + { + this.value = value; + } + + public object Value + { + get + { + return value; + } + } + + public Node Previous + { + get + { + return previous; + } + set + { + previous = value; + } + } + + public Node Next + { + get + { + return next; + } + set + { + next = value; + } + } + } + + #endregion + + #region DequeEnumerator Class + + [Serializable()] + private class DequeEnumerator : IEnumerator + { + private Deque owner; + + private Node currentNode; + + private object current = null; + + private bool moveResult = false; + + private long version; + + public DequeEnumerator(Deque owner) + { + this.owner = owner; + currentNode = owner.front; + this.version = owner.version; + } + + #region IEnumerator Members + + public void Reset() + { + #region Require + + if(version != owner.version) + { + throw new InvalidOperationException( + "The Deque was modified after the enumerator was created."); + } + + #endregion + + currentNode = owner.front; + moveResult = false; + } + + public object Current + { + get + { + #region Require + + if(!moveResult) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the Deque or after the last element."); + } + + #endregion + + return current; + } + } + + public bool MoveNext() + { + #region Require + + if(version != owner.version) + { + throw new InvalidOperationException( + "The Deque was modified after the enumerator was created."); + } + + #endregion + + if(currentNode != null) + { + current = currentNode.Value; + currentNode = currentNode.Next; + + moveResult = true; + } + else + { + moveResult = false; + } + + return moveResult; + } + + #endregion + } + + #endregion + + #region SynchronizedDeque Class + + // Implements a synchronization wrapper around a deque. + [Serializable()] + private class SynchronizedDeque : Deque + { + #region SynchronziedDeque Members + + #region Fields + + // The wrapped deque. + private Deque deque; + + // The object to lock on. + private object root; + + #endregion + + #region Construction + + public SynchronizedDeque(Deque deque) + { + #region Require + + if(deque == null) + { + throw new ArgumentNullException("deque"); + } + + #endregion + + this.deque = deque; + this.root = deque.SyncRoot; + } + + #endregion + + #region Methods + + public override void Clear() + { + lock(root) + { + deque.Clear(); + } + } + + public override bool Contains(object obj) + { + bool result; + + lock(root) + { + result = deque.Contains(obj); + } + + return result; + } + + public override void PushFront(object obj) + { + lock(root) + { + deque.PushFront(obj); + } + } + + public override void PushBack(object obj) + { + lock(root) + { + deque.PushBack(obj); + } + } + + public override object PopFront() + { + object obj; + + lock(root) + { + obj = deque.PopFront(); + } + + return obj; + } + + public override object PopBack() + { + object obj; + + lock(root) + { + obj = deque.PopBack(); + } + + return obj; + } + + public override object PeekFront() + { + object obj; + + lock(root) + { + obj = deque.PeekFront(); + } + + return obj; + } + + public override object PeekBack() + { + object obj; + + lock(root) + { + obj = deque.PeekBack(); + } + + return obj; + } + + public override object[] ToArray() + { + object[] array; + + lock(root) + { + array = deque.ToArray(); + } + + return array; + } + + public override object Clone() + { + object clone; + + lock(root) + { + clone = deque.Clone(); + } + + return clone; + } + + public override void CopyTo(Array array, int index) + { + lock(root) + { + deque.CopyTo(array, index); + } + } + + public override IEnumerator GetEnumerator() + { + IEnumerator e; + + lock(root) + { + e = deque.GetEnumerator(); + } + + return e; + } + + #endregion + + #region Properties + + public override int Count + { + get + { + lock(root) + { + return deque.Count; + } + } + } + + public override bool IsSynchronized + { + get + { + return true; + } + } + + #endregion + + #endregion + } + + #endregion + + #endregion + + #region ICollection Members + + /// + /// Gets a value indicating whether access to the Deque is synchronized + /// (thread-safe). + /// + public virtual bool IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets the number of elements contained in the Deque. + /// + public virtual int Count + { + get + { + return count; + } + } + + /// + /// Copies the Deque elements to an existing one-dimensional Array, + /// starting at the specified array index. + /// + /// + /// The one-dimensional Array that is the destination of the elements + /// copied from Deque. The Array must have zero-based indexing. + /// + /// + /// The zero-based index in array at which copying begins. + /// + public virtual void CopyTo(Array array, int index) + { + #region Require + + if(array == null) + { + throw new ArgumentNullException("array"); + } + else if(index < 0) + { + throw new ArgumentOutOfRangeException("index", index, + "Index is less than zero."); + } + else if(array.Rank > 1) + { + throw new ArgumentException("Array is multidimensional."); + } + else if(index >= array.Length) + { + throw new ArgumentException("Index is equal to or greater " + + "than the length of array."); + } + else if(Count > array.Length - index) + { + throw new ArgumentException( + "The number of elements in the source Deque is greater " + + "than the available space from index to the end of the " + + "destination array."); + } + + #endregion + + int i = index; + + foreach(object obj in this) + { + array.SetValue(obj, i); + i++; + } + } + + /// + /// Gets an object that can be used to synchronize access to the Deque. + /// + public virtual object SyncRoot + { + get + { + return this; + } + } + + #endregion + + #region IEnumerable Members + + /// + /// Returns an enumerator that can iterate through the Deque. + /// + /// + /// An IEnumerator for the Deque. + /// + public virtual IEnumerator GetEnumerator() + { + return new DequeEnumerator(this); + } + + #endregion + + #region ICloneable Members + + /// + /// Creates a shallow copy of the Deque. + /// + /// + /// A shallow copy of the Deque. + /// + public virtual object Clone() + { + Deque clone = new Deque(this); + + clone.version = this.version; + + return clone; + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Enumerator.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Enumerator.cs new file mode 100644 index 0000000..5f01e34 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Enumerator.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Collections.Generic +{ + public partial class Deque + { + #region Enumerator Class + + [Serializable()] + private class Enumerator : IEnumerator + { + private Deque owner; + + private Node currentNode; + + private T current = default(T); + + private bool moveResult = false; + + private long version; + + // A value indicating whether the enumerator has been disposed. + private bool disposed = false; + + public Enumerator(Deque owner) + { + this.owner = owner; + currentNode = owner.front; + this.version = owner.version; + } + + #region IEnumerator Members + + public void Reset() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + else if(version != owner.version) + { + throw new InvalidOperationException( + "The Deque was modified after the enumerator was created."); + } + + #endregion + + currentNode = owner.front; + moveResult = false; + } + + public object Current + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + else if(!moveResult) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the Deque or after the last element."); + } + + #endregion + + return current; + } + } + + public bool MoveNext() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + else if(version != owner.version) + { + throw new InvalidOperationException( + "The Deque was modified after the enumerator was created."); + } + + #endregion + + if(currentNode != null) + { + current = currentNode.Value; + currentNode = currentNode.Next; + + moveResult = true; + } + else + { + moveResult = false; + } + + return moveResult; + } + + #endregion + + #region IEnumerator Members + + T IEnumerator.Current + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + else if(!moveResult) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the Deque or after the last element."); + } + + #endregion + + return current; + } + } + + #endregion + + #region IDisposable Members + + public void Dispose() + { + disposed = true; + } + + #endregion + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Node.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Node.cs new file mode 100644 index 0000000..aa80fcc --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Node.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Collections.Generic +{ + public partial class Deque + { + #region Node Class + + // Represents a node in the deque. + [Serializable()] + private class Node + { + private T value; + + private Node previous = null; + + private Node next = null; + + public Node(T value) + { + this.value = value; + } + + public T Value + { + get + { + return value; + } + } + + public Node Previous + { + get + { + return previous; + } + set + { + previous = value; + } + } + + public Node Next + { + get + { + return next; + } + set + { + next = value; + } + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Synchronized.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Synchronized.cs new file mode 100644 index 0000000..a68249a --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.Synchronized.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Sanford.Collections.Generic +{ + public partial class Deque + { + #region SynchronizedDeque Class + + // Implements a synchronization wrapper around a deque. + [Serializable()] + private class SynchronizedDeque : Deque, IEnumerable + { + #region SynchronziedDeque Members + + #region Fields + + // The wrapped deque. + private Deque deque; + + // The object to lock on. + private object root; + + #endregion + + #region Construction + + public SynchronizedDeque(Deque deque) + { + #region Require + + if(deque == null) + { + throw new ArgumentNullException("deque"); + } + + #endregion + + this.deque = deque; + this.root = deque.SyncRoot; + } + + #endregion + + #region Methods + + public override void Clear() + { + lock(root) + { + deque.Clear(); + } + } + + public override bool Contains(T item) + { + lock(root) + { + return deque.Contains(item); + } + } + + public override void PushFront(T item) + { + lock(root) + { + deque.PushFront(item); + } + } + + public override void PushBack(T item) + { + lock(root) + { + deque.PushBack(item); + } + } + + public override T PopFront() + { + lock(root) + { + return deque.PopFront(); + } + } + + public override T PopBack() + { + lock(root) + { + return deque.PopBack(); + } + } + + public override T PeekFront() + { + lock(root) + { + return deque.PeekFront(); + } + } + + public override T PeekBack() + { + lock(root) + { + return deque.PeekBack(); + } + } + + public override T[] ToArray() + { + lock(root) + { + return deque.ToArray(); + } + } + + public override object Clone() + { + lock(root) + { + return deque.Clone(); + } + } + + public override void CopyTo(Array array, int index) + { + lock(root) + { + deque.CopyTo(array, index); + } + } + + public override IEnumerator GetEnumerator() + { + lock(root) + { + return deque.GetEnumerator(); + } + } + + /// + /// Returns an enumerator that can iterate through the Deque. + /// + /// + /// An IEnumerator for the Deque. + /// + IEnumerator IEnumerable.GetEnumerator() + { + lock(root) + { + return ((IEnumerable)deque).GetEnumerator(); + } + } + + #endregion + + #region Properties + + public override int Count + { + get + { + lock(root) + { + return deque.Count; + } + } + } + + public override bool IsSynchronized + { + get + { + return true; + } + } + + #endregion + + #endregion + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.cs new file mode 100644 index 0000000..686ea28 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/Deque/GenericDeque.cs @@ -0,0 +1,604 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Sanford.Collections.Generic +{ + /// + /// Represents a simple double-ended-queue collection of objects. + /// + [Serializable()] + public partial class Deque : ICollection, IEnumerable, ICloneable + { + #region Deque Members + + #region Fields + + // The node at the front of the deque. + private Node front = null; + + // The node at the back of the deque. + private Node back = null; + + // The number of elements in the deque. + private int count = 0; + + // The version of the deque. + private long version = 0; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the Deque class. + /// + public Deque() + { + } + + /// + /// Initializes a new instance of the Deque class that contains + /// elements copied from the specified collection. + /// + /// + /// The collection whose elements are copied to the new Deque. + /// + public Deque(IEnumerable collection) + { + #region Require + + if(collection == null) + { + throw new ArgumentNullException("col"); + } + + #endregion + + foreach(T item in collection) + { + PushBack(item); + } + } + + #endregion + + #region Methods + + /// + /// Removes all objects from the Deque. + /// + public virtual void Clear() + { + count = 0; + + front = back = null; + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Determines whether or not an element is in the Deque. + /// + /// + /// The Object to locate in the Deque. + /// + /// + /// true if obj if found in the Deque; otherwise, + /// false. + /// + public virtual bool Contains(T obj) + { + foreach(T o in this) + { + if(EqualityComparer.Default.Equals(o, obj)) + { + return true; + } + } + + return false; + } + + /// + /// Inserts an object at the front of the Deque. + /// + /// + /// The object to push onto the deque; + /// + public virtual void PushFront(T item) + { + // The new node to add to the front of the deque. + Node newNode = new Node(item); + + // Link the new node to the front node. The current front node at + // the front of the deque is now the second node in the deque. + newNode.Next = front; + + // If the deque isn't empty. + if(Count > 0) + { + // Link the current front to the new node. + front.Previous = newNode; + } + + // Make the new node the front of the deque. + front = newNode; + + // Keep track of the number of elements in the deque. + count++; + + // If this is the first element in the deque. + if(Count == 1) + { + // The front and back nodes are the same. + back = front; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Inserts an object at the back of the Deque. + /// + /// + /// The object to push onto the deque; + /// + public virtual void PushBack(T item) + { + // The new node to add to the back of the deque. + Node newNode = new Node(item); + + // Link the new node to the back node. The current back node at + // the back of the deque is now the second to the last node in the + // deque. + newNode.Previous = back; + + // If the deque is not empty. + if(Count > 0) + { + // Link the current back node to the new node. + back.Next = newNode; + } + + // Make the new node the back of the deque. + back = newNode; + + // Keep track of the number of elements in the deque. + count++; + + // If this is the first element in the deque. + if(Count == 1) + { + // The front and back nodes are the same. + front = back; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Removes and returns the object at the front of the Deque. + /// + /// + /// The object at the front of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual T PopFront() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + // Get the object at the front of the deque. + T item = front.Value; + + // Move the front back one node. + front = front.Next; + + // Keep track of the number of nodes in the deque. + count--; + + // If the deque is not empty. + if(Count > 0) + { + // Tie off the previous link in the front node. + front.Previous = null; + } + // Else the deque is empty. + else + { + // Indicate that there is no back node. + back = null; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + + return item; + } + + /// + /// Removes and returns the object at the back of the Deque. + /// + /// + /// The object at the back of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual T PopBack() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + // Get the object at the back of the deque. + T item = back.Value; + + // Move back node forward one node. + back = back.Previous; + + // Keep track of the number of nodes in the deque. + count--; + + // If the deque is not empty. + if(Count > 0) + { + // Tie off the next link in the back node. + back.Next = null; + } + // Else the deque is empty. + else + { + // Indicate that there is no front node. + front = null; + } + + version++; + + #region Invariant + + AssertValid(); + + #endregion + + return item; + } + + /// + /// Returns the object at the front of the Deque without removing it. + /// + /// + /// The object at the front of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual T PeekFront() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + return front.Value; + } + + /// + /// Returns the object at the back of the Deque without removing it. + /// + /// + /// The object at the back of the Deque. + /// + /// + /// The Deque is empty. + /// + public virtual T PeekBack() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException("Deque is empty."); + } + + #endregion + + return back.Value; + } + + /// + /// Copies the Deque to a new array. + /// + /// + /// A new array containing copies of the elements of the Deque. + /// + public virtual T[] ToArray() + { + T[] array = new T[Count]; + int index = 0; + + foreach(T item in this) + { + array[index] = item; + index++; + } + + return array; + } + + /// + /// Returns a synchronized (thread-safe) wrapper for the Deque. + /// + /// + /// The Deque to synchronize. + /// + /// + /// A synchronized wrapper around the Deque. + /// + public static Deque Synchronized(Deque deque) + { + #region Require + + if(deque == null) + { + throw new ArgumentNullException("deque"); + } + + #endregion + + return new SynchronizedDeque(deque); + } + + [Conditional("DEBUG")] + private void AssertValid() + { + int n = 0; + Node current = front; + + while(current != null) + { + n++; + current = current.Next; + } + + Debug.Assert(n == Count); + + if(Count > 0) + { + Debug.Assert(front != null && back != null, "Front/Back Null Test - Count > 0"); + + Node f = front; + Node b = back; + + while(f.Next != null && b.Previous != null) + { + f = f.Next; + b = b.Previous; + } + + Debug.Assert(f.Next == null && b.Previous == null, "Front/Back Termination Test"); + Debug.Assert(f == back && b == front, "Front/Back Equality Test"); + } + else + { + Debug.Assert(front == null && back == null, "Front/Back Null Test - Count == 0"); + } + } + + #endregion + + #endregion + + #region ICollection Members + + /// + /// Gets a value indicating whether access to the Deque is synchronized + /// (thread-safe). + /// + public virtual bool IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets the number of elements contained in the Deque. + /// + public virtual int Count + { + get + { + return count; + } + } + + /// + /// Copies the Deque elements to an existing one-dimensional Array, + /// starting at the specified array index. + /// + /// + /// The one-dimensional Array that is the destination of the elements + /// copied from Deque. The Array must have zero-based indexing. + /// + /// + /// The zero-based index in array at which copying begins. + /// + public virtual void CopyTo(Array array, int index) + { + #region Require + + if(array == null) + { + throw new ArgumentNullException("array"); + } + else if(index < 0) + { + throw new ArgumentOutOfRangeException("index", index, + "Index is less than zero."); + } + else if(array.Rank > 1) + { + throw new ArgumentException("Array is multidimensional."); + } + else if(index >= array.Length) + { + throw new ArgumentException("Index is equal to or greater " + + "than the length of array."); + } + else if(Count > array.Length - index) + { + throw new ArgumentException( + "The number of elements in the source Deque is greater " + + "than the available space from index to the end of the " + + "destination array."); + } + + #endregion + + int i = index; + + foreach(object obj in this) + { + array.SetValue(obj, i); + i++; + } + } + + /// + /// Gets an object that can be used to synchronize access to the Deque. + /// + public virtual object SyncRoot + { + get + { + return this; + } + } + + #endregion + + #region IEnumerable Members + + /// + /// Returns an enumerator that can iterate through the Deque. + /// + /// + /// An IEnumerator for the Deque. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator(this); + } + + #endregion + + #region ICloneable Members + + /// + /// Creates a shallow copy of the Deque. + /// + /// + /// A shallow copy of the Deque. + /// + public virtual object Clone() + { + Deque clone = new Deque(this); + + clone.version = this.version; + + return clone; + } + + #endregion + + #region IEnumerable Members + + /// + /// Gets and returns the Enumerator. + /// + public virtual IEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/ICommand.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/ICommand.cs new file mode 100644 index 0000000..8a74f1e --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/ICommand.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Collections.Generic +{ + internal interface ICommand + { + void Execute(); + void Undo(); + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoManager.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoManager.cs new file mode 100644 index 0000000..4910b72 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoManager.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; + +namespace Sanford.Collections.Generic +{ + internal class UndoManager + { + private Stack undoStack = new Stack(); + + private Stack redoStack = new Stack(); + + #region Methods + + public void Execute(ICommand command) + { + command.Execute(); + + undoStack.Push(command); + redoStack.Clear(); + } + + /// + /// Undoes the last operation. + /// + /// + /// true if the last operation was undone, false if there + /// are no more operations left to undo. + /// + public bool Undo() + { + #region Guard + + if(undoStack.Count == 0) + { + return false; + } + + #endregion + + ICommand command = undoStack.Pop(); + + command.Undo(); + + redoStack.Push(command); + + return true; + } + + /// + /// Redoes the last operation. + /// + /// + /// true if the last operation was redone, false if there + /// are no more operations left to redo. + /// + public bool Redo() + { + #region Guard + + if(redoStack.Count == 0) + { + return false; + } + + #endregion + + ICommand command = redoStack.Pop(); + + command.Execute(); + + undoStack.Push(command); + + return true; + } + + /// + /// Clears the undo/redo history. + /// + public void ClearHistory() + { + undoStack.Clear(); + redoStack.Clear(); + } + + #endregion + + #region Properties + + /// + /// The number of operations left to undo. + /// + public int UndoCount + { + get + { + return undoStack.Count; + } + } + + /// + /// The number of operations left to redo. + /// + public int RedoCount + { + get + { + return redoStack.Count; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Commands.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Commands.cs new file mode 100644 index 0000000..e54f997 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Commands.cs @@ -0,0 +1,511 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Sanford.Collections.Generic +{ + public partial class UndoableList : IList + { + + #region SetCommand + + private class SetCommand : ICommand + { + private IList theList; + + private int index; + + private T oldItem; + + private T newItem; + + private bool undone = true; + + public SetCommand(IList theList, int index, T item) + { + this.theList = theList; + this.index = index; + this.newItem = item; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index < theList.Count); + + oldItem = theList[index]; + theList[index] = newItem; + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index < theList.Count); + Debug.Assert(theList[index].Equals(newItem)); + + theList[index] = oldItem; + undone = true; + } + + #endregion + } + + #endregion + + #region InsertCommand + + private class InsertCommand : ICommand + { + private IList theList; + + private int index; + + private T item; + + private bool undone = true; + + private int count; + + public InsertCommand(IList theList, int index, T item) + { + this.theList = theList; + this.index = index; + this.item = item; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index <= theList.Count); + + count = theList.Count; + theList.Insert(index, item); + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index <= theList.Count); + Debug.Assert(theList[index].Equals(item)); + + theList.RemoveAt(index); + undone = true; + + Debug.Assert(theList.Count == count); + } + + #endregion + } + + #endregion + + #region InsertRangeCommand + + private class InsertRangeCommand : ICommand + { + private List theList; + + private int index; + + private List insertList; + + private bool undone = true; + + public InsertRangeCommand(List theList, int index, IEnumerable collection) + { + this.theList = theList; + this.index = index; + + insertList = new List(collection); + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index <= theList.Count); + + theList.InsertRange(index, insertList); + + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index <= theList.Count); + + theList.RemoveRange(index, insertList.Count); + + undone = true; + } + + #endregion + } + + #endregion + + #region RemoveAtCommand + + private class RemoveAtCommand : ICommand + { + private IList theList; + + private int index; + + private T item; + + private bool undone = true; + + private int count; + + public RemoveAtCommand(IList theList, int index) + { + this.theList = theList; + this.index = index; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index < theList.Count); + + item = theList[index]; + count = theList.Count; + theList.RemoveAt(index); + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index < theList.Count); + + theList.Insert(index, item); + undone = true; + + Debug.Assert(theList.Count == count); + } + + #endregion + } + + #endregion + + #region RemoveRangeCommand + + private class RemoveRangeCommand : ICommand + { + private List theList; + + private int index; + + private int count; + + private List rangeList = new List(); + + private bool undone = true; + + public RemoveRangeCommand(List theList, int index, int count) + { + this.theList = theList; + this.index = index; + this.count = count; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + Debug.Assert(index >= 0 && index < theList.Count); + Debug.Assert(index + count <= theList.Count); + + rangeList = new List(theList.GetRange(index, count)); + + theList.RemoveRange(index, count); + + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + theList.InsertRange(index, rangeList); + + undone = true; + } + + #endregion + } + + #endregion + + #region ClearCommand + + private class ClearCommand : ICommand + { + private IList theList; + + private IList undoList; + + private bool undone = true; + + public ClearCommand(IList theList) + { + this.theList = theList; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + undoList = new List(theList); + + theList.Clear(); + + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + Debug.Assert(theList.Count == 0); + + foreach(T item in undoList) + { + theList.Add(item); + } + + undoList.Clear(); + + undone = true; + } + + #endregion + } + + #endregion + + #region ReverseCommand + + private class ReverseCommand : ICommand + { + private List theList; + + private int index; + + private int count; + + private bool reverseRange; + + private bool undone = true; + + public ReverseCommand(List theList) + { + this.theList = theList; + this.reverseRange = false; + } + + public ReverseCommand(List theList, int index, int count) + { + this.theList = theList; + this.index = index; + this.count = count; + this.reverseRange = true; + } + + #region ICommand Members + + public void Execute() + { + #region Guard + + if(!undone) + { + return; + } + + #endregion + + if(reverseRange) + { + theList.Reverse(index, count); + } + else + { + theList.Reverse(); + } + + undone = false; + } + + public void Undo() + { + #region Guard + + if(undone) + { + return; + } + + #endregion + + if(reverseRange) + { + theList.Reverse(index, count); + } + else + { + theList.Reverse(); + } + + undone = true; + } + + #endregion + } + + #endregion + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Test.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Test.cs new file mode 100644 index 0000000..e8167ca --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.Test.cs @@ -0,0 +1,277 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Sanford.Collections.Generic +{ + public partial class UndoableList : IList + { + /// + /// This is the main command that will test the UndoableList. + /// + [Conditional("DEBUG")] + public static void Test() + { + int count = 10; + List comparisonList = new List(count); + UndoableList undoList = new UndoableList(count); + + PopulateLists(comparisonList, undoList, count); + TestAdd(comparisonList, undoList); + TestClear(comparisonList, undoList); + TestInsert(comparisonList, undoList); + TestInsertRange(comparisonList, undoList); + TestRemove(comparisonList, undoList); + TestRemoveAt(comparisonList, undoList); + TestRemoveRange(comparisonList, undoList); + TestReverse(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestAdd(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + Stack redoStack = new Stack(); + + while(comparisonList.Count > 0) + { + redoStack.Push(comparisonList[comparisonList.Count - 1]); + comparisonList.RemoveAt(comparisonList.Count - 1); + Debug.Assert(undoList.Undo()); + TestEquals(comparisonList, undoList); + } + + while(redoStack.Count > 0) + { + comparisonList.Add(redoStack.Pop()); + Debug.Assert(undoList.Redo()); + TestEquals(comparisonList, undoList); + } + } + + [Conditional("DEBUG")] + private static void TestClear(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + undoList.Clear(); + + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestInsert(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + int index = comparisonList.Count / 2; + + comparisonList.Insert(index, 999); + undoList.Insert(index, 999); + + comparisonList.RemoveAt(index); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + + comparisonList.Insert(index, 999); + Debug.Assert(undoList.Redo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestInsertRange(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + int[] range = { 1, 2, 3, 4, 5 }; + int index = comparisonList.Count / 2; + + comparisonList.InsertRange(index, range); + undoList.InsertRange(index, range); + + TestEquals(comparisonList, undoList); + + comparisonList.RemoveRange(index, range.Length); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + + comparisonList.InsertRange(index, range); + Debug.Assert(undoList.Redo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestRemove(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + int index = comparisonList.Count / 2; + + int item = comparisonList[index]; + + comparisonList.Remove(item); + undoList.Remove(item); + + TestEquals(comparisonList, undoList); + + comparisonList.Insert(index, item); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestRemoveAt(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + int index = comparisonList.Count / 2; + + int item = comparisonList[index]; + + comparisonList.RemoveAt(index); + undoList.RemoveAt(index); + + TestEquals(comparisonList, undoList); + + comparisonList.Insert(index, item); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestRemoveRange(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + int index = comparisonList.Count / 2; + int count = comparisonList.Count - index; + + List range = comparisonList.GetRange(index, count); + + comparisonList.RemoveRange(index, count); + undoList.RemoveRange(index, count); + + TestEquals(comparisonList, undoList); + + comparisonList.InsertRange(index, range); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void TestReverse(List comparisonList, UndoableList undoList) + { + TestEquals(comparisonList, undoList); + + comparisonList.Reverse(); + undoList.Reverse(); + + TestEquals(comparisonList, undoList); + + comparisonList.Reverse(); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + + comparisonList.Reverse(); + Debug.Assert(undoList.Redo()); + + TestEquals(comparisonList, undoList); + + int count = comparisonList.Count / 2; + + comparisonList.Reverse(0, count); + undoList.Reverse(0, count); + + TestEquals(comparisonList, undoList); + + comparisonList.Reverse(0, count); + Debug.Assert(undoList.Undo()); + + TestEquals(comparisonList, undoList); + + comparisonList.Reverse(0, count); + Debug.Assert(undoList.Redo()); + + TestEquals(comparisonList, undoList); + } + + [Conditional("DEBUG")] + private static void PopulateLists(IList a, IList b, int count) + { + Random r = new Random(); + int item; + + for(int i = 0; i < count; i++) + { + item = r.Next(); + a.Add(item); + b.Add(item); + } + } + + [Conditional("DEBUG")] + private static void TestEquals(ICollection a, ICollection b) + { + bool equals = true; + + if(a.Count != b.Count) + { + equals = false; + } + IEnumerator aEnumerator = a.GetEnumerator(); + IEnumerator bEnumerator = b.GetEnumerator(); + + while(equals && aEnumerator.MoveNext() && bEnumerator.MoveNext()) + { + equals = aEnumerator.Current.Equals(bEnumerator.Current); + } + + Debug.Assert(equals); + } + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.cs new file mode 100644 index 0000000..866b907 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Generic/UndoableList/UndoableList.cs @@ -0,0 +1,530 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Sanford.Collections.Generic +{ + /// + /// Represents a list with undo/redo functionality. + /// + /// + /// The type of elements in the list. + /// + public partial class UndoableList : IList + { + #region UndoableList Members + + #region Fields + + private List theList; + + private UndoManager undoManager = new UndoManager(); + + #endregion + + #region Construction + + /// + /// The undoable construction list. + /// + public UndoableList() + { + theList = new List(); + } + + /// + /// The collection list of undoables. + /// + public UndoableList(IEnumerable collection) + { + theList = new List(collection); + } + + /// + /// The capacity list of undoables. + /// + public UndoableList(int capacity) + { + theList = new List(capacity); + } + + #endregion + + #region Methods + + /// + /// Undoes the last operation. + /// + /// + /// true if the last operation was undone, false if there + /// are no more operations left to undo. + /// + public bool Undo() + { + return undoManager.Undo(); + } + + /// + /// Redoes the last operation. + /// + /// + /// true if the last operation was redone, false if there + /// are no more operations left to redo. + /// + public bool Redo() + { + return undoManager.Redo(); + } + + /// + /// Clears the undo/redo history. + /// + public void ClearHistory() + { + undoManager.ClearHistory(); + } + + #region List Wrappers + + /// + /// Searches the entire list for an element using the default comparer. + /// + public int BinarySearch(T item) + { + return theList.BinarySearch(item); + } + + /// + /// Searches the entire list for an element using a specified comparer. + /// + public int BinarySearch(T item, IComparer comparer) + { + return theList.BinarySearch(item, comparer); + } + + /// + /// Searches a range of elements in the sorted list for an element using a specified comparer. + /// + public int BinarySearch(int index, int count, T item, IComparer comparer) + { + return theList.BinarySearch(index, count, item, comparer); + } + + /// + /// Determines whenever the list contains the undo/redo option. + /// + public bool Contains(T item) + { + return theList.Contains(item); + } + + /// + /// Converts all the data that is being read into the option chosen. + /// + public List ConvertAll(Converter converter) + { + return theList.ConvertAll(converter); + } + + /// + /// If the data exists and matches, it returns the value as true. + /// + public bool Exists(Predicate match) + { + return theList.Exists(match); + } + + /// + /// Initiates trying to find the data that matches. + /// + public T Find(Predicate match) + { + return theList.Find(match); + } + + /// + /// Initiates trying to find all the data results that match. + /// + public List FindAll(Predicate match) + { + return theList.FindAll(match); + } + + /// + /// Finds the index to the data. + /// + public int FindIndex(Predicate match) + { + return theList.FindIndex(match); + } + + /// + /// Finds the index to the data based on the start of the index. + /// + public int FindIndex(int startIndex, Predicate match) + { + return theList.FindIndex(startIndex, match); + } + + /// + /// Finds the index to the data based on the start of the index and the count. + /// + public int FindIndex(int startIndex, int count, Predicate match) + { + return theList.FindIndex(startIndex, count, match); + } + + /// + /// Searches for an element that matches the conditions defined by the T in Predicate, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + /// + public int FindLastIndex(Predicate match) + { + return theList.FindLastIndex(match); + } + + /// + /// Searches for an element that matches the conditions defined by the T in Predicate and extended from the start of the index, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + /// + public int FindLastIndex(int startIndex, Predicate match) + { + return theList.FindLastIndex(startIndex, match); + } + + /// + /// Searches for an element that matches the conditions defined by the T in Predicate and extended from the start of the index and to show a specific number of options, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + /// + public int FindLastIndex(int startIndex, int count, Predicate match) + { + return theList.FindLastIndex(startIndex, count, match); + } + + /// + /// Searches for an element that matches the conditions defined by T, then returns the last element that matches, otherwise it will be T by default. + /// + public T FindLast(Predicate match) + { + return theList.FindLast(match); + } + + /// + /// Searches for the item, then returns the last occurrence of the item in the list. + /// + public int LastIndexOf(T item) + { + return theList.LastIndexOf(item); + } + + /// + /// Searches for the item, then returns the last occurrence of the item within the range of elements in the list. + /// + public int LastIndexOf(T item, int index) + { + return theList.LastIndexOf(item, index); + } + + /// + /// Searches for the item, then returns the last occurrence of the item within the range of elements in the list and contains a specified number of elements and ends at the specific index. + /// + public int LastIndexOf(T item, int index, int count) + { + return theList.LastIndexOf(item, index, count); + } + + /// + /// Determines whenever every element in the list matches the conditions set by the Predicate. + /// + public bool TrueForAll(Predicate match) + { + return theList.TrueForAll(match); + } + + /// + /// Copies the elements of the list to a new array. + /// + public T[] ToArray() + { + return theList.ToArray(); + } + + /// + /// Sets the capacity to the actual number of elements in the list, if the number is less than a threshold value. + /// + public void TrimExcess() + { + theList.TrimExcess(); + } + + /// + /// Adds a range of elements to insert from the list with the number of elements. + /// + public void AddRange(IEnumerable collection) + { + InsertRangeCommand command = new InsertRangeCommand(theList, theList.Count, collection); + + undoManager.Execute(command); + } + + /// + /// Inserts the range of elements from the list index into the undo/redo manager. + /// + public void InsertRange(int index, IEnumerable collection) + { + InsertRangeCommand command = new InsertRangeCommand(theList, index, collection); + + undoManager.Execute(command); + } + + /// + /// Removes a range of elements to insert from the list with the number of elements. + /// + public void RemoveRange(int index, int count) + { + RemoveRangeCommand command = new RemoveRangeCommand(theList, index, count); + + undoManager.Execute(command); + } + + /// + /// Reverts any added element or any removed element from the list. + /// + public void Reverse() + { + ReverseCommand command = new ReverseCommand(theList); + + undoManager.Execute(command); + } + + /// + /// Reverts any added element or any removed element from the list and shows the number of elements. + /// + public void Reverse(int index, int count) + { + ReverseCommand command = new ReverseCommand(theList, index, count); + + undoManager.Execute(command); + } + + #endregion + + #endregion + + #region Properties + + /// + /// The number of operations left to undo. + /// + public int UndoCount + { + get + { + return undoManager.UndoCount; + } + } + + /// + /// The number of operations left to redo. + /// + public int RedoCount + { + get + { + return undoManager.RedoCount; + } + } + + #endregion + + #endregion + + #region IList Members + + /// + /// Searches for a list of undo/redo functions via an index. + /// + public int IndexOf(T item) + { + return theList.IndexOf(item); + } + + /// + /// Inserts the undo/redo listed options from the index. + /// + public void Insert(int index, T item) + { + InsertCommand command = new InsertCommand(theList, index, item); + + undoManager.Execute(command); + } + + /// + /// Allows to remove the undo/redo options listed by command. + /// + public void RemoveAt(int index) + { + RemoveAtCommand command = new RemoveAtCommand(theList, index); + + undoManager.Execute(command); + } + + /// + /// Gets or sets the undo/redo options from the list. + /// + public T this[int index] + { + get + { + return theList[index]; + } + set + { + SetCommand command = new SetCommand(theList, index, value); + + undoManager.Execute(command); + } + } + + #endregion + + #region ICollection Members + + /// + /// Adds an undo/redo option to the list of undo/redo options. + /// + public void Add(T item) + { + InsertCommand command = new InsertCommand(theList, Count, item); + + undoManager.Execute(command); + } + + /// + /// Clears an undo/redo option from the list of undo/redo options. + /// + public void Clear() + { + #region Guard + + if(Count == 0) + { + return; + } + + #endregion + + ClearCommand command = new ClearCommand(theList); + + undoManager.Execute(command); + } + + /// + /// Copies an undo/redo option from the list to an array. + /// + public void CopyTo(T[] array, int arrayIndex) + { + theList.CopyTo(array, arrayIndex); + } + + /// + /// Counts the list of undo/redo options from the list. + /// + public int Count + { + get + { + return theList.Count; + } + } + + /// + /// Checks if the list is read only, and returns if it is false. + /// + public bool IsReadOnly + { + get + { + return false; + } + } + + /// + /// Removes an undo/redo option from the list. + /// + public bool Remove(T item) + { + int index = IndexOf(item); + bool result; + + if(index >= 0) + { + RemoveAtCommand command = new RemoveAtCommand(theList, index); + + undoManager.Execute(command); + + result = true; + } + else + { + result = false; + } + + return result; + } + + #endregion + + #region IEnumerable Members + + /// + /// Gets an enumerator and returns an enumerator that iterates through the list. + /// + public IEnumerator GetEnumerator() + { + return theList.GetEnumerator(); + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return theList.GetEnumerator(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlEnumerator.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlEnumerator.cs new file mode 100644 index 0000000..03e84f0 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlEnumerator.cs @@ -0,0 +1,167 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Provides functionality for iterating over an AVL tree. + /// + internal class AvlEnumerator : IEnumerator + { + #region AvlEnumerator Members + + #region Instance Fields + + // The root of the AVL tree. + private IAvlNode root; + + // The number of nodes in the tree. + private readonly int count; + + // The object at the current position. + private object current = null; + + // The current index. + private int index; + + // Used for traversing the tree inorder. + private System.Collections.Stack nodeStack = new System.Collections.Stack(); + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the AvlEnumerator class. + /// + /// + /// The root of the AVL tree to iterate over. + /// + public AvlEnumerator(IAvlNode root) + { + this.root = root; + this.count = root.Count; + + Reset(); + } + + /// + /// Initializes a new instance of the AvlEnumerator class. + /// + /// + /// The root of the AVL tree to iterate over. + /// + /// + /// The number of nodes in the tree. + /// + public AvlEnumerator(IAvlNode root, int count) + { + Debug.Assert(count <= root.Count); + + this.root = root; + this.count = count; + + Reset(); + } + + #endregion + + #endregion + + #region IEnumerator Members + + /// + /// Sets the enumerator to its initial position, which is before + /// the first element in the AVL tree. + /// + public void Reset() + { + index = 0; + + nodeStack.Clear(); + + IAvlNode currentNode = root; + + // Push nodes on to the stack to get to the first item. + while(currentNode != AvlNode.NullNode) + { + nodeStack.Push(currentNode); + currentNode = currentNode.LeftChild; + } + } + + /// + /// Gets the current element in the AVL tree. + /// + /// + /// The enumerator is positioned before the first element in the AVL + /// tree or after the last element. + /// + public object Current + { + get + { + if(index == 0) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the collection or after the last " + + "element."); + } + + return current; + } + } + + /// + /// Advances the enumerator to the next element of the AVL tree. + /// + /// + /// true if the enumerator was successfully advanced to the + /// next element; false if the enumerator has passed the end + /// of the collection. + /// + public bool MoveNext() + { + bool result; + + // If the end of the AVL tree has not yet been reached. + if(index < count) + { + // Get the next node. + IAvlNode currentNode = (IAvlNode)nodeStack.Pop(); + + current = currentNode.Data; + + currentNode = currentNode.RightChild; + + while(currentNode != AvlNode.NullNode) + { + nodeStack.Push(currentNode); + currentNode = currentNode.LeftChild; + } + + index++; + + result = true; + } + else + { + result = false; + } + + return result; + } + + #endregion + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlNode.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlNode.cs new file mode 100644 index 0000000..5c89cb0 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/AvlNode.cs @@ -0,0 +1,440 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents a node in an AVL tree. + /// + [ImmutableObject(true)] + internal class AvlNode : IAvlNode + { + #region AvlNode Members + + #region Class Fields + + // For use as a null node. + public static readonly NullAvlNode NullNode = new NullAvlNode(); + + #endregion + + #region Instance Fields + + // The data represented by this node. + private readonly object data; + + // The number of nodes in the subtree. + private readonly int count; + + // The height of this node. + private readonly int height; + + // Left and right children. + private readonly IAvlNode leftChild; + private readonly IAvlNode rightChild; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the AvlNode class with the specified + /// data and left and right children. + /// + /// + /// The data for the node. + /// + /// + /// The left child. + /// + /// + /// The right child. + /// + public AvlNode(object data, IAvlNode leftChild, IAvlNode rightChild) + { + // Preconditions. + Debug.Assert(leftChild != null && rightChild != null); + + this.data = data; + this.leftChild = leftChild; + this.rightChild = rightChild; + + count = 1 + leftChild.Count + rightChild.Count; + height = 1 + Math.Max(leftChild.Height, rightChild.Height); + } + + #endregion + + #region Methods + + #region Rotation Methods + + // Left - left single rotation. + private IAvlNode DoLLRotation(IAvlNode node) + { + /* + * An LL rotation looks like the following: + * + * A B + * / / \ + * B ---> C A + * / + * C + */ + + // Create right child of the new root. + IAvlNode a = new AvlNode( + node.Data, + node.LeftChild.RightChild, + node.RightChild); + + IAvlNode b = new AvlNode( + node.LeftChild.Data, + node.LeftChild.LeftChild, + a); + + // Postconditions. + Debug.Assert(b.Data == node.LeftChild.Data); + Debug.Assert(b.LeftChild == node.LeftChild.LeftChild); + Debug.Assert(b.RightChild.Data == node.Data); + + return b; + } + + // Left - right double rotation. + private IAvlNode DoLRRotation(IAvlNode node) + { + /* + * An LR rotation looks like the following: + * + * Perform an RR rotation at B: + * + * A A + * / / + * B ---> C + * \ / + * C B + * + * Perform an LL rotation at A: + * + * A C + * / / \ + * C ---> B A + * / + * B + */ + + IAvlNode a = new AvlNode( + node.Data, + DoRRRotation(node.LeftChild), + node.RightChild); + + IAvlNode c = DoLLRotation(a); + + // Postconditions. + Debug.Assert(c.Data == node.LeftChild.RightChild.Data); + Debug.Assert(c.LeftChild.Data == node.LeftChild.Data); + Debug.Assert(c.RightChild.Data == node.Data); + + return c; + } + + // Right - right single rotation. + private IAvlNode DoRRRotation(IAvlNode node) + { + /* + * An RR rotation looks like the following: + * + * A B + * \ / \ + * B ---> A C + * \ + * C + */ + + // Create left child of the new root. + IAvlNode a = new AvlNode( + node.Data, + node.LeftChild, + node.RightChild.LeftChild); + + IAvlNode b = new AvlNode( + node.RightChild.Data, + a, + node.RightChild.RightChild); + + // Postconditions. + Debug.Assert(b.Data == node.RightChild.Data); + Debug.Assert(b.RightChild == node.RightChild.RightChild); + Debug.Assert(b.LeftChild.Data == node.Data); + + return b; + } + + // Right - left double rotation. + private IAvlNode DoRLRotation(IAvlNode node) + { + /* + * An RL rotation looks like the following: + * + * Perform an LL rotation at B: + * + * A A + * \ \ + * B ---> C + * / \ + * C B + * + * Perform an RR rotation at A: + * + * A C + * \ / \ + * C ---> A B + * \ + * B + */ + + IAvlNode a = new AvlNode( + node.Data, + node.LeftChild, + DoLLRotation(node.RightChild)); + + IAvlNode c = DoRRRotation(a); + + // Postconditions. + Debug.Assert(c.Data == node.RightChild.LeftChild.Data); + Debug.Assert(c.LeftChild.Data == node.Data); + Debug.Assert(c.RightChild.Data == node.RightChild.Data); + + return c; + } + + #endregion + + #endregion + + #endregion + + #region IAvlNode Members + + /// + /// Removes the current node from the AVL tree. + /// + /// + /// The node to in the tree to replace the current node. + /// + public IAvlNode Remove() + { + IAvlNode result; + + /* + * Deal with the three cases for removing a node from a binary tree. + */ + + // If the node has no right children. + if(this.RightChild == AvlNode.NullNode) + { + // The replacement node is the node's left child. + result = this.LeftChild; + } + // Else if the node's right child has no left children. + else if(this.RightChild.LeftChild == AvlNode.NullNode) + { + // The replacement node is the node's right child. + result = new AvlNode( + this.RightChild.Data, + this.LeftChild, + this.RightChild.RightChild); + } + // Else the node's right child has left children. + else + { + /* + * Go to the node's right child and descend as far left as + * possible. The node found at this point will replace the + * node to be removed. + */ + + IAvlNode replacement = AvlNode.NullNode; + IAvlNode rightChild = RemoveReplacement(this.RightChild, ref replacement); + + // Create new node with the replacement node and the new + // right child. + result = new AvlNode( + replacement.Data, + this.LeftChild, + rightChild); + } + + return result; + } + + // Finds and removes replacement node for deletion (third case). + private IAvlNode RemoveReplacement(IAvlNode node, ref IAvlNode replacement) + { + IAvlNode newNode; + + // If the bottom of the left tree has been found. + if(node.LeftChild == AvlNode.NullNode) + { + // The replacement node is the node found at this point. + replacement = node; + + // Get the node's right child. This will be needed as we + // ascend back up the tree. + newNode = node.RightChild; + } + // Else the bottom of the left tree has not been found. + else + { + // Create new node and continue descending down the left tree. + newNode = new AvlNode(node.Data, + RemoveReplacement(node.LeftChild, ref replacement), + node.RightChild); + + // If the node is out of balance. + if(!newNode.IsBalanced()) + { + // Rebalance the node. + newNode = newNode.Balance(); + } + } + + // Postconditions. + Debug.Assert(newNode.IsBalanced()); + + return newNode; + } + + /// + /// Balances the subtree represented by the node. + /// + /// + /// The root node of the balanced subtree. + /// + public IAvlNode Balance() + { + IAvlNode result; + + if(BalanceFactor < -1) + { + if(leftChild.BalanceFactor < 0) + { + result = DoLLRotation(this); + } + else + { + result = DoLRRotation(this); + } + } + else if(BalanceFactor > 1) + { + if(rightChild.BalanceFactor > 0) + { + result = DoRRRotation(this); + } + else + { + result = DoRLRotation(this); + } + } + else + { + result = this; + } + + Debug.Assert(result.IsBalanced()); + + return result; + } + + /// + /// Indicates whether or not the subtree the node represents is in + /// balance. + /// + /// + /// true if the subtree is in balance; otherwise, false. + /// + public bool IsBalanced() + { + return BalanceFactor >= -1 && BalanceFactor <= 1; + } + + /// + /// Gets the balance factor of the subtree the node represents. + /// + public int BalanceFactor + { + get + { + return rightChild.Height - leftChild.Height; + } + } + + /// + /// Gets the number of nodes in the subtree. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets the node's data. + /// + public object Data + { + get + { + return data; + } + } + + /// + /// Gets the height of the subtree the node represents. + /// + public int Height + { + get + { + return height; + } + } + + /// + /// Gets the node's left child. + /// + public IAvlNode LeftChild + { + get + { + return leftChild; + } + } + + /// + /// Gets the node's right child. + /// + public IAvlNode RightChild + { + get + { + return rightChild; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/IAvlNode.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/IAvlNode.cs new file mode 100644 index 0000000..7715416 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/IAvlNode.cs @@ -0,0 +1,91 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents the functionality and properties of AVL nodes. + /// + internal interface IAvlNode + { + /// + /// Removes the current node from the AVL tree. + /// + /// + /// The node to in the tree to replace the current node. + /// + IAvlNode Remove(); + + /// + /// Balances the subtree represented by the node. + /// + /// + /// The root node of the balanced subtree. + /// + IAvlNode Balance(); + + /// + /// Indicates whether or not the subtree the node represents is in + /// balance. + /// + /// + /// true if the subtree is in balance; otherwise, false. + /// + bool IsBalanced(); + + /// + /// Gets the balance factor of the subtree the node represents. + /// + int BalanceFactor + { + get; + } + + /// + /// Gets the number of nodes in the subtree. + /// + int Count + { + get; + } + + /// + /// Gets the node's data. + /// + object Data + { + get; + } + + /// + /// Gets the height of the subtree the node represents. + /// + int Height + { + get; + } + + /// + /// Gets the node's left child. + /// + IAvlNode LeftChild + { + get; + } + + /// + /// Gets the node's right child. + /// + IAvlNode RightChild + { + get; + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/NullAvlNode.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/NullAvlNode.cs new file mode 100644 index 0000000..dabf81f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/AVL Tree Classes/NullAvlNode.cs @@ -0,0 +1,124 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.ComponentModel; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents a null AVL node. + /// + [ImmutableObject(true)] + internal class NullAvlNode : IAvlNode + { + #region IAvlNode Members + + /// + /// Removes the current node from the AVL tree. + /// + /// + /// The node to in the tree to replace the current node. + /// + public IAvlNode Remove() + { + return this; + } + + /// + /// Balances the subtree represented by the node. + /// + /// + /// The root node of the balanced subtree. + /// + public IAvlNode Balance() + { + return this; + } + + /// + /// Indicates whether or not the subtree the node represents is in + /// balance. + /// + /// + /// true if the subtree is in balance; otherwise, false. + /// + public bool IsBalanced() + { + return true; + } + + /// + /// Gets the balance factor of the subtree the node represents. + /// + public int BalanceFactor + { + get + { + return 0; + } + } + + /// + /// Gets the number of nodes in the subtree. + /// + public int Count + { + get + { + return 0; + } + } + + /// + /// Gets the node's data. + /// + public object Data + { + get + { + return null; + } + } + + /// + /// Gets the height of the subtree the node represents. + /// + public int Height + { + get + { + return 0; + } + } + + /// + /// Gets the node's left child. + /// + public IAvlNode LeftChild + { + get + { + return this; + } + } + + /// + /// Gets the node's right child. + /// + public IAvlNode RightChild + { + get + { + return this; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Array.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Array.cs new file mode 100644 index 0000000..a97a411 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Array.cs @@ -0,0 +1,213 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.ComponentModel; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents an array data structure. + /// + [ImmutableObject(true)] + public class Array : IEnumerable + { + #region Array Members + + #region Instance Fields + + // The length of the array. + private int length; + + // The head node of the random access list. + private RalTopNode head; + + #endregion + + #region Construction + + /// + /// Initialize an instance of the Array class with the specified array + /// length. + /// + /// + /// The length of the array. + /// + public Array(int length) + { + // Precondition. + if(length < 0) + { + throw new ArgumentOutOfRangeException("length", length, + "Array length out of range."); + } + + this.length = length; + + int n = length; + int exponent; + int count; + + head = null; + + /* + * The following algorithm creates the trees for the array. The + * trees have the form of a random access list. + */ + + // While there are still nodes to create. + while(n > 0) + { + // Get the log based 2 of the number of nodes. + exponent = (int)Math.Log(n, 2); + + // Get the number of nodes for each subtree. + count = ((int)Math.Pow(2, exponent) - 1) / 2; + + // Create the top node representing the subtree. + head = new RalTopNode( + new RalTreeNode( + null, + CreateSubTree(count), + CreateSubTree(count)), + head); + + // Get the remaining number of nodes to create. + n -= head.Root.Count; + } + } + + /// + /// Initializes a new instance of the Array class with the specified + /// head of the random access list and the length of the array. + /// + /// + /// The head of the random access list. + /// + /// + /// The length of the array. + /// + private Array(RalTopNode head, int length) + { + this.head = head; + this.length = length; + } + + #endregion + + #region Methods + + /// + /// Gets the value of the specified element in the current Array. + /// + /// + /// An integer that represents the position of the Array element to + /// get. + /// + /// + /// The value at the specified position in the Array. + /// + /// + /// index is outside the range of valid indexes for the current Array. + /// + public object GetValue(int index) + { + // Preconditions. + if(index < 0 || index >= Length) + { + throw new ArgumentOutOfRangeException( + "Index out of range."); + } + + return head.GetValue(index); + } + + /// + /// Sets the specified element in the current Array to the specified + /// value. + /// + /// + /// The new value for the specified element. + /// + /// + /// An integer that represents the position of the Array element to set. + /// + /// + /// A new array with the element at the specified position set to the + /// specified value. + /// + /// + /// index is outside the range of valid indexes for the current Array. + /// + public Array SetValue(object value, int index) + { + // Preconditions. + if(index < 0 || index >= Length) + { + throw new ArgumentOutOfRangeException( + "Index out of range."); + } + + return new Array(head.SetValue(value, index), Length); + } + + // Creates subtrees within the random access list. + private RalTreeNode CreateSubTree(int count) + { + RalTreeNode result = null; + + if(count > 0) + { + int c = count / 2; + + result = new RalTreeNode( + null, + CreateSubTree(c), + CreateSubTree(c)); + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets an integer that represents the total number of elements in all + /// the dimensions of the Array. + /// + public int Length + { + get + { + return length; + } + } + + #endregion + + #endregion + + #region IEnumerable Members + + /// + /// Returns an IEnumerator for the Array. + /// + /// + /// An IEnumerator for the Array. + /// + public IEnumerator GetEnumerator() + { + return new RalEnumerator(head, length); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/ArrayList.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/ArrayList.cs new file mode 100644 index 0000000..4c3ca12 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/ArrayList.cs @@ -0,0 +1,694 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/28/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents a collection of elements accessible by index and supports + /// insertion and deletion. + /// + [ImmutableObject(true)] + public class ArrayList + { + #region ArrayList Members + + #region Constants + + // The height of the tree pool. + private const int TreePoolHeight = 30; + + // The default height of the initial tree. + private const int DefaultCapacityHeight = 5; + + #endregion + + #region Readonly + + /* + * The tree pool is a tree made up of null nodes. It is completely + * balanced and is used to form a template of nodes for use in the + * ArrayList. Initially, a small subtree is taken from the tree pool + * when an ArrayList is created. New nodes replace the null nodes as + * new versions of the ArrayList are created. Once the tree has been + * filled, another subtree of equal height is taken from the tree pool + * to enlarge the tree for the next version of the ArrayList. + * + * The reasoning behind this approach is that the Add method of the + * ArrayList will probably be the most widely used operation. By having + * a prefabricated balanced tree, no rebalancing has to take place as + * new nodes are added to the tree. Their position in the tree has + * already been determined by the existing null tree. This improves + * performance. + */ + + private static readonly IAvlNode TreePool; + + #endregion + + #region Fields + + // The number of items in the ArrayList. + private int count = 0; + + // The root of the tree. + private IAvlNode root; + + #endregion + + #region Contstruction + + /// + /// Initializes the ArrayList class. + /// + static ArrayList() + { + IAvlNode parent = AvlNode.NullNode; + IAvlNode child = AvlNode.NullNode; + + // Create the tree pool. + for(int i = 0; i < TreePoolHeight; i++) + { + parent = new AvlNode(null, child, child); + child = parent; + } + + TreePool = parent; + + // Postconditions. + Debug.Assert(TreePool.Height == TreePoolHeight); + } + + /// + /// Initializes a new instance of the ArrayList class. + /// + public ArrayList() + { + root = GetSubTree(DefaultCapacityHeight); + } + + /// + /// Initializes a new instance of the ArrayList class that contains + /// elements copied from the specified collection. + /// + /// + /// The ICollection whose elements are copied to the new list. + /// + public ArrayList(ICollection collection) + { + if(collection.Count > 0) + { + int height = (int)Math.Log(collection.Count, 2) + 1; + + root = CollectionToTree(collection.GetEnumerator(), height); + } + else + { + root = GetSubTree(DefaultCapacityHeight); + } + + count = collection.Count; + } + + /// + /// Initializes a new instance of the ArrayList class with the + /// specified root and count. + /// + /// + /// The root of the tree. + /// + /// + /// The number of items in the ArrayList. + /// + private ArrayList(IAvlNode root, int count) + { + this.root = root; + this.count = count; + } + + #endregion + + #region Methods + + /// + /// Adds an object to the end of the ArrayList. + /// + /// + /// The Object to be added to the end of the ArrayList. + /// + /// + /// A new ArrayList object with the specified value added at the end. + /// + public ArrayList Add(object value) + { + ArrayList result; + + // If the tree has been filled. + if(count == root.Count) + { + // Create a new ArrayList while enlarging the tree. The + // current count serves as an index for setting the specified + // value. + result = new ArrayList( + SetValue(count, value, EnlargeTree()), + count + 1); + } + // Else the tree has not been filled. + else + { + // Create a new ArrayList. The current count serves as an index + // for setting the specified value. + result = new ArrayList( + SetValue(count, value, root), + count + 1); + } + + // Postconditions. + Debug.Assert(result.Count == Count + 1); + Debug.Assert(result.GetValue(result.Count - 1) == value); + + return result; + } + + /// + /// Determines whether an element is in the ArrayList. + /// + /// + /// The Object to locate in the ArrayList. + /// + /// + /// true if item is found in the ArrayList; otherwise, + /// false. + /// + public bool Contains(object value) + { + return IndexOf(value) > -1; + } + + /// + /// Returns the zero-based index of the first occurrence of a value in + /// the ArrayList. + /// + /// + /// The Object to locate in the ArrayList. + /// + /// + /// The zero-based index of the first occurrence of value within the + /// ArrayList, if found; otherwise, -1. + /// + public int IndexOf(object value) + { + int index = 0; + + // Iterate through the ArrayList and compare each value with the + // specified value. If they match, return the index of the value. + foreach(object v in this) + { + if(value.Equals(v)) + { + return index; + } + + index++; + } + + // The specified value is not in the ArrayList. + return -1; + } + + /// + /// Inserts an element into the ArrayList at the specified index. + /// + /// + /// The zero-based index at which value should be inserted. + /// + /// + /// The Object to insert. + /// + /// + /// A new ArrayList with the specified object inserted at the specified + /// index. + /// + /// + /// index is less than zero or index is greater than Count. + /// + public ArrayList Insert(int index, object value) + { + // Preconditions. + if(index < 0 || index > Count) + { + throw new ArgumentOutOfRangeException( + "ArrayList index out of range."); + } + + // Create new ArrayList with the value inserted at the specified index. + ArrayList result = new ArrayList(Insert(index, value, root), count + 1); + + // Post conditions. + Debug.Assert(result.GetValue(index) == value); + + return result; + } + + /// + /// Removes the first occurrence of a specified object from the + /// ArrayList. + /// + /// + /// The Object to remove from the ArrayList. + /// + /// + /// A new ArrayList with the first occurrent of the specified object + /// removed. + /// + public ArrayList Remove(object value) + { + ArrayList result; + int index = IndexOf(value); + + // If the object is in the ArrayList. + if(index > -1) + { + // Remove the object. + result = RemoveAt(index); + + // Postcondition. + Debug.Assert(result.Count == Count - 1); + } + // Else the object is not in the ArrayList. + else + { + result = this; + } + + return result; + } + + /// + /// Removes the element at the specified index of the ArrayList. + /// + /// + /// The zero-based index of the element to remove. + /// + /// + /// A new ArrayList with the element at the specified index removed. + /// + /// + /// index is less than zero or index is equal to or greater than Count. + /// + public ArrayList RemoveAt(int index) + { + // Preconditions. + if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "ArrayList index out of range."); + } + + // Create a new ArrayList with the element at the specified index + // removed. + ArrayList result = new ArrayList(RemoveAt(index, root), count - 1); + + // Postconditions. + Debug.Assert(result.Count == Count - 1); + + return result; + } + + /// + /// Gets the value at the specified index. + /// + /// + /// The zero-based index of the element to get. + /// + /// + /// The value at the specified index. + /// + /// + /// index is less than zero or index is equal to or greater than Count. + /// + public object GetValue(int index) + { + // Preconditions. + if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "Index out of range."); + } + + return GetValue(index, root); + } + + /// + /// Sets the value at the specified index. + /// + /// + /// The zero-based index of the element to set. + /// + /// + /// The value to set at the specified index. + /// + /// + /// A new ArrayList with the specified value set at the specified index. + /// + /// + /// index is less than zero or index is equal to or greater than Count. + /// + public ArrayList SetValue(int index, object value) + { + // Preconditions. + if(index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException( + "ArrayList index out of range."); + } + + // Create a new ArrayList with the specified value set at the + // specified index. + ArrayList result = new ArrayList(SetValue(index, value, root), count); + + // Postconditions. + Debug.Assert(result.GetValue(index) == value); + + return result; + } + + private IAvlNode CollectionToTree(IEnumerator enumerator, int height) + { + IAvlNode result; + + if(height == 0) + { + object data = null; + + if(enumerator.MoveNext()) + { + data = enumerator.Current; + } + + result = new AvlNode( + data, + AvlNode.NullNode, + AvlNode.NullNode); + } + else + { + IAvlNode leftChild, rightChild; + object data = null; + + leftChild = CollectionToTree(enumerator, height - 1); + + if(enumerator.MoveNext()) + { + data = enumerator.Current; + + rightChild = CollectionToTree(enumerator, height - 1); + } + else + { + rightChild = GetSubTree(height - 1); + } + + result = new AvlNode( + data, + leftChild, + rightChild); + } + + Debug.Assert(result.IsBalanced()); + + return result; + } + + // Enlarges the tree used by the ArrayList. + private IAvlNode EnlargeTree() + { + // Preconditions. + Debug.Assert(root.Height <= TreePool.Height); + + // Create new root for the enlarged tree. + IAvlNode result = new AvlNode(null, root, GetSubTree(root.Height)); + + // Postconditions. + Debug.Assert(result.BalanceFactor == 0); + Debug.Assert(result.Height == root.Height + 1); + + return result; + } + + // Recursive GetValue helper method. + private object GetValue(int index, IAvlNode node) + { + // Preconditions. + Debug.Assert(index >= 0 && index < Count); + Debug.Assert(node != AvlNode.NullNode); + + object result; + int leftCount = node.LeftChild.Count; + + // If the node has been found. + if(index == leftCount) + { + // Get value. + result = node.Data; + } + // Else if the node is in the left tree. + else if(index < leftCount) + { + // Move search to left child. + result = GetValue(index, node.LeftChild); + } + // Else if the node is in the right tree. + else + { + // Move search to the right child. + result = GetValue(index - (leftCount + 1), node.RightChild); + } + + return result; + } + + // Recursive SetValue helper method. + private IAvlNode SetValue(int index, object value, IAvlNode node) + { + // Preconditions. + Debug.Assert(index >= 0 && index < node.Count); + Debug.Assert(node != AvlNode.NullNode); + + IAvlNode result; + int leftCount = node.LeftChild.Count; + + // If the node has been found. + if(index == leftCount) + { + // Create new node with the new value. + result = new AvlNode(value, node.LeftChild, node.RightChild); + } + // Else if the node is in the left tree. + else if(index < leftCount) + { + // Create new node and move search to the left child. The new + // node will reuse the right child subtree. + result = new AvlNode( + node.Data, + SetValue(index, value, node.LeftChild), + node.RightChild); + } + // Else if the node is in the right tree. + else + { + // Create new node and move search to the right child. The new + // node will reuse the left child subtree. + result = new AvlNode( + node.Data, + node.LeftChild, + SetValue(index - (leftCount + 1), value, node.RightChild)); + } + + return result; + } + + // Gets a subtree from the tree pool at the specified height. + private static IAvlNode GetSubTree(int height) + { + // Preconditions. + Debug.Assert(height >= 0 && height <= TreePool.Height); + + IAvlNode result = TreePool; + + // How far to descend into the tree pool to get the subtree. + int d = TreePool.Height - height; + + // Descend down the tree pool until arriving at the root of the + // subtree. + for(int i = 0; i < d; i++) + { + result = result.LeftChild; + } + + // Postconditions. + Debug.Assert(result.Height == height); + + return result; + } + + // Recursive Insert helper method. + private IAvlNode Insert(int index, object value, IAvlNode node) + { + // Preconditions. + Debug.Assert(index >= 0 && index <= Count); + Debug.Assert(node != null); + + /* + * The insertion algorithm searches for the correct place to add a + * new node at the bottom of the tree using the specified index. + */ + + IAvlNode result; + + // If the bottom of the tree has not yet been reached. + if(node != AvlNode.NullNode) + { + int leftCount = node.LeftChild.Count; + + // If we need to descend to the left. + if(index <= leftCount) + { + // Create new node and move search to the left child. The + // new node will reuse the right child subtree. + result = new AvlNode( + node.Data, + Insert(index, value, node.LeftChild), + node.RightChild); + } + // Else we need to descend to the right. + else + { + // Create new node and move search to the right child. The + // new node will reuse the left child subtree. + result = new AvlNode( + node.Data, + node.LeftChild, + Insert(index - (leftCount + 1), + value, + node.RightChild)); + } + } + // Else the bottom of the tree has been reached. + else + { + // Create new node at the specified index. + result = new AvlNode(value, AvlNode.NullNode, AvlNode.NullNode); + } + + /* + * This check isn't necessary if a node has already been rebalanced + * after an insertion. AVL tree insertions never require more than + * one rebalancing. However, it's easier to go ahead and check at + * this point since we're using recursion. This may need optimizing + * in the future. + */ + + // If the node is not balanced. + if(!result.IsBalanced()) + { + // Rebalance node. + result = result.Balance(); + } + + // Postconditions. + Debug.Assert(result.IsBalanced()); + + return result; + } + + // Recursive RemoveAt helper method. + private IAvlNode RemoveAt(int index, IAvlNode node) + { + // Preconditions. + Debug.Assert(index >= 0 && index < Count); + Debug.Assert(node != AvlNode.NullNode); + + IAvlNode newNode = AvlNode.NullNode; + + int leftCount = node.LeftChild.Count; + + // If the node has been found. + if(index == leftCount) + { + newNode = node.Remove(); + } + // Else if the node is in the left tree. + else if(index < leftCount) + { + // Create new node and move search to the left child. The new + // node will reuse the right child subtree. + newNode = new AvlNode( + node.Data, + RemoveAt(index, node.LeftChild), + node.RightChild); + } + // Else if the node is in the right tree. + else + { + // Create new node and move search to the right child. The new + // node will reuse the left child subtree. + newNode = new AvlNode( + node.Data, + node.LeftChild, + RemoveAt(index - (leftCount + 1), node.RightChild)); + } + + // If the node is out of balance. + if(!newNode.IsBalanced()) + { + // Rebalance node. + newNode = newNode.Balance(); + } + + // Postconditions. + Debug.Assert(newNode.IsBalanced()); + + return newNode; + } + + #endregion + + /// + /// Gets the number of elements contained in the ArrayList. + /// + public int Count + { + get + { + return count; + } + } + + #endregion + + #region IEnumerable Members + + /// + /// Returns an enumerator that can iterate through the ArrayList. + /// + /// + /// An IEnumerator that can be used to iterate through the ArrayList. + /// + public IEnumerator GetEnumerator() + { + return new AvlEnumerator(root, Count); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalEnumerator.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalEnumerator.cs new file mode 100644 index 0000000..9612cbb --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalEnumerator.cs @@ -0,0 +1,211 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Provides functionality for enumerating a RandomAccessList. + /// + internal class RalEnumerator : IEnumerator + { + #region Enumerator Members + + #region Instance Fields + + // The object at the current position. + private object current = null; + + // The current index position. + private int index; + + // For storing and traversing the nodes in the tree. + private System.Collections.Stack treeStack = new System.Collections.Stack(); + + // The first top node in the list. + private RalTopNode head; + + // The current top node in the list. + private RalTopNode currentTopNode; + + // The number of nodes in the list. + private int count; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the Enumerator with the specified + /// head of the list and the number of nodes in the list. + /// + /// + /// The head of the list. + /// + /// + /// The number of nodes in the list. + /// + public RalEnumerator(RalTopNode head, int count) + { + this.head = head; + this.count = count; + + if(count > 0) + { + Debug.Assert(head != null); + } + + Reset(); + } + + #endregion + + #endregion + + #region IEnumerator Members + + /// + /// Sets the enumerator to its initial position, which is before + /// the first element in the random access list. + /// + public void Reset() + { + index = -1; + currentTopNode = head; + treeStack.Clear(); + + // If the list is not empty. + if(count > 0) + { + // Push the first node in the list onto the stack. + treeStack.Push(head.Root); + } + } + + /// + /// Gets the current element in the random access list. + /// + /// + /// The enumerator is positioned before the first element in the + /// random access list or after the last element. + /// + public object Current + { + get + { + // Preconditions. + if(index < 0 || index >= count) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the collection or after the last element."); + } + + return current; + } + } + + /// + /// Advances the enumerator to the next element in the random access + /// list. + /// + /// + /// true if the enumerator was successfully advanced to the + /// next element; false if the enumerator has passed the end + /// of the collection. + /// + public bool MoveNext() + { + // Move index to the next position. + index++; + + // If the index has moved beyond the end of the list, return false. + if(index >= count) + return false; + + RalTreeNode currentNode; + + // Get the node at the top of the stack. + currentNode = (RalTreeNode)treeStack.Peek(); + + // Get the value at the top of the stack. + current = currentNode.Value; + + // If there are still left children to traverse. + if(currentNode.LeftChild != null) + { + // If the left child is not null, the right child should not be + // null either. + Debug.Assert(currentNode.RightChild != null); + + // Push left child onto stack. + treeStack.Push(currentNode.LeftChild); + } + // Else the bottom of the tree has been reached. + else + { + // If the left child is null, the right child should be null, + // too. + Debug.Assert(currentNode.RightChild == null); + + // Move back up in the tree to the parent node. + treeStack.Pop(); + + RalTreeNode previousNode; + + // Whild the stack is not empty. + while(treeStack.Count > 0) + { + // Get the previous node. + previousNode = (RalTreeNode)treeStack.Peek(); + + // If the bottom of the left tree has been reached. + if(currentNode == previousNode.LeftChild) + { + // Push the right child onto the stack so that the + // right tree will now be traversed. + treeStack.Push(previousNode.RightChild); + + // Finished. + break; + } + // Else the bottom of the right tree has been reached. + else + { + // Keep track of the current node. + currentNode = previousNode; + + // Pop the stack to move back up the tree. + treeStack.Pop(); + } + } + + // If the stack is empty. + if(treeStack.Count == 0) + { + // Move to the next tree in the list. + currentTopNode = currentTopNode.NextNode; + + // If the end of the list has not yet been reached. + if(currentTopNode != null) + { + // Begin with the next tree. + treeStack.Push(currentTopNode.Root); + } + } + } + + return true; + } + + #endregion + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTopNode.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTopNode.cs new file mode 100644 index 0000000..4e834f7 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTopNode.cs @@ -0,0 +1,155 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents the top nodes in a RandomAccessList. + /// + [ImmutableObject(true)] + internal class RalTopNode + { + #region RalTopNode Members + + #region Instance Fields + + // The root of the tree the top node represents. + private readonly RalTreeNode root; + + // The next top node in the list. + private readonly RalTopNode nextNode; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the RalTopNode with the specified + /// root of the tree this node represents and the next top node in the + /// list. + /// + /// + /// The root node of the tree this top node represents. + /// + /// + /// The next top node in the list. + /// + public RalTopNode(RalTreeNode root, RalTopNode nextNode) + { + Debug.Assert(root != null); + + this.root = root; + this.nextNode = nextNode; + } + + #endregion + + #region Methods + + /// + /// Gets the value at the specified element in the random access list. + /// + /// + /// An integer that represents the position of the random access list + /// element to get. + /// + /// + /// The value at the specified position in the random access list. + /// + public object GetValue(int index) + { + int i = index; + RalTopNode currentNode = this; + + // Find the top node containing the specified element. + while(i >= currentNode.Root.Count) + { + i -= currentNode.Root.Count; + currentNode = currentNode.NextNode; + + Debug.Assert(currentNode != null); + } + + return currentNode.Root.GetValue(i); + } + + /// + /// Sets the specified element in the current random access list to the + /// specified value. + /// + /// + /// The new value for the specified element. + /// + /// + /// An integer that represents the position of the random access list + /// element to set. + /// + /// + /// A new random access list top node with the element at the specified + /// position set to the specified value. + /// + public RalTopNode SetValue(object value, int index) + { + RalTopNode result; + + // If the element is in the tree represented by the current top + // node. + if(index < Root.Count) + { + // Descend into the tree. + result = new RalTopNode( + root.SetValue(value, index), + NextNode); + } + // Else the element is further along in the list. + else + { + // Move to the next top node. + result = new RalTopNode( + root, + NextNode.SetValue(value, index - Root.Count)); + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets the root node represented by the top node. + /// + public RalTreeNode Root + { + get + { + return root; + } + } + + /// + /// Gets the next top node in the random access list. + /// + public RalTopNode NextNode + { + get + { + return nextNode; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTreeNode.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTreeNode.cs new file mode 100644 index 0000000..bf1051b --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RAL Helper Classes/RalTreeNode.cs @@ -0,0 +1,250 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents subtree nodes within random access lists. + /// + [ImmutableObject(true)] + internal class RalTreeNode + { + #region RalTreeNode Members + + #region Instance Fields + + // The value represented by this node. + private readonly object value; + + // The number of nodes in the tree. + private readonly int count; + + // Left and right children. + private readonly RalTreeNode leftChild = null; + private readonly RalTreeNode rightChild = null; + + #endregion + + #region Construction + + /// + /// Initializes an instance of the RandomAccessListNode with the + /// specified value, left child, and right child. + /// + /// + /// The value to store in the node. + /// + /// + /// The left child. + /// + /// + /// The right child. + /// + public RalTreeNode( + object value, + RalTreeNode leftChild, + RalTreeNode rightChild) + { + this.value = value; + this.leftChild = leftChild; + this.rightChild = rightChild; + + count = 1; + + if(leftChild != null) + { + count += leftChild.Count * 2; + + Debug.Assert(rightChild != null); + Debug.Assert(count == 1 + leftChild.Count + rightChild.Count); + } + } + + #endregion + + #region Methods + + /// + /// Gets the value at the specified element in the random access list + /// subtree. + /// + /// + /// An integer that represents the position of the random access list + /// subtree element to get. + /// + /// + /// The value at the specified position in the random access list + /// subtree. + /// + public object GetValue(int index) + { + Debug.Assert(index < Count); + + return GetValue(index, this); + } + + // Recursive method for getting the value at the specified position. + private object GetValue(int index, RalTreeNode node) + { + object result; + + // If the position of the value to get has been reached. + if(index == 0) + { + // Get the value. + result = node.Value; + } + // Else the position of the value to get has not been reached. + else + { + int n = node.Count / 2; + + // If the value is in the left subtree. + if(index <= n) + { + Debug.Assert(node.LeftChild != null); + + // Descend into the left subtree. + result = GetValue(index - 1, node.LeftChild); + } + // Else the value is in the right subtree. + else + { + Debug.Assert(node.RightChild != null); + + // Descend into the right subtree. + result = GetValue(index - 1 - n, node.RightChild); + } + } + + return result; + } + + /// + /// Sets the specified element in the current random access list + /// subtree to the specified value. + /// + /// + /// The new value for the specified element. + /// + /// + /// An integer that represents the position of the random access list + /// subtree element to set. + /// + /// + /// A new random access list tree node with the element at the specified + /// position set to the specified value. + /// + public RalTreeNode SetValue(object value, int index) + { + return SetValue(value, index, this); + } + + // Recursive method for setting the value at the specified position. + private RalTreeNode SetValue(object value, int index, RalTreeNode node) + { + RalTreeNode result; + + // If the position of the value to set has been reached. + if(index == 0) + { + // Set the value. + result = new RalTreeNode( + value, + node.LeftChild, + node.RightChild); + } + // Else if the position of the value to set has not been reached. + else + { + Debug.Assert(node.LeftChild != null); + + int n = Count / 2; + + // If the value is in the left subtree. + if(index <= n) + { + // Descend into the left subtree. + result = new RalTreeNode( + node.Value, + node.LeftChild.SetValue(value, index - 1), + node.RightChild); + } + // Else if the value is in the right subtree. + else + { + Debug.Assert(node.RightChild != null); + + // Descend into the right subtree. + result = new RalTreeNode( + node.Value, + node.LeftChild, + node.RightChild.SetValue(value, index - 1 - n)); + } + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets the number of nodes in the tree. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets the left child. + /// + public RalTreeNode LeftChild + { + get + { + return leftChild; + } + } + + /// + /// Gets the right child. + /// + public RalTreeNode RightChild + { + get + { + return rightChild; + } + } + + /// + /// Gets the value represented by this node. + /// + public object Value + { + get + { + return value; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RandomAccessList.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RandomAccessList.cs new file mode 100644 index 0000000..76ce0b3 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/RandomAccessList.cs @@ -0,0 +1,302 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Implements Chris Okasaki's random access list. + /// + [ImmutableObject(true)] + public class RandomAccessList : IEnumerable + { + #region RandomAccessList Members + + #region Class Fields + + /// + /// Represents an empty random access list. + /// + public static readonly RandomAccessList Empty = new RandomAccessList(); + + #endregion + + #region Instance Fields + + // The number of elements in the random access list. + private readonly int count; + + // The first top node in the list. + private readonly RalTopNode first; + + // A random access list representing the head of the current list. + private RandomAccessList head = null; + + // A random access list representing the tail of the current list. + private RandomAccessList tail = null; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the RandomAccessList class. + /// + public RandomAccessList() + { + count = 0; + first = null; + } + + /// + /// Initializes a new instance of the RandomAccessList class with the + /// specified first top node and the number of elements in the list. + /// + /// + /// The first top node in the list. + /// + /// + /// The number of nodes in the list. + /// + private RandomAccessList(RalTopNode first, int count) + { + this.first = first; + this.count = count; + } + + #endregion + + #region Methods + + /// + /// Prepends a value to the random access list. + /// + /// + /// The value to prepend to the list. + /// + /// + /// A new random access list with the specified value prepended to the + /// list. + /// + public RandomAccessList Cons(object value) + { + RandomAccessList result; + + // If the list is empty, or there is only one tree in the list, or + // the first tree is smaller than the second tree. + if(Count == 0 || + first.NextNode == null || + first.Root.Count < first.NextNode.Root.Count) + { + // Create a new first node with the specified value. + RalTreeNode newRoot = new RalTreeNode(value, null, null); + + // Create a new random access list. + result = new RandomAccessList( + new RalTopNode(newRoot, first), + Count + 1); + } + // Else the first and second trees in the list are the same size. + else + { + Debug.Assert(first.Root.Count == first.NextNode.Root.Count); + + // Create a new first node with the old first and second node + // as the left and right children respectively. + RalTreeNode newRoot = new RalTreeNode( + value, + first.Root, + first.NextNode.Root); + + // Create a new random access list. + result = new RandomAccessList( + new RalTopNode(newRoot, first.NextNode.NextNode), + Count + 1); + } + + return result; + } + + /// + /// Gets the value at the specified position in the current + /// RandomAccessList. + /// + /// + /// An integer that represents the position of the RandomAccessList + /// element to get. + /// + /// + /// The value at the specified position in the RandomAccessList. + /// + /// + /// index is outside the range of valid indexes for the current + /// RandomAccessList. + /// + public object GetValue(int index) + { + // Precondition. + if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "Index out of range."); + } + + return first.GetValue(index); + } + + /// + /// Sets the specified element in the current RandomAccessList to the + /// specified value. + /// + /// + /// The new value for the specified element. + /// + /// + /// An integer that represents the position of the RandomAccessList + /// element to set. + /// + /// + /// A new RandomAccessList with the element at the specified position + /// set to the specified value. + /// + /// + /// index is outside the range of valid indexes for the current + /// RandomAccessList. + /// + public RandomAccessList SetValue(object value, int index) + { + // Precondition. + if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "Index out of range."); + } + + return new RandomAccessList(first.SetValue(value, index), Count); + } + + #endregion + + #region Properties + + /// + /// Gets the number of elements in the RandomAccessList. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets a RandomAccessList with first element of the current + /// RandomAccessList. + /// + /// + /// If the RandomAccessList is empty. + /// + public RandomAccessList Head + { + get + { + // Preconditions. + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot get the head of an empty random access list."); + } + + if(head == null) + { + RalTreeNode newRoot = new RalTreeNode( + first.Root.Value, null, null); + + RalTopNode newFirst = new RalTopNode(newRoot, null); + + head = new RandomAccessList(newFirst, 1); + } + + return head; + } + } + + /// + /// Gets a RandomAccessList with all but the first element of the + /// current RandomAccessList. + /// + /// + /// If the RandomAccessList is empty. + /// + public RandomAccessList Tail + { + get + { + // Precondition. + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot get the tail of an empty random access list."); + } + + if(tail == null) + { + if(Count == 1) + { + tail = Empty; + } + else + { + if(first.Root.Count > 1) + { + RalTreeNode left = first.Root.LeftChild; + RalTreeNode right = first.Root.RightChild; + + RalTopNode newSecond = new RalTopNode( + right, first.NextNode); + RalTopNode newFirst = new RalTopNode( + left, newSecond); + + tail = new RandomAccessList(newFirst, Count - 1); + } + else + { + tail = new RandomAccessList(first.NextNode, Count - 1); + } + } + } + + return tail; + } + } + + #endregion + + #endregion + + #region IEnumerable Members + + /// + /// Returns an IEnumerator for the RandomAccessList. + /// + /// + /// An IEnumerator for the RandomAccessList. + /// + public IEnumerator GetEnumerator() + { + return new RalEnumerator(first, Count); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/SortedList.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/SortedList.cs new file mode 100644 index 0000000..074fddd --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/SortedList.cs @@ -0,0 +1,509 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents a collection of key-and-value pairs that are sorted by the + /// keys and are accessible by key. + /// + [ImmutableObject(true)] + public class SortedList : IEnumerable + { + #region SortedList Members + + #region Class Fields + + /// + /// An empty SortedList. + /// + public static readonly SortedList Empty = new SortedList(); + + #endregion + + #region Instance Fields + + // The compare object used for making comparisions. + private IComparer comparer = null; + + // The root of the AVL tree. + private IAvlNode root = AvlNode.NullNode; + + // Represents the method responsible for comparing keys. + private delegate int CompareHandler(object x, object y); + + // The actual delegate to use for comparing keys. + private CompareHandler compareHandler; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the SortedList class that is empty + /// and is sorted according to the IComparable interface implemented by + /// each key added to the SortedList. + /// + public SortedList() + { + InitializeCompareHandler(); + } + + /// + /// Initializes a new instance of the SortedList class that is empty + /// and is sorted according to the specified IComparer interface. + /// + /// + /// The IComparer implementation to use when comparing keys, or a null + /// reference to use the IComparable implementation of each key. + /// + public SortedList(IComparer comparer) + { + this.comparer = comparer; + + InitializeCompareHandler(); + } + + /// + /// Initializes a new instance of the SortedList class with the + /// specified root node and the IComparer interface to use for sorting + /// keys. + /// + /// + /// The root of the AVL tree. + /// + /// + /// The IComparer implementation to use when comparing keys, or a null + /// reference to use the IComparable implementation of each key. + /// + private SortedList(IAvlNode root, IComparer comparer) + { + this.root = root; + this.comparer = comparer; + + InitializeCompareHandler(); + } + + #endregion + + #region Methods + + /// + /// Adds an element with the specified key and value to the SortedList. + /// + /// + /// The key of the element to add. + /// + /// + /// The value of the element to add. The value can be a null reference. + /// + /// + /// A new SortedList with the specified key and value added to the + /// previous SortedList. + /// + /// + /// key is a null reference. + /// + /// + /// An element with the specified key already exists in the SortedList, + /// or The SortedList is set to use the IComparable interface, and key + /// does not implement the IComparable interface. + /// + public SortedList Add(object key, object value) + { + // Preconditions. + if(key == null) + { + throw new ArgumentNullException("key", + "Key cannot be null."); + } + else if(comparer == null && !(key is IComparable)) + { + throw new ArgumentException( + "Key does not implement IComparable interface."); + } + + return new SortedList( + Add(key, value, root), + comparer); + } + + /// + /// Determines whether the SortedList contains a specific key. + /// + /// + /// The key to locate in the SortedList. + /// + /// + /// true if the SortedList contains an element with the + /// specified key; otherwise, false. + /// + public bool Contains(object key) + { + return this[key] != null; + } + + /// + /// Returns an IDictionaryEnumerator that can iterate through the + /// SortedList. + /// + /// + /// An IDictionaryEnumerator for the SortedList. + /// + public IDictionaryEnumerator GetEnumerator() + { + return new SortedListEnumerator(root); + } + + /// + /// Removes the element with the specified key from SortedList. + /// + /// + /// + /// + /// The key of the element to remove. + /// + /// + /// key is a null reference. + /// + /// + /// The SortedList is set to use the IComparable interface, and key + /// does not implement the IComparable interface. + /// + public SortedList Remove(object key) + { + // Preconditions. + if(key == null) + { + throw new ArgumentNullException("key", + "Key cannot be null."); + } + else if(comparer == null && !(key is IComparable)) + { + throw new ArgumentException( + "Key does not implement IComparable interface."); + } + + return new SortedList(Remove(key, root), comparer); + } + + // Initializes the delegate to use for making key comparisons. + private void InitializeCompareHandler() + { + if(comparer == null) + { + compareHandler = new CompareHandler(CompareWithoutComparer); + } + else + { + compareHandler = new CompareHandler(CompareWithComparer); + } + } + + // Method for comparing keys using the IComparable interface. + private int CompareWithoutComparer(object x, object y) + { + return ((IComparable)x).CompareTo(y); + } + + // Method for comparing keys using the provided comparer. + private int CompareWithComparer(object x, object y) + { + return comparer.Compare(x, y); + } + + // Adds key/value pair to the internal AVL tree. + private IAvlNode Add(object key, object value, IAvlNode node) + { + IAvlNode result; + + // If the bottom of the tree has been reached. + if(node == AvlNode.NullNode) + { + // Create new node representing the new key/value pair. + result = new AvlNode( + new DictionaryEntry(key, value), + AvlNode.NullNode, + AvlNode.NullNode); + } + // Else the bottom of the tree has not been reached. + else + { + DictionaryEntry entry = (DictionaryEntry)node.Data; + int compareResult = compareHandler(key, entry.Key); + + // If the specified key is less than the current key. + if(compareResult < 0) + { + // Create new node and continue searching to the left. + result = new AvlNode( + node.Data, + Add(key, value, node.LeftChild), + node.RightChild); + } + // Else the specified key is greater than the current key. + else if(compareResult > 0) + { + // Create new node and continue searching to the right. + result = new AvlNode( + node.Data, + node.LeftChild, + Add(key, value, node.RightChild)); + } + // Else the specified key is equal to the current key. + else + { + // Throw exception. Duplicate keys are not allowed. + throw new ArgumentException( + "Item is already in the collection."); + } + } + + // If the current node is not balanced. + if(!result.IsBalanced()) + { + // Balance node. + result = result.Balance(); + } + + return result; + } + + // Search for the node with the specified key. + private object Search(object key, IAvlNode node) + { + object result; + + // If the key is not in the SortedList. + if(node == AvlNode.NullNode) + { + // Result is null. + result = null; + } + // Else the key has not yet been found. + else + { + DictionaryEntry entry = (DictionaryEntry)node.Data; + int compareResult = compareHandler(key, entry.Key); + + // If the specified key is less than the current key. + if(compareResult < 0) + { + // Search to the left. + result = Search(key, node.LeftChild); + } + // Else if the specified key is greater than the current key. + else if(compareResult > 0) + { + // Search to the right. + result = Search(key, node.RightChild); + } + // Else the key has been found. + else + { + // Get value. + result = entry.Value; + } + } + + return result; + } + + // Remove the node with the specified key. + private IAvlNode Remove(object key, IAvlNode node) + { + IAvlNode result; + + // The the key does not exist in the SortedList. + if(node == AvlNode.NullNode) + { + // Result is null. + result = node; + } + // Else the key has not yet been found. + else + { + DictionaryEntry entry = (DictionaryEntry)node.Data; + int compareResult = compareHandler(key, entry.Key); + + // If the specified key is less than the current key. + if(compareResult < 0) + { + // Create node and continue searching to the left. + result = new AvlNode( + node.Data, + Remove(key, node.LeftChild), + node.RightChild); + } + // Else if the specified key is greater than the current key. + else if(compareResult > 0) + { + // Create node and continue searching to the right. + result = new AvlNode( + node.Data, + node.LeftChild, + Remove(key, node.RightChild)); + } + // Else the node to remove has been found. + else + { + // Remove node. + result = node.Remove(); + } + } + + // If the node is out of balance. + if(!result.IsBalanced()) + { + // Rebalance node. + result = result.Balance(); + } + + // Postconditions. + Debug.Assert(result.IsBalanced()); + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets the value associated with the specified key. + /// + public object this[object key] + { + get + { + return Search(key, root); + } + } + + /// + /// Gets the number of elements contained in the SortedList. + /// + public int Count + { + get + { + return root.Count; + } + } + + #endregion + + #region SortedListEnumerator Class + + /// + /// Provides functionality for iterating through a SortedList. + /// + private class SortedListEnumerator : IDictionaryEnumerator + { + #region SortedListEnumerator Members + + #region Instance Fields + + private AvlEnumerator enumerator; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the SortedListEnumerator class + /// with the specified root of the AVL tree to iterate over. + /// + /// + /// The root of the AVL tree the SortedList uses internally. + /// + public SortedListEnumerator(IAvlNode root) + { + enumerator = new AvlEnumerator(root); + } + + #endregion + + #endregion + + #region IDictionaryEnumerator Members + + public object Key + { + get + { + DictionaryEntry entry = (DictionaryEntry)enumerator.Current; + + return entry.Key; + } + } + + public object Value + { + get + { + DictionaryEntry entry = (DictionaryEntry)enumerator.Current; + + return entry.Value; + } + } + + public DictionaryEntry Entry + { + get + { + DictionaryEntry entry = (DictionaryEntry)enumerator.Current; + + return entry; + } + } + + #endregion + + #region IEnumerator Members + + public void Reset() + { + enumerator.Reset(); + } + + public object Current + { + get + { + return enumerator.Current; + } + } + + public bool MoveNext() + { + return enumerator.MoveNext(); + } + + #endregion + } + + #endregion + + #endregion + + #region IEnumerable Members + + IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return new AvlEnumerator(root); + } + + #endregion + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Stack.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Stack.cs new file mode 100644 index 0000000..f429ded --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/Immutable/Stack.cs @@ -0,0 +1,315 @@ +/* + * Created by: Leslie Sanford + * + * Last modified: 02/23/2005 + * + * Contact: jabberdabber@hotmail.com + */ + +using System; +using System.Collections; +using System.ComponentModel; + +namespace Sanford.Collections.Immutable +{ + /// + /// Represents a simple last-in-first-out collection of objects. + /// + [ImmutableObject(true)] + public class Stack : IEnumerable + { + #region Stack Members + + #region Class Fields + + /// + /// An empty Stack. + /// + public static readonly Stack Empty = new Stack(); + + #endregion + + #region Instance Fields + + // The number of elements in the stack. + private readonly int count; + + // The top node in the stack. + private Node top = null; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the Stack class. + /// + public Stack() + { + count = 0; + } + + /// + /// Initializes a new instance of the Stack class with the + /// specified top node and the number of elements in the stack. + /// + /// + /// The top node in the stack. + /// + /// + /// The number of elements in the stack. + /// + private Stack(Node top, int count) + { + this.top = top; + this.count = count; + } + + #endregion + + #region Methods + + /// + /// Inserts an object at the top of the Stack. + /// + /// + /// The Object to push onto the Stack. + /// + /// + /// A new stack with the specified object on the top of the stack. + /// + public Stack Push(object obj) + { + Node newTop = new Node(obj, top); + + return new Stack(newTop, Count + 1); + } + + /// + /// Removes the object at the top of the Stack. + /// + /// + /// A new stack with top of the previous stack removed. + /// + /// + /// The Stack is empty. + /// + public Stack Pop() + { + // Preconditions. + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot pop an empty stack."); + } + + Stack result; + + if(Count - 1 == 0) + { + result = Empty; + } + else + { + result = new Stack(top.Next, Count - 1); + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets the number of elements in the Stack. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets the top of the stack. + /// + /// + /// The Stack is empty. + /// + public object Top + { + get + { + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot access the top when the stack is empty."); + } + + return top.Value; + } + } + + #endregion + + #region Node Class + + /// + /// Represents a node in the stack. + /// + private class Node + { + private Node next = null; + + private object value; + + public Node(object value, Node next) + { + this.value = value; + this.next = next; + } + + public Node Next + { + get + { + return next; + } + } + + public object Value + { + get + { + return value; + } + } + } + + #endregion + + #region StackEnumerator Class + + /// + /// Provides functionality for iterating over the Stack class. + /// + private class StackEnumerator : IEnumerator + { + #region StackEnumerator Members + + #region Instance Fields + + // The stack to iterate over. + private Stack owner; + + // The current index into the stack. + private int index; + + // The current node. + private Node current; + + // The next node in the stack. + private Node next; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the StackEnumerator class with + /// the specified stack to iterate over. + /// + /// + /// The Stack to iterate over. + /// + public StackEnumerator(Stack owner) + { + this.owner = owner; + + Reset(); + } + + #endregion + + #region IEnumerator Members + + /// + /// Sets the enumerator to its initial position, which is before + /// the first element in the Stack. + /// + public void Reset() + { + index = -1; + + next = owner.top; + } + + /// + /// Gets the current element in the Stack. + /// + /// + /// The enumerator is positioned before the first element of the + /// Stack or after the last element. + /// + public object Current + { + get + { + // Preconditions. + if(index < 0 || index >= owner.Count) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the collection or after the last element."); + } + + return current.Value; + } + } + + /// + /// Advances the enumerator to the next element of the Stack. + /// + /// + public bool MoveNext() + { + index++; + + if(index >= owner.Count) + { + return false; + } + + current = next; + next = next.Next; + + return true; + } + + #endregion + } + + #endregion + + #endregion + + #endregion + + #region IEnumerable Members + + /// + /// Returns an IEnumerator for the Stack. + /// + /// + /// An IEnumerator for the Stack. + /// + public IEnumerator GetEnumerator() + { + return new StackEnumerator(this); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/PriorityQueue.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/PriorityQueue.cs new file mode 100644 index 0000000..0661ad0 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/PriorityQueue.cs @@ -0,0 +1,905 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.Diagnostics; + +namespace Sanford.Collections +{ + /// + /// Represents the priority queue data structure. + /// + public class PriorityQueue : ICollection + { + #region PriorityQueue Members + + #region Fields + + // The maximum level of the skip list. + private const int LevelMaxValue = 16; + + // The probability value used to randomly select the next level value. + private const double Probability = 0.5; + + // The current level of the skip list. + private int currentLevel = 1; + + // The header node of the skip list. + private Node header = new Node(null, LevelMaxValue); + + // Used to generate node levels. + private Random rand = new Random(); + + // The number of elements in the PriorityQueue. + private int count = 0; + + // The version of this PriorityQueue. + private long version = 0; + + // Used for comparing and sorting elements. + private IComparer comparer; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the PriorityQueue class. + /// + /// + /// The PriorityQueue will cast its elements to the IComparable + /// interface when making comparisons. + /// + public PriorityQueue() + { + comparer = new DefaultComparer(); + } + + /// + /// Initializes a new instance of the PriorityQueue class with the + /// specified IComparer. + /// + /// + /// The IComparer to use for comparing and ordering elements. + /// + /// + /// If the specified IComparer is null, the PriorityQueue will cast its + /// elements to the IComparable interface when making comparisons. + /// + public PriorityQueue(IComparer comparer) + { + // If no comparer was provided. + if(comparer == null) + { + // Use the DefaultComparer. + this.comparer = new DefaultComparer(); + } + // Else a comparer was provided. + else + { + // Use the provided comparer. + this.comparer = comparer; + } + } + + #endregion + + #region Methods + + /// + /// Enqueues the specified element into the PriorityQueue. + /// + /// + /// The element to enqueue into the PriorityQueue. + /// + /// + /// If element is null. + /// + public virtual void Enqueue(object element) + { + #region Require + + if(element == null) + { + throw new ArgumentNullException("element"); + } + + #endregion + + Node x = header; + Node[] update = new Node[LevelMaxValue]; + int nextLevel = NextLevel(); + + // Find the place in the queue to insert the new element. + for(int i = currentLevel - 1; i >= 0; i--) + { + while(x[i] != null && comparer.Compare(x[i].Element, element) > 0) + { + x = x[i]; + } + + update[i] = x; + } + + // If the new node's level is greater than the current level. + if(nextLevel > currentLevel) + { + for(int i = currentLevel; i < nextLevel; i++) + { + update[i] = header; + } + + // Update level. + currentLevel = nextLevel; + } + + // Create new node. + Node newNode = new Node(element, nextLevel); + + // Insert the new node into the list. + for(int i = 0; i < nextLevel; i++) + { + newNode[i] = update[i][i]; + update[i][i] = newNode; + } + + // Keep track of the number of elements in the PriorityQueue. + count++; + + version++; + + #region Ensure + + Debug.Assert(Contains(element), "Contains Test", "Contains test for element " + element.ToString() + " failed."); + + #endregion + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Removes the element at the head of the PriorityQueue. + /// + /// + /// The element at the head of the PriorityQueue. + /// + /// + /// If Count is zero. + /// + public virtual object Dequeue() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot dequeue into an empty PriorityQueue."); + } + + #endregion + + // Get the first item in the queue. + object element = header[0].Element; + + // Keep track of the node that is about to be removed. + Node oldNode = header[0]; + + // Update the header so that its pointers that pointed to the + // node to be removed now point to the node that comes after it. + for(int i = 0; i < currentLevel && header[i] == oldNode; i++) + { + header[i] = oldNode[i]; + } + + // Update the current level of the list in case the node that + // was removed had the highest level. + while(currentLevel > 1 && header[currentLevel - 1] == null) + { + currentLevel--; + } + + // Keep track of how many items are in the queue. + count--; + + version++; + + #region Ensure + + Debug.Assert(count >= 0); + + #endregion + + #region Invariant + + AssertValid(); + + #endregion + + return element; + } + + /// + /// Removes the specified element from the PriorityQueue. + /// + /// + /// The element to remove. + /// + /// + /// If element is null + /// + public virtual void Remove(object element) + { + #region Require + + if(element == null) + { + throw new ArgumentNullException("element"); + } + + #endregion + + Node x = header; + Node[] update = new Node[LevelMaxValue]; + int nextLevel = NextLevel(); + + // Find the specified element. + for(int i = currentLevel - 1; i >= 0; i--) + { + while(x[i] != null && comparer.Compare(x[i].Element, element) > 0) + { + x = x[i]; + } + + update[i] = x; + } + + x = x[0]; + + // If the specified element was found. + if(x != null && comparer.Compare(x.Element, element) == 0) + { + // Remove element. + for(int i = 0; i < currentLevel && update[i][i] == x; i++) + { + update[i][i] = x[i]; + } + + // Update list level. + while(currentLevel > 1 && header[currentLevel - 1] == null) + { + currentLevel--; + } + + // Keep track of the number of elements in the PriorityQueue. + count--; + + version++; + } + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Returns a value indicating whether the specified element is in the + /// PriorityQueue. + /// + /// + /// The element to test. + /// + /// + /// true if the element is in the PriorityQueue; otherwise + /// false. + /// + public virtual bool Contains(object element) + { + #region Guard + + if(element == null) + { + return false; + } + + #endregion + + bool found; + Node x = header; + + // Find the specified element. + for(int i = currentLevel - 1; i >= 0; i--) + { + while(x[i] != null && comparer.Compare(x[i].Element, element) > 0) + { + x = x[i]; + } + } + + x = x[0]; + + // If the element is in the PriorityQueue. + if(x != null && comparer.Compare(x.Element, element) == 0) + { + found = true; + } + // Else the element is not in the PriorityQueue. + else + { + found = false; + } + + return found; + } + + /// + /// Returns the element at the head of the PriorityQueue without + /// removing it. + /// + /// + /// The element at the head of the PriorityQueue. + /// + public virtual object Peek() + { + #region Require + + if(Count == 0) + { + throw new InvalidOperationException( + "Cannot peek into an empty PriorityQueue."); + } + + #endregion + + return header[0].Element; + } + + /// + /// Removes all elements from the PriorityQueue. + /// + public virtual void Clear() + { + header = new Node(null, LevelMaxValue); + + currentLevel = 1; + + count = 0; + + version++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Returns a synchronized wrapper of the specified PriorityQueue. + /// + /// + /// The PriorityQueue to synchronize. + /// + /// + /// A synchronized PriorityQueue. + /// + /// + /// If queue is null. + /// + public static PriorityQueue Synchronized(PriorityQueue queue) + { + #region Require + + if(queue == null) + { + throw new ArgumentNullException("queue"); + } + + #endregion + + return new SynchronizedPriorityQueue(queue); + } + + // Generates a random level for the next node. + private int NextLevel() + { + int nextLevel = 1; + + while(rand.NextDouble() < Probability && + nextLevel < LevelMaxValue && + nextLevel <= currentLevel) + { + nextLevel++; + } + + return nextLevel; + } + + // Makes sure none of the PriorityQueue's invariants have been violated. + [Conditional("DEBUG")] + private void AssertValid() + { + int n = 0; + Node x = header[0]; + + while(x != null) + { + if(x[0] != null) + { + Debug.Assert(comparer.Compare(x.Element, x[0].Element) >= 0, "Order test"); + } + + x = x[0]; + n++; + } + + Debug.Assert(n == Count, "Count test."); + + for(int i = 1; i < currentLevel; i++) + { + Debug.Assert(header[i] != null, "Level non-null test."); + } + + for(int i = currentLevel; i < LevelMaxValue; i++) + { + Debug.Assert(header[i] == null, "Level null test."); + } + } + + /// + /// Tests the methods in the Priority Queue. + /// + [Conditional("DEBUG")] + public static void Test() + { + Random r = new Random(); + PriorityQueue queue = new PriorityQueue(); + int count = 1000; + int element; + + for(int i = 0; i < count; i++) + { + element = r.Next(); + queue.Enqueue(element); + + Debug.Assert(queue.Contains(element), "Contains Test"); + } + + Debug.Assert(queue.Count == count, "Count Test"); + + int previousElement = (int)queue.Peek(); + int peekElement; + + for(int i = 0; i < count; i++) + { + peekElement = (int)queue.Peek(); + element = (int)queue.Dequeue(); + + Debug.Assert(element == peekElement, "Peek Test"); + Debug.Assert(element <= previousElement, "Order Test"); + + previousElement = element; + } + + Debug.Assert(queue.Count == 0); + } + + #endregion + + #region Private Classes + + #region SynchronizedPriorityQueue Class + + // A synchronized wrapper for the PriorityQueue class. + private class SynchronizedPriorityQueue : PriorityQueue + { + private PriorityQueue queue; + + private object root; + + public SynchronizedPriorityQueue(PriorityQueue queue) + { + #region Require + + if(queue == null) + { + throw new ArgumentNullException("queue"); + } + + #endregion + + this.queue = queue; + + root = queue.SyncRoot; + } + + public override void Enqueue(object element) + { + lock(root) + { + queue.Enqueue(element); + } + } + + public override object Dequeue() + { + lock(root) + { + return queue.Dequeue(); + } + } + + public override void Remove(object element) + { + lock(root) + { + queue.Remove(element); + } + } + + public override void Clear() + { + lock(root) + { + queue.Clear(); + } + } + + public override bool Contains(object element) + { + lock(root) + { + return queue.Contains(element); + } + } + + public override object Peek() + { + lock(root) + { + return queue.Peek(); + } + } + + public override void CopyTo(Array array, int index) + { + lock(root) + { + queue.CopyTo(array, index); + } + } + + public override int Count + { + get + { + lock(root) + { + return queue.Count; + } + } + } + + public override bool IsSynchronized + { + get + { + return true; + } + } + + public override object SyncRoot + { + get + { + return root; + } + } + + public override IEnumerator GetEnumerator() + { + lock(root) + { + return queue.GetEnumerator(); + } + } + } + + #endregion + + #region DefaultComparer Class + + // The IComparer to use of no comparer was provided. + private class DefaultComparer : IComparer + { + #region IComparer Members + + public int Compare(object x, object y) + { + #region Require + + if(!(y is IComparable)) + { + throw new ArgumentException( + "Item does not implement IComparable."); + } + + #endregion + + IComparable a = x as IComparable; + + Debug.Assert(a != null); + + return a.CompareTo(y); + } + + #endregion + } + + #endregion + + #region Node Class + + // Represents a node in the list of nodes. + private class Node + { + private Node[] forward; + + private object element; + + public Node(object element, int level) + { + this.forward = new Node[level]; + this.element = element; + } + + public Node this[int index] + { + get + { + return forward[index]; + } + set + { + forward[index] = value; + } + } + + public object Element + { + get + { + return element; + } + } + } + + #endregion + + #region PriorityQueueEnumerator Class + + // Implements the IEnumerator interface for the PriorityQueue class. + private class PriorityQueueEnumerator : IEnumerator + { + private PriorityQueue owner; + + private Node head; + + private Node currentNode; + + private bool moveResult; + + private long version; + + public PriorityQueueEnumerator(PriorityQueue owner) + { + this.owner = owner; + this.version = owner.version; + head = owner.header; + + Reset(); + } + + #region IEnumerator Members + + public void Reset() + { + #region Require + + if(version != owner.version) + { + throw new InvalidOperationException( + "The PriorityQueue was modified after the enumerator was created."); + } + + #endregion + + currentNode = head; + moveResult = true; + } + + public object Current + { + get + { + #region Require + + if(currentNode == head || currentNode == null) + { + throw new InvalidOperationException( + "The enumerator is positioned before the first " + + "element of the collection or after the last element."); + } + + #endregion + + return currentNode.Element; + } + } + + public bool MoveNext() + { + #region Require + + if(version != owner.version) + { + throw new InvalidOperationException( + "The PriorityQueue was modified after the enumerator was created."); + } + + #endregion + + if(moveResult) + { + currentNode = currentNode[0]; + } + + if(currentNode == null) + { + moveResult = false; + } + + return moveResult; + } + + #endregion + } + + #endregion + + #endregion + + #endregion + + #region ICollection Members + + /// + /// Gets a value indicating whenever PriorityQueue is synchronized. + /// + public virtual bool IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets the number of elements contained in PriorityQueue. + /// + public virtual int Count + { + get + { + return count; + } + } + + /// + /// Copies the elements of the PriorityQueue to an array, starting at a particular array index. + /// + public virtual void CopyTo(Array array, int index) + { + #region Require + + if(array == null) + { + throw new ArgumentNullException("array"); + } + else if(index < 0) + { + throw new ArgumentOutOfRangeException("index", index, + "Array index out of range."); + } + else if(array.Rank > 1) + { + throw new ArgumentException( + "Array has more than one dimension.", "array"); + } + else if(index >= array.Length) + { + throw new ArgumentException( + "index is equal to or greater than the length of array.", "index"); + } + else if(Count > array.Length - index) + { + throw new ArgumentException( + "The number of elements in the PriorityQueue is greater " + + "than the available space from index to the end of the " + + "destination array.", "index"); + } + + #endregion + + int i = index; + + foreach(object element in this) + { + array.SetValue(element, i); + i++; + } + } + + /// + /// Gets an object that can be used to synchronize access to the PriorityQueue. + /// + public virtual object SyncRoot + { + get + { + return this; + } + } + + #endregion + + #region IEnumerable Members + + /// + /// Gets the enumerator for the Priority Queue, then returns the enumerator through a collection. + /// + public virtual IEnumerator GetEnumerator() + { + return new PriorityQueueEnumerator(this); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Collections/SkipList.cs b/Sanford.Multimedia.Midi.Core/Sanford.Collections/SkipList.cs new file mode 100644 index 0000000..0194943 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Collections/SkipList.cs @@ -0,0 +1,1110 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + + +namespace Sanford.Collections +{ + /// + /// Represents a collection of key-and-value pairs. + /// + /// + /// The SkipList class is an implementation of the IDictionary interface. It + /// is based on the data structure created by William Pugh. + /// + public class SkipList : IDictionary + { + #region SkipList Members + + #region Constants + + // Maximum level any node in a skip list can have + private const int MaxLevel = 32; + + // Probability factor used to determine the node level + private const double Probability = 0.5; + + #endregion + + #region Fields + + // The skip list header. It also serves as the NIL node. + private Node header = new Node(MaxLevel); + + // Comparer for comparing keys. + private IComparer comparer; + + // Random number generator for generating random node levels. + private Random random = new Random(); + + // Current maximum list level. + private int listLevel; + + // Current number of elements in the skip list. + private int count; + + // Version of the skip list. Used for validation checks with + // enumerators. + private long version = 0; + + #endregion + + /// + /// Initializes a new instance of the SkipList class that is empty and + /// is sorted according to the IComparable interface implemented by + /// each key added to the SkipList. + /// + /// + /// Each key must implement the IComparable interface to be capable of + /// comparisons with every other key in the SortedList. The elements + /// are sorted according to the IComparable implementation of each key + /// added to the SkipList. + /// + public SkipList() + { + // Initialize the skip list. + Initialize(); + } + + /// + /// Initializes a new instance of the SkipList class that is empty and + /// is sorted according to the specified IComparer interface. + /// + /// + /// The IComparer implementation to use when comparing keys. + /// + /// + /// The elements are sorted according to the specified IComparer + /// implementation. If comparer is a null reference, the IComparable + /// implementation of each key is used; therefore, each key must + /// implement the IComparable interface to be capable of comparisons + /// with every other key in the SkipList. + /// + public SkipList(IComparer comparer) + { + // Initialize comparer with the client provided comparer. + this.comparer = comparer; + + // Initialize the skip list. + Initialize(); + } + + /// + /// Destructor. + /// + ~SkipList() + { + Clear(); + } + + #region Private Helper Methods + + /// + /// Initializes the SkipList. + /// + private void Initialize() + { + listLevel = 1; + count = 0; + + // When the list is empty, make sure all forward references in the + // header point back to the header. This is important because the + // header is used as the sentinel to mark the end of the skip list. + for(int i = 0; i < MaxLevel; i++) + { + header.forward[i] = header; + } + } + + /// + /// Returns a level value for a new SkipList node. + /// + /// + /// The level value for a new SkipList node. + /// + private int GetNewLevel() + { + int level = 1; + + // Determines the next node level. + while(random.NextDouble() < Probability && level < MaxLevel && + level <= listLevel) + { + level++; + } + + return level; + } + + /// + /// Searches for the specified key. + /// + /// + /// The key to search for. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + private bool Search(object key) + { + Node curr; + Node[] dummy = new Node[MaxLevel]; + + return Search(key, out curr, dummy); + } + + /// + /// Searches for the specified key. + /// + /// + /// The key to search for. + /// + /// + /// A SkipList node to hold the results of the search. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + private bool Search(object key, out Node curr) + { + Node[] dummy = new Node[MaxLevel]; + + return Search(key, out curr, dummy); + } + + /// + /// Searches for the specified key. + /// + /// + /// The key to search for. + /// + /// + /// An array of nodes holding references to the places in the SkipList + /// search in which the search dropped down one level. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + private bool Search(object key, Node[] update) + { + Node curr; + + return Search(key, out curr, update); + } + + /// + /// Searches for the specified key. + /// + /// + /// The key to search for. + /// + /// + /// A SkipList node to hold the results of the search. + /// + /// + /// An array of nodes holding references to the places in the SkipList + /// search in which the search dropped down one level. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + private bool Search(object key, out Node curr, Node[] update) + { + // Make sure key isn't null. + if(key == null) + { + throw new ArgumentNullException("An attempt was made to pass a null key to a SkipList."); + } + + bool result; + + // Check to see if we will search with a comparer. + if(comparer != null) + { + result = SearchWithComparer(key, out curr, update); + } + // Else we're using the IComparable interface. + else + { + result = SearchWithComparable(key, out curr, update); + } + + return result; + } + + /// + /// Search for the specified key using a comparer. + /// + /// + /// The key to search for. + /// + /// + /// A SkipList node to hold the results of the search. + /// + /// + /// An array of nodes holding references to the places in the SkipList + /// search in which the search dropped down one level. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + private bool SearchWithComparer(object key, out Node curr, + Node[] update) + { + bool found = false; + + // Start from the beginning of the skip list. + curr = header; + + // Work our way down from the top of the skip list to the bottom. + for(int i = listLevel - 1; i >= 0; i--) + { + // While we haven't reached the end of the skip list and the + // current key is less than the search key. + while(curr.forward[i] != header && + comparer.Compare(curr.forward[i].Entry.Key, key) < 0) + { + // Move forward in the skip list. + curr = curr.forward[i]; + } + + // Keep track of each node where we move down a level. This + // will be used later to rearrange node references when + // inserting or deleting a new element. + update[i] = curr; + } + + // Move ahead in the skip list. If the new key doesn't already + // exist in the skip list, this should put us at either the end of + // the skip list or at a node with a key greater than the search key. + // If the new key already exists in the skip list, this should put + // us at a node with a key equal to the search key. + curr = curr.forward[0]; + + // If we haven't reached the end of the skip list and the + // current key is equal to the search key. + if(curr != header && comparer.Compare(key, curr.Entry.Key) == 0) + { + // Indicate that we've found the search key. + found = true; + } + + return found; + } + + /// + /// Search for the specified key using the IComparable interface + /// implemented by each key. + /// + /// + /// The key to search for. + /// + /// + /// A SkipList node to hold the results of the search. + /// + /// + /// An array of nodes holding references to the places in the SkipList + /// search in which the search dropped down one level. + /// + /// + /// Returns true if the specified key is in the SkipList. + /// + /// + /// Assumes each key inserted into the SkipList implements the + /// IComparable interface. + /// + /// If the specified key is in the SkipList, the curr parameter will + /// reference the node with the key. If the specified key is not in the + /// SkipList, the curr paramater will either hold the node with the + /// first key value greater than the specified key or it will have the + /// same value as the header indicating that the search reached the end + /// of the SkipList. + /// + private bool SearchWithComparable(object key, out Node curr, + Node[] update) + { + // Make sure key is comparable. + if(!(key is IComparable)) + { + throw new ArgumentException("The SkipList was set to use the IComparable interface and an attempt was made to add a key that does not support this interface."); + } + + bool found = false; + IComparable comp; + + // Begin at the start of the skip list. + curr = header; + + // Work our way down from the top of the skip list to the bottom. + for(int i = listLevel - 1; i >= 0; i--) + { + // Get the comparable interface for the current key. + comp = (IComparable)curr.forward[i].Key; + + // While we haven't reached the end of the skip list and the + // current key is less than the search key. + while(curr.forward[i] != header && comp.CompareTo(key) < 0) + { + // Move forward in the skip list. + curr = curr.forward[i]; + // Get the comparable interface for the current key. + comp = (IComparable)curr.forward[i].Key; + } + + // Keep track of each node where we move down a level. This + // will be used later to rearrange node references when + // inserting a new element. + update[i] = curr; + } + + // Move ahead in the skip list. If the new key doesn't already + // exist in the skip list, this should put us at either the end of + // the skip list or at a node with a key greater than the search key. + // If the new key already exists in the skip list, this should put + // us at a node with a key equal to the search key. + curr = curr.forward[0]; + + // Get the comparable interface for the current key. + comp = (IComparable)curr.Key; + + // If we haven't reached the end of the skip list and the + // current key is equal to the search key. + if(curr != header && comp.CompareTo(key) == 0) + { + // Indicate that we've found the search key. + found = true; + } + + return found; + } + + /// + /// Inserts a key/value pair into the SkipList. + /// + /// + /// The key to insert into the SkipList. + /// + /// + /// The value to insert into the SkipList. + /// + /// + /// An array of nodes holding references to places in the SkipList in + /// which the search for the place to insert the new key/value pair + /// dropped down one level. + /// + private void Insert(object key, object val, Node[] update) + { + // Get the level for the new node. + int newLevel = GetNewLevel(); + + // If the level for the new node is greater than the skip list + // level. + if(newLevel > listLevel) + { + // Make sure our update references above the current skip list + // level point to the header. + for(int i = listLevel; i < newLevel; i++) + { + update[i] = header; + } + + // The current skip list level is now the new node level. + listLevel = newLevel; + } + + // Create the new node. + Node newNode = new Node(newLevel, key, val); + + // Insert the new node into the skip list. + for(int i = 0; i < newLevel; i++) + { + // The new node forward references are initialized to point to + // our update forward references which point to nodes further + // along in the skip list. + newNode.forward[i] = update[i].forward[i]; + + // Take our update forward references and point them towards + // the new node. + update[i].forward[i] = newNode; + } + + // Keep track of the number of nodes in the skip list. + count++; + + // Indicate that the skip list has changed. + version++; + } + + #endregion + + #endregion + + #region Node Class + + /// + /// Represents a node in the SkipList. + /// + private class Node : IDisposable + { + #region Fields + + // References to nodes further along in the skip list. + public Node[] forward; + + // Node key. + private Object key; + + // Node value. + private Object val; + + #endregion + + /// + /// Initializes an instant of a Node with its node level. + /// + /// + /// The node level. + /// + public Node(int level) + { + forward = new Node[level]; + } + + /// + /// Initializes an instant of a Node with its node level and + /// key/value pair. + /// + /// + /// The node level. + /// + /// + /// The key for the node. + /// + /// + /// The value for the node. + /// + public Node(int level, object key, object val) + { + forward = new Node[level]; + + Key = key; + Value = val; + } + + /// + /// Key property. + /// + public Object Key + { + get + { + return key; + } + set + { + key = value; + } + } + + /// + /// Value property. + /// + public Object Value + { + get + { + return val; + } + set + { + val = value; + } + } + + /// + /// Node dictionary Entry property - contains key/value pair. + /// + public DictionaryEntry Entry + { + get + { + return new DictionaryEntry(Key, Value); + } + } + + #region IDisposable Members + + /// + /// Disposes the Node. + /// + public void Dispose() + { + for(int i = 0; i < forward.Length; i++) + { + forward[i] = null; + } + } + + #endregion + } + + #endregion + + #region SkipListEnumerator Class + + /// + /// Enumerates the elements of a skip list. + /// + private class SkipListEnumerator : IDictionaryEnumerator + { + #region SkipListEnumerator Members + + #region Fields + + // The skip list to enumerate. + private SkipList list; + + // The current node. + private Node current; + + // The version of the skip list we are enumerating. + private long version; + + // Keeps track of previous move result so that we can know + // whether or not we are at the end of the skip list. + private bool moveResult = true; + + #endregion + + /// + /// Initializes an instance of a SkipListEnumerator. + /// + /// + public SkipListEnumerator(SkipList list) + { + this.list = list; + version = list.version; + current = list.header; + } + + #endregion + + #region IDictionaryEnumerator Members + + /// + /// Gets both the key and the value of the current dictionary + /// entry. + /// + public DictionaryEntry Entry + { + get + { + DictionaryEntry entry; + + // Make sure the skip list hasn't been modified since the + // enumerator was created. + if(version != list.version) + { + throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator."); + } + // Make sure we are not before the beginning or beyond the + // end of the skip list. + else if(current == list.header) + { + throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator."); + } + // Finally, all checks have passed. Get the current entry. + else + { + entry = current.Entry; + } + + return entry; + } + } + + /// + /// Gets the key of the current dictionary entry. + /// + public object Key + { + get + { + object key = Entry.Key; + + return key; + } + } + + /// + /// Gets the value of the current dictionary entry. + /// + public object Value + { + get + { + object val = Entry.Value; + + return val; + } + } + + #endregion + + #region IEnumerator Members + + /// + /// Advances the enumerator to the next element of the skip list. + /// + /// + /// true if the enumerator was successfully advanced to the next + /// element; false if the enumerator has passed the end of the + /// skip list. + /// + public bool MoveNext() + { + // Make sure the skip list hasn't been modified since the + // enumerator was created. + if(version == list.version) + { + // If the result of the previous move operation was true + // we can still move forward in the skip list. + if(moveResult) + { + // Move forward in the skip list. + current = current.forward[0]; + + // If we are at the end of the skip list. + if(current == list.header) + { + // Indicate that we've reached the end of the skip + // list. + moveResult = false; + } + } + } + // Else this version of the enumerator doesn't match that of + // the skip list. The skip list has been modified since the + // creation of the enumerator. + else + { + throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator."); + } + + return moveResult; + } + + /// + /// Sets the enumerator to its initial position, which is before + /// the first element in the skip list. + /// + public void Reset() + { + // Make sure the skip list hasn't been modified since the + // enumerator was created. + if(version == list.version) + { + current = list.header; + moveResult = true; + } + // Else this version of the enumerator doesn't match that of + // the skip list. The skip list has been modified since the + // creation of the enumerator. + else + { + throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator."); + } + } + + /// + /// Gets the current element in the skip list. + /// + public object Current + { + get + { + return Entry; + } + } + + #endregion + } + + #endregion + + #region IDictionary Members + + /// + /// Adds an element with the provided key and value to the SkipList. + /// + /// + /// The Object to use as the key of the element to add. + /// + /// + /// The Object to use as the value of the element to add. + /// + public void Add(object key, object value) + { + Node[] update = new Node[MaxLevel]; + + // If key does not already exist in the skip list. + if(!Search(key, update)) + { + // Inseart key/value pair into the skip list. + Insert(key, value, update); + } + // Else throw an exception. The IDictionary Add method throws an + // exception if an attempt is made to add a key that already + // exists in the skip list. + else + { + throw new ArgumentException("An attempt was made to add an element in which the key of the element already exists in the SkipList."); + } + } + + /// + /// Removes all elements from the SkipList. + /// + public void Clear() + { + // Start at the beginning of the skip list. + Node curr = header.forward[0]; + Node prev; + + // While we haven't reached the end of the skip list. + while(curr != header) + { + // Keep track of the previous node. + prev = curr; + // Move forward in the skip list. + curr = curr.forward[0]; + // Dispose of the previous node. + prev.Dispose(); + } + + // Initialize skip list and indicate that it has been changed. + Initialize(); + version++; + } + + /// + /// Determines whether the SkipList contains an element with the + /// specified key. + /// + /// + /// The key to locate in the SkipList. + /// + /// + /// true if the SkipList contains an element with the key; otherwise, + /// false. + /// + public bool Contains(object key) + { + return Search(key); + } + + /// + /// Returns an IDictionaryEnumerator for the SkipList. + /// + /// + /// An IDictionaryEnumerator for the SkipList. + /// + public IDictionaryEnumerator GetEnumerator() + { + return new SkipListEnumerator(this); + } + + /// + /// Removes the element with the specified key from the SkipList. + /// + /// + /// The key of the element to remove. + /// + public void Remove(object key) + { + Node[] update = new Node[MaxLevel]; + Node curr; + + if(Search(key, out curr, update)) + { + // Take the forward references that point to the node to be + // removed and reassign them to the nodes that come after it. + for(int i = 0; i < listLevel && + update[i].forward[i] == curr; i++) + { + update[i].forward[i] = curr.forward[i]; + } + + curr.Dispose(); + + // After removing the node, we may need to lower the current + // skip list level if the node had the highest level of all of + // the nodes. + while(listLevel > 1 && header.forward[listLevel - 1] == header) + { + listLevel--; + } + + // Keep track of the number of nodes. + count--; + // Indicate that the skip list has changed. + version++; + } + } + + /// + /// Gets a value indicating whether the SkipList has a fixed size. + /// + public bool IsFixedSize + { + get + { + return false; + } + } + + /// + /// Gets a value indicating whether the IDictionary is read-only. + /// + public bool IsReadOnly + { + get + { + return false; + } + } + + /// + /// Gets or sets the element with the specified key. This is the + /// indexer for the SkipList. + /// + public object this[object key] + { + get + { + object val = null; + Node curr; + + if(Search(key, out curr)) + { + val = curr.Entry.Value; + } + + return val; + } + set + { + Node[] update = new Node[MaxLevel]; + Node curr; + + // If the search key already exists in the skip list. + if(Search(key, out curr, update)) + { + // Replace the current value with the new value. + curr.Value = value; + // Indicate that the skip list has changed. + version++; + } + // Else the key doesn't exist in the skip list. + else + { + // Insert the key and value into the skip list. + Insert(key, value, update); + } + } + } + + /// + /// Gets an ICollection containing the keys of the SkipList. + /// + public ICollection Keys + { + get + { + // Start at the beginning of the skip list. + Node curr = header.forward[0]; + // Create a collection to hold the keys. + ArrayList collection = new ArrayList(); + + // While we haven't reached the end of the skip list. + while(curr != header) + { + // Add the key to the collection. + collection.Add(curr.Entry.Key); + // Move forward in the skip list. + curr = curr.forward[0]; + } + + return collection; + } + } + + /// + /// Gets an ICollection containing the values of the SkipList. + /// + public ICollection Values + { + get + { + // Start at the beginning of the skip list. + Node curr = header.forward[0]; + // Create a collection to hold the values. + ArrayList collection = new ArrayList(); + + // While we haven't reached the end of the skip list. + while(curr != header) + { + // Add the value to the collection. + collection.Add(curr.Entry.Value); + // Move forward in the skip list. + curr = curr.forward[0]; + } + + return collection; + } + } + + #endregion + + #region ICollection Members + + /// + /// Copies the elements of the SkipList to an Array, starting at a + /// particular Array index. + /// + /// + /// The one-dimensional Array that is the destination of the elements + /// copied from SkipList. + /// + /// + /// The zero-based index in array at which copying begins. + /// + public void CopyTo(Array array, int index) + { + // Make sure array isn't null. + if(array == null) + { + throw new ArgumentNullException("An attempt was made to pass a null array to the CopyTo method of a SkipList."); + } + // Make sure index is not negative. + else if(index < 0) + { + throw new ArgumentOutOfRangeException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList."); + } + // Array bounds checking. + else if(index >= array.Length) + { + throw new ArgumentException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList."); + } + // Make sure that the number of elements in the skip list is not + // greater than the available space from index to the end of the + // array. + else if((array.Length - index) < Count) + { + throw new ArgumentException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList."); + } + // Else copy elements from skip list into array. + else + { + // Start at the beginning of the skip list. + Node curr = header.forward[0]; + + // While we haven't reached the end of the skip list. + while(curr != header) + { + // Copy current value into array. + array.SetValue(curr.Entry.Value, index); + + // Move forward in the skip list and array. + curr = curr.forward[0]; + index++; + } + } + } + + /// + /// Gets the number of elements contained in the SkipList. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets a value indicating whether access to the SkipList is + /// synchronized (thread-safe). + /// + public bool IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets an object that can be used to synchronize access to the + /// SkipList. + /// + public object SyncRoot + { + get + { + return this; + } + } + + #endregion + + #region IEnumerable Members + + /// + /// Returns an enumerator that can iterate through the SkipList. + /// + /// + /// An IEnumerator that can be used to iterate through the collection. + /// + IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return new SkipListEnumerator(this); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi.Core.csproj b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi.Core.csproj new file mode 100644 index 0000000..252ac39 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi.Core.csproj @@ -0,0 +1,12 @@ + + + netcoreapp3.1 + Local + + + 7.0.0 + + + docs\Sanford.Multimedia.Midi.XML + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/IClock.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/IClock.cs new file mode 100644 index 0000000..bec9a87 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/IClock.cs @@ -0,0 +1,92 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents functionality for generating events for driving Sequence playback. + /// + public interface IClock + { + #region IClock Members + + /// + /// Occurs when an IClock generates a tick. + /// + event EventHandler Tick; + + /// + /// Occurs when an IClock starts generating Ticks. + /// + /// + /// When an IClock is started, it resets itself and generates ticks to + /// drive playback from the beginning of the Sequence. + /// + event EventHandler Started; + + /// + /// Occurs when an IClock continues generating Ticks. + /// + /// + /// When an IClock is continued, it generates ticks to drive playback + /// from the current position within the Sequence. + /// + event EventHandler Continued; + + /// + /// Occurs when an IClock is stopped. + /// + event EventHandler Stopped; + + /// + /// Gets a value indicating whether the IClock is running. + /// + bool IsRunning + { + get; + } + + /// + /// Determines the number of ticks. + /// + int Ticks + { + get; + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/MidiInternalClock.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/MidiInternalClock.cs new file mode 100644 index 0000000..3f1b4b8 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/MidiInternalClock.cs @@ -0,0 +1,406 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using Sanford.Multimedia.Timers; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Generates clock events internally. + /// + public class MidiInternalClock : PpqnClock, IComponent + { + #region MidiInternalClock Members + + #region Fields + + // Used for generating tick events. + private ITimer timer; + + // Parses meta message tempo change messages. + private TempoChangeBuilder builder = new TempoChangeBuilder(); + + // Tick accumulator. + private int ticks = 0; + + // Indicates whether the clock has been disposed. + private bool disposed = false; + + private ISite site = null; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the MidiInternalClock class. + /// + public MidiInternalClock() + : this(TimerCaps.Default.periodMin) + { + } + + /// + /// Initializes a new instance of MidiInternalClock class with a specified base and a newly named integer. + /// + /// + /// The timer period in which the MidiInternalClock will use to determine the amount of time. + /// + public MidiInternalClock(int timerPeriod) : base(timerPeriod) + { + timer = TimerFactory.Create(); + timer.Period = timerPeriod; + timer.Tick += new EventHandler(HandleTick); + } + + /// + /// Initializes a new instance of the MidiInternalClock class with the + /// specified IContainer. + /// + /// + /// The IContainer to which the MidiInternalClock will add itself. + /// + public MidiInternalClock(IContainer container) : + this() + { + // Required for Windows.Forms Class Composition Designer support + container.Add(this); + } + + #endregion + + #region Methods + + /// + /// Starts the MidiInternalClock. + /// + public void Start() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("MidiInternalClock"); + } + + #endregion + + #region Guard + + if(running) + { + return; + } + + #endregion + + ticks = 0; + + Reset(); + + OnStarted(EventArgs.Empty); + + // Start the multimedia timer in order to start generating ticks. + timer.Start(); + + // Indicate that the clock is now running. + running = true; + + } + + /// + /// Resumes tick generation from the current position. + /// + public void Continue() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("MidiInternalClock"); + } + + #endregion + + #region Guard + + if(running) + { + return; + } + + #endregion + + // Raise Continued event. + OnContinued(EventArgs.Empty); + + // Start multimedia timer in order to start generating ticks. + timer.Start(); + + // Indicate that the clock is now running. + running = true; + } + + /// + /// Stops the MidiInternalClock. + /// + public void Stop() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("MidiInternalClock"); + } + + #endregion + + #region Guard + + if(!running) + { + return; + } + + #endregion + + // Stop the multimedia timer. + timer.Stop(); + + // Indicate that the clock is not running. + running = false; + + OnStopped(EventArgs.Empty); + } + + /// + /// Sets the amount of ticks determined by the integer. + /// + public void SetTicks(int ticks) + { + #region Require + + if(ticks < 0) + { + throw new ArgumentOutOfRangeException(); + } + + #endregion + + if(IsRunning) + { + Stop(); + } + + this.ticks = ticks; + + Reset(); + } + + /// + /// Processes with the meta message determined, along with the tempo. + /// + public void Process(MetaMessage message) + { + #region Require + + if(message == null) + { + throw new ArgumentNullException("message"); + } + + #endregion + + #region Guard + + if(message.MetaType != MetaType.Tempo) + { + return; + } + + #endregion + + TempoChangeBuilder builder = new TempoChangeBuilder(message); + + // Set the new tempo. + Tempo = builder.Tempo; + } + + #region Event Raiser Methods + + /// + /// Disposes of the MidiInternalClock when closed. + /// + protected virtual void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if(handler != null) + { + handler(this, e); + } + } + + #endregion + + #region Event Handler Methods + + // Handles Tick events generated by the multimedia timer. + private void HandleTick(object sender, EventArgs e) + { + int t = GenerateTicks(); + + for(int i = 0; i < t; i++) + { + OnTick(EventArgs.Empty); + + ticks++; + } + } + + #endregion + + #endregion + + #region Properties + + /// + /// Gets or sets the tempo in microseconds per beat. + /// + public int Tempo + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("MidiInternalClock"); + } + + #endregion + + return GetTempo(); + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("MidiInternalClock"); + } + + #endregion + + SetTempo(value); + } + } + + /// + /// Gets the ticks in microseconds per beat. + /// + public override int Ticks + { + get + { + return ticks; + } + } + + #endregion + + #endregion + + #region IComponent Members + + /// + /// Initializes the Disposed event. + /// + public event EventHandler Disposed; + + /// + /// Initializes the Site functionality using ISite. + /// + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Performs the main Dispose functionality for when the application is closed. + /// + public void Dispose() + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + if(running) + { + // Stop the multimedia timer. + timer.Stop(); + } + + disposed = true; + + timer.Dispose(); + + GC.SuppressFinalize(this); + + OnDisposed(EventArgs.Empty); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/PpqnClock.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/PpqnClock.cs new file mode 100644 index 0000000..2ecc5fd --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Clocks/PpqnClock.cs @@ -0,0 +1,324 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides basic functionality for generating tick events with pulses per + /// quarter note resolution. + /// + public abstract class PpqnClock : IClock + { + #region PpqnClock Members + + #region Fields + + /// + /// The default tempo in microseconds: 120bpm. + /// + public const int DefaultTempo = 500000; + + /// + /// The minimum pulses per quarter note value. + /// + public const int PpqnMinValue = 24; + + // The number of microseconds per millisecond. + private const int MicrosecondsPerMillisecond = 1000; + + // The pulses per quarter note value. + private int ppqn = PpqnMinValue; + + // The tempo in microseconds. + private int tempo = DefaultTempo; + + // The product of the timer period, the pulses per quarter note, and + // the number of microseconds per millisecond. + private int periodResolution; + + // The number of ticks per MIDI clock. + private int ticksPerClock; + + // The running fractional tick count. + private int fractionalTicks = 0; + + // The timer period. + private readonly int timerPeriod; + + /// + /// Indicates whether the clock is running. + /// + protected bool running = false; + + #endregion + + #region Construction + + /// + /// The PpqnClock determines how many ticks and timer period is used for the PPQN format. + /// + /// + /// The timerPeriod integer determines the amount of time there is. + /// + protected PpqnClock(int timerPeriod) + { + #region Require + + if(timerPeriod < 1) + { + throw new ArgumentOutOfRangeException("timerPeriod", timerPeriod, + "Timer period cannot be less than one."); + } + + #endregion + + this.timerPeriod = timerPeriod; + + CalculatePeriodResolution(); + CalculateTicksPerClock(); + } + + #endregion + + #region Methods + + /// + /// Gets the tempos per beat. + /// + protected int GetTempo() + { + return tempo; + } + + /// + /// Sets the tempos to be used per beat. + /// + protected void SetTempo(int tempo) + { + #region Require + + if(tempo < 1) + { + throw new ArgumentOutOfRangeException( + "Tempo out of range."); + } + + #endregion + + this.tempo = tempo; + } + + /// + /// Resets the amount of ticks. + /// + protected void Reset() + { + fractionalTicks = 0; + } + + /// + /// Generates the amount of ticks. + /// + protected int GenerateTicks() + { + int ticks = (fractionalTicks + periodResolution) / tempo; + fractionalTicks += periodResolution - ticks * tempo; + + return ticks; + } + + /// + /// Calculates the amount of time that the timer will have. + /// + private void CalculatePeriodResolution() + { + periodResolution = ppqn * timerPeriod * MicrosecondsPerMillisecond; + } + + /// + /// Calculates the amount of ticks per clock. + /// + private void CalculateTicksPerClock() + { + ticksPerClock = ppqn / PpqnMinValue; + } + + /// + /// An event that handles the ticks. + /// + protected virtual void OnTick(EventArgs e) + { + EventHandler handler = Tick; + + if(handler != null) + { + handler(this, EventArgs.Empty); + } + } + + /// + /// An event that starts the PPQN Clock. + /// + protected virtual void OnStarted(EventArgs e) + { + EventHandler handler = Started; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// An event that stops the PPQN Clock. + /// + protected virtual void OnStopped(EventArgs e) + { + EventHandler handler = Stopped; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// An event that continues the PPQN Clock. + /// + protected virtual void OnContinued(EventArgs e) + { + EventHandler handler = Continued; + + if(handler != null) + { + handler(this, e); + } + } + + #endregion + + #region Properties + + /// + /// An integer that gets and sets the PPQN Clock value. + /// + public int Ppqn + { + get + { + return ppqn; + } + set + { + #region Require + + if(value < PpqnMinValue) + { + throw new ArgumentOutOfRangeException("Ppqn", value, + "Pulses per quarter note is smaller than 24."); + } + + #endregion + + ppqn = value; + + CalculatePeriodResolution(); + CalculateTicksPerClock(); + } + } + + /// + /// An abstract integer that gets the amount of ticks. + /// + public abstract int Ticks + { + get; + } + + /// + /// An integer that determines the ticks per clock. + /// + /// + /// The amount of ticks per clock. + /// + public int TicksPerClock + { + get + { + return ticksPerClock; + } + } + + #endregion + + #endregion + + #region IClock Members + + /// + /// This event occurs when PPQN Clock generates a tick. + /// + public event System.EventHandler Tick; + + /// + /// This event occurs when PPQN Clock is started and starts generating ticks. + /// + public event System.EventHandler Started; + + /// + /// This event occurs when PPQN Clock continues generating ticks. + /// + public event System.EventHandler Continued; + + /// + /// This event occurs when PPQN Clock has stopped. + /// + public event System.EventHandler Stopped; + + /// + /// Checks if PPQN Clock is running. + /// + public bool IsRunning + { + get + { + return running; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Construction.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Construction.cs new file mode 100644 index 0000000..714c992 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Construction.cs @@ -0,0 +1,82 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Threading; +using Sanford.Threading; + +namespace Sanford.Multimedia.Midi +{ + public partial class InputDevice : MidiDevice + { + #region Construction + + /// + /// Initializes a new instance of the InputDevice class with the + /// specified device ID. + /// + public InputDevice(int deviceID, bool postEventsOnCreationContext = true, bool postDriverCallbackToDelegateQueue = true) + : base(deviceID) + { + midiInProc = HandleMessage; + + delegateQueue = new DelegateQueue(); + int result = midiInOpen(out handle, deviceID, midiInProc, IntPtr.Zero, CALLBACK_FUNCTION); + + System.Diagnostics.Debug.WriteLine("MidiIn handle:" + handle.ToInt64()); + + if (result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new InputDeviceException(result); + } + + PostEventsOnCreationContext = postEventsOnCreationContext; + PostDriverCallbackToDelegateQueue = postDriverCallbackToDelegateQueue; + } + + /// + /// The Input Device handler. + /// + ~InputDevice() + { + if (!IsDisposed) + { + midiInReset(handle); + midiInClose(handle); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Events.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Events.cs new file mode 100644 index 0000000..27ee277 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Events.cs @@ -0,0 +1,253 @@ +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Handles the MIDI Message Events. + /// + /// + /// This provides the basic functionality for all MIDI messages. + /// + public delegate void MidiMessageEventHandler(IMidiMessage message); + + public partial class InputDevice + { + /// + /// Gets or sets a value indicating whether the midi events should be posted on the same synchronization context as the device constructor was called. + /// Default is true. If set to false the events are fired on the driver callback or the thread of the driver callback delegate queue, depending on the PostDriverCallbackToDelegateQueue property. + /// + /// + /// true if midi events should be posted on the same synchronization context as the device constructor was called; otherwise, false. + /// + public bool PostEventsOnCreationContext + { + get; + set; + } + + /// + /// Occurs when any message was received. The underlying type of the message is as specific as possible. + /// Channel, Common, Realtime or SysEx. + /// + public event MidiMessageEventHandler MessageReceived; + + /// + /// Occurs when a short message was received. + /// + public event EventHandler ShortMessageReceived; + + /// + /// Occurs when a channel message was received. + /// + public event EventHandler ChannelMessageReceived; + + /// + /// Occurs when a system ex message was received. + /// + public event EventHandler SysExMessageReceived; + + /// + /// Occurs when a system common message was received. + /// + public event EventHandler SysCommonMessageReceived; + + /// + /// Occurs when a system realtime message was received. + /// + public event EventHandler SysRealtimeMessageReceived; + + /// + /// Occurs when a invalid short message was received. + /// + public event EventHandler InvalidShortMessageReceived; + + /// + /// Occurs when a invalid system ex message message was received. + /// + public event EventHandler InvalidSysExMessageReceived; + + /// + /// Occurs when a short message was sent. + /// + protected virtual void OnShortMessage(ShortMessageEventArgs e) + { + EventHandler handler = ShortMessageReceived; + + if (handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when a message was received. + /// + protected void OnMessageReceived(IMidiMessage message) + { + MidiMessageEventHandler handler = MessageReceived; + + if (handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(message); + }, null); + } + else + { + handler(message); + } + } + } + + /// + /// Occurs when a channel message is received. + /// + protected virtual void OnChannelMessageReceived(ChannelMessageEventArgs e) + { + EventHandler handler = ChannelMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when a system ex message is received. + /// + protected virtual void OnSysExMessageReceived(SysExMessageEventArgs e) + { + EventHandler handler = SysExMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when a system common message is received. + /// + protected virtual void OnSysCommonMessageReceived(SysCommonMessageEventArgs e) + { + EventHandler handler = SysCommonMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when a system realtime message is received. + /// + protected virtual void OnSysRealtimeMessageReceived(SysRealtimeMessageEventArgs e) + { + EventHandler handler = SysRealtimeMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when an invalid short message is received. + /// + protected virtual void OnInvalidShortMessageReceived(InvalidShortMessageEventArgs e) + { + EventHandler handler = InvalidShortMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + + /// + /// Occurs when an invalid system ex message is received. + /// + protected virtual void OnInvalidSysExMessageReceived(InvalidSysExMessageEventArgs e) + { + EventHandler handler = InvalidSysExMessageReceived; + + if(handler != null) + { + if (PostEventsOnCreationContext) + { + context.Post(delegate (object dummy) + { + handler(this, e); + }, null); + } + else + { + handler(this, e); + } + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Fields.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Fields.cs new file mode 100644 index 0000000..ff11255 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Fields.cs @@ -0,0 +1,71 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Threading; +using Sanford.Threading; + +namespace Sanford.Multimedia.Midi +{ + public partial class InputDevice + { + private delegate void GenericDelegate(T args); + + private DelegateQueue delegateQueue = null; + + private volatile int bufferCount = 0; + + private readonly object lockObject = new object(); + + private MidiInProc midiInProc; + + private bool recording = false; + + private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder(); + + private ChannelMessageBuilder cmBuilder = new ChannelMessageBuilder(); + + private SysCommonMessageBuilder scBuilder = new SysCommonMessageBuilder(); + + private IntPtr handle; + + private volatile bool resetting = false; + + private int sysExBufferSize = 4096; + + private List sysExData = new List(); + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Messaging.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Messaging.cs new file mode 100644 index 0000000..d05c1ed --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Messaging.cs @@ -0,0 +1,341 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; +using Sanford.Multimedia; + +namespace Sanford.Multimedia.Midi +{ + internal struct MidiInParams + { + public readonly IntPtr Param1; + public readonly IntPtr Param2; + + public MidiInParams(IntPtr param1, IntPtr param2) + { + Param1 = param1; + Param2 = param2; + } + } + + public partial class InputDevice : MidiDevice + { + /// + /// Gets or sets a value indicating whether the midi input driver callback should be posted on a delegate queue with its own thread. + /// Default is true. If set to false the driver callback directly calls the events for lowest possible latency. + /// + /// + /// true if the midi input driver callback should be posted on a delegate queue with its own thread; otherwise, false. + /// + public bool PostDriverCallbackToDelegateQueue + { + get; + set; + } + + //int FLastParam2; + + private void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2) + { + var param = new MidiInParams(param1, param2); + + if (msg == MIM_OPEN) + { + } + else if (msg == MIM_CLOSE) + { + } + else if (msg == MIM_DATA) + { + if (PostDriverCallbackToDelegateQueue) + delegateQueue.Post(HandleShortMessage, param); + else + HandleShortMessage(param); + } + else if (msg == MIM_MOREDATA) + { + if (PostDriverCallbackToDelegateQueue) + delegateQueue.Post(HandleShortMessage, param); + else + HandleShortMessage(param); + } + else if (msg == MIM_LONGDATA) + { + if (PostDriverCallbackToDelegateQueue) + delegateQueue.Post(HandleSysExMessage, param); + else + HandleSysExMessage(param); + } + else if (msg == MIM_ERROR) + { + if (PostDriverCallbackToDelegateQueue) + delegateQueue.Post(HandleInvalidShortMessage, param); + else + HandleInvalidShortMessage(param); + } + else if (msg == MIM_LONGERROR) + { + if (PostDriverCallbackToDelegateQueue) + delegateQueue.Post(HandleInvalidSysExMessage, param); + else + HandleInvalidSysExMessage(param); + } + } + + private void HandleShortMessage(object state) + { + + var param = (MidiInParams)state; + int message = param.Param1.ToInt32(); + int timestamp = param.Param2.ToInt32(); + + //first send RawMessage + OnShortMessage(new ShortMessageEventArgs(message, timestamp)); + + int status = ShortMessage.UnpackStatus(message); + + if (status >= (int)ChannelCommand.NoteOff && + status <= (int)ChannelCommand.PitchWheel + + ChannelMessage.MidiChannelMaxValue) + { + cmBuilder.Message = message; + cmBuilder.Build(); + + cmBuilder.Result.Timestamp = timestamp; + OnMessageReceived(cmBuilder.Result); + OnChannelMessageReceived(new ChannelMessageEventArgs(cmBuilder.Result)); + } + else if (status == (int)SysCommonType.MidiTimeCode || + status == (int)SysCommonType.SongPositionPointer || + status == (int)SysCommonType.SongSelect || + status == (int)SysCommonType.TuneRequest) + { + scBuilder.Message = message; + scBuilder.Build(); + + scBuilder.Result.Timestamp = timestamp; + OnMessageReceived(scBuilder.Result); + OnSysCommonMessageReceived(new SysCommonMessageEventArgs(scBuilder.Result)); + } + else + { + SysRealtimeMessageEventArgs e = null; + + switch ((SysRealtimeType)status) + { + case SysRealtimeType.ActiveSense: + e = SysRealtimeMessageEventArgs.ActiveSense; + break; + + case SysRealtimeType.Clock: + e = SysRealtimeMessageEventArgs.Clock; + break; + + case SysRealtimeType.Continue: + e = SysRealtimeMessageEventArgs.Continue; + break; + + case SysRealtimeType.Reset: + e = SysRealtimeMessageEventArgs.Reset; + break; + + case SysRealtimeType.Start: + e = SysRealtimeMessageEventArgs.Start; + break; + + case SysRealtimeType.Stop: + e = SysRealtimeMessageEventArgs.Stop; + break; + + case SysRealtimeType.Tick: + e = SysRealtimeMessageEventArgs.Tick; + break; + } + + e.Message.Timestamp = timestamp; + OnMessageReceived(e.Message); + OnSysRealtimeMessageReceived(e); + } + } + + private void HandleSysExMessage(object state) + { + lock (lockObject) + { + var param = (MidiInParams)state; + IntPtr headerPtr = param.Param1; + + MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); + + if (!resetting) + { + for (int i = 0; i < header.bytesRecorded; i++) + { + sysExData.Add(Marshal.ReadByte(header.data, i)); + } + + if (sysExData.Count > 1 && sysExData[0] == 0xF0 && sysExData[sysExData.Count - 1] == 0xF7) + { + SysExMessage message = new SysExMessage(sysExData.ToArray()); + message.Timestamp = param.Param2.ToInt32(); + + sysExData.Clear(); + + OnMessageReceived(message); + OnSysExMessageReceived(new SysExMessageEventArgs(message)); + } + + int result = AddSysExBuffer(); + + if (result != DeviceException.MMSYSERR_NOERROR) + { + Exception ex = new InputDeviceException(result); + + OnError(new ErrorEventArgs(ex)); + } + } + + ReleaseBuffer(headerPtr); + } + } + + private void HandleInvalidShortMessage(object state) + { + var param = (MidiInParams)state; + OnInvalidShortMessageReceived(new InvalidShortMessageEventArgs(param.Param1.ToInt32())); + } + + private void HandleInvalidSysExMessage(object state) + { + lock (lockObject) + { + var param = (MidiInParams)state; + IntPtr headerPtr = param.Param1; + + MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); + + if (!resetting) + { + byte[] data = new byte[header.bytesRecorded]; + + Marshal.Copy(header.data, data, 0, data.Length); + + OnInvalidSysExMessageReceived(new InvalidSysExMessageEventArgs(data)); + + int result = AddSysExBuffer(); + + if (result != DeviceException.MMSYSERR_NOERROR) + { + Exception ex = new InputDeviceException(result); + + OnError(new ErrorEventArgs(ex)); + } + } + + ReleaseBuffer(headerPtr); + } + } + + private void ReleaseBuffer(IntPtr headerPtr) + { + int result = midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader); + + if (result != DeviceException.MMSYSERR_NOERROR) + { + Exception ex = new InputDeviceException(result); + + OnError(new ErrorEventArgs(ex)); + } + + headerBuilder.Destroy(headerPtr); + + bufferCount--; + + Debug.Assert(bufferCount >= 0); + + Monitor.Pulse(lockObject); + } + + /// + /// Creates a system ex buffer for MIDI headers. + /// + public int AddSysExBuffer() + { + int result; + + // Initialize the MidiHeader builder. + headerBuilder.BufferLength = sysExBufferSize; + headerBuilder.Build(); + + // Get the pointer to the built MidiHeader. + IntPtr headerPtr = headerBuilder.Result; + + // Prepare the header to be used. + result = midiInPrepareHeader(Handle, headerPtr, SizeOfMidiHeader); + + // If the header was perpared successfully. + if (result == DeviceException.MMSYSERR_NOERROR) + { + bufferCount++; + + // Add the buffer to the InputDevice. + result = midiInAddBuffer(Handle, headerPtr, SizeOfMidiHeader); + + // If the buffer could not be added. + if (result != MidiDeviceException.MMSYSERR_NOERROR) + { + // Unprepare header - there's a chance that this will fail + // for whatever reason, but there's not a lot that can be + // done at this point. + midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader); + + bufferCount--; + + // Destroy header. + headerBuilder.Destroy(); + } + } + // Else the header could not be prepared. + else + { + // Destroy header. + headerBuilder.Destroy(); + } + + return result; + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Properties.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Properties.cs new file mode 100644 index 0000000..0ac6e3a --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Properties.cs @@ -0,0 +1,88 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; + +namespace Sanford.Multimedia.Midi +{ + public partial class InputDevice + { + /// + /// Gets the Input Device handle. + /// + public override IntPtr Handle + { + get + { + return handle; + } + } + + /// + /// Gets and sets the system ex buffer size. + /// + public int SysExBufferSize + { + get + { + return sysExBufferSize; + } + set + { + #region Require + + if(value < 1) + { + throw new ArgumentOutOfRangeException(); + } + + #endregion + + sysExBufferSize = value; + } + } + + /// + /// Determines how many Input Devices there are. + /// + public static int DeviceCount + { + get + { + return midiInGetNumDevs(); + } + } + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.PublicMethods.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.PublicMethods.cs new file mode 100644 index 0000000..2c20688 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.PublicMethods.cs @@ -0,0 +1,235 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Diagnostics; +using System.Threading; + +namespace Sanford.Multimedia.Midi +{ + public partial class InputDevice + { + /// + /// Closes the MIDI input device. + /// + public override void Close() + { + #region Guard + + if(IsDisposed) + { + return; + } + + #endregion + + Dispose(true); + } + + /// + /// Starts recording from the MIDI input device. + /// + public void StartRecording() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("InputDevice"); + } + + #endregion + + #region Guard + + if(recording) + { + return; + } + + #endregion + + lock(lockObject) + { + int result = AddSysExBuffer(); + + if(result == DeviceException.MMSYSERR_NOERROR) + { + result = AddSysExBuffer(); + } + + if(result == DeviceException.MMSYSERR_NOERROR) + { + result = AddSysExBuffer(); + } + + if(result == DeviceException.MMSYSERR_NOERROR) + { + result = AddSysExBuffer(); + } + + if(result == DeviceException.MMSYSERR_NOERROR) + { + result = midiInStart(Handle); + } + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + recording = true; + } + else + { + throw new InputDeviceException(result); + } + } + } + + /// + /// Stops recording from the MIDI input device. + /// + public void StopRecording() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("InputDevice"); + } + + #endregion + + #region Guard + + if(!recording) + { + return; + } + + #endregion + + lock(lockObject) + { + int result = midiInStop(Handle); + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + recording = false; + } + else + { + throw new InputDeviceException(result); + } + } + } + + /// + /// Resets the MIDI input device. + /// + public override void Reset() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("InputDevice"); + } + + #endregion + + lock(lockObject) + { + resetting = true; + + int result = midiInReset(Handle); + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + recording = false; + + while(bufferCount > 0) + { + Monitor.Wait(lockObject); + } + + resetting = false; + } + else + { + resetting = false; + + throw new InputDeviceException(result); + } + } + } + + /// + /// Initializes the MIDI input device capabilities. + /// + /// + /// This will show the device ID for the MIDI input device. + /// + public static MidiInCaps GetDeviceCapabilities(int deviceID) + { + int result; + MidiInCaps caps = new MidiInCaps(); + + IntPtr devID = (IntPtr)deviceID; + result = midiInGetDevCaps(devID, ref caps, SizeOfMidiHeader); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new InputDeviceException(result); + } + + return caps; + } + + /// + /// When closed, all connections to the MIDI input device are disposed. + /// + public override void Dispose() + { + #region Guard + + if(IsDisposed) + { + return; + } + + #endregion + + Dispose(true); + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Win32.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Win32.cs new file mode 100644 index 0000000..988e9b3 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.Win32.cs @@ -0,0 +1,95 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Midi + { + public partial class InputDevice + { + // Represents the method that handles messages from Windows. + private delegate void MidiInProc(IntPtr handle, int msg, IntPtr instance, IntPtr param1, IntPtr param2); + + #region Win32 MIDI Input Functions and Constants + + [DllImport("winmm.dll")] + private static extern int midiInOpen(out IntPtr handle, int deviceID, + MidiInProc proc, IntPtr instance, int flags); + + [DllImport("winmm.dll")] + private static extern int midiInClose(IntPtr handle); + + [DllImport("winmm.dll")] + private static extern int midiInStart(IntPtr handle); + + [DllImport("winmm.dll")] + private static extern int midiInStop(IntPtr handle); + + [DllImport("winmm.dll")] + private static extern int midiInReset(IntPtr handle); + + [DllImport("winmm.dll")] + private static extern int midiInPrepareHeader(IntPtr handle, + IntPtr headerPtr, int sizeOfMidiHeader); + + [DllImport("winmm.dll")] + private static extern int midiInUnprepareHeader(IntPtr handle, + IntPtr headerPtr, int sizeOfMidiHeader); + + [DllImport("winmm.dll")] + private static extern int midiInAddBuffer(IntPtr handle, + IntPtr headerPtr, int sizeOfMidiHeader); + + [DllImport("winmm.dll")] + private static extern int midiInGetDevCaps(IntPtr deviceID, + ref MidiInCaps caps, int sizeOfMidiInCaps); + + [DllImport("winmm.dll")] + private static extern int midiInGetNumDevs(); + + private const int MIDI_IO_STATUS = 0x00000020; + + private const int MIM_OPEN = 0x3C1; + private const int MIM_CLOSE = 0x3C2; + private const int MIM_DATA = 0x3C3; + private const int MIM_LONGDATA = 0x3C4; + private const int MIM_ERROR = 0x3C5; + private const int MIM_LONGERROR = 0x3C6; + private const int MIM_MOREDATA = 0x3CC; + private const int MHDR_DONE = 0x00000001; + + #endregion + } + } diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.cs new file mode 100644 index 0000000..2e1737f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/InputDevice.cs @@ -0,0 +1,137 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents a MIDI device capable of receiving MIDI events. + /// + public partial class InputDevice : MidiDevice + { + /// + /// Disposes the data when closed. + /// + protected override void Dispose(bool disposing) + { + if(disposing) + { + lock(lockObject) + { + Reset(); + + int result = midiInClose(handle); + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + delegateQueue.Dispose(); + } + else + { + throw new InputDeviceException(result); + } + } + } + else + { + midiInReset(handle); + midiInClose(handle); + } + + base.Dispose(disposing); + } + } + + /// + /// The exception that is thrown when a error occurs with the InputDevice + /// class. + /// + public class InputDeviceException : MidiDeviceException + { + #region InputDeviceException Members + + #region Win32 Midi Input Error Function + + [DllImport("winmm.dll", CharSet = CharSet.Unicode)] + private static extern int midiInGetErrorText(int errCode, + StringBuilder errMsg, int sizeOfErrMsg); + + #endregion + + #region Fields + + // Error message. + private StringBuilder errMsg = new StringBuilder(128); + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the InputDeviceException class with + /// the specified error code. + /// + /// + /// The error code. + /// + public InputDeviceException(int errCode) : base(errCode) + { + // Get error message. + midiInGetErrorText(errCode, errMsg, errMsg.Capacity); + } + + #endregion + + #region Properties + + /// + /// Gets a message that describes the current exception. + /// + public override string Message + { + get + { + return errMsg.ToString(); + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/MidiInCaps.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/MidiInCaps.cs new file mode 100644 index 0000000..d36da93 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/InputDevice Class/MidiInCaps.cs @@ -0,0 +1,79 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents MIDI input device capabilities. + /// + [StructLayout(LayoutKind.Sequential)] + public struct MidiInCaps + { + #region MidiInCaps Members + + /// + /// Manufacturer identifier of the device driver for the Midi output + /// device. + /// + public short mid; + + /// + /// Product identifier of the Midi output device. + /// + public short pid; + + /// + /// Version number of the device driver for the Midi output device. The + /// high-order byte is the major version number, and the low-order byte + /// is the minor version number. + /// + public int driverVersion; + + /// + /// Product name. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string name; + + /// + /// Optional functionality supported by the device. + /// + public int support; + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDevice.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDevice.cs new file mode 100644 index 0000000..6a952ca --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDevice.cs @@ -0,0 +1,125 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using Sanford.Multimedia; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The base abstract class for all MIDI devices. + /// + public abstract class MidiDevice : Device + { + #region MidiDevice Members + + #region Win32 Midi Device Functions + + [DllImport("winmm.dll")] + private static extern int midiConnect(IntPtr handleA, IntPtr handleB, IntPtr reserved); + + [DllImport("winmm.dll")] + private static extern int midiDisconnect(IntPtr handleA, IntPtr handleB, IntPtr reserved); + + #endregion + + /// + /// Size of the MidiHeader structure. + /// + protected static readonly int SizeOfMidiHeader; + + static MidiDevice() + { + SizeOfMidiHeader = Marshal.SizeOf(typeof(MidiHeader)); + } + + /// + /// The main function for all MIDI devices. + /// + public MidiDevice(int deviceID) : base(deviceID) + { + } + + /// + /// Connects a MIDI InputDevice to a MIDI thru or OutputDevice, or + /// connects a MIDI thru device to a MIDI OutputDevice. + /// + /// + /// Handle to a MIDI InputDevice or a MIDI thru device (for thru + /// devices, this handle must belong to a MIDI OutputDevice). + /// + /// + /// Handle to the MIDI OutputDevice or thru device. + /// + /// + /// If an error occurred while connecting the two devices. + /// + public static void Connect(IntPtr handleA, IntPtr handleB) + { + int result = midiConnect(handleA, handleB, IntPtr.Zero); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new MidiDeviceException(result); + } + } + + /// + /// Disconnects a MIDI InputDevice from a MIDI thru or OutputDevice, or + /// disconnects a MIDI thru device from a MIDI OutputDevice. + /// + /// + /// Handle to a MIDI InputDevice or a MIDI thru device. + /// + /// + /// Handle to the MIDI OutputDevice to be disconnected. + /// + /// + /// If an error occurred while disconnecting the two devices. + /// + public static void Disconnect(IntPtr handleA, IntPtr handleB) + { + int result = midiDisconnect(handleA, handleB, IntPtr.Zero); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new MidiDeviceException(result); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDeviceException.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDeviceException.cs new file mode 100644 index 0000000..a153198 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiDeviceException.cs @@ -0,0 +1,100 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The base class for all MIDI device exception classes. + /// + public class MidiDeviceException : DeviceException + { + #region Error Codes + + /// + /// This error occurs when the header is not prepared. + /// + public const int MIDIERR_UNPREPARED = 64; /* header not prepared */ + /// + /// This error occurs when the MIDI player is still playing something. + /// + public const int MIDIERR_STILLPLAYING = 65; /* still something playing */ + /// + /// This error occurs when there are no configured instruments. + /// + public const int MIDIERR_NOMAP = 66; /* no configured instruments */ + /// + /// This error occurs when the hardware is still busy. + /// + public const int MIDIERR_NOTREADY = 67; /* hardware is still busy */ + /// + /// This error occurs when the port is no longer connected. + /// + public const int MIDIERR_NODEVICE = 68; /* port no longer connected */ + /// + /// This error occurs when there is an invalid MIF. + /// + public const int MIDIERR_INVALIDSETUP = 69; /* invalid MIF */ + /// + /// This error occurs when the operation is unsupported with open mode. + /// + public const int MIDIERR_BADOPENMODE = 70; /* operation unsupported w/ open mode */ + /// + /// This error occurs when the through device is eating up a message. + /// + public const int MIDIERR_DONT_CONTINUE = 71; /* thru device 'eating' a message */ + /// + /// This error is the last error in range. + /// + public const int MIDIERR_LASTERROR = 71; /* last error in range */ + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the DeviceException class with the + /// specified error code. + /// + /// + /// The error code. + /// + public MidiDeviceException(int errCode) : base(errCode) + { + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeader.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeader.cs new file mode 100644 index 0000000..7bc4ed6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeader.cs @@ -0,0 +1,101 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents the Windows Multimedia MIDIHDR structure. + /// + [StructLayout(LayoutKind.Sequential)] + internal struct MidiHeader + { + #region MidiHeader Members + + /// + /// Pointer to MIDI data. + /// + public IntPtr data; + + /// + /// Size of the buffer. + /// + public int bufferLength; + + /// + /// Actual amount of data in the buffer. This value should be less than + /// or equal to the value given in the dwBufferLength member. + /// + public int bytesRecorded; + + /// + /// Custom user data. + /// + public int user; + + /// + /// Flags giving information about the buffer. + /// + public int flags; + + /// + /// Reserved; do not use. + /// + public IntPtr next; + + /// + /// Reserved; do not use. + /// + public int reserved; + + /// + /// Offset into the buffer when a callback is performed. (This + /// callback is generated because the MEVT_F_CALLBACK flag is + /// set in the dwEvent member of the MidiEventArgs structure.) + /// This offset enables an application to determine which + /// event caused the callback. + /// + public int offset; + + /// + /// Reserved; do not use. + /// + [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] + public int[] reservedArray; + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeaderBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeaderBuilder.cs new file mode 100644 index 0000000..5664cca --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/MidiHeaderBuilder.cs @@ -0,0 +1,248 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Builds a pointer to a MidiHeader structure. + /// + internal class MidiHeaderBuilder + { + // The length of the system exclusive buffer. + private int bufferLength; + + // The system exclusive data. + private byte[] data; + + // Indicates whether the pointer to the MidiHeader has been built. + private bool built = false; + + // The built pointer to the MidiHeader. + private IntPtr result; + + /// + /// Initializes a new instance of the MidiHeaderBuilder. + /// + public MidiHeaderBuilder() + { + BufferLength = 1; + } + + #region Methods + + /// + /// Builds the pointer to the MidiHeader structure. + /// + public void Build() + { + MidiHeader header = new MidiHeader(); + + // Initialize the MidiHeader. + header.bufferLength = BufferLength; + header.bytesRecorded = BufferLength; + header.data = Marshal.AllocHGlobal(BufferLength); + header.flags = 0; + + // Write data to the MidiHeader. + for(int i = 0; i < BufferLength; i++) + { + Marshal.WriteByte(header.data, i, data[i]); + } + + try + { + result = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MidiHeader))); + } + catch(Exception) + { + Marshal.FreeHGlobal(header.data); + + throw; + } + + try + { + Marshal.StructureToPtr(header, result, false); + } + catch(Exception) + { + Marshal.FreeHGlobal(header.data); + Marshal.FreeHGlobal(result); + + throw; + } + + built = true; + } + + /// + /// Initializes the MidiHeaderBuilder with the specified SysExMessage. + /// + /// + /// The SysExMessage to use for initializing the MidiHeaderBuilder. + /// + public void InitializeBuffer(SysExMessage message) + { + // If this is a start system exclusive message. + if(message.SysExType == SysExType.Start) + { + BufferLength = message.Length; + + // Copy entire message. + for(int i = 0; i < BufferLength; i++) + { + data[i] = message[i]; + } + } + // Else this is a continuation message. + else + { + BufferLength = message.Length - 1; + + // Copy all but the first byte of message. + for(int i = 0; i < BufferLength; i++) + { + data[i] = message[i + 1]; + } + } + } + + public void InitializeBuffer(ICollection events) + { + #region Require + + if(events == null) + { + throw new ArgumentNullException("events"); + } + else if(events.Count % 4 != 0) + { + throw new ArgumentException("Stream events not word aligned."); + } + + #endregion + + #region Guard + + if(events.Count == 0) + { + return; + } + + #endregion + + BufferLength = events.Count; + + events.CopyTo(data, 0); + } + + /// + /// Releases the resources associated with the built MidiHeader pointer. + /// + public void Destroy() + { + #region Require + + if(!built) + { + throw new InvalidOperationException("Cannot destroy MidiHeader"); + } + + #endregion + + Destroy(result); + } + + /// + /// Releases the resources associated with the specified MidiHeader pointer. + /// + /// + /// The MidiHeader pointer. + /// + public void Destroy(IntPtr headerPtr) + { + MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); + + Marshal.FreeHGlobal(header.data); + Marshal.FreeHGlobal(headerPtr); + } + + #endregion + + #region Properties + + /// + /// The length of the system exclusive buffer. + /// + public int BufferLength + { + get + { + return bufferLength; + } + set + { + #region Require + + if(value <= 0) + { + throw new ArgumentOutOfRangeException("BufferLength", value, + "MIDI header buffer length out of range."); + } + + #endregion + + bufferLength = value; + data = new byte[value]; + } + } + + /// + /// Gets the pointer to the MidiHeader. + /// + public IntPtr Result + { + get + { + return result; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/MidiOutCaps.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/MidiOutCaps.cs new file mode 100644 index 0000000..bfab960 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/MidiOutCaps.cs @@ -0,0 +1,107 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents MIDI output device capabilities. + /// + [StructLayout(LayoutKind.Sequential)] + public struct MidiOutCaps + { + #region MidiOutCaps Members + + /// + /// Manufacturer identifier of the device driver for the Midi output + /// device. + /// + public short mid; + + /// + /// Product identifier of the Midi output device. + /// + public short pid; + + /// + /// Version number of the device driver for the Midi output device. The + /// high-order byte is the major version number, and the low-order byte + /// is the minor version number. + /// + public int driverVersion; + + /// + /// Product name. + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string name; + + /// + /// Flags describing the type of the Midi output device. + /// + public short technology; + + /// + /// Number of voices supported by an internal synthesizer device. If + /// the device is a port, this member is not meaningful and is set + /// to 0. + /// + public short voices; + + /// + /// Maximum number of simultaneous notes that can be played by an + /// internal synthesizer device. If the device is a port, this member + /// is not meaningful and is set to 0. + /// + public short notes; + + /// + /// Channels that an internal synthesizer device responds to, where the + /// least significant bit refers to channel 0 and the most significant + /// bit to channel 15. Port devices that transmit on all channels set + /// this member to 0xFFFF. + /// + public short channelMask; + + /// + /// Optional functionality supported by the device. + /// + public int support; + + #endregion + } + +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/NoOpEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/NoOpEventArgs.cs new file mode 100644 index 0000000..18674d6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/NoOpEventArgs.cs @@ -0,0 +1,65 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The event args class for no operations. + /// + public class NoOpEventArgs : EventArgs + { + private int data; + + /// + /// The function for the no operation events. + /// + public NoOpEventArgs(int data) + { + this.data = data; + } + + /// + /// Gets and returns the data. + /// + public int Data + { + get + { + return data; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDevice.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDevice.cs new file mode 100644 index 0000000..906b2ef --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDevice.cs @@ -0,0 +1,309 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents a device capable of sending MIDI messages. + /// + public sealed class OutputDevice : OutputDeviceBase + { + #region Win32 Midi Output Functions and Constants + + [DllImport("winmm.dll")] + private static extern int midiOutOpen(out IntPtr DeviceHandle, int deviceID, + MidiOutProc proc, IntPtr instance, int flags); + + [DllImport("winmm.dll")] + private static extern int midiOutClose(IntPtr DeviceHandle); + + #endregion + + private MidiOutProc midiOutProc; + + private bool runningStatusEnabled = false; + + private int runningStatus = 0; + + #region Construction + + /// + /// Initializes a new instance of the OutputDevice class. + /// + public OutputDevice(int deviceID) : base(deviceID) + { + midiOutProc = HandleMessage; + + int result = midiOutOpen(out DeviceHandle, deviceID, midiOutProc, IntPtr.Zero, CALLBACK_FUNCTION); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + + #endregion + + /// + /// When closed, disposes of the MIDI output device. + /// + protected override void Dispose(bool disposing) + { + if(disposing) + { + lock(lockObject) + { + Reset(); + + // Close the OutputDevice. + int result = midiOutClose(Handle); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + // Throw an exception. + throw new OutputDeviceException(result); + } + } + } + else + { + midiOutReset(Handle); + midiOutClose(Handle); + } + + base.Dispose(disposing); + } + + /// + /// Closes the OutputDevice. + /// + /// + /// If an error occurred while closing the OutputDevice. + /// + public override void Close() + { + #region Guard + + if(IsDisposed) + { + return; + } + + #endregion + + Dispose(true); + } + + /// + /// Resets the OutputDevice. + /// + public override void Reset() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + runningStatus = 0; + + base.Reset(); + } + + /// + /// Sends the MIDI output channel device message. + /// + public override void Send(ChannelMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(lockObject) + { + // If running status is enabled. + if(runningStatusEnabled) + { + // If the message's status value matches the running status. + if(message.Status == runningStatus) + { + // Send only the two data bytes without the status byte. + Send(message.Message >> 8); + } + // Else the message's status value does not match the running + // status. + else + { + // Send complete message with status byte. + Send(message.Message); + + // Update running status. + runningStatus = message.Status; + } + } + // Else running status has not been enabled. + else + { + Send(message.Message); + } + } + } + + /// + /// Sends a system ex MIDI output device message. + /// + public override void Send(SysExMessage message) + { + // System exclusive cancels running status. + runningStatus = 0; + + base.Send(message); + } + + /// + /// Sends a system common MIDI output device message. + /// + public override void Send(SysCommonMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + // System common cancels running status. + runningStatus = 0; + + base.Send(message); + } + + #region Properties + + /// + /// Gets or sets a value indicating whether the OutputDevice uses + /// a running status. + /// + public bool RunningStatusEnabled + { + get + { + return runningStatusEnabled; + } + set + { + runningStatusEnabled = value; + + // Reset running status. + runningStatus = 0; + } + } + + #endregion + } + + /// + /// The exception that is thrown when a error occurs with the OutputDevice + /// class. + /// + public class OutputDeviceException : MidiDeviceException + { + #region OutputDeviceException Members + + #region Win32 Midi Output Error Function + + [DllImport("winmm.dll", CharSet = CharSet.Unicode)] + private static extern int midiOutGetErrorText(int errCode, + StringBuilder message, int sizeOfMessage); + + #endregion + + #region Fields + + // The error message. + private StringBuilder message = new StringBuilder(128); + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the OutputDeviceException class with + /// the specified error code. + /// + /// + /// The error code. + /// + public OutputDeviceException(int errCode) : base(errCode) + { + // Get error message. + midiOutGetErrorText(errCode, message, message.Capacity); + } + + #endregion + + #region Properties + + /// + /// Gets a message that describes the current exception. + /// + public override string Message + { + get + { + return message.ToString(); + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDeviceBase.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDeviceBase.cs new file mode 100644 index 0000000..af7b650 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputDeviceBase.cs @@ -0,0 +1,457 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; +using Sanford.Threading; + +namespace Sanford.Multimedia.Midi +{ + /// + /// This is an abstract class for MIDI output devices. + /// + public abstract class OutputDeviceBase : MidiDevice + { + /// + /// Handles resetting the MIDI output device. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutReset(IntPtr DeviceHandle); + + /// + /// Handles the MIDI output device short messages. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutShortMsg(IntPtr DeviceHandle, int message); + + /// + /// Handles preparing the headers for the MIDI output device. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutPrepareHeader(IntPtr DeviceHandle, + IntPtr headerPtr, int sizeOfMidiHeader); + + /// + /// Handles unpreparing the headers for the MIDI output device. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutUnprepareHeader(IntPtr DeviceHandle, + IntPtr headerPtr, int sizeOfMidiHeader); + + /// + /// Handles the MIDI output device long message. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutLongMsg(IntPtr DeviceHandle, + IntPtr headerPtr, int sizeOfMidiHeader); + + /// + /// Obtains the MIDI output device caps. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutGetDevCaps(IntPtr deviceID, + ref MidiOutCaps caps, int sizeOfMidiOutCaps); + + /// + /// Obtains the number of MIDI output devices. + /// + [DllImport("winmm.dll")] + protected static extern int midiOutGetNumDevs(); + + /// + /// A construct integer that tells the compiler that hexadecimal value 0x3C7 means MOM_OPEN. + /// + protected const int MOM_OPEN = 0x3C7; + + /// + /// A construct integer that tells the compiler that hexadecimal value 0x3C8 means MOM_CLOSE. + /// + protected const int MOM_CLOSE = 0x3C8; + + /// + /// A construct integer that tells the compiler that hexadecimal value 0x3C9 means MOM_DONE. + /// + protected const int MOM_DONE = 0x3C9; + + /// + /// This delegate is a generic delegate for the MIDI output devices. + /// + protected delegate void GenericDelegate(T args); + + /// + /// Represents the method that handles messages from Windows. + /// + protected delegate void MidiOutProc(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2); + + /// + /// For releasing buffers. + /// + protected DelegateQueue delegateQueue = new DelegateQueue(); + + /// + /// This object remains locked in place. + /// + protected readonly object lockObject = new object(); + + /// + /// The number of buffers still in the queue. + /// + protected int bufferCount = 0; + + /// + /// Builds MidiHeader structures for sending system exclusive messages. + /// + private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder(); + + /// + /// The device handle. + /// + protected IntPtr DeviceHandle = IntPtr.Zero; + + /// + /// Base class for output devices with an integer. + /// + /// + /// Device ID is used here. + /// + public OutputDeviceBase(int deviceID) : base(deviceID) + { + } + + /// + /// Disposes when it has been closed. + /// + ~OutputDeviceBase() + { + Dispose(false); + } + + /// + /// This dispose function will dispose all delegates that are queued when closed. + /// + protected override void Dispose(bool disposing) + { + if(disposing) + { + delegateQueue.Dispose(); + } + + base.Dispose(disposing); + } + + /// + /// Sends the MIDI output channel device message. + /// + public virtual void Send(ChannelMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + Send(message.Message); + } + + /// + /// Sends a short MIDI output channel device message. + /// + public virtual void SendShort(int message) + { + #region Require + + if (IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + Send(message); + } + + /// + /// Sends a system ex MIDI output channel device message. + /// + public virtual void Send(SysExMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(lockObject) + { + headerBuilder.InitializeBuffer(message); + headerBuilder.Build(); + + // Prepare system exclusive buffer. + int result = midiOutPrepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); + + // If the system exclusive buffer was prepared successfully. + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + bufferCount++; + + // Send system exclusive message. + result = midiOutLongMsg(Handle, headerBuilder.Result, SizeOfMidiHeader); + + // If the system exclusive message could not be sent. + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + midiOutUnprepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); + bufferCount--; + headerBuilder.Destroy(); + + // Throw an exception. + throw new OutputDeviceException(result); + } + } + // Else the system exclusive buffer could not be prepared. + else + { + // Destroy system exclusive buffer. + headerBuilder.Destroy(); + + // Throw an exception. + throw new OutputDeviceException(result); + } + } + } + + /// + /// Sends a system common MIDI output device message. + /// + public virtual void Send(SysCommonMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + Send(message.Message); + } + + /// + /// Sends a system realtime MIDI output device message. + /// + public virtual void Send(SysRealtimeMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + Send(message.Message); + } + + /// + /// Resets the MIDI output device. + /// + public override void Reset() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(lockObject) + { + // Reset the OutputDevice. + int result = midiOutReset(Handle); + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + while(bufferCount > 0) + { + Monitor.Wait(lockObject); + } + } + else + { + // Throw an exception. + throw new OutputDeviceException(result); + } + } + } + + /// + /// Sends a MIDI output device message. + /// + protected void Send(int message) + { + lock(lockObject) + { + int result = midiOutShortMsg(Handle, message); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + + /// + /// Initializes the MIDI output device capabilities. + /// + public static MidiOutCaps GetDeviceCapabilities(int deviceID) + { + MidiOutCaps caps = new MidiOutCaps(); + + // Get the device's capabilities. + IntPtr devId = (IntPtr)deviceID; + int result = midiOutGetDevCaps(devId, ref caps, Marshal.SizeOf(caps)); + + // If the capabilities could not be retrieved. + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + // Throw an exception. + throw new OutputDeviceException(result); + } + + return caps; + } + + /// + /// Handles Windows messages. + /// + protected virtual void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2) + { + if(msg == MOM_OPEN) + { + } + else if(msg == MOM_CLOSE) + { + } + else if(msg == MOM_DONE) + { + delegateQueue.Post(ReleaseBuffer, param1); + } + } + + /// + /// Releases buffers. + /// + private void ReleaseBuffer(object state) + { + lock(lockObject) + { + IntPtr headerPtr = (IntPtr)state; + + // Unprepare the buffer. + int result = midiOutUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + Exception ex = new OutputDeviceException(result); + + OnError(new ErrorEventArgs(ex)); + } + + // Release the buffer resources. + headerBuilder.Destroy(headerPtr); + + bufferCount--; + + Monitor.Pulse(lockObject); + + Debug.Assert(bufferCount >= 0); + } + } + + /// + /// When closed, disposes the object that is locked in place. + /// + public override void Dispose() + { + #region Guard + + if(IsDisposed) + { + return; + } + + #endregion + + lock(lockObject) + { + Close(); + } + } + + /// + /// Handles the MIDI output device pointer. + /// + public override IntPtr Handle + { + get + { + return DeviceHandle; + } + } + + /// + /// Counts the number of MIDI output devices. + /// + public static int DeviceCount + { + get + { + return midiOutGetNumDevs(); + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputStream.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputStream.cs new file mode 100644 index 0000000..fd5dfae --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Device Classes/OutputDevice Classes/OutputStream.cs @@ -0,0 +1,665 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Threading; +using Sanford.Multimedia.Timers; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Sealed class stream for MIDI output devices. + /// + public sealed class OutputStream : OutputDeviceBase + { + [DllImport("winmm.dll")] + private static extern int midiStreamOpen(ref IntPtr DeviceHandle, ref int deviceID, int reserved, + OutputDevice.MidiOutProc proc, IntPtr instance, uint flag); + + [DllImport("winmm.dll")] + private static extern int midiStreamClose(IntPtr DeviceHandle); + + [DllImport("winmm.dll")] + private static extern int midiStreamOut(IntPtr DeviceHandle, IntPtr headerPtr, int sizeOfMidiHeader); + + [DllImport("winmm.dll")] + private static extern int midiStreamPause(IntPtr DeviceHandle); + + [DllImport("winmm.dll")] + private static extern int midiStreamPosition(IntPtr DeviceHandle, ref Time t, int sizeOfTime); + + [DllImport("winmm.dll")] + private static extern int midiStreamProperty(IntPtr DeviceHandle, ref Property p, uint flags); + + [DllImport("winmm.dll")] + private static extern int midiStreamRestart(IntPtr DeviceHandle); + + [DllImport("winmm.dll")] + private static extern int midiStreamStop(IntPtr DeviceHandle); + + [StructLayout(LayoutKind.Sequential)] + private struct Property + { + public int sizeOfProperty; + public int property; + } + + private const uint MIDIPROP_SET = 0x80000000; + private const uint MIDIPROP_GET = 0x40000000; + private const uint MIDIPROP_TIMEDIV = 0x00000001; + private const uint MIDIPROP_TEMPO = 0x00000002; + + private const byte MEVT_CALLBACK = 0x40; + + private const byte MEVT_SHORTMSG = 0x00; + private const byte MEVT_TEMPO = 0x01; + private const byte MEVT_NOP = 0x02; + private const byte MEVT_LONGMSG = 0x80; + private const byte MEVT_COMMENT = 0x82; + private const byte MEVT_VERSION = 0x84; + + private const int MOM_POSITIONCB = 0x3CA; + + private const int SizeOfMidiEvent = 12; + + private const int EventTypeIndex = 11; + + private const int EventCodeOffset = 8; + + private MidiOutProc midiOutProc; + + private int offsetTicks = 0; + + private byte[] streamID = new byte[4]; + + private List events = new List(); + + private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder(); + + /// + /// Handles the event for no operations. + /// + public event EventHandler NoOpOccurred; + + /// + /// Stream for MIDI output devices. + /// + public OutputStream(int deviceID) : base(deviceID) + { + midiOutProc = HandleMessage; + + int result = midiStreamOpen(ref DeviceHandle, ref deviceID, 1, midiOutProc, IntPtr.Zero, CALLBACK_FUNCTION); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + + /// + /// Disposes the streams when closed. + /// + protected override void Dispose(bool disposing) + { + if(disposing) + { + lock(lockObject) + { + Reset(); + + int result = midiStreamClose(Handle); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + else + { + midiOutReset(Handle); + midiStreamClose(Handle); + } + + base.Dispose(disposing); + } + + /// + /// When the application is closed, this will dispose of any streams. + /// + public override void Close() + { + #region Guard + + if(IsDisposed) + { + return; + } + + #endregion + + Dispose(true); + } + + /// + /// Starts playing the stream. + /// + public void StartPlaying() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + lock(lockObject) + { + int result = midiStreamRestart(Handle); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + + /// + /// Pauses playing the stream. + /// + public void PausePlaying() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + lock(lockObject) + { + int result = midiStreamPause(Handle); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + + /// + /// Stops playing the stream. + /// + public void StopPlaying() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + lock(lockObject) + { + int result = midiStreamStop(Handle); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + + /// + /// Resets the MIDI output device playing the stream. + /// + public override void Reset() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + offsetTicks = 0; + events.Clear(); + + base.Reset(); + } + + /// + /// Writes to the MIDI output device stream. + /// + public void Write(MidiEvent e) + { + switch(e.MidiMessage.MessageType) + { + case MessageType.Channel: + case MessageType.SystemCommon: + case MessageType.SystemRealtime: + Write(e.DeltaTicks, (ShortMessage)e.MidiMessage); + break; + + case MessageType.SystemExclusive: + Write(e.DeltaTicks, (SysExMessage)e.MidiMessage); + break; + + case MessageType.Meta: + Write(e.DeltaTicks, (MetaMessage)e.MidiMessage); + break; + } + } + + private void Write(int deltaTicks, ShortMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + // Delta time. + events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); + + // Stream ID. + events.AddRange(streamID); + + // Event code. + byte[] eventCode = message.GetBytes(); + eventCode[eventCode.Length - 1] = MEVT_SHORTMSG; + events.AddRange(eventCode); + + offsetTicks = 0; + } + + private void Write(int deltaTicks, SysExMessage message) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + // Delta time. + events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); + + // Stream ID. + events.AddRange(streamID); + + // Event code. + byte[] eventCode = BitConverter.GetBytes(message.Length); + eventCode[eventCode.Length - 1] = MEVT_LONGMSG; + events.AddRange(eventCode); + + byte[] sysExData; + + if(message.Length % 4 != 0) + { + sysExData = new byte[message.Length + (message.Length % 4)]; + message.GetBytes().CopyTo(sysExData, 0); + } + else + { + sysExData = message.GetBytes(); + } + + // SysEx data. + events.AddRange(sysExData); + + offsetTicks = 0; + } + + private void Write(int deltaTicks, MetaMessage message) + { + if(message.MetaType == MetaType.Tempo) + { + // Delta time. + events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); + + // Stream ID. + events.AddRange(streamID); + + TempoChangeBuilder builder = new TempoChangeBuilder(message); + + byte[] t = BitConverter.GetBytes(builder.Tempo); + + t[t.Length - 1] = MEVT_SHORTMSG | MEVT_TEMPO; + + // Event code. + events.AddRange(t); + + offsetTicks = 0; + } + else + { + offsetTicks += deltaTicks; + } + } + + /// + /// Writes the no operation for MIDI output device streams. + /// + public void WriteNoOp(int deltaTicks, int data) + { + // Delta time. + events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); + + // Stream ID. + events.AddRange(streamID); + + // Event code. + byte[] eventCode = BitConverter.GetBytes(data); + eventCode[eventCode.Length - 1] = (byte)(MEVT_NOP | MEVT_CALLBACK); + events.AddRange(eventCode); + + offsetTicks = 0; + } + + /// + /// Clears out all the MIDI output device streams when done. + /// + public void Flush() + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + lock(lockObject) + { + headerBuilder.InitializeBuffer(events); + headerBuilder.Build(); + + events.Clear(); + + int result = midiOutPrepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); + + if(result == MidiDeviceException.MMSYSERR_NOERROR) + { + bufferCount++; + } + else + { + headerBuilder.Destroy(); + + throw new OutputDeviceException(result); + } + + result = midiStreamOut(Handle, headerBuilder.Result, SizeOfMidiHeader); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + midiOutUnprepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); + + headerBuilder.Destroy(); + + throw new OutputDeviceException(result); + } + } + } + + /// + /// Initializes the amount of time for the MIDI output device stream. + /// + public Time GetTime(TimeType type) + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + Time t = new Time(); + + t.type = (int)type; + + lock(lockObject) + { + int result = midiStreamPosition(Handle, ref t, Marshal.SizeOf(typeof(Time))); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + + return t; + } + + private void OnNoOpOccurred(NoOpEventArgs e) + { + EventHandler handler = NoOpOccurred; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// Handles the messages for the MIDI output device streams. + /// + protected override void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2) + { + if(msg == MOM_POSITIONCB) + { + delegateQueue.Post(HandleNoOp, param1); + } + else + { + base.HandleMessage(DeviceHandle, msg, instance, param1, param2); + } + } + + private void HandleNoOp(object state) + { + IntPtr headerPtr = (IntPtr)state; + MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); + + byte[] midiEvent = new byte[SizeOfMidiEvent]; + + for(int i = 0; i < midiEvent.Length; i++) + { + midiEvent[i] = Marshal.ReadByte(header.data, header.offset + i); + } + + // If this is a NoOp event. + if((midiEvent[EventTypeIndex] & MEVT_NOP) == MEVT_NOP) + { + // Clear the event type byte. + midiEvent[EventTypeIndex] = 0; + + NoOpEventArgs e = new NoOpEventArgs(BitConverter.ToInt32(midiEvent, EventCodeOffset)); + + context.Post(new SendOrPostCallback(delegate(object s) + { + OnNoOpOccurred(e); + }), null); + } + } + + /// + /// Gets the size of the MIDI output device stream and sets the amount to be divided. + /// + public int Division + { + get + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + Property d = new Property(); + + d.sizeOfProperty = Marshal.SizeOf(typeof(Property)); + + lock(lockObject) + { + int result = midiStreamProperty(Handle, ref d, MIDIPROP_GET | MIDIPROP_TIMEDIV); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + + return d.property; + } + set + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + else if(value < PpqnClock.PpqnMinValue) + { + throw new ArgumentOutOfRangeException("Ppqn", value, + "Pulses per quarter note is smaller than 24."); + } + + #endregion + + Property d = new Property(); + + d.sizeOfProperty = Marshal.SizeOf(typeof(Property)); + d.property = value; + + lock(lockObject) + { + int result = midiStreamProperty(Handle, ref d, MIDIPROP_SET | MIDIPROP_TIMEDIV); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + } + + /// + /// Gets the amount of tempo, then sets the tempo for the MIDI output device stream. + /// + public int Tempo + { + get + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + + #endregion + + Property t = new Property(); + t.sizeOfProperty = Marshal.SizeOf(typeof(Property)); + + lock(lockObject) + { + int result = midiStreamProperty(Handle, ref t, MIDIPROP_GET | MIDIPROP_TEMPO); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + + return t.property; + } + set + { + #region Require + + if(IsDisposed) + { + throw new ObjectDisposedException("OutputStream"); + } + else if(value < 0) + { + throw new ArgumentOutOfRangeException("Tempo", value, + "Tempo out of range."); + } + + #endregion + + Property t = new Property(); + t.sizeOfProperty = Marshal.SizeOf(typeof(Property)); + t.property = value; + + lock(lockObject) + { + int result = midiStreamProperty(Handle, ref t, MIDIPROP_SET | MIDIPROP_TEMPO); + + if(result != MidiDeviceException.MMSYSERR_NOERROR) + { + throw new OutputDeviceException(result); + } + } + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/GeneralMidi.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/GeneralMidi.cs new file mode 100644 index 0000000..7dfe191 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/GeneralMidi.cs @@ -0,0 +1,682 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +namespace Sanford.Multimedia.Midi +{ + /// + /// Defines constants representing the General MIDI instrument set. + /// + public enum GeneralMidiInstrument + { + /// + /// Instrument sample: Acoustic Grand Piano. + /// + AcousticGrandPiano, + + /// + /// Instrument sample: Bright Acoustic Piano. + /// + BrightAcousticPiano, + + /// + /// Instrument sample: Electric Grand Piano. + /// + ElectricGrandPiano, + + /// + /// Instrument sample: Honky Tonk Piano. + /// + HonkyTonkPiano, + + /// + /// Instrument sample: Electric Piano 1. + /// + ElectricPiano1, + + /// + /// Instrument sample: Electric Piano 2. + /// + ElectricPiano2, + + /// + /// Instrument sample: Harpsichord. + /// + Harpsichord, + + /// + /// Instrument sample: Clavinet. + /// + Clavinet, + + /// + /// Instrument sample: Celesta. + /// + Celesta, + + /// + /// Instrument sample: Glockenspiel. + /// + Glockenspiel, + + /// + /// Instrument sample: Music Box. + /// + MusicBox, + + /// + /// Instrument sample: Vibraphone. + /// + Vibraphone, + + /// + /// Instrument sample: Marimba. + /// + Marimba, + + /// + /// Instrument sample: Xylophone. + /// + Xylophone, + + /// + /// Instrument sample: Tubular Bells. + /// + TubularBells, + + /// + /// Instrument sample: Dulcimer. + /// + Dulcimer, + + /// + /// Instrument sample: Drawbar Organ. + /// + DrawbarOrgan, + + /// + /// Instrument sample: Percussive Organ. + /// + PercussiveOrgan, + + /// + /// Instrument sample: Rock Organ. + /// + RockOrgan, + + /// + /// Instrument sample: Church Organ. + /// + ChurchOrgan, + + /// + /// Instrument sample: Reed Organ. + /// + ReedOrgan, + + /// + /// Instrument sample: Accordion. + /// + Accordion, + + /// + /// Instrument sample: Harmonica. + /// + Harmonica, + + /// + /// Instrument sample: Tango Accordion. + /// + TangoAccordion, + + /// + /// Instrument sample: Acoustic Guitar Nylon. + /// + AcousticGuitarNylon, + + /// + /// Instrument sample: Acoustic Guitar Steel. + /// + AcousticGuitarSteel, + + /// + /// Instrument sample: Electric Guitar Jazz. + /// + ElectricGuitarJazz, + + /// + /// Instrument sample: Electric Guitar Clean. + /// + ElectricGuitarClean, + + /// + /// Instrument sample: Electric Guitar Muted. + /// + ElectricGuitarMuted, + + /// + /// Instrument sample: Overdriven Guitar. + /// + OverdrivenGuitar, + + /// + /// Instrument sample: Distortion Guitar. + /// + DistortionGuitar, + + /// + /// Instrument sample: Guitar Harmonics. + /// + GuitarHarmonics, + + /// + /// Instrument sample: Acoustic Bass. + /// + AcousticBass, + + /// + /// Instrument sample: Electric Bass Finger. + /// + ElectricBassFinger, + + /// + /// Instrument sample: Electric Bass Pick. + /// + ElectricBassPick, + + /// + /// Instrument sample: Fretless Bass. + /// + FretlessBass, + + /// + /// Instrument sample: Slap Bass 1. + /// + SlapBass1, + + /// + /// Instrument sample: Slap Bass 2. + /// + SlapBass2, + + /// + /// Instrument sample: Synth Bass 1. + /// + SynthBass1, + + /// + /// Instrument sample: Synth Bass 2. + /// + SynthBass2, + + /// + /// Instrument sample: Violin. + /// + Violin, + + /// + /// Instrument sample: Viola. + /// + Viola, + + /// + /// Instrument sample: Cello. + /// + Cello, + + /// + /// Instrument sample: Contrabass. + /// + Contrabass, + + /// + /// Instrument sample: Tremolo Strings. + /// + TremoloStrings, + + /// + /// Instrument sample: Pizzicato Strings. + /// + PizzicatoStrings, + + /// + /// Instrument sample: Orchestral Harp. + /// + OrchestralHarp, + + /// + /// Instrument sample: Timpani. + /// + Timpani, + + /// + /// Instrument sample: String Ensemble 1. + /// + StringEnsemble1, + + /// + /// Instrument sample: String Ensemble 2. + /// + StringEnsemble2, + + /// + /// Instrument sample: Synth Strings 1. + /// + SynthStrings1, + + /// + /// Instrument sample: Synth Strings 2. + /// + SynthStrings2, + + /// + /// Instrument sample: Aah (Choir). + /// + ChoirAahs, + + /// + /// Instrument sample: Ooh (Voice). + /// + VoiceOohs, + + /// + /// Instrument sample: Synth Voice. + /// + SynthVoice, + + /// + /// Instrument sample: Orchestra Hit. + /// + OrchestraHit, + + /// + /// Instrument sample: Trumpet. + /// + Trumpet, + + /// + /// Instrument sample: Trombone. + /// + Trombone, + + /// + /// Instrument sample: Tuba. + /// + Tuba, + + /// + /// Instrument sample: Muted Trumpet. + /// + MutedTrumpet, + + /// + /// Instrument sample: French Horn. + /// + FrenchHorn, + + /// + /// Instrument sample: Brass Section. + /// + BrassSection, + + /// + /// Instrument sample: Synth Brass 1. + /// + SynthBrass1, + + /// + /// Instrument sample: Synth Brass 2. + /// + SynthBrass2, + + /// + /// Instrument sample: Soprano Saxophone. + /// + SopranoSax, + + /// + /// Instrument sample: Alto Saxophone. + /// + AltoSax, + + /// + /// Instrument sample: Tenor Saxophone. + /// + TenorSax, + + /// + /// Instrument sample: Baritone Saxophone. + /// + BaritoneSax, + + /// + /// Instrument sample: Oboe. + /// + Oboe, + + /// + /// Instrument sample: English Horn. + /// + EnglishHorn, + + /// + /// Instrument sample: Bassoon. + /// + Bassoon, + + /// + /// Instrument sample: Clarinet. + /// + Clarinet, + + /// + /// Instrument sample: Piccolo. + /// + Piccolo, + + /// + /// Instrument sample: Flute. + /// + Flute, + + /// + /// Instrument sample: Recorder. + /// + Recorder, + + /// + /// Instrument sample: Pan Flute. + /// + PanFlute, + + /// + /// Instrument sample: Blown Bottle. + /// + BlownBottle, + + /// + /// Instrument sample: Shakuhachi. + /// + Shakuhachi, + + /// + /// Instrument sample: Whistle. + /// + Whistle, + + /// + /// Instrument sample: Ocarina. + /// + Ocarina, + + /// + /// Instrument sample: Lead 1 (Square). + /// + Lead1Square, + + /// + /// Instrument sample: Lead 2 (Sawtooth). + /// + Lead2Sawtooth, + + /// + /// Instrument sample: Lead 3 (Calliope). + /// + Lead3Calliope, + + /// + /// Instrument sample: Lead 4 (Chiff). + /// + Lead4Chiff, + + /// + /// Instrument sample: Lead 5 (Charang). + /// + Lead5Charang, + + /// + /// Instrument sample: Lead 6 (Voice). + /// + Lead6Voice, + + /// + /// Instrument sample: Lead 7 (Fifths). + /// + Lead7Fifths, + + /// + /// Instrument sample: Lead 8 (Bass And Lead). + /// + Lead8BassAndLead, + + /// + /// Instrument sample: Pad 1 (New Age). + /// + Pad1NewAge, + + /// + /// Instrument sample: Pad 2 (Warm). + /// + Pad2Warm, + + /// + /// Instrument sample: Pad 3 (Polysynth). + /// + Pad3Polysynth, + + /// + /// Instrument sample: Pad 4 (Choir). + /// + Pad4Choir, + + /// + /// Instrument sample: Pad 5 (Bowed). + /// + Pad5Bowed, + + /// + /// Instrument sample: Pad 6 (Metallic). + /// + Pad6Metallic, + + /// + /// Instrument sample: Pad 7 (Halo). + /// + Pad7Halo, + + /// + /// Instrument sample: Pad 8 (Sweep). + /// + Pad8Sweep, + + /// + /// Instrument sample: Fx 1 (Rain). + /// + Fx1Rain, + + /// + /// Instrument sample: Fx 2 (Soundtrack). + /// + Fx2Soundtrack, + + /// + /// Instrument sample: Fx 3 (Crystal). + /// + Fx3Crystal, + + /// + /// Instrument sample: Fx 4 (Atmosphere). + /// + Fx4Atmosphere, + + /// + /// Instrument sample: Fx 5 (Brightness). + /// + Fx5Brightness, + + /// + /// Instrument sample: Fx 6 (Goblins). + /// + Fx6Goblins, + + /// + /// Instrument sample: Fx 7 (Echoes). + /// + Fx7Echoes, + + /// + /// Instrument sample: Fx 8 (Sci-Fi). + /// + Fx8SciFi, + + /// + /// Instrument sample: Sitar. + /// + Sitar, + + /// + /// Instrument sample: Banjo. + /// + Banjo, + + /// + /// Instrument sample: Shamisen. + /// + Shamisen, + + /// + /// Instrument sample: Koto. + /// + Koto, + + /// + /// Instrument sample: Kalimba. + /// + Kalimba, + + /// + /// Instrument sample: Bag Pipe. + /// + BagPipe, + + /// + /// Instrument sample: Fiddle. + /// + Fiddle, + + /// + /// Instrument sample: Shanai. + /// + Shanai, + + /// + /// Instrument sample: Tinkle Bell. + /// + TinkleBell, + + /// + /// Instrument sample: Agogo. + /// + Agogo, + + /// + /// Instrument sample: Steel Drums. + /// + SteelDrums, + + /// + /// Instrument sample: Woodblock. + /// + Woodblock, + + /// + /// Instrument sample: Taiko Drum. + /// + TaikoDrum, + + /// + /// Instrument sample: Melodic Tom. + /// + MelodicTom, + + /// + /// Instrument sample: Synth Drum. + /// + SynthDrum, + + /// + /// Instrument sample: Reverse Cymbal. + /// + ReverseCymbal, + + /// + /// Instrument sample: Guitar Fret Noise. + /// + GuitarFretNoise, + + /// + /// Instrument sample: Breath Noise. + /// + BreathNoise, + + /// + /// Instrument sample: Seashore. + /// + Seashore, + + /// + /// Instrument sample: Bird Tweet. + /// + BirdTweet, + + /// + /// Instrument sample: Telephone Ring. + /// + TelephoneRing, + + /// + /// Instrument sample: Helicopter. + /// + Helicopter, + + /// + /// Instrument sample: Applause. + /// + Applause, + + /// + /// Instrument sample: Gunshot. + /// + Gunshot + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ChannelMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ChannelMessage.cs new file mode 100644 index 0000000..95b69d2 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ChannelMessage.cs @@ -0,0 +1,746 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + #region Channel Command Types + + /// + /// Defines constants for ChannelMessage types. + /// + public enum ChannelCommand + { + /// + /// Represents the note-off command type. + /// + NoteOff = 0x80, + + /// + /// Represents the note-on command type. + /// + NoteOn = 0x90, + + /// + /// Represents the poly pressure (aftertouch) command type. + /// + PolyPressure = 0xA0, + + /// + /// Represents the controller command type. + /// + Controller = 0xB0, + + /// + /// Represents the program change command type. + /// + ProgramChange = 0xC0, + + /// + /// Represents the channel pressure (aftertouch) command + /// type. + /// + ChannelPressure = 0xD0, + + /// + /// Represents the pitch wheel command type. + /// + PitchWheel = 0xE0 + } + + #endregion + + #region Controller Types + + /// + /// Defines constants for controller types. + /// + public enum ControllerType + { + /// + /// The Bank Select coarse. + /// + BankSelect, + + /// + /// The Modulation Wheel coarse. + /// + ModulationWheel, + + /// + /// The Breath Control coarse. + /// + BreathControl, + + /// + /// The Foot Pedal coarse. + /// + FootPedal = 4, + + /// + /// The Portamento Time coarse. + /// + PortamentoTime, + + /// + /// The Data Entry Slider coarse. + /// + DataEntrySlider, + + /// + /// The Volume coarse. + /// + Volume, + + /// + /// The Balance coarse. + /// + Balance, + + /// + /// The Pan position coarse. + /// + Pan = 10, + + /// + /// The Expression coarse. + /// + Expression, + + /// + /// The Effect Control 1 coarse. + /// + EffectControl1, + + /// + /// The Effect Control 2 coarse. + /// + EffectControl2, + + /// + /// The General Puprose Slider 1 + /// + GeneralPurposeSlider1 = 16, + + /// + /// The General Puprose Slider 2 + /// + GeneralPurposeSlider2, + + /// + /// The General Puprose Slider 3 + /// + GeneralPurposeSlider3, + + /// + /// The General Puprose Slider 4 + /// + GeneralPurposeSlider4, + + /// + /// The Bank Select fine. + /// + BankSelectFine = 32, + + /// + /// The Modulation Wheel fine. + /// + ModulationWheelFine, + + /// + /// The Breath Control fine. + /// + BreathControlFine, + + /// + /// The Foot Pedal fine. + /// + FootPedalFine = 36, + + /// + /// The Portamento Time fine. + /// + PortamentoTimeFine, + + /// + /// The Data Entry Slider fine. + /// + DataEntrySliderFine, + + /// + /// The Volume fine. + /// + VolumeFine, + + /// + /// The Balance fine. + /// + BalanceFine, + + /// + /// The Pan position fine. + /// + PanFine = 42, + + /// + /// The Expression fine. + /// + ExpressionFine, + + /// + /// The Effect Control 1 fine. + /// + EffectControl1Fine, + + /// + /// The Effect Control 2 fine. + /// + EffectControl2Fine, + + /// + /// The Hold Pedal 1. + /// + HoldPedal1 = 64, + + /// + /// The Portamento. + /// + Portamento, + + /// + /// The Sustenuto Pedal. + /// + SustenutoPedal, + + /// + /// The Soft Pedal. + /// + SoftPedal, + + /// + /// The Legato Pedal. + /// + LegatoPedal, + + /// + /// The Hold Pedal 2. + /// + HoldPedal2, + + /// + /// The Sound Variation. + /// + SoundVariation, + + /// + /// The Sound Timbre. + /// + SoundTimbre, + + /// + /// The Sound Release Time. + /// + SoundReleaseTime, + + /// + /// The Sound Attack Time. + /// + SoundAttackTime, + + /// + /// The Sound Brightness. + /// + SoundBrightness, + + /// + /// The Sound Control 6. + /// + SoundControl6, + + /// + /// The Sound Control 7. + /// + SoundControl7, + + /// + /// The Sound Control 8. + /// + SoundControl8, + + /// + /// The Sound Control 9. + /// + SoundControl9, + + /// + /// The Sound Control 10. + /// + SoundControl10, + + /// + /// The General Purpose Button 1. + /// + GeneralPurposeButton1, + + /// + /// The General Purpose Button 2. + /// + GeneralPurposeButton2, + + /// + /// The General Purpose Button 3. + /// + GeneralPurposeButton3, + + /// + /// The General Purpose Button 4. + /// + GeneralPurposeButton4, + + /// + /// The Effects Level. + /// + EffectsLevel = 91, + + /// + /// The Tremolo Level. + /// + TremoloLevel, + + /// + /// The Chorus Level. + /// + ChorusLevel, + + /// + /// The Celeste Level. + /// + CelesteLevel, + + /// + /// The Phaser Level. + /// + PhaserLevel, + + /// + /// The Data Button Increment. + /// + DataButtonIncrement, + + /// + /// The Data Button Decrement. + /// + DataButtonDecrement, + + /// + /// The NonRegistered Parameter Fine. + /// + NonRegisteredParameterFine, + + /// + /// The NonRegistered Parameter Coarse. + /// + NonRegisteredParameterCoarse, + + /// + /// The Registered Parameter Fine. + /// + RegisteredParameterFine, + + /// + /// The Registered Parameter Coarse. + /// + RegisteredParameterCoarse, + + /// + /// The All Sound Off. + /// + AllSoundOff = 120, + + /// + /// The All Controllers Off. + /// + AllControllersOff, + + /// + /// The Local Keyboard. + /// + LocalKeyboard, + + /// + /// The All Notes Off. + /// + AllNotesOff, + + /// + /// The Omni Mode Off. + /// + OmniModeOff, + + /// + /// The Omni Mode On. + /// + OmniModeOn, + + /// + /// The Mono Operation. + /// + MonoOperation, + + /// + /// The Poly Operation. + /// + PolyOperation + } + + #endregion + + /// + /// Represents MIDI channel messages. + /// + [ImmutableObject(true)] + public sealed class ChannelMessage : ShortMessage + { + #region ChannelEventArgs Members + + #region Constants + + // + // Bit manipulation constants. + // + + private const int MidiChannelMask = ~15; + private const int CommandMask = ~240; + + /// + /// Maximum value allowed for MIDI channels. + /// + public const int MidiChannelMaxValue = 15; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the ChannelEventArgs class with the + /// specified command, MIDI channel, and data 1 values. + /// + /// + /// The command value. + /// + /// + /// The MIDI channel. + /// + /// + /// The data 1 value. + /// + /// + /// If midiChannel is less than zero or greater than 15. Or if + /// data1 is less than zero or greater than 127. + /// + public ChannelMessage(ChannelCommand command, int midiChannel, int data1) + { + msg = 0; + + msg = PackCommand(msg, command); + msg = PackMidiChannel(msg, midiChannel); + msg = PackData1(msg, data1); + + #region Ensure + + Debug.Assert(Command == command); + Debug.Assert(MidiChannel == midiChannel); + Debug.Assert(Data1 == data1); + + #endregion + } + + /// + /// Initializes a new instance of the ChannelEventArgs class with the + /// specified command, MIDI channel, data 1, and data 2 values. + /// + /// + /// The command value. + /// + /// + /// The MIDI channel. + /// + /// + /// The data 1 value. + /// + /// + /// The data 2 value. + /// + /// + /// If midiChannel is less than zero or greater than 15. Or if + /// data1 or data 2 is less than zero or greater than 127. + /// + public ChannelMessage(ChannelCommand command, int midiChannel, + int data1, int data2) + { + msg = 0; + + msg = PackCommand(msg, command); + msg = PackMidiChannel(msg, midiChannel); + msg = PackData1(msg, data1); + msg = PackData2(msg, data2); + + #region Ensure + + Debug.Assert(Command == command); + Debug.Assert(MidiChannel == midiChannel); + Debug.Assert(Data1 == data1); + Debug.Assert(Data2 == data2); + + #endregion + } + + internal ChannelMessage(int message) + { + this.msg = message; + } + + #endregion + + #region Methods + + /// + /// Returns a value for the current ChannelEventArgs suitable for use in + /// hashing algorithms. + /// + /// + /// A hash code for the current ChannelEventArgs. + /// + public override int GetHashCode() + { + return msg; + } + + /// + /// Determines whether two ChannelEventArgs instances are equal. + /// + /// + /// The ChannelMessageEventArgs to compare with the current ChannelEventArgs. + /// + /// + /// true if the specified object is equal to the current + /// ChannelMessageEventArgs; otherwise, false. + /// + public override bool Equals(object obj) + { + #region Guard + + if(!(obj is ChannelMessage)) + { + return false; + } + + #endregion + + ChannelMessage e = (ChannelMessage)obj; + + return this.msg == e.msg; + } + + /// + /// Returns a value indicating how many bytes are used for the + /// specified ChannelCommand. + /// + /// + /// The ChannelCommand value to test. + /// + /// + /// The number of bytes used for the specified ChannelCommand. + /// + internal static int DataBytesPerType(ChannelCommand command) + { + int result; + + if(command == ChannelCommand.ChannelPressure || + command == ChannelCommand.ProgramChange) + { + result = 1; + } + else + { + result = 2; + } + + return result; + } + + /// + /// Unpacks the command value from the specified integer channel + /// message. + /// + /// + /// The message to unpack. + /// + /// + /// The command value for the packed message. + /// + internal static ChannelCommand UnpackCommand(int message) + { + return (ChannelCommand)(message & DataMask & MidiChannelMask); + } + + /// + /// Unpacks the MIDI channel from the specified integer channel + /// message. + /// + /// + /// The message to unpack. + /// + /// + /// The MIDI channel for the pack message. + /// + internal static int UnpackMidiChannel(int message) + { + return message & DataMask & CommandMask; + } + + /// + /// Packs the MIDI channel into the specified integer message. + /// + /// + /// The message into which the MIDI channel is packed. + /// + /// + /// The MIDI channel to pack into the message. + /// + /// + /// An integer message. + /// + /// + /// If midiChannel is less than zero or greater than 15. + /// + internal static int PackMidiChannel(int message, int midiChannel) + { + #region Preconditons + + if(midiChannel < 0 || midiChannel > MidiChannelMaxValue) + { + throw new ArgumentOutOfRangeException("midiChannel", midiChannel, + "MIDI channel out of range."); + } + + #endregion + + return (message & MidiChannelMask) | midiChannel; + } + + /// + /// Packs the command value into an integer message. + /// + /// + /// The message into which the command is packed. + /// + /// + /// The command value to pack into the message. + /// + /// + /// An integer message. + /// + internal static int PackCommand(int message, ChannelCommand command) + { + return (message & CommandMask) | (int)command; + } + + #endregion + + #region Properties + + /// + /// Gets the channel command value. + /// + public ChannelCommand Command + { + get + { + return UnpackCommand(msg); + } + } + + /// + /// Gets the MIDI channel. + /// + public int MidiChannel + { + get + { + return UnpackMidiChannel(msg); + } + } + + /// + /// Gets the first data value. + /// + public int Data1 + { + get + { + return UnpackData1(msg); + } + } + + /// + /// Gets the second data value. + /// + public int Data2 + { + get + { + return UnpackData2(msg); + } + } + + /// + /// Gets the EventType. + /// + public override MessageType MessageType + { + get + { + return MessageType.Channel; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ChannelMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ChannelMessageEventArgs.cs new file mode 100644 index 0000000..fe5030a --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ChannelMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The class that contains events for channel messages. + /// + public class ChannelMessageEventArgs : MidiEventArgs + { + private ChannelMessage message; + + /// + /// The function that contains events for channel messages. + /// + public ChannelMessageEventArgs(ChannelMessage message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets the channel messages. + /// + public ChannelMessage Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidShortMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidShortMessageEventArgs.cs new file mode 100644 index 0000000..086a3e0 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidShortMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// This class declares invalid short message events. + /// + public class InvalidShortMessageEventArgs : MidiEventArgs + { + private int message; + + /// + /// Main function for when the invalid short message event is declared. + /// + public InvalidShortMessageEventArgs(int message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message. + /// + public int Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidSysExMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidSysExMessageEventArgs.cs new file mode 100644 index 0000000..34acfda --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/InvalidSysExMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// This class declares invalid exclusive system message events. + /// + public class InvalidSysExMessageEventArgs : MidiEventArgs + { + private byte[] messageData; + + /// + /// Main function for declared invalid exclusive system message events. + /// + public InvalidSysExMessageEventArgs(byte[] messageData, int absoluteTicks = -1) + { + this.messageData = messageData; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message data. + /// + public ICollection MessageData + { + get + { + return messageData; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MetaMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MetaMessageEventArgs.cs new file mode 100644 index 0000000..a7cb2b3 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MetaMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Class for declaring metadata message events. + /// + public class MetaMessageEventArgs : MidiEventArgs + { + private MetaMessage message; + + /// + /// Main function for declaring metadata message events. + /// + public MetaMessageEventArgs(MetaMessage message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message. + /// + public MetaMessage Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MidiEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MidiEventArgs.cs new file mode 100644 index 0000000..cffd73c --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/MidiEventArgs.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Class for MIDI events. + /// + public class MidiEventArgs : EventArgs + { + /// + /// Gets and sets the ticks for the MIDI events. + /// + public int AbsoluteTicks { get; set; } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ShortMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ShortMessageEventArgs.cs new file mode 100644 index 0000000..873eb9c --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/ShortMessageEventArgs.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Raw short message as int or byte array, useful when working with VST. + /// + public class ShortMessageEventArgs : MidiEventArgs + { + ShortMessage message; + + /// + /// A short message event that calculates the absolute ticks. + /// + public ShortMessageEventArgs(ShortMessage message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// A short message event that uses a timestamp and calculates the absolute ticks. + /// + public ShortMessageEventArgs(int message, int timestamp = 0, int absoluteTicks = -1) + { + this.message = new ShortMessage(message); + this.message.Timestamp = timestamp; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// A short message event that calculates the status byte, data 1 byte, data 2 byte, and absolute ticks. + /// + public ShortMessageEventArgs(byte status, byte data1, byte data2, int absoluteTicks = -1) + { + this.message = new ShortMessage(status, data1, data2); + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message. + /// + public ShortMessage Message + { + get + { + return message; + } + } + + /// + /// Returns the channel message event. + /// + public static ShortMessageEventArgs FromChannelMessage(ChannelMessageEventArgs arg) + { + return new ShortMessageEventArgs(arg.Message); + } + + /// + /// Returns the common system message event. + /// + public static ShortMessageEventArgs FromSysCommonMessage(SysCommonMessageEventArgs arg) + { + return new ShortMessageEventArgs(arg.Message); + } + + /// + /// Returns the realtime system message event. + /// + public static ShortMessageEventArgs FromSysRealtimeMessage(SysRealtimeMessageEventArgs arg) + { + return new ShortMessageEventArgs(arg.Message); + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysCommonMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysCommonMessageEventArgs.cs new file mode 100644 index 0000000..21b670a --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysCommonMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Class for system common message events. + /// + public class SysCommonMessageEventArgs : MidiEventArgs + { + private SysCommonMessage message; + + /// + /// Main function for system common message events. + /// + public SysCommonMessageEventArgs(SysCommonMessage message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message. + /// + public SysCommonMessage Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysExMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysExMessageEventArgs.cs new file mode 100644 index 0000000..bcfa178 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysExMessageEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Class for exclusive system message events. + /// + public class SysExMessageEventArgs : MidiEventArgs + { + private SysExMessage message; + + /// + /// Main function for exclusive system message events. + /// + public SysExMessageEventArgs(SysExMessage message, int absoluteTicks = -1) + { + this.message = message; + this.AbsoluteTicks = absoluteTicks; + } + + /// + /// Gets and returns the message. + /// + public SysExMessage Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysRealtimeMessageEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysRealtimeMessageEventArgs.cs new file mode 100644 index 0000000..146a0f6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/EventArgs/SysRealtimeMessageEventArgs.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Class for system realtime message events. + /// + public class SysRealtimeMessageEventArgs : EventArgs + { + /// + /// Requests the start for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Start = new SysRealtimeMessageEventArgs(SysRealtimeMessage.StartMessage); + + /// + /// Requests to continue for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Continue = new SysRealtimeMessageEventArgs(SysRealtimeMessage.ContinueMessage); + + /// + /// Requests to stop for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Stop = new SysRealtimeMessageEventArgs(SysRealtimeMessage.StopMessage); + + /// + /// Requests the clock for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Clock = new SysRealtimeMessageEventArgs(SysRealtimeMessage.ClockMessage); + + /// + /// Requests the ticks for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Tick = new SysRealtimeMessageEventArgs(SysRealtimeMessage.TickMessage); + + /// + /// Requests the active sense for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs ActiveSense = new SysRealtimeMessageEventArgs(SysRealtimeMessage.ActiveSenseMessage); + + /// + /// Requests to restart for the system realtime message event. + /// + public static readonly SysRealtimeMessageEventArgs Reset = new SysRealtimeMessageEventArgs(SysRealtimeMessage.ResetMessage); + + private SysRealtimeMessage message; + + private SysRealtimeMessageEventArgs(SysRealtimeMessage message) + { + this.message = message; + } + + /// + /// Gets and returns the message. + /// + public SysRealtimeMessage Message + { + get + { + return message; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/IMidiMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/IMidiMessage.cs new file mode 100644 index 0000000..286311f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/IMidiMessage.cs @@ -0,0 +1,114 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Defines constants representing MIDI message types. + /// + public enum MessageType + { + /// + /// Channel messages. + /// + Channel, + + /// + /// Exclusive system messages. + /// + SystemExclusive, + + /// + /// Common system messages. + /// + SystemCommon, + + /// + /// Realtime system messages. + /// + SystemRealtime, + + /// + /// Metadata messages. + /// + Meta, + + /// + /// Short messages. + /// + Short + } + + /// + /// Represents the basic functionality for all MIDI messages. + /// + public interface IMidiMessage + { + /// + /// Gets a byte array representation of the MIDI message. + /// + /// + /// A byte array representation of the MIDI message. + /// + byte[] GetBytes(); + + /// + /// Gets the MIDI message's status value. + /// + int Status + { + get; + } + + /// + /// Gets the MIDI event's type. + /// + MessageType MessageType + { + get; + } + + /// + /// Delta samples when the event should be processed in the next audio buffer. + /// Leave at 0 for realtime input to play as fast as possible. + /// Set to the desired sample in the next buffer if you play a midi sequence synchronized to the audio callback + /// + int DeltaFrames + { + get; + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/ChannelMessageBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/ChannelMessageBuilder.cs new file mode 100644 index 0000000..086a923 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/ChannelMessageBuilder.cs @@ -0,0 +1,256 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides functionality for building ChannelMessages. + /// + public class ChannelMessageBuilder : IMessageBuilder + { + #region ChannelMessageBuilder Members + + #region Class Fields + + // Stores the ChannelMessages. + private static Hashtable messageCache = Hashtable.Synchronized(new Hashtable()); + + #endregion + + #region Fields + + // The channel message as a packed integer. + private int message = 0; + + // The built ChannelMessage + private ChannelMessage result = null; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the ChannelMessageBuilder class. + /// + public ChannelMessageBuilder() + { + Command = ChannelCommand.Controller; + MidiChannel = 0; + Data1 = (int)ControllerType.AllSoundOff; + Data2 = 0; + } + + /// + /// Initializes a new instance of the ChannelMessageBuilder class with + /// the specified ChannelMessageEventArgs. + /// + /// + /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder. + /// + /// + /// The ChannelMessageBuilder uses the specified ChannelMessageEventArgs to + /// initialize its property values. + /// + public ChannelMessageBuilder(ChannelMessage message) + { + Initialize(message); + } + + #endregion + + #region Methods + + /// + /// Initializes the ChannelMessageBuilder with the specified + /// ChannelMessageEventArgs. + /// + /// + /// The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder. + /// + public void Initialize(ChannelMessage message) + { + this.message = message.Message; + } + + /// + /// Clears the ChannelMessageEventArgs cache. + /// + public static void Clear() + { + messageCache.Clear(); + } + + #endregion + + #region Properties + + /// + /// Gets the number of messages in the ChannelMessageEventArgs cache. + /// + public static int Count + { + get + { + return messageCache.Count; + } + } + + /// + /// Gets the built ChannelMessageEventArgs. + /// + public ChannelMessage Result + { + get + { + return result; + } + } + + /// + /// Gets or sets the ChannelMessageEventArgs as a packed integer. + /// + internal int Message + { + get + { + return message; + } + set + { + message = value; + } + } + + /// + /// Gets or sets the Command value to use for building the + /// ChannelMessageEventArgs. + /// + public ChannelCommand Command + { + get + { + return ChannelMessage.UnpackCommand(message); + } + set + { + message = ChannelMessage.PackCommand(message, value); + } + } + + /// + /// Gets or sets the MIDI channel to use for building the + /// ChannelMessageEventArgs. + /// + /// + /// MidiChannel is set to a value less than zero or greater than 15. + /// + public int MidiChannel + { + get + { + return ChannelMessage.UnpackMidiChannel(message); + } + set + { + message = ChannelMessage.PackMidiChannel(message, value); + } + } + + /// + /// Gets or sets the first data value to use for building the + /// ChannelMessageEventArgs. + /// + /// + /// Data1 is set to a value less than zero or greater than 127. + /// + public int Data1 + { + get + { + return ShortMessage.UnpackData1(message); + } + set + { + message = ShortMessage.PackData1(message, value); + } + } + + /// + /// Gets or sets the second data value to use for building the + /// ChannelMessageEventArgs. + /// + /// + /// Data2 is set to a value less than zero or greater than 127. + /// + public int Data2 + { + get + { + return ShortMessage.UnpackData2(message); + } + set + { + message = ShortMessage.PackData2(message, value); + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds a ChannelMessageEventArgs. + /// + public void Build() + { + result = (ChannelMessage)messageCache[message]; + + // If the message does not exist. + if(result == null) + { + result = new ChannelMessage(message); + + // Add message to cache. + messageCache.Add(message, result); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/IMessageBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/IMessageBuilder.cs new file mode 100644 index 0000000..ae75c49 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/IMessageBuilder.cs @@ -0,0 +1,51 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents functionality for building MIDI messages. + /// + public interface IMessageBuilder + { + #region IMessageBuilder Members + + /// + /// Builds the MIDI message. + /// + void Build(); + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/KeySignatureBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/KeySignatureBuilder.cs new file mode 100644 index 0000000..b1eb641 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/KeySignatureBuilder.cs @@ -0,0 +1,424 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using Sanford.Multimedia; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Builds key signature MetaMessages. + /// + public class KeySignatureBuilder : IMessageBuilder + { + private Key key = Key.CMajor; + + private MetaMessage result = null; + + /// + /// Initializes a new instance of the KeySignatureBuilder class. + /// + public KeySignatureBuilder() + { + } + + /// + /// Initializes a new instance of the KeySignatureBuilder class with + /// the specified key signature MetaMessage. + /// + /// + /// The key signature MetaMessage to use for initializing the + /// KeySignatureBuilder class. + /// + public KeySignatureBuilder(MetaMessage message) + { + Initialize(message); + } + + /// + /// Initializes the KeySignatureBuilder with the specified MetaMessage. + /// + /// + /// The key signature MetaMessage to use for initializing the + /// KeySignatureBuilder. + /// + public void Initialize(MetaMessage message) + { + #region Require + + if(message == null) + { + throw new ArgumentNullException("message"); + } + else if(message.MetaType != MetaType.KeySignature) + { + throw new ArgumentException("Wrong meta event type.", "messaege"); + } + + #endregion + + sbyte b = (sbyte)message[0]; + + // If the key is major. + if(message[1] == 0) + { + switch(b) + { + case -7: + key = Key.CFlatMajor; + break; + + case -6: + key = Key.GFlatMajor; + break; + + case -5: + key = Key.DFlatMajor; + break; + + case -4: + key = Key.AFlatMajor; + break; + + case -3: + key = Key.EFlatMajor; + break; + + case -2: + key = Key.BFlatMajor; + break; + + case -1: + key = Key.FMajor; + break; + + case 0: + key = Key.CMajor; + break; + + case 1: + key = Key.GMajor; + break; + + case 2: + key = Key.DMajor; + break; + + case 3: + key = Key.AMajor; + break; + + case 4: + key = Key.EMajor; + break; + + case 5: + key = Key.BMajor; + break; + + case 6: + key = Key.FSharpMajor; + break; + + case 7: + key = Key.CSharpMajor; + break; + } + + } + // Else the key is minor. + else + { + switch(b) + { + case -7: + key = Key.AFlatMinor; + break; + + case -6: + key = Key.EFlatMinor; + break; + + case -5: + key = Key.BFlatMinor; + break; + + case -4: + key = Key.FMinor; + break; + + case -3: + key = Key.CMinor; + break; + + case -2: + key = Key.GMinor; + break; + + case -1: + key = Key.DMinor; + break; + + case 0: + key = Key.AMinor; + break; + + case 1: + key = Key.EMinor; + break; + + case 2: + key = Key.BMinor; + break; + + case 3: + key = Key.FSharpMinor; + break; + + case 4: + key = Key.CSharpMinor; + break; + + case 5: + key = Key.GSharpMinor; + break; + + case 6: + key = Key.DSharpMinor; + break; + + case 7: + key = Key.ASharpMinor; + break; + } + } + } + + /// + /// Gets or sets the key. + /// + public Key Key + { + get + { + return key; + } + set + { + key = value; + } + } + + /// + /// The build key signature MetaMessage. + /// + public MetaMessage Result + { + get + { + return result; + } + } + + #region IMessageBuilder Members + + /// + /// Builds the key signature MetaMessage. + /// + public void Build() + { + byte[] data = new byte[MetaMessage.KeySigLength]; + + unchecked + { + switch(Key) + { + case Key.CFlatMajor: + data[0] = (byte)-7; + data[1] = 0; + break; + + case Key.GFlatMajor: + data[0] = (byte)-6; + data[1] = 0; + break; + + case Key.DFlatMajor: + data[0] = (byte)-5; + data[1] = 0; + break; + + case Key.AFlatMajor: + data[0] = (byte)-4; + data[1] = 0; + break; + + case Key.EFlatMajor: + data[0] = (byte)-3; + data[1] = 0; + break; + + case Key.BFlatMajor: + data[0] = (byte)-2; + data[1] = 0; + break; + + case Key.FMajor: + data[0] = (byte)-1; + data[1] = 0; + break; + + case Key.CMajor: + data[0] = 0; + data[1] = 0; + break; + + case Key.GMajor: + data[0] = 1; + data[1] = 0; + break; + + case Key.DMajor: + data[0] = 2; + data[1] = 0; + break; + + case Key.AMajor: + data[0] = 3; + data[1] = 0; + break; + + case Key.EMajor: + data[0] = 4; + data[1] = 0; + break; + + case Key.BMajor: + data[0] = 5; + data[1] = 0; + break; + + case Key.FSharpMajor: + data[0] = 6; + data[1] = 0; + break; + + case Key.CSharpMajor: + data[0] = 7; + data[1] = 0; + break; + + case Key.AFlatMinor: + data[0] = (byte)-7; + data[1] = 1; + break; + + case Key.EFlatMinor: + data[0] = (byte)-6; + data[1] = 1; + break; + + case Key.BFlatMinor: + data[0] = (byte)-5; + data[1] = 1; + break; + + case Key.FMinor: + data[0] = (byte)-4; + data[1] = 1; + break; + + case Key.CMinor: + data[0] = (byte)-3; + data[1] = 1; + break; + + case Key.GMinor: + data[0] = (byte)-2; + data[1] = 1; + break; + + case Key.DMinor: + data[0] = (byte)-1; + data[1] = 1; + break; + + case Key.AMinor: + data[0] = 1; + data[1] = 0; + break; + + case Key.EMinor: + data[0] = 1; + data[1] = 1; + break; + + case Key.BMinor: + data[0] = 2; + data[1] = 1; + break; + + case Key.FSharpMinor: + data[0] = 3; + data[1] = 1; + break; + + case Key.CSharpMinor: + data[0] = 4; + data[1] = 1; + break; + + case Key.GSharpMinor: + data[0] = 5; + data[1] = 1; + break; + + case Key.DSharpMinor: + data[0] = 6; + data[1] = 1; + break; + + case Key.ASharpMinor: + data[0] = 7; + data[1] = 1; + break; + } + } + + result = new MetaMessage(MetaType.KeySignature, data); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/MetaTextBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/MetaTextBuilder.cs new file mode 100644 index 0000000..a468ad2 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/MetaTextBuilder.cs @@ -0,0 +1,419 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides functionality for building meta text messages. + /// + public class MetaTextBuilder : IMessageBuilder + { + #region MetaTextBuilder Members + + #region Fields + + // The text represented by the MetaMessage. + private string text; + + // The MetaMessage type - must be one of the text based types. + private MetaType type = MetaType.Text; + + // The built MetaMessage. + private MetaMessage result = null; + + // Indicates whether or not the text has changed since the message was + // last built. + private bool changed = true; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the MetaMessageTextBuilder class. + /// + public MetaTextBuilder() + { + text = string.Empty; + } + + /// + /// Initializes a new instance of the MetaMessageTextBuilder class with the + /// specified type. + /// + /// + /// The type of MetaMessage. + /// + /// + /// If the MetaMessage type is not a text based type. + /// + /// + /// The MetaMessage type must be one of the following text based + /// types: + /// + /// + /// Copyright + /// + /// + /// Cuepoint + /// + /// + /// DeviceName + /// + /// + /// InstrumentName + /// + /// + /// Lyric + /// + /// + /// Marker + /// + /// + /// ProgramName + /// + /// + /// Text + /// + /// + /// TrackName + /// + /// + /// If the MetaMessage is not a text based type, an exception + /// will be thrown. + /// + public MetaTextBuilder(MetaType type) + { + #region Require + + if(!IsTextType(type)) + { + throw new ArgumentException("Not text based meta message type.", + "message"); + } + + #endregion + + this.text = string.Empty; + } + + /// + /// Initializes a new instance of the MetaMessageTextBuilder class with the + /// specified type. + /// + /// + /// The type of MetaMessage. + /// + /// + /// The text string of MetaMessage. + /// + /// + /// If the MetaMessage type is not a text based type. + /// + /// + /// The MetaMessage type must be one of the following text based + /// types: + /// + /// + /// Copyright + /// + /// + /// Cuepoint + /// + /// + /// DeviceName + /// + /// + /// InstrumentName + /// + /// + /// Lyric + /// + /// + /// Marker + /// + /// + /// ProgramName + /// + /// + /// Text + /// + /// + /// TrackName + /// + /// + /// If the MetaMessage is not a text based type, an exception + /// will be thrown. + /// + public MetaTextBuilder(MetaType type, string text) + { + #region Require + + if(!IsTextType(type)) + { + throw new ArgumentException("Not text based meta message type.", + "message"); + } + + #endregion + + this.type = type; + + if(text != null) + { + this.text = text; + } + else + { + this.text = string.Empty; + } + } + + + /// + /// Initializes a new instance of the MetaMessageTextBuilder class with the + /// specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the MetaMessageTextBuilder. + /// + /// + /// If the MetaMessage is not a text based type. + /// + /// + /// The MetaMessage must be one of the following text based types: + /// + /// + /// Copyright + /// + /// + /// Cuepoint + /// + /// + /// DeviceName + /// + /// + /// InstrumentName + /// + /// + /// Lyric + /// + /// + /// Marker + /// + /// + /// ProgramName + /// + /// + /// Text + /// + /// + /// TrackName + /// + /// + /// If the MetaMessage is not a text based type, an exception will be + /// thrown. + /// + public MetaTextBuilder(MetaMessage message) + { + Initialize(message); + } + + #endregion + + #region Methods + + /// + /// Initializes the MetaMessageTextBuilder with the specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the MetaMessageTextBuilder. + /// + /// + /// If the MetaMessage is not a text based type. + /// + public void Initialize(MetaMessage message) + { + #region Require + + if(!IsTextType(message.MetaType)) + { + throw new ArgumentException("Not text based meta message.", + "message"); + } + + #endregion + + ASCIIEncoding encoding = new ASCIIEncoding(); + + text = encoding.GetString(message.GetBytes()); + this.type = message.MetaType; + } + + /// + /// Indicates whether or not the specified MetaType is a text based + /// type. + /// + /// + /// The MetaType to test. + /// + /// + /// true if the MetaType is a text based type; + /// otherwise, false. + /// + private bool IsTextType(MetaType type) + { + bool result; + + if(type == MetaType.Copyright || + type == MetaType.CuePoint || + type == MetaType.DeviceName || + type == MetaType.InstrumentName || + type == MetaType.Lyric || + type == MetaType.Marker || + type == MetaType.ProgramName || + type == MetaType.Text || + type == MetaType.TrackName) + { + result = true; + } + else + { + result = false; + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the text for the MetaMessage. + /// + public string Text + { + get + { + return text; + } + set + { + if(value != null) + { + text = value; + } + else + { + text = string.Empty; + } + + changed = true; + } + } + + /// + /// Gets or sets the MetaMessage type. + /// + /// + /// If the type is not a text based type. + /// + public MetaType Type + { + get + { + return type; + } + set + { + #region Require + + if(!IsTextType(value)) + { + throw new ArgumentException("Not text based meta message type.", + "message"); + } + + #endregion + + type = value; + + changed = true; + } + } + + /// + /// Gets the built MetaMessage. + /// + public MetaMessage Result + { + get + { + return result; + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds the text MetaMessage. + /// + public void Build() + { + // If the text has changed since the last time this method was + // called. + if(changed) + { + // + // Build text MetaMessage. + // + + ASCIIEncoding encoding = new ASCIIEncoding(); + byte[] data = encoding.GetBytes(text); + result = new MetaMessage(Type, data); + changed = false; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SongPositionPointerBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SongPositionPointerBuilder.cs new file mode 100644 index 0000000..d0d5b07 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SongPositionPointerBuilder.cs @@ -0,0 +1,266 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides functionality for building song position pointer messages. + /// + public class SongPositionPointerBuilder : IMessageBuilder + { + #region SongPositionPointerBuilder Members + + #region Constants + + // The number of ticks per 16th note. + private const int TicksPer16thNote = 6; + + // Used for packing and unpacking the song position. + private const int Shift = 7; + + // Used for packing and unpacking the song position. + private const int Mask = 127; + + #endregion + + #region Fields + + // The scale used for converting from the song position to the position + // in ticks. + private int tickScale; + + // Pulses per quarter note resolution. + private int ppqn; + + // Used for building the SysCommonMessage to represent the song + // position pointer. + private SysCommonMessageBuilder builder; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the SongPositionPointerBuilder class. + /// + public SongPositionPointerBuilder() + { + builder = new SysCommonMessageBuilder(); + builder.Type = SysCommonType.SongPositionPointer; + + Ppqn = PpqnClock.PpqnMinValue; + } + + /// + /// Initializes a new instance of the SongPositionPointerBuilder class + /// with the specified song position pointer message. + /// + /// + /// The song position pointer message to use for initializing the + /// SongPositionPointerBuilder. + /// + /// + /// If message is not a song position pointer message. + /// + public SongPositionPointerBuilder(SysCommonMessage message) + { + builder = new SysCommonMessageBuilder(); + builder.Type = SysCommonType.SongPositionPointer; + + Initialize(message); + + Ppqn = PpqnClock.PpqnMinValue; + } + + #endregion + + #region Methods + + /// + /// Initializes the SongPositionPointerBuilder with the specified + /// SysCommonMessage. + /// + /// + /// The SysCommonMessage to use to initialize the + /// SongPositionPointerBuilder. + /// + /// + /// If the SysCommonMessage is not a song position pointer message. + /// + public void Initialize(SysCommonMessage message) + { + #region Require + + if(message == null) + { + throw new ArgumentNullException("message"); + } + else if(message.SysCommonType != SysCommonType.SongPositionPointer) + { + throw new ArgumentException( + "Message is not a song position pointer message."); + } + + #endregion + + builder.Initialize(message); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the sequence position in ticks. + /// + /// + /// Value is set to less than zero. + /// + /// + /// Note: the position in ticks value is converted to the song position + /// pointer value. Since the song position pointer has a lower + /// resolution than the position in ticks, there is a probable loss of + /// resolution when setting the position in ticks value. + /// + public int PositionInTicks + { + get + { + return SongPosition * tickScale * TicksPer16thNote; + } + set + { + #region Require + + if(value < 0) + { + throw new ArgumentOutOfRangeException("PositionInTicks", value, + "Position in ticks out of range."); + } + + #endregion + + SongPosition = value / (tickScale * TicksPer16thNote); + } + } + + /// + /// Gets or sets the PulsesPerQuarterNote object. + /// + /// + /// Value is not a multiple of 24. + /// + public int Ppqn + { + get + { + return ppqn; + } + set + { + #region Require + + if(value < PpqnClock.PpqnMinValue) + { + throw new ArgumentOutOfRangeException("Ppqn", value, + "Pulses per quarter note is smaller than 24."); + } + + #endregion + + ppqn = value; + + tickScale = ppqn / PpqnClock.PpqnMinValue; + } + } + + /// + /// Gets or sets the song position. + /// + /// + /// Value is set to less than zero. + /// + public int SongPosition + { + get + { + return (builder.Data2 << Shift) | builder.Data1; + } + set + { + #region Require + + if(value < 0) + { + throw new ArgumentOutOfRangeException("SongPosition", value, + "Song position pointer out of range."); + } + + #endregion + + builder.Data1 = value & Mask; + builder.Data2 = value >> Shift; + } + } + + /// + /// Gets the built song position pointer message. + /// + public SysCommonMessage Result + { + get + { + return builder.Result; + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds a song position pointer message. + /// + public void Build() + { + builder.Build(); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SysCommonMessageBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SysCommonMessageBuilder.cs new file mode 100644 index 0000000..d79a1b9 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/SysCommonMessageBuilder.cs @@ -0,0 +1,233 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides functionality for building SysCommonMessages. + /// + public class SysCommonMessageBuilder : IMessageBuilder + { + #region SysCommonMessageBuilder Members + + #region Class Fields + + // Stores the SystemCommonMessages. + private static Hashtable messageCache = Hashtable.Synchronized(new Hashtable()); + + #endregion + + #region Fields + + // The SystemCommonMessage as a packed integer. + private int message = 0; + + // The built SystemCommonMessage. + private SysCommonMessage result = null; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the SysCommonMessageBuilder class. + /// + public SysCommonMessageBuilder() + { + Type = SysCommonType.TuneRequest; + } + + /// + /// Initializes a new instance of the SysCommonMessageBuilder class + /// with the specified SystemCommonMessage. + /// + /// + /// The SysCommonMessage to use for initializing the + /// SysCommonMessageBuilder. + /// + /// + /// The SysCommonMessageBuilder uses the specified SysCommonMessage to + /// initialize its property values. + /// + public SysCommonMessageBuilder(SysCommonMessage message) + { + Initialize(message); + } + + #endregion + + #region Methods + + /// + /// Initializes the SysCommonMessageBuilder with the specified + /// SysCommonMessage. + /// + /// + /// The SysCommonMessage to use for initializing the + /// SysCommonMessageBuilder. + /// + public void Initialize(SysCommonMessage message) + { + this.message = message.Message; + } + + /// + /// Clears the SysCommonMessageBuilder cache. + /// + public static void Clear() + { + messageCache.Clear(); + } + + #endregion + + #region Properties + + /// + /// Gets the number of messages in the SysCommonMessageBuilder cache. + /// + public static int Count + { + get + { + return messageCache.Count; + } + } + + /// + /// Gets the built SysCommonMessage. + /// + public SysCommonMessage Result + { + get + { + return result; + } + } + + /// + /// Gets or sets the SysCommonMessage as a packed integer. + /// + internal int Message + { + get + { + return message; + } + set + { + message = value; + } + } + + /// + /// Gets or sets the type of SysCommonMessage. + /// + public SysCommonType Type + { + get + { + return (SysCommonType)ShortMessage.UnpackStatus(message); + } + set + { + message = ShortMessage.PackStatus(message, (int)value); + } + } + + /// + /// Gets or sets the first data value to use for building the + /// SysCommonMessage. + /// + /// + /// Data1 is set to a value less than zero or greater than 127. + /// + public int Data1 + { + get + { + return ShortMessage.UnpackData1(message); + } + set + { + message = ShortMessage.PackData1(message, value); + } + } + + /// + /// Gets or sets the second data value to use for building the + /// SysCommonMessage. + /// + /// + /// Data2 is set to a value less than zero or greater than 127. + /// + public int Data2 + { + get + { + return ShortMessage.UnpackData2(message); + } + set + { + message = ShortMessage.PackData2(message, value); + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds a SysCommonMessage. + /// + public void Build() + { + result = (SysCommonMessage)messageCache[message]; + + if(result == null) + { + result = new SysCommonMessage(message); + + messageCache.Add(message, result); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TempoChangeBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TempoChangeBuilder.cs new file mode 100644 index 0000000..db5a323 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TempoChangeBuilder.cs @@ -0,0 +1,242 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides functionality for building tempo messages. + /// + public class TempoChangeBuilder : IMessageBuilder + { + #region TempoChangeBuilder Members + + #region Constants + + // Value used for shifting bits for packing and unpacking tempo values. + private const int Shift = 8; + + #endregion + + #region Fields + + // The mesage's tempo. + private int tempo = PpqnClock.DefaultTempo; + + // The built MetaMessage. + private MetaMessage result = null; + + // Indicates whether the tempo property has been changed since + // the last time the message was built. + private bool changed = true; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the TempoChangeBuilder class. + /// + public TempoChangeBuilder() + { + } + + /// + /// Initialize a new instance of the TempoChangeBuilder class with the + /// specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the TempoChangeBuilder class. + /// + /// + /// If the specified MetaMessage is not a tempo type. + /// + /// + /// The TempoChangeBuilder uses the specified MetaMessage to initialize + /// its property values. + /// + public TempoChangeBuilder(MetaMessage m) + { + Initialize(m); + } + + #endregion + + #region Methods + + /// + /// Initializes the TempoChangeBuilder with the specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the TempoChangeBuilder. + /// + /// + /// If the specified MetaMessage is not a tempo type. + /// + public void Initialize(MetaMessage m) + { + #region Require + + if(m == null) + { + throw new ArgumentNullException("m"); + } + else if(m.MetaType != MetaType.Tempo) + { + throw new ArgumentException("Wrong meta message type.", "m"); + } + + #endregion + + int t = 0; + + // If this platform uses little endian byte order. + if(BitConverter.IsLittleEndian) + { + int d = m.Length - 1; + + // Pack tempo. + for(int i = 0; i < m.Length; i++) + { + t |= m[d] << (Shift * i); + d--; + } + } + // Else this platform uses big endian byte order. + else + { + // Pack tempo. + for(int i = 0; i < m.Length; i++) + { + t |= m[i] << (Shift * i); + } + } + + tempo = t; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the tempo. + /// + /// + /// Value is set to less than zero. + /// + public int Tempo + { + get + { + return tempo; + } + set + { + #region Require + + if(value < 0) + { + throw new ArgumentOutOfRangeException("Tempo", value, + "Tempo is out of range."); + } + + #endregion + + tempo = value; + + changed = true; + } + } + + /// + /// Gets the built message. + /// + public MetaMessage Result + { + get + { + return result; + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds the tempo change MetaMessage. + /// + public void Build() + { + // If the tempo has been changed since the last time the message + // was built. + if(changed) + { + byte[] data = new byte[MetaMessage.TempoLength]; + + // If this platform uses little endian byte order. + if(BitConverter.IsLittleEndian) + { + int d = data.Length - 1; + + // Unpack tempo. + for(int i = 0; i < data.Length; i++) + { + data[d] = (byte)(tempo >> (Shift * i)); + d--; + } + } + // Else this platform uses big endian byte order. + else + { + // Unpack tempo. + for(int i = 0; i < data.Length; i++) + { + data[i] = (byte)(tempo >> (Shift * i)); + } + } + + changed = false; + + result = new MetaMessage(MetaType.Tempo, data); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TimeSignatureBuilder.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TimeSignatureBuilder.cs new file mode 100644 index 0000000..90b17ec --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/Message Builders/TimeSignatureBuilder.cs @@ -0,0 +1,277 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Provides easy to use functionality for time signature MetaMessages. + /// + public class TimeSignatureBuilder : IMessageBuilder + { + #region TimeSignature Members + + #region Constants + + // Default numerator value. + private const byte DefaultNumerator = 4; + + // Default denominator value. + private const byte DefaultDenominator = 2; + + // Default clocks per metronome click value. + private const byte DefaultClocksPerMetronomeClick = 24; + + // Default thirty second notes per quarter note value. + private const byte DefaultThirtySecondNotesPerQuarterNote = 8; + + #endregion + + #region Fields + + // The raw data making up the time signature meta message. + private byte[] data = new byte[MetaMessage.TimeSigLength]; + + // The built time signature meta message. + private MetaMessage result = null; + + // Indicates whether any of the properties have changed since the + // last time the message was built. + private bool changed = true; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the TimeSignatureBuilder class. + /// + public TimeSignatureBuilder() + { + Numerator = DefaultNumerator; + Denominator = DefaultDenominator; + ClocksPerMetronomeClick = DefaultClocksPerMetronomeClick; + ThirtySecondNotesPerQuarterNote = DefaultThirtySecondNotesPerQuarterNote; + } + + /// + /// Initializes a new instance of the TimeSignatureBuilder class with the + /// specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the TimeSignatureBuilder class. + /// + /// + /// If the specified MetaMessage is not a time signature type. + /// + /// + /// The TimeSignatureBuilder uses the specified MetaMessage to + /// initialize its property values. + /// + public TimeSignatureBuilder(MetaMessage message) + { + Initialize(message); + } + + #endregion + + #region Methods + + /// + /// Initializes the TimeSignatureBuilder with the specified MetaMessage. + /// + /// + /// The MetaMessage to use for initializing the TimeSignatureBuilder. + /// + /// + /// If the specified MetaMessage is not a time signature type. + /// + public void Initialize(MetaMessage message) + { + #region Require + + if(message.MetaType != MetaType.TimeSignature) + { + throw new ArgumentException("Wrong meta event type.", "message"); + } + + #endregion + + data = message.GetBytes(); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the numerator. + /// + /// + /// Numerator is set to a value less than one. + /// + public byte Numerator + { + get + { + return data[0]; + } + set + { + #region Require + + if(value < 1) + { + throw new ArgumentOutOfRangeException("Numerator", value, + "Numerator out of range."); + } + + #endregion + + data[0] = value; + + changed = true; + } + } + + /// + /// Gets or sets the denominator. + /// + /// + /// Denominator is set to a value less than 2. + /// + /// + /// Denominator is set to a value that is not a power of 2. + /// + public byte Denominator + { + get + { + return Convert.ToByte(Math.Pow(2, data[1])); + } + set + { + #region Require + + if(value < 2 || value > 32) + { + throw new ArgumentOutOfRangeException("Denominator must be between 2 and 32."); + } + else if((value & (value - 1)) != 0) + { + throw new ArgumentException("Denominator must be a power of 2."); + } + + #endregion + + data[1] = Convert.ToByte(Math.Log(value, 2)); + + changed = true; + } + } + + /// + /// Gets or sets the clocks per metronome click. + /// + /// + /// Clocks per metronome click determines how many MIDI clocks occur + /// for each metronome click. + /// + public byte ClocksPerMetronomeClick + { + get + { + return data[2]; + } + set + { + data[2] = value; + + changed = true; + } + } + + /// + /// Gets or sets how many thirty second notes there are for each + /// quarter note. + /// + public byte ThirtySecondNotesPerQuarterNote + { + get + { + return data[3]; + } + set + { + data[3] = value; + + changed = true; + } + } + + /// + /// Gets the built message. + /// + public MetaMessage Result + { + get + { + return result; + } + } + + #endregion + + #endregion + + #region IMessageBuilder Members + + /// + /// Builds the time signature MetaMessage. + /// + public void Build() + { + // If any of the properties have changed since the last time the + // message was built. + if(changed) + { + result = new MetaMessage(MetaType.TimeSignature, data); + changed = false; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessageDispatcher.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessageDispatcher.cs new file mode 100644 index 0000000..8f5cdea --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessageDispatcher.cs @@ -0,0 +1,220 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Dispatches IMidiMessages to their corresponding sink. + /// + public class MessageDispatcher + { + #region MessageDispatcher Members + + #region Events + + /// + /// Handles dispatching the channel message. + /// + public event EventHandler ChannelMessageDispatched; + + /// + /// Handles dispatching the system ex message. + /// + public event EventHandler SysExMessageDispatched; + + /// + /// Handles dispatching the system common message. + /// + public event EventHandler SysCommonMessageDispatched; + + /// + /// Handles dispatching the system realtime message. + /// + public event EventHandler SysRealtimeMessageDispatched; + + /// + /// Handles dispatching the metadata message. + /// + public event EventHandler MetaMessageDispatched; + + #endregion + + /// + /// Dispatches IMidiMessages to their corresponding sink. + /// + /// + /// The MidiEvent to dispatch. + /// + /// + /// The Track to dispatch. + /// + public void Dispatch(MidiEvent evt, Track track) + { + #region Require + + // The IMidiMessage to dispatch. + var message = evt.MidiMessage; + + if(message == null) + { + throw new ArgumentNullException("message"); + } + + #endregion + + switch(message.MessageType) + { + case MessageType.Channel: + OnChannelMessageDispatched(new ChannelMessageEventArgs((ChannelMessage)message, evt.AbsoluteTicks), track); + break; + + case MessageType.SystemExclusive: + OnSysExMessageDispatched(new SysExMessageEventArgs((SysExMessage)message, evt.AbsoluteTicks), track); + break; + + case MessageType.Meta: + OnMetaMessageDispatched(new MetaMessageEventArgs((MetaMessage)message, evt.AbsoluteTicks), track); + break; + + case MessageType.SystemCommon: + OnSysCommonMessageDispatched(new SysCommonMessageEventArgs((SysCommonMessage)message, evt.AbsoluteTicks), track); + break; + + case MessageType.SystemRealtime: + switch(((SysRealtimeMessage)message).SysRealtimeType) + { + case SysRealtimeType.ActiveSense: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.ActiveSense, track); + break; + + case SysRealtimeType.Clock: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Clock, track); + break; + + case SysRealtimeType.Continue: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Continue, track); + break; + + case SysRealtimeType.Reset: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Reset, track); + break; + + case SysRealtimeType.Start: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Start, track); + break; + + case SysRealtimeType.Stop: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Stop, track); + break; + + case SysRealtimeType.Tick: + OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs.Tick, track); + break; + } + + break; + } + } + + /// + /// Dispatches the channel message. + /// + protected virtual void OnChannelMessageDispatched(ChannelMessageEventArgs e, Track track) + { + EventHandler handler = ChannelMessageDispatched; + + if(handler != null) + { + handler(track, e); + } + } + + /// + /// Dispatches the system ex message. + /// + protected virtual void OnSysExMessageDispatched(SysExMessageEventArgs e, Track track) + { + EventHandler handler = SysExMessageDispatched; + + if(handler != null) + { + handler(track, e); + } + } + + /// + /// Dispatches the system common message. + /// + protected virtual void OnSysCommonMessageDispatched(SysCommonMessageEventArgs e, Track track) + { + EventHandler handler = SysCommonMessageDispatched; + + if(handler != null) + { + handler(track, e); + } + } + + /// + /// Dispatches the system realtime message. + /// + protected virtual void OnSysRealtimeMessageDispatched(SysRealtimeMessageEventArgs e, Track track) + { + EventHandler handler = SysRealtimeMessageDispatched; + + if(handler != null) + { + handler(track, e); + } + } + + /// + /// Dispatches the metadata message. + /// + protected virtual void OnMetaMessageDispatched(MetaMessageEventArgs e, Track track) + { + EventHandler handler = MetaMessageDispatched; + + if(handler != null) + { + handler(track, e); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessagesHierarchy.cd b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessagesHierarchy.cd new file mode 100644 index 0000000..b9134fe --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MessagesHierarchy.cd @@ -0,0 +1,120 @@ + + + + + + QIAFAAAAAAAEAAAAiAAABAACAAIAAIAAAAAAAAgAASA= + Sanford.Multimedia.Midi\Messages\ChannelMessage.cs + + + + + + AAiAEgAkAAAEQAgAiEAAIABAAAABAKAAAAAQAAAAAAA= + Sanford.Multimedia.Midi\Messages\MetaMessage.cs + + + + + + + AAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAA= + Sanford.Multimedia.Midi\Messages\ShortMessage.cs + + + + + + CICAIAAMAIQEEAggAAACCCAAAAAAAAAIAAQKIAAAACQ= + Sanford.Multimedia.Midi\Messages\ShortMessage.cs + + + + + + + AAAEAAAAAAAEAAAAgAAAAAACAAAAAIAAAAAAAAAAAAA= + Sanford.Multimedia.Midi\Messages\SysCommonMessage.cs + + + + + + + + + + + + + + AACAAAAEBAAEEBAAiAACAABAAAAAAIAAAAAQAAAAIAA= + Sanford.Multimedia.Midi\Messages\SysExMessage.cs + + + + + + + AAAAAACAAAAEEAAggAAAAAAAAAAABKAAAAAAMAAAAIA= + Sanford.Multimedia.Midi\Messages\SysRealtimeMessage.cs + + + + + + AACAAAAEAAAEAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAA= + Sanford.Multimedia.Midi\Messages\IMidiMessage.cs + + + + + + AAAEAAAgAAAAEACAAAIAAAAAAAAAAIAAAAAAAAAAAAA= + Sanford.Multimedia.Midi\Messages\IMidiMessage.cs + + + + + + AACAIAAAAQAAAAQAgAAAAAAAAAAAAAAAAgAAIAAAAAA= + Sanford.Multimedia.Midi\Messages\ChannelMessage.cs + + + + + + MDokEAAABOiiowAIBJgAAFKCjIJQBAi2AEaAATASRAA= + Sanford.Multimedia.Midi\Messages\ChannelMessage.cs + + + + + + AAAAEAIBAAAAAAAAAAgAAQCAEAAABAAAIEEICACAAAA= + Sanford.Multimedia.Midi\Messages\MetaMessage.cs + + + + + + AAQACAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAEAAAA= + Sanford.Multimedia.Midi\Messages\SysCommonMessage.cs + + + + + + AAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAA= + Sanford.Multimedia.Midi\Messages\SysExMessage.cs + + + + + + AAAACAAAACAABAAAAAAAAAAAAAAIAAAAIAAAAAAAQgA= + Sanford.Multimedia.Midi\Messages\SysRealtimeMessage.cs + + + + \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MetaMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MetaMessage.cs new file mode 100644 index 0000000..ccb6f2d --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MetaMessage.cs @@ -0,0 +1,513 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + #region Meta Message Types + + /// + /// Represents MetaMessage types. + /// + public enum MetaType + { + /// + /// Represents sequencer number type. + /// + SequenceNumber, + + /// + /// Represents the text type. + /// + Text, + + /// + /// Represents the copyright type. + /// + Copyright, + + /// + /// Represents the track name type. + /// + TrackName, + + /// + /// Represents the instrument name type. + /// + InstrumentName, + + /// + /// Represents the lyric type. + /// + Lyric, + + /// + /// Represents the marker type. + /// + Marker, + + /// + /// Represents the cue point type. + /// + CuePoint, + + /// + /// Represents the program name type. + /// + ProgramName, + + /// + /// Represents the device name type. + /// + DeviceName, + + /// + /// Represents then end of track type. + /// + EndOfTrack = 0x2F, + + /// + /// Represents the tempo type. + /// + Tempo = 0x51, + + /// + /// Represents the Smpte offset type. + /// + SmpteOffset = 0x54, + + /// + /// Represents the time signature type. + /// + TimeSignature = 0x58, + + /// + /// Represents the key signature type. + /// + KeySignature, + + /// + /// Represents the proprietary event type. + /// + ProprietaryEvent = 0x7F + } + + #endregion + + /// + /// Represents MIDI meta messages. + /// + /// + /// Meta messages are MIDI messages that are stored in MIDI files. These + /// messages are not sent or received via MIDI but are read and + /// interpretted from MIDI files. They provide information that describes + /// a MIDI file's properties. For example, tempo changes are implemented + /// using meta messages. + /// + [ImmutableObject(true)] + public sealed class MetaMessage : MidiMessageBase, IMidiMessage + { + #region MetaMessage Members + + #region Constants + + /// + /// The amount to shift data bytes when calculating the hash code. + /// + private const int Shift = 7; + + // + // Meta message length constants. + // + + /// + /// Length in bytes for tempo meta message data. + /// + public const int TempoLength = 3; + + /// + /// Length in bytes for SMPTE offset meta message data. + /// + public const int SmpteOffsetLength = 5; + + /// + /// Length in bytes for time signature meta message data. + /// + public const int TimeSigLength = 4; + + /// + /// Length in bytes for key signature meta message data. + /// + public const int KeySigLength = 2; + + #endregion + + #region Class Fields + + /// + /// End of track meta message. + /// + public static readonly MetaMessage EndOfTrackMessage = + new MetaMessage(MetaType.EndOfTrack, new byte[0]); + + #endregion + + #region Fields + + // The meta message type. + private MetaType type; + + // The meta message data. + private byte[] data; + + // The hash code value. + private int hashCode; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the MetaMessage class. + /// + /// + /// The type of MetaMessage. + /// + /// + /// The MetaMessage data. + /// + /// + /// The length of the MetaMessage is not valid for the MetaMessage type. + /// + /// + /// Each MetaMessage has type and length properties. For certain + /// types, the length of the message data must be a specific value. For + /// example, tempo messages must have a data length of exactly three. + /// Some MetaMessage types can have any data length. Text messages are + /// an example of a MetaMessage that can have a variable data length. + /// When a MetaMessage is created, the length of the data is checked + /// to make sure that it is valid for the specified type. If it is not, + /// an exception is thrown. + /// + public MetaMessage(MetaType type, byte[] data) + { + #region Require + + if(data == null) + { + throw new ArgumentNullException("data"); + } + else if(!ValidateDataLength(type, data.Length)) + { + throw new ArgumentException( + "Length of data not valid for meta message type."); + } + + #endregion + + this.type = type; + + // Create storage for meta message data. + this.data = new byte[data.Length]; + + // Copy data into storage. + data.CopyTo(this.data, 0); + + CalculateHashCode(); + } + + #endregion + + #region Methods + + /// + /// Gets a copy of the data bytes for this meta message. + /// + /// + /// A copy of the data bytes for this meta message. + /// + public byte[] GetBytes() + { + return (byte[])data.Clone(); + } + + /// + /// Returns a value for the current MetaMessage suitable for use in + /// hashing algorithms. + /// + /// + /// A hash code for the current MetaMessage. + /// + public override int GetHashCode() + { + return hashCode; + } + + /// + /// Determines whether two MetaMessage instances are equal. + /// + /// + /// The MetaMessage to compare with the current MetaMessage. + /// + /// + /// true if the specified MetaMessage is equal to the current + /// MetaMessage; otherwise, false. + /// + public override bool Equals(object obj) + { + #region Guard + + if(!(obj is MetaMessage)) + { + return false; + } + + #endregion + + bool equal = true; + MetaMessage message = (MetaMessage)obj; + + // If the types do not match. + if(MetaType != message.MetaType) + { + // The messages are not equal + equal = false; + } + + // If the message lengths are not equal. + if(equal && Length != message.Length) + { + // The message are not equal. + equal = false; + } + + // Check to see if the data is equal. + for(int i = 0; i < Length && equal; i++) + { + // If a data value does not match. + if(this[i] != message[i]) + { + // The messages are not equal. + equal = false; + } + } + + return equal; + } + + // Calculates the hash code. + private void CalculateHashCode() + { + // TODO: This algorithm may need work. + + hashCode = (int)MetaType; + + for(int i = 0; i < data.Length; i += 3) + { + hashCode ^= data[i]; + } + + for(int i = 1; i < data.Length; i += 3) + { + hashCode ^= data[i] << Shift; + } + + for(int i = 2; i < data.Length; i += 3) + { + hashCode ^= data[i] << Shift * 2; + } + } + + /// + /// Validates data length. + /// + /// + /// The MetaMessage type. + /// + /// + /// The length of the MetaMessage data. + /// + /// + /// true if the data length is valid for this type of + /// MetaMessage; otherwise, false. + /// + private bool ValidateDataLength(MetaType type, int length) + { + #region Require + + Debug.Assert(length >= 0); + + #endregion + + bool result = true; + + // Determine which type of meta message this is and check to make + // sure that the data length value is valid. + switch(type) + { + case MetaType.SequenceNumber: + if(length != 0 || length != 2) + { + result = false; + } + break; + + case MetaType.EndOfTrack: + if(length != 0) + { + result = false; + } + break; + + case MetaType.Tempo: + if(length != TempoLength) + { + result = false; + } + break; + + case MetaType.SmpteOffset: + if(length != SmpteOffsetLength) + { + result = false; + } + break; + + case MetaType.TimeSignature: + if(length != TimeSigLength) + { + result = false; + } + break; + + case MetaType.KeySignature: + if(length != KeySigLength) + { + result = false; + } + break; + + default: + result = true; + break; + } + + return result; + } + + #endregion + + #region Properties + + /// + /// Gets the element at the specified index. + /// + /// + /// index is less than zero or greater than or equal to Length. + /// + public byte this[int index] + { + get + { + #region Require + + if(index < 0 || index >= Length) + { + throw new ArgumentOutOfRangeException("index", index, + "Index into MetaMessage out of range."); + } + + #endregion + + return data[index]; + } + } + + /// + /// Gets the length of the meta message. + /// + public int Length + { + get + { + return data.Length; + } + } + + /// + /// Gets the type of meta message. + /// + public MetaType MetaType + { + get + { + return type; + } + } + + #endregion + + #endregion + + #region IMidiMessage Members + + /// + /// Gets the status value. + /// + public int Status + { + get + { + // All meta messages have the same status value (0xFF). + return 0xFF; + } + } + + /// + /// Gets the MetaMessage's MessageType. + /// + public MessageType MessageType + { + get + { + return MessageType.Meta; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/InputDeviceMidiEvents.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/InputDeviceMidiEvents.cs new file mode 100644 index 0000000..88ac601 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/InputDeviceMidiEvents.cs @@ -0,0 +1,136 @@ + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// MidiSignal provides all midi events from an input device. + /// + public class InputDeviceMidiEvents : MidiEvents + { + readonly InputDevice FInDevice; + + /// + /// Gets the device ID. + /// + public int DeviceID { + get { + if (FInDevice != null) { + return FInDevice.DeviceID; + } + else { + return -1; + } + } + } + + /// + /// Create Midisignal with an input device which fires the events + /// + /// + public InputDeviceMidiEvents(InputDevice inDevice) + { + FInDevice = inDevice; + FInDevice.StartRecording(); + } + + /// + /// Disposes the input device when closed. + /// + public void Dispose() + { + FInDevice.Dispose(); + } + + /// + /// Initializes the MIDI events from device ID. + /// + public static InputDeviceMidiEvents FromDeviceID(int deviceID) + { + var deviceCount = InputDevice.DeviceCount; + if (deviceCount > 0) + { + deviceID %= deviceCount; + return new InputDeviceMidiEvents(new InputDevice(deviceID)); + } + return null; + } + + /// + /// All incoming midi messages in short format + /// + public event MidiMessageEventHandler MessageReceived + { + add + { + FInDevice.MessageReceived += value; + } + remove + { + FInDevice.MessageReceived -= value; + } + } + + /// + /// All incoming midi messages in short format + /// + public event EventHandler ShortMessageReceived { + add { + FInDevice.ShortMessageReceived += value; + } + remove { + FInDevice.ShortMessageReceived -= value; + } + } + + /// + /// Channel messages like, note, controller, program, ... + /// + public event EventHandler ChannelMessageReceived { + add { + FInDevice.ChannelMessageReceived += value; + } + remove { + FInDevice.ChannelMessageReceived -= value; + } + } + + /// + /// SysEx messages + /// + public event EventHandler SysExMessageReceived { + add { + FInDevice.SysExMessageReceived += value; + } + remove { + FInDevice.SysExMessageReceived -= value; + } + } + + /// + /// Midi timecode, song position, song select, tune request + /// + public event EventHandler SysCommonMessageReceived { + add { + FInDevice.SysCommonMessageReceived += value; + } + remove { + FInDevice.SysCommonMessageReceived -= value; + } + } + + /// + /// Timing events, midi clock, start, stop, reset, active sense, tick + /// + public event EventHandler SysRealtimeMessageReceived { + add { + FInDevice.SysRealtimeMessageReceived += value; + } + remove { + FInDevice.SysRealtimeMessageReceived -= value; + } + } + } +} + + diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MergeMidiEvents.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MergeMidiEvents.cs new file mode 100644 index 0000000..ff0b7d9 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MergeMidiEvents.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Takes a number of MidiEvents and merges them into a new single MidiEvent source + /// + public class MergeMidiEvents : MidiEvents + { + /// + /// Gets the device ID and returns with a value of -3. + /// + public int DeviceID + { + get + { + return -3; + } + } + + readonly List FMidiEventsList = new List(); + + /// + /// Merges the MIDI events. + /// + public MergeMidiEvents(IEnumerable midiEvents) + { + foreach (var elem in midiEvents) + { + if (elem != null) + FMidiEventsList.Add(elem); + } + } + + /// + /// Gets and returns the MIDI event sources from the events list. + /// + public IEnumerable EventSources + { + get + { + return FMidiEventsList; + } + } + + /// + /// Disposes of the MergeMidiEvents when closed. + /// + public void Dispose() + { + } + + /// + /// Handles the event for when a MIDI message is received. + /// + public event MidiMessageEventHandler MessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.MessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.MessageReceived -= value; + } + } + } + + /// + /// Handles the event for when a short message is received. + /// + public event EventHandler ShortMessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.ShortMessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.ShortMessageReceived -= value; + } + } + } + + /// + /// Handles the event for when a channel message is received. + /// + public event EventHandler ChannelMessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.ChannelMessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.ChannelMessageReceived -= value; + } + } + } + + /// + /// Handles the event for when an exclusive system message is received. + /// + public event EventHandler SysExMessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.SysExMessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.SysExMessageReceived -= value; + } + } + } + + /// + /// Handles the event for when a common system message is received. + /// + public event EventHandler SysCommonMessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.SysCommonMessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.SysCommonMessageReceived -= value; + } + } + } + + /// + /// Handles the event for when a realtime system message is received. + /// + public event EventHandler SysRealtimeMessageReceived + { + add + { + foreach (var elem in FMidiEventsList) + { + elem.SysRealtimeMessageReceived += value; + } + } + remove + { + foreach (var elem in FMidiEventsList) + { + elem.SysRealtimeMessageReceived -= value; + } + } + } + + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MidiEvents.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MidiEvents.cs new file mode 100644 index 0000000..000433f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/MidiEvents.cs @@ -0,0 +1,53 @@ + +using System; + +namespace Sanford.Multimedia.Midi +{ + + /// + /// An event source that combines all possible midi events + /// + public interface MidiEvents : IDisposable + { + /// + /// Gets the device identifier of the input devive. + /// Set it to any negative value for custom event sources. + /// + int DeviceID { get; } + + /// + /// Occurs when any message was received. The underlying type of the message should be as specific as possible. + /// Channel, Common, Realtime or SysEx. + /// + event MidiMessageEventHandler MessageReceived; + + /// + /// All incoming midi short messages + /// + event EventHandler ShortMessageReceived; + + /// + /// Channel messages like, note, controller, program, ... + /// + event EventHandler ChannelMessageReceived; + + /// + /// SysEx messages + /// + event EventHandler SysExMessageReceived; + + /// + /// Midi timecode, song position, song select, tune request + /// + event EventHandler SysCommonMessageReceived; + + /// + /// Timing events, midi clock, start, stop, reset, active sense, tick + /// + event EventHandler SysRealtimeMessageReceived; + } + + + + +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/OutputDeviceEventSink.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/OutputDeviceEventSink.cs new file mode 100644 index 0000000..d339df7 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/MidiEvents/OutputDeviceEventSink.cs @@ -0,0 +1,127 @@ +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Event sink that sends midi messages to an output device + /// + public class OutputDeviceEventSink : IDisposable + { + readonly OutputDevice FOutDevice; + readonly MidiEvents FEventSource; + + /// + /// Gets the device ID and returns with a value of -1. + /// + public int DeviceID + { + get + { + if (FOutDevice != null) + { + return FOutDevice.DeviceID; + } + else + { + return -1; + } + } + } + + /// + /// Initializes and registers the MIDI output device events. + /// + public OutputDeviceEventSink(OutputDevice outDevice, MidiEvents eventSource) + { + FOutDevice = outDevice; + FEventSource = eventSource; + + RegisterEvents(); + + } + + private void RegisterEvents() + { + FEventSource.MessageReceived += FEventSource_MessageReceived; + FEventSource.ShortMessageReceived += EventSource_RawMessageReceived; + FEventSource.ChannelMessageReceived += EventSource_ChannelMessageReceived; + FEventSource.SysCommonMessageReceived += EventSource_SysCommonMessageReceived; + FEventSource.SysExMessageReceived += EventSource_SysExMessageReceived; + FEventSource.SysRealtimeMessageReceived += EventSource_SysRealtimeMessageReceived; + } + + + private void UnRegisterEvents() + { + FEventSource.MessageReceived -= FEventSource_MessageReceived; + FEventSource.ShortMessageReceived -= EventSource_RawMessageReceived; + FEventSource.ChannelMessageReceived -= EventSource_ChannelMessageReceived; + FEventSource.SysCommonMessageReceived -= EventSource_SysCommonMessageReceived; + FEventSource.SysExMessageReceived -= EventSource_SysExMessageReceived; + FEventSource.SysRealtimeMessageReceived -= EventSource_SysRealtimeMessageReceived; + } + + private void FEventSource_MessageReceived(IMidiMessage message) + { + var shortMessage = message as ShortMessage; + if (shortMessage != null) + { + FOutDevice.SendShort(shortMessage.Message); + return; + } + + var sysExMessage = message as SysExMessage; + if (sysExMessage != null) + FOutDevice.Send(sysExMessage); + } + + + private void EventSource_SysRealtimeMessageReceived(object sender, SysRealtimeMessageEventArgs e) + { + FOutDevice.Send(e.Message); + } + + private void EventSource_SysExMessageReceived(object sender, SysExMessageEventArgs e) + { + FOutDevice.Send(e.Message); + } + + private void EventSource_SysCommonMessageReceived(object sender, SysCommonMessageEventArgs e) + { + FOutDevice.Send(e.Message); + } + + private void EventSource_ChannelMessageReceived(object sender, ChannelMessageEventArgs e) + { + FOutDevice.Send(e.Message); + } + + private void EventSource_RawMessageReceived(object sender, ShortMessageEventArgs e) + { + FOutDevice.SendShort(e.Message.Message); + } + + /// + /// Disposes the underying output device and removes the events from the source + /// + public void Dispose() + { + UnRegisterEvents(); + FOutDevice.Dispose(); + } + + /// + /// Sources and initializes the events for the MIDI output device. + /// + public static OutputDeviceEventSink FromDeviceID(int deviceID, MidiEvents eventSource) + { + var deviceCount = OutputDevice.DeviceCount; + if (deviceCount > 0) + { + deviceID %= deviceCount; + return new OutputDeviceEventSink(new OutputDevice(deviceID), eventSource); + } + return null; + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ShortMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ShortMessage.cs new file mode 100644 index 0000000..63acd74 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/ShortMessage.cs @@ -0,0 +1,297 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Base abstract class for delta frames for MIDI messages. + /// + public abstract class MidiMessageBase + { + /// + /// Delta samples when the event should be processed in the next audio buffer. + /// Leave at 0 for realtime input to play as fast as possible. + /// Set to the desired sample in the next buffer if you play a midi sequence synchronized to the audio callback + /// + public int DeltaFrames + { + get; + set; + } + + } + + /// + /// Represents the basic class for all MIDI short messages. + /// + /// + /// MIDI short messages represent all MIDI messages except meta messages + /// and system exclusive messages. This includes channel messages, system + /// realtime messages, and system common messages. + /// + public class ShortMessage : MidiMessageBase, IMidiMessage + { + #region ShortMessage Members + + #region Constants + + /// + /// The maximum value for data. + /// + public const int DataMaxValue= 255; + + /// + /// The maximum value for statuses. + /// + public const int StatusMaxValue = 255; + + // + // Bit manipulation constants. + // + + private const int StatusMask = ~255; + /// + /// Bit manipulation constant for data mask. + /// + protected const int DataMask = ~StatusMask; + private const int Data1Mask = ~65280; + private const int Data2Mask = ~Data1Mask + DataMask; + private const int Shift = 8; + + #endregion + + /// + /// The message is set at 0. + /// + protected int msg = 0; + + byte[] message; + bool rawMessageBuilt; + + #region Methods + + /// + /// Gets and returns the bytes for the MIDI short message. + /// + public byte[] GetBytes() + { + return Bytes; + } + + /// + /// Main function for MIDI short messages. + /// + public ShortMessage() + { + //sub classes will fill the msg field + } + + /// + /// Initializes the message for the MIDI short message function. + /// + public ShortMessage(int message) + { + this.msg = message; + } + + /// + /// Initializes the short message based on status and two bytes of data. + /// + public ShortMessage(byte status, byte data1, byte data2) + { + this.message = new byte[] { status, data1, data2 }; + rawMessageBuilt = true; + msg = BuildIntMessage(this.message); + } + + private static byte[] BuildByteMessage(int intMessage) + { + unchecked + { + return new byte[] { (byte)ShortMessage.UnpackStatus(intMessage), + (byte)ShortMessage.UnpackData1(intMessage), + (byte)ShortMessage.UnpackData2(intMessage) }; + } + } + + private static int BuildIntMessage(byte[] message) + { + var intMessage = 0; + intMessage = ShortMessage.PackStatus(intMessage, message[0]); + intMessage = ShortMessage.PackData1(intMessage, message[1]); + intMessage = ShortMessage.PackData2(intMessage, message[2]); + return intMessage; + } + + internal static int PackStatus(int message, int status) + { + #region Require + + if(status < 0 || status > StatusMaxValue) + { + throw new ArgumentOutOfRangeException("status", status, + "Status value out of range."); + } + + #endregion + + return (message & StatusMask) | status; + } + + internal static int PackData1(int message, int data1) + { + #region Require + + if(data1 < 0 || data1 > DataMaxValue) + { + throw new ArgumentOutOfRangeException("data1", data1, + "Data 1 value out of range."); + } + + #endregion + + return (message & Data1Mask) | (data1 << Shift); + } + + internal static int PackData2(int message, int data2) + { + #region Require + + if(data2 < 0 || data2 > DataMaxValue) + { + throw new ArgumentOutOfRangeException("data2", data2, + "Data 2 value out of range."); + } + + #endregion + + return (message & Data2Mask) | (data2 << (Shift * 2)); + } + + internal static int UnpackStatus(int message) + { + return message & DataMask; + } + + internal static int UnpackData1(int message) + { + return (message & ~Data1Mask) >> Shift; + } + + internal static int UnpackData2(int message) + { + return (message & ~Data2Mask) >> (Shift * 2); + } + + #endregion + + #region Properties + + /// + /// Gets the timestamp of the midi input driver in milliseconds since the midi input driver was started. + /// + /// + /// The timestamp in milliseconds since the midi input driver was started. + /// + public int Timestamp + { + get; + internal set; + } + + /// + /// Gets the short message as a packed integer. + /// + /// + /// The message is packed into an integer value with the low-order byte + /// of the low-word representing the status value. The high-order byte + /// of the low-word represents the first data value, and the low-order + /// byte of the high-word represents the second data value. + /// + public int Message + { + get + { + return msg; + } + } + + /// + /// Gets the messages's status value. + /// + public int Status + { + get + { + return UnpackStatus(msg); + } + } + + /// + /// Gets the bytes for the MIDI short message. + /// + /// + /// The message for the short message. + /// + public byte[] Bytes + { + get + { + if (!rawMessageBuilt) + { + this.message = BuildByteMessage(msg); + rawMessageBuilt = true; + } + return message; + } + } + + /// + /// Gets the message type and returns the message type with a short message. + /// + public virtual MessageType MessageType + { + get + { + return MessageType.Short; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysCommonMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysCommonMessage.cs new file mode 100644 index 0000000..767391c --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysCommonMessage.cs @@ -0,0 +1,257 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + #region System Common Message Types + + /// + /// Defines constants representing the various system common message types. + /// + public enum SysCommonType + { + /// + /// Represents the MTC system common message type. + /// + MidiTimeCode = 0xF1, + + /// + /// Represents the song position pointer type. + /// + SongPositionPointer, + + /// + /// Represents the song select type. + /// + SongSelect, + + /// + /// Represents the tune request type. + /// + TuneRequest = 0xF6 + } + + #endregion + + /// + /// Represents MIDI system common messages. + /// + [ImmutableObject(true)] + public sealed class SysCommonMessage : ShortMessage + { + #region SysCommonMessage Members + + #region Construction + + /// + /// Initializes a new instance of the SysCommonMessage class with the + /// specified type. + /// + /// + /// The type of SysCommonMessage. + /// + public SysCommonMessage(SysCommonType type) + { + msg = (int)type; + + #region Ensure + + Debug.Assert(SysCommonType == type); + + #endregion + } + + /// + /// Initializes a new instance of the SysCommonMessage class with the + /// specified type and the first data value. + /// + /// + /// The type of SysCommonMessage. + /// + /// + /// The first data value. + /// + /// + /// If data1 is less than zero or greater than 127. + /// + public SysCommonMessage(SysCommonType type, int data1) + { + msg = (int)type; + msg = PackData1(msg, data1); + + #region Ensure + + Debug.Assert(SysCommonType == type); + Debug.Assert(Data1 == data1); + + #endregion + } + + /// + /// Initializes a new instance of the SysCommonMessage class with the + /// specified type, first data value, and second data value. + /// + /// + /// The type of SysCommonMessage. + /// + /// + /// The first data value. + /// + /// + /// The second data value. + /// + /// + /// If data1 or data2 is less than zero or greater than 127. + /// + public SysCommonMessage(SysCommonType type, int data1, int data2) + { + msg = (int)type; + msg = PackData1(msg, data1); + msg = PackData2(msg, data2); + + #region Ensure + + Debug.Assert(SysCommonType == type); + Debug.Assert(Data1 == data1); + Debug.Assert(Data2 == data2); + + #endregion + } + + internal SysCommonMessage(int message) + { + this.msg = message; + } + + #endregion + + #region Methods + + /// + /// Returns a value for the current SysCommonMessage suitable for use + /// in hashing algorithms. + /// + /// + /// A hash code for the current SysCommonMessage. + /// + public override int GetHashCode() + { + return msg; + } + + /// + /// Determines whether two SysCommonMessage instances are equal. + /// + /// + /// The SysCommonMessage to compare with the current SysCommonMessage. + /// + /// + /// true if the specified SysCommonMessage is equal to the + /// current SysCommonMessage; otherwise, false. + /// + public override bool Equals(object obj) + { + #region Guard + + if(!(obj is SysCommonMessage)) + { + return false; + } + + #endregion + + SysCommonMessage message = (SysCommonMessage)obj; + + return (this.SysCommonType == message.SysCommonType && + this.Data1 == message.Data1 && + this.Data2 == message.Data2); + } + + #endregion + + #region Properties + + /// + /// Gets the SysCommonType. + /// + public SysCommonType SysCommonType + { + get + { + return (SysCommonType)UnpackStatus(msg); + } + } + + /// + /// Gets the first data value. + /// + public int Data1 + { + get + { + return UnpackData1(msg); + } + } + + /// + /// Gets the second data value. + /// + public int Data2 + { + get + { + return UnpackData2(msg); + } + } + + /// + /// Gets the MessageType. + /// + public override MessageType MessageType + { + get + { + return MessageType.SystemCommon; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysExMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysExMessage.cs new file mode 100644 index 0000000..04b3e2e --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysExMessage.cs @@ -0,0 +1,284 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Defines constants representing various system exclusive message types. + /// + public enum SysExType + { + /// + /// Represents the start of system exclusive message type. + /// + Start = 0xF0, + + /// + /// Represents the continuation of a system exclusive message. + /// + Continuation = 0xF7 + } + + /// + /// Represents MIDI system exclusive messages. + /// + public sealed class SysExMessage : MidiMessageBase, IMidiMessage, IEnumerable + { + #region SysExEventMessage Members + + #region Constants + + /// + /// Maximum value for system exclusive channels. + /// + public const int SysExChannelMaxValue = 127; + + #endregion + + #region Fields + + // The system exclusive data. + private byte[] data; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the SysExMessageEventArgs class with the + /// specified system exclusive data. + /// + /// + /// The system exclusive data. + /// + /// + /// The system exclusive data's status byte, the first byte in the + /// data, must have a value of 0xF0 or 0xF7. + /// + public SysExMessage(byte[] data) + { + #region Require + + if(data.Length < 1) + { + throw new ArgumentException( + "System exclusive data is too short.", "data"); + } + else if(data[0] != (byte)SysExType.Start && + data[0] != (byte)SysExType.Continuation) + { + throw new ArgumentException( + "Unknown status value.", "data"); + } + + #endregion + + this.data = new byte[data.Length]; + data.CopyTo(this.data, 0); + } + + #endregion + + #region Methods + + /// + /// Gets a byte array representation for the exclusive system message. + /// + /// + /// A clone of the byte array. + /// + public byte[] GetBytes() + { + byte[] clone = new byte[data.Length]; + + data.CopyTo(clone, 0); + + return clone; + } + + /// + /// Copies the data to a byte array buffer and index. + /// + public void CopyTo(byte[] buffer, int index) + { + data.CopyTo(buffer, index); + } + + /// + /// Determines whenever the specified object is equal to the current object. + /// + public override bool Equals(object obj) + { + #region Guard + + if(!(obj is SysExMessage)) + { + return false; + } + + #endregion + + SysExMessage message = (SysExMessage)obj; + + bool equals = true; + + if(this.Length != message.Length) + { + equals = false; + } + + for(int i = 0; i < this.Length && equals; i++) + { + if(this[i] != message[i]) + { + equals = false; + } + } + + return equals; + } + + /// + /// Returns the hash code for the current object. + /// + public override int GetHashCode() + { + return data.GetHashCode(); + } + + #endregion + + #region Properties + + /// + /// Gets the timestamp of the midi input driver in milliseconds since the midi input driver was started. + /// + /// + /// The timestamp in milliseconds since the midi input driver was started. + /// + public int Timestamp + { + get; + internal set; + } + + /// + /// Gets the element at the specified index. + /// + /// + /// If index is less than zero or greater than or equal to the length + /// of the message. + /// + public byte this[int index] + { + get + { + #region Require + + if(index < 0 || index >= Length) + { + throw new ArgumentOutOfRangeException("index", index, + "Index into system exclusive message out of range."); + } + + #endregion + + return data[index]; + } + } + + /// + /// Gets the length of the system exclusive data. + /// + public int Length + { + get + { + return data.Length; + } + } + + /// + /// Gets the system exclusive type. + /// + public SysExType SysExType + { + get + { + return (SysExType)data[0]; + } + } + + #endregion + + #endregion + + /// + /// Gets the status value. + /// + public int Status + { + get + { + return (int)data[0]; + } + } + + /// + /// Gets the MessageType. + /// + public MessageType MessageType + { + get + { + return MessageType.SystemExclusive; + } + } + + #region IEnumerable Members + + /// + /// Returns an enumerator for the exclusive system message. + /// + public IEnumerator GetEnumerator() + { + return data.GetEnumerator(); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysRealtimeMessage.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysRealtimeMessage.cs new file mode 100644 index 0000000..9544af6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Messages/SysRealtimeMessage.cs @@ -0,0 +1,227 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + #region System Realtime Message Types + + /// + /// Defines constants representing the various system realtime message types. + /// + public enum SysRealtimeType + { + /// + /// Represents the clock system realtime type. + /// + Clock = 0xF8, + + /// + /// Represents the tick system realtime type. + /// + Tick, + + /// + /// Represents the start system realtime type. + /// + Start, + + /// + /// Represents the continue system realtime type. + /// + Continue, + + /// + /// Represents the stop system realtime type. + /// + Stop, + + /// + /// Represents the active sense system realtime type. + /// + ActiveSense = 0xFE, + + /// + /// Represents the reset system realtime type. + /// + Reset + } + + #endregion + + /// + /// Represents MIDI system realtime messages. + /// + /// + /// System realtime messages are MIDI messages that are primarily concerned + /// with controlling and synchronizing MIDI devices. + /// + [ImmutableObject(true)] + public sealed class SysRealtimeMessage : ShortMessage + { + #region SysRealtimeMessage Members + + #region System Realtime Messages + + /// + /// The instance of the system realtime start message. + /// + public static readonly SysRealtimeMessage StartMessage = + new SysRealtimeMessage(SysRealtimeType.Start); + + /// + /// The instance of the system realtime continue message. + /// + public static readonly SysRealtimeMessage ContinueMessage = + new SysRealtimeMessage(SysRealtimeType.Continue); + + /// + /// The instance of the system realtime stop message. + /// + public static readonly SysRealtimeMessage StopMessage = + new SysRealtimeMessage(SysRealtimeType.Stop); + + /// + /// The instance of the system realtime clock message. + /// + public static readonly SysRealtimeMessage ClockMessage = + new SysRealtimeMessage(SysRealtimeType.Clock); + + /// + /// The instance of the system realtime tick message. + /// + public static readonly SysRealtimeMessage TickMessage = + new SysRealtimeMessage(SysRealtimeType.Tick); + + /// + /// The instance of the system realtime active sense message. + /// + public static readonly SysRealtimeMessage ActiveSenseMessage = + new SysRealtimeMessage(SysRealtimeType.ActiveSense); + + /// + /// The instance of the system realtime reset message. + /// + public static readonly SysRealtimeMessage ResetMessage = + new SysRealtimeMessage(SysRealtimeType.Reset); + + #endregion + + // Make construction private so that a system realtime message cannot + // be constructed directly. + private SysRealtimeMessage(SysRealtimeType type) + { + msg = (int)type; + + #region Ensure + + Debug.Assert(SysRealtimeType == type); + + #endregion + } + + #region Methods + + /// + /// Returns a value for the current SysRealtimeMessage suitable for use in + /// hashing algorithms. + /// + /// + /// A hash code for the current SysRealtimeMessage. + /// + public override int GetHashCode() + { + return msg; + } + + /// + /// Determines whether two SysRealtimeMessage instances are equal. + /// + /// + /// The SysRealtimeMessage to compare with the current SysRealtimeMessage. + /// + /// + /// true if the specified SysRealtimeMessage is equal to the current + /// SysRealtimeMessage; otherwise, false. + /// + public override bool Equals(object obj) + { + #region Guard + + if(!(obj is SysRealtimeMessage)) + { + return false; + } + + #endregion + + SysRealtimeMessage message = (SysRealtimeMessage)obj; + + return this.msg == message.msg; + } + + #endregion + + #region Properties + + /// + /// Gets the SysRealtimeType. + /// + public SysRealtimeType SysRealtimeType + { + get + { + return (SysRealtimeType)msg; + } + } + + /// + /// Gets the MessageType. + /// + public override MessageType MessageType + { + get + { + return MessageType.SystemRealtime; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/MidiNoteConverter.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/MidiNoteConverter.cs new file mode 100644 index 0000000..942b54e --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/MidiNoteConverter.cs @@ -0,0 +1,156 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Converts a MIDI note number to its corresponding frequency. + /// + public sealed class MidiNoteConverter + { + /// + /// The minimum value a note ID can have. + /// + public const int NoteIDMinValue = 0; + + /// + /// The maximum value a note ID can have. + /// + public const int NoteIDMaxValue = 127; + + // Table for holding frequency values. + private readonly static double[] NoteToFrequencyTable = new double[NoteIDMaxValue + 1]; + + static MidiNoteConverter() + { + // The number of notes per octave. + int notesPerOctave = 12; + + // Reference frequency used for calculations. + double referenceFrequency = 440; + + // The note ID of the reference frequency. + int referenceNoteID = 69; + + double exponent; + + // Fill table with the frequencies of all MIDI notes. + for(int i = 0; i < NoteToFrequencyTable.Length; i++) + { + exponent = (double)(i - referenceNoteID) / notesPerOctave; + + NoteToFrequencyTable[i] = referenceFrequency * Math.Pow(2.0, exponent); + } + } + + // Prevents instances of this class from being created - no need for + // an instance to be created since this class only has static methods. + private MidiNoteConverter() + { + } + + /// + /// Converts the specified note to a frequency. + /// + /// + /// The ID of the note to convert. + /// + /// + /// The frequency of the specified note. + /// + public static double NoteToFrequency(int noteID) + { + #region Require + + if(noteID < NoteIDMinValue || noteID > NoteIDMaxValue) + { + throw new ArgumentOutOfRangeException("Note ID out of range."); + } + + #endregion + + return NoteToFrequencyTable[noteID]; + } + + /// + /// Converts the specified frequency to a note. + /// + /// + /// The frequency to convert. + /// + /// + /// The ID of the note closest to the specified frequency. + /// + public static int FrequencyToNote(double frequency) + { + int noteID = 0; + bool found = false; + + // Search for the note with a frequency near the specified frequency. + for(int i = 0; i < NoteIDMaxValue && !found; i++) + { + noteID = i; + + // If the specified frequency is less than the frequency of + // the next note. + if(frequency < NoteToFrequency(noteID + 1)) + { + // Indicate that the note ID for the specified frequency + // has been found. + found = true; + } + } + + // If the note is not the first or last note, narrow the results. + if(noteID > 0 && noteID < NoteIDMaxValue) + { + // Get the frequency of the previous note. + double previousFrequncy = NoteToFrequency(noteID - 1); + // Get the frequency of the next note. + double nextFrequency = NoteToFrequency(noteID + 1); + + // If the next note is closer in frequency than the previous note. + if(nextFrequency - frequency < frequency - previousFrequncy) + { + // Move to the next note. + noteID++; + } + } + + return noteID; + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelChaser.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelChaser.cs new file mode 100644 index 0000000..d5f53d4 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelChaser.cs @@ -0,0 +1,188 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The class that contains the channel chaser functionality. + /// + public class ChannelChaser + { + private ChannelMessage[,] controllerMessages; + + private ChannelMessage[] programChangeMessages; + + private ChannelMessage[] pitchBendMessages; + + private ChannelMessage[] channelPressureMessages; + + private ChannelMessage[] polyPressureMessages; + + /// + /// Handles the chased events. + /// + public event EventHandler Chased; + + /// + /// The main functions for ChannelChaser. + /// + public ChannelChaser() + { + int c = ChannelMessage.MidiChannelMaxValue + 1; + int d = ShortMessage.DataMaxValue + 1; + + controllerMessages = new ChannelMessage[c, d]; + + programChangeMessages = new ChannelMessage[c]; + pitchBendMessages = new ChannelMessage[c]; + channelPressureMessages = new ChannelMessage[c]; + polyPressureMessages = new ChannelMessage[c]; + } + + /// + /// For processing channel messages. + /// + public void Process(ChannelMessage message) + { + switch(message.Command) + { + case ChannelCommand.Controller: + controllerMessages[message.MidiChannel, message.Data1] = message; + break; + + case ChannelCommand.ChannelPressure: + channelPressureMessages[message.MidiChannel] = message; + break; + + case ChannelCommand.PitchWheel: + pitchBendMessages[message.MidiChannel] = message; + break; + + case ChannelCommand.PolyPressure: + polyPressureMessages[message.MidiChannel] = message; + break; + + case ChannelCommand.ProgramChange: + programChangeMessages[message.MidiChannel] = message; + break; + } + } + + /// + /// Chases messages to an array so that it can determine between the MIDI channel value and data value, then detect the program change messages, pitch bend messages, channel pressure messages and poly pressure messages. + /// + public void Chase() + { + ArrayList chasedMessages = new ArrayList(); + + for(int c = 0; c <= ChannelMessage.MidiChannelMaxValue; c++) + { + for(int n = 0; n <= ShortMessage.DataMaxValue; n++) + { + if(controllerMessages[c, n] != null) + { + chasedMessages.Add(controllerMessages[c, n]); + + controllerMessages[c, n] = null; + } + } + + if(programChangeMessages[c] != null) + { + chasedMessages.Add(programChangeMessages[c]); + + programChangeMessages[c] = null; + } + + if(pitchBendMessages[c] != null) + { + chasedMessages.Add(pitchBendMessages[c]); + + pitchBendMessages[c] = null; + } + + if(channelPressureMessages[c] != null) + { + chasedMessages.Add(channelPressureMessages[c]); + + channelPressureMessages[c] = null; + } + + if(polyPressureMessages[c] != null) + { + chasedMessages.Add(polyPressureMessages[c]); + + polyPressureMessages[c] = null; + } + } + + OnChased(new ChasedEventArgs(chasedMessages)); + } + + /// + /// Resets all the channel chaser values. + /// + public void Reset() + { + for(int c = 0; c <= ChannelMessage.MidiChannelMaxValue; c++) + { + for(int n = 0; n <= ShortMessage.DataMaxValue; n++) + { + controllerMessages[c, n] = null; + } + + programChangeMessages[c] = null; + pitchBendMessages[c] = null; + channelPressureMessages[c] = null; + polyPressureMessages[c] = null; + } + } + + /// + /// Handles the chased event. + /// + protected virtual void OnChased(ChasedEventArgs e) + { + EventHandler handler = Chased; + + if(handler != null) + { + handler(this, e); + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelStopper.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelStopper.cs new file mode 100644 index 0000000..be04f65 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChannelStopper.cs @@ -0,0 +1,232 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; + +namespace Sanford.Multimedia.Midi +{ + /// + /// The ChannelStopper class, which provides pedal messages and sustenuto messages. + /// + public class ChannelStopper + { + private ChannelMessage[,] noteOnMessage; + + private bool[] holdPedal1Message; + + private bool[] holdPedal2Message; + + private bool[] sustenutoMessage; + + private ChannelMessageBuilder builder = new ChannelMessageBuilder(); + + /// + /// Handles the stopped event. + /// + public event EventHandler Stopped; + + /// + /// This function contains the pedal messages and sustenuto messages. + /// + public ChannelStopper() + { + int c = ChannelMessage.MidiChannelMaxValue + 1; + int d = ShortMessage.DataMaxValue + 1; + + noteOnMessage = new ChannelMessage[c, d]; + + holdPedal1Message = new bool[c]; + holdPedal2Message = new bool[c]; + sustenutoMessage = new bool[c]; + } + + /// + /// Processes the channel message. + /// + public void Process(ChannelMessage message) + { + switch(message.Command) + { + case ChannelCommand.NoteOn: + if(message.Data2 > 0) + { + noteOnMessage[message.MidiChannel, message.Data1] = message; + } + else + { + noteOnMessage[message.MidiChannel, message.Data1] = null; + } + break; + + case ChannelCommand.NoteOff: + noteOnMessage[message.MidiChannel, message.Data1] = null; + break; + + case ChannelCommand.Controller: + switch(message.Data1) + { + case (int)ControllerType.HoldPedal1: + if(message.Data2 > 63) + { + holdPedal1Message[message.MidiChannel] = true; + } + else + { + holdPedal1Message[message.MidiChannel] = false; + } + break; + + case (int)ControllerType.HoldPedal2: + if(message.Data2 > 63) + { + holdPedal2Message[message.MidiChannel] = true; + } + else + { + holdPedal2Message[message.MidiChannel] = false; + } + break; + + case (int)ControllerType.SustenutoPedal: + if(message.Data2 > 63) + { + sustenutoMessage[message.MidiChannel] = true; + } + else + { + sustenutoMessage[message.MidiChannel] = false; + } + break; + } + break; + } + } + + /// + /// Switches all sound off when stopped. + /// + public void AllSoundOff() + { + ArrayList stoppedMessages = new ArrayList(); + + for(int c = 0; c <= ChannelMessage.MidiChannelMaxValue; c++) + { + for(int n = 0; n <= ShortMessage.DataMaxValue; n++) + { + if(noteOnMessage[c, n] != null) + { + builder.MidiChannel = c; + builder.Command = ChannelCommand.NoteOff; + builder.Data1 = noteOnMessage[c, n].Data1; + builder.Build(); + + stoppedMessages.Add(builder.Result); + + noteOnMessage[c, n] = null; + } + } + + if(holdPedal1Message[c]) + { + builder.MidiChannel = c; + builder.Command = ChannelCommand.Controller; + builder.Data1 = (int)ControllerType.HoldPedal1; + builder.Build(); + + stoppedMessages.Add(builder.Result); + + holdPedal1Message[c] = false; + } + + if(holdPedal2Message[c]) + { + builder.MidiChannel = c; + builder.Command = ChannelCommand.Controller; + builder.Data1 = (int)ControllerType.HoldPedal2; + builder.Build(); + + stoppedMessages.Add(builder.Result); + + holdPedal2Message[c] = false; + } + + if(sustenutoMessage[c]) + { + builder.MidiChannel = c; + builder.Command = ChannelCommand.Controller; + builder.Data1 = (int)ControllerType.SustenutoPedal; + builder.Build(); + + stoppedMessages.Add(builder.Result); + + sustenutoMessage[c] = false; + } + } + + OnStopped(new StoppedEventArgs(stoppedMessages)); + } + + /// + /// Resets all the messages. + /// + public void Reset() + { + for(int c = 0; c <= ChannelMessage.MidiChannelMaxValue; c++) + { + for(int n = 0; n <= ShortMessage.DataMaxValue; n++) + { + noteOnMessage[c, n] = null; + } + + holdPedal1Message[c] = false; + holdPedal2Message[c] = false; + sustenutoMessage[c] = false; + } + } + + /// + /// Handles the event when the channels are stopped. + /// + protected virtual void OnStopped(StoppedEventArgs e) + { + EventHandler handler = Stopped; + + if(handler != null) + { + handler(this, e); + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChasedEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChasedEventArgs.cs new file mode 100644 index 0000000..4acef68 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/ChasedEventArgs.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// A class for chased events. + /// + public class ChasedEventArgs : EventArgs + { + private ICollection messages; + + /// + /// Main function for chased events. + /// + public ChasedEventArgs(ICollection messages) + { + this.messages = messages; + } + + /// + /// Gets and returns messages. + /// + public ICollection Messages + { + get + { + return messages; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/StoppedEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/StoppedEventArgs.cs new file mode 100644 index 0000000..d8e5c82 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Processing/StoppedEventArgs.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// A class for stopped events. + /// + public class StoppedEventArgs : EventArgs + { + private ICollection messages; + + /// + /// Main function for stopped events. + /// + public StoppedEventArgs(ICollection messages) + { + this.messages = messages; + } + + /// + /// Gets and returns messages. + /// + public ICollection Messages + { + get + { + return messages; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiEvent.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiEvent.cs new file mode 100644 index 0000000..3735ec3 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiEvent.cs @@ -0,0 +1,160 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia.Midi +{ + /// + /// A class for MIDI events. + /// + public class MidiEvent + { + private object owner = null; + + private int absoluteTicks; + + private IMidiMessage message; + + private MidiEvent next = null; + + private MidiEvent previous = null; + + internal MidiEvent(object owner, int absoluteTicks, IMidiMessage message) + { + #region Require + + if(owner == null) + { + throw new ArgumentNullException("owner"); + } + else if(absoluteTicks < 0) + { + throw new ArgumentOutOfRangeException("absoluteTicks", absoluteTicks, + "Absolute ticks out of range."); + } + else if(message == null) + { + throw new ArgumentNullException("e"); + } + + #endregion + + this.owner = owner; + this.absoluteTicks = absoluteTicks; + this.message = message; + } + + internal void SetAbsoluteTicks(int absoluteTicks) + { + this.absoluteTicks = absoluteTicks; + } + + internal object Owner + { + get + { + return owner; + } + } + + /// + /// Gets and returns the amount of absolute ticks. + /// + public int AbsoluteTicks + { + get + { + return absoluteTicks; + } + } + + /// + /// Gets the amount of delta ticks from absolute ticks, subtracted from the previous absolute ticks, if the previous tick is not null; otherwise, obtains the amount of absolute ticks. + /// + public int DeltaTicks + { + get + { + int deltaTicks; + + if(Previous != null) + { + deltaTicks = AbsoluteTicks - previous.AbsoluteTicks; + } + else + { + deltaTicks = AbsoluteTicks; + } + + return deltaTicks; + } + } + + /// + /// Gets and returns the MIDI message. + /// + public IMidiMessage MidiMessage + { + get + { + return message; + } + } + + internal MidiEvent Next + { + get + { + return next; + } + set + { + next = value; + } + } + + internal MidiEvent Previous + { + get + { + return previous; + } + set + { + previous = value; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiFileProperties.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiFileProperties.cs new file mode 100644 index 0000000..448c87b --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/MidiFileProperties.cs @@ -0,0 +1,412 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Diagnostics; +using System.IO; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Defintes constants representing SMPTE frame rates. + /// + public enum SmpteFrameRate + { + /// + /// 24 SMPTE Frames. + /// + Smpte24 = 24, + + /// + /// 25 SMPTE Frames. + /// + Smpte25 = 25, + + /// + /// 29 SMPTE Frames. + /// + Smpte30Drop = 29, + + /// + /// 30 SMPTE Frames. + /// + Smpte30 = 30 + } + + /// + /// The different types of sequences. + /// + public enum SequenceType + { + /// + /// The PPQN Sequence Type. + /// + Ppqn, + + /// + /// The SMPTE Sequence Type. + /// + Smpte + } + + /// + /// Represents MIDI file properties. + /// + internal class MidiFileProperties + { + private const int PropertyLength = 2; + + private static readonly byte[] MidiFileHeader = + { + (byte)'M', + (byte)'T', + (byte)'h', + (byte)'d', + 0, + 0, + 0, + 6 + }; + + private int format = 1; + + private int trackCount = 0; + + private int division = PpqnClock.PpqnMinValue; + + private SequenceType sequenceType = SequenceType.Ppqn; + + public MidiFileProperties() + { + } + + public void Read(Stream strm) + { + #region Require + + if(strm == null) + { + throw new ArgumentNullException("strm"); + } + + #endregion + + format = trackCount = division = 0; + + FindHeader(strm); + Format = (int)ReadProperty(strm); + TrackCount = (int)ReadProperty(strm); + Division = (int)ReadProperty(strm); + + #region Invariant + + AssertValid(); + + #endregion + } + + private void FindHeader(Stream stream) + { + bool found = false; + int result; + + while(!found) + { + result = stream.ReadByte(); + + if(result == 'M') + { + result = stream.ReadByte(); + + if(result == 'T') + { + result = stream.ReadByte(); + + if(result == 'h') + { + result = stream.ReadByte(); + + if(result == 'd') + { + found = true; + } + } + } + } + + if(result < 0) + { + throw new MidiFileException("Unable to find MIDI file header."); + } + } + + // Eat the header length. + for(int i = 0; i < 4; i++) + { + if(stream.ReadByte() < 0) + { + throw new MidiFileException("Unable to find MIDI file header."); + } + } + } + + private ushort ReadProperty(Stream strm) + { + byte[] data = new byte[PropertyLength]; + + int result = strm.Read(data, 0, data.Length); + + if(result != data.Length) + { + throw new MidiFileException("End of MIDI file unexpectedly reached."); + } + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(data); + } + + return BitConverter.ToUInt16(data, 0); + } + + public void Write(Stream strm) + { + #region Require + + if(strm == null) + { + throw new ArgumentNullException("strm"); + } + + #endregion + + strm.Write(MidiFileHeader, 0, MidiFileHeader.Length); + WriteProperty(strm, (ushort)Format); + WriteProperty(strm, (ushort)TrackCount); + WriteProperty(strm, (ushort)Division); + } + + private void WriteProperty(Stream strm, ushort property) + { + byte[] data = BitConverter.GetBytes(property); + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(data); + } + + strm.Write(data, 0, PropertyLength); + } + + private static bool IsSmpte(int division) + { + bool result; + byte[] data = BitConverter.GetBytes((short)division); + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(data); + } + + if((sbyte)data[0] < 0) + { + result = true; + } + else + { + result = false; + } + + return result; + } + + [Conditional("DEBUG")] + private void AssertValid() + { + if(trackCount > 1) + { + Debug.Assert(Format == 1 || Format == 2); + } + + if(IsSmpte(Division)) + { + Debug.Assert(SequenceType == SequenceType.Smpte); + } + else + { + Debug.Assert(SequenceType == SequenceType.Ppqn); + Debug.Assert(Division >= PpqnClock.PpqnMinValue); + } + } + + public int Format + { + get + { + return format; + } + set + { + #region Require + + if(value < 0 || value > 2) + { + throw new ArgumentOutOfRangeException("Format", value, + "MIDI file format out of range."); + } + else if(value == 0 && trackCount > 1) + { + throw new ArgumentException( + "MIDI file format invalid for this track count."); + } + + #endregion + + format = value; + + #region Invariant + + AssertValid(); + + #endregion + } + } + + public int TrackCount + { + get + { + return trackCount; + } + set + { + #region Require + + if(value < 0) + { + throw new ArgumentOutOfRangeException("TrackCount", value, + "Track count out of range."); + } + else if(value > 1 && Format == 0) + { + throw new ArgumentException( + "Track count invalid for this format."); + } + + #endregion + + trackCount = value; + + #region Invariant + + AssertValid(); + + #endregion + } + } + + public int Division + { + get + { + return division; + } + set + { + if(IsSmpte(value)) + { + byte[] data = BitConverter.GetBytes((short)value); + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(data); + } + + if((sbyte)data[0] != -(int)SmpteFrameRate.Smpte24 && + (sbyte)data[0] != -(int)SmpteFrameRate.Smpte25 && + (sbyte)data[0] != -(int)SmpteFrameRate.Smpte30 && + (sbyte)data[0] != -(int)SmpteFrameRate.Smpte30Drop) + { + throw new ArgumentException("Invalid SMPTE frame rate."); + } + else + { + sequenceType = SequenceType.Smpte; + } + } + else + { + if(value < PpqnClock.PpqnMinValue) + { + throw new ArgumentOutOfRangeException("Ppqn", value, + "Pulses per quarter note is smaller than 24."); + } + else + { + sequenceType = SequenceType.Ppqn; + } + } + + division = value; + + #region Invariant + + AssertValid(); + + #endregion + } + } + + public SequenceType SequenceType + { + get + { + return sequenceType; + } + } + } + + /// + /// MIDI File Exception handles errors relating to the application being unable to read or write to a MIDI or Sequence. + /// + public class MidiFileException : ApplicationException + { + /// + /// The message that will display when an error occurs with a MIDI or Sequence format + /// + public MidiFileException(string message) : base(message) + { + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/RecordingSession.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/RecordingSession.cs new file mode 100644 index 0000000..b952517 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/RecordingSession.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Midi +{ + /// + /// This class initializes the recording sessions. + /// + public class RecordingSession + { + private IClock clock; + + private List buffer = new List(); + + private Track result = new Track(); + + /// + /// Main function for the recording sessions. + /// + public RecordingSession(IClock clock) + { + this.clock = clock; + } + + /// + /// Builds the tracks, sorts and compares between a buffer and a timestamp, then creates a timestamped message with the amount of ticks. + /// + public void Build() + { + result = new Track(); + + buffer.Sort(new TimestampComparer()); + + foreach(TimestampedMessage tm in buffer) + { + result.Insert(tm.ticks, tm.message); + } + } + + /// + /// Removes all elements from the list. + /// + public void Clear() + { + buffer.Clear(); + } + + /// + /// Gets and returns the track result for the recording session. + /// + public Track Result + { + get + { + return result; + } + } + + /// + /// Records a channel message if the clock is running. + /// + public void Record(ChannelMessage message) + { + if(clock.IsRunning) + { + buffer.Add(new TimestampedMessage(clock.Ticks, message)); + } + } + + /// + /// Records an external system message if the clock is running. + /// + public void Record(SysExMessage message) + { + if(clock.IsRunning) + { + buffer.Add(new TimestampedMessage(clock.Ticks, message)); + } + } + + private struct TimestampedMessage + { + public int ticks; + + public IMidiMessage message; + + public TimestampedMessage(int ticks, IMidiMessage message) + { + this.ticks = ticks; + this.message = message; + } + } + + private class TimestampComparer : IComparer + { + #region IComparer Members + + public int Compare(TimestampedMessage x, TimestampedMessage y) + { + if(x.ticks > y.ticks) + { + return 1; + } + else if(x.ticks < y.ticks) + { + return -1; + } + else + { + return 0; + } + } + + #endregion + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequence.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequence.cs new file mode 100644 index 0000000..c325b09 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequence.cs @@ -0,0 +1,919 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents a collection of Tracks. + /// + public sealed class Sequence : IComponent, ICollection + { + #region Sequence Members + + #region Fields + + // The collection of Tracks for the Sequence. + private List tracks = new List(); + + // The Sequence's MIDI file properties. + private MidiFileProperties properties = new MidiFileProperties(); + + private BackgroundWorker loadWorker = new BackgroundWorker(); + + private BackgroundWorker saveWorker = new BackgroundWorker(); + + private ISite site = null; + + private bool disposed = false; + + #endregion + + #region Events + + /// + /// When the loading of the sequence is complete. + /// + public event EventHandler LoadCompleted; + + /// + /// When the loading of the sequence has changed. + /// + public event ProgressChangedEventHandler LoadProgressChanged; + + /// + /// When the sequence is saved. + /// + public event EventHandler SaveCompleted; + + /// + /// When the save progress for the sequence has changed. + /// + public event ProgressChangedEventHandler SaveProgressChanged; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the Sequence class. + /// + public Sequence() + { + InitializeBackgroundWorkers(); + } + + /// + /// Initializes a new instance of the Sequence class with the specified division. + /// + /// + /// The Sequence's division value. + /// + public Sequence(int division) + { + properties.Division = division; + properties.Format = 1; + + InitializeBackgroundWorkers(); + } + + /// + /// Initializes a new instance of the Sequence class with the specified + /// file name of the MIDI file to load. + /// + /// + /// The name of the MIDI file to load. + /// + public Sequence(string fileName) + { + InitializeBackgroundWorkers(); + + Load(fileName); + } + + /// + /// Initializes a new instance of the Sequence class with the specified + /// file stream of the MIDI file to load. + /// + /// + /// The stream of the MIDI file to load. + /// + public Sequence(Stream fileStream) + { + InitializeBackgroundWorkers(); + + Load(fileStream); + } + + private void InitializeBackgroundWorkers() + { + loadWorker.DoWork += new DoWorkEventHandler(LoadDoWork); + loadWorker.ProgressChanged += new ProgressChangedEventHandler(OnLoadProgressChanged); + loadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnLoadCompleted); + loadWorker.WorkerReportsProgress = true; + + saveWorker.DoWork += new DoWorkEventHandler(SaveDoWork); + saveWorker.ProgressChanged += new ProgressChangedEventHandler(OnSaveProgressChanged); + saveWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnSaveCompleted); + saveWorker.WorkerReportsProgress = true; + } + + #endregion + + #region Methods + + /// + /// Loads a MIDI file into the Sequence. + /// + /// + /// The MIDI file's name. + /// + public void Load(string fileName) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(IsBusy) + { + throw new InvalidOperationException(); + } + else if(fileName == null) + { + throw new ArgumentNullException("fileName"); + } + + #endregion + + FileStream stream = new FileStream(fileName, FileMode.Open, + FileAccess.Read, FileShare.Read); + + using(stream) + { + MidiFileProperties newProperties = new MidiFileProperties(); + TrackReader reader = new TrackReader(); + List newTracks = new List(); + + newProperties.Read(stream); + + for(int i = 0; i < newProperties.TrackCount; i++) + { + reader.Read(stream); + newTracks.Add(reader.Track); + } + + properties = newProperties; + tracks = newTracks; + } + + #region Ensure + + Debug.Assert(Count == properties.TrackCount); + + #endregion + } + + /// + /// Loads a MIDI stream into the Sequence. + /// + /// + /// The MIDI file's stream. + /// + public void Load(Stream fileStream) + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if (IsBusy) + { + throw new InvalidOperationException(); + } + else if (fileStream == null) + { + throw new ArgumentNullException("fileStream"); + } + + #endregion + + using (fileStream) + { + MidiFileProperties newProperties = new MidiFileProperties(); + TrackReader reader = new TrackReader(); + List newTracks = new List(); + + newProperties.Read(fileStream); + + for (int i = 0; i < newProperties.TrackCount; i++) + { + reader.Read(fileStream); + newTracks.Add(reader.Track); + } + + properties = newProperties; + tracks = newTracks; + } + + #region Ensure + + Debug.Assert(Count == properties.TrackCount); + + #endregion + } + + /// + /// Loads the sequence asynchronously. + /// + public void LoadAsync(string fileName) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(IsBusy) + { + throw new InvalidOperationException(); + } + else if(fileName == null) + { + throw new ArgumentNullException("fileName"); + } + + #endregion + + loadWorker.RunWorkerAsync(fileName); + } + + /// + /// Cancels loading the sequence asynchronously. + /// + public void LoadAsyncCancel() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + loadWorker.CancelAsync(); + } + + /// + /// Saves the Sequence as a MIDI file. + /// + /// + /// The name to use for saving the MIDI file. + /// + public void Save(string fileName) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(fileName == null) + { + throw new ArgumentNullException("fileName"); + } + + #endregion + + FileStream stream = new FileStream(fileName, FileMode.Create, + FileAccess.Write, FileShare.None); + using (stream) + { + Save(stream); + } + } + + /// + /// Saves the Sequence as a Stream. + /// + /// + /// The stream to use for saving the sequence. + /// + public void Save(Stream stream) + { + properties.Write(stream); + + TrackWriter writer = new TrackWriter(); + + foreach(Track trk in tracks) + { + writer.Track = trk; + writer.Write(stream); + } + } + + /// + /// Saves the sequence asynchronously. + /// + public void SaveAsync(string fileName) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(IsBusy) + { + throw new InvalidOperationException(); + } + else if(fileName == null) + { + throw new ArgumentNullException("fileName"); + } + + #endregion + + saveWorker.RunWorkerAsync(fileName); + } + + /// + /// Cancels saving the sequence asynchronously. + /// + public void SaveAsyncCancel() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + saveWorker.CancelAsync(); + } + + /// + /// Gets the length in ticks of the Sequence. + /// + /// + /// The length in ticks of the Sequence. + /// + /// + /// The length in ticks of the Sequence is represented by the Track + /// with the longest length. + /// + public int GetLength() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + int length = 0; + + foreach(Track t in this) + { + if(t.Length > length) + { + length = t.Length; + } + } + + return length; + } + + private void OnLoadCompleted(object sender, RunWorkerCompletedEventArgs e) + { + EventHandler handler = LoadCompleted; + + if(handler != null) + { + handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); + } + } + + private void OnLoadProgressChanged(object sender, ProgressChangedEventArgs e) + { + ProgressChangedEventHandler handler = LoadProgressChanged; + + if(handler != null) + { + handler(this, e); + } + } + + private void LoadDoWork(object sender, DoWorkEventArgs e) + { + string fileName = (string)e.Argument; + + FileStream stream = new FileStream(fileName, FileMode.Open, + FileAccess.Read, FileShare.Read); + + using(stream) + { + MidiFileProperties newProperties = new MidiFileProperties(); + TrackReader reader = new TrackReader(); + List newTracks = new List(); + + newProperties.Read(stream); + + float percentage; + + for(int i = 0; i < newProperties.TrackCount && !loadWorker.CancellationPending; i++) + { + reader.Read(stream); + newTracks.Add(reader.Track); + + percentage = (i + 1f) / newProperties.TrackCount; + + loadWorker.ReportProgress((int)(100 * percentage)); + } + + if(loadWorker.CancellationPending) + { + e.Cancel = true; + } + else + { + properties = newProperties; + tracks = newTracks; + } + } + } + + private void OnSaveCompleted(object sender, RunWorkerCompletedEventArgs e) + { + EventHandler handler = SaveCompleted; + + if(handler != null) + { + handler(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, null)); + } + } + + private void OnSaveProgressChanged(object sender, ProgressChangedEventArgs e) + { + ProgressChangedEventHandler handler = SaveProgressChanged; + + if(handler != null) + { + handler(this, e); + } + } + + private void SaveDoWork(object sender, DoWorkEventArgs e) + { + string fileName = (string)e.Argument; + + FileStream stream = new FileStream(fileName, FileMode.Create, + FileAccess.Write, FileShare.None); + + using(stream) + { + properties.Write(stream); + + TrackWriter writer = new TrackWriter(); + + float percentage; + + for(int i = 0; i < tracks.Count && !saveWorker.CancellationPending; i++) + { + writer.Track = tracks[i]; + writer.Write(stream); + + percentage = (i + 1f) / properties.TrackCount; + + saveWorker.ReportProgress((int)(100 * percentage)); + } + + if(saveWorker.CancellationPending) + { + e.Cancel = true; + } + } + } + + #endregion + + #region Properties + + /// + /// Gets the Track at the specified index. + /// + /// + /// The index of the Track to get. + /// + /// + /// The Track at the specified index. + /// + public Track this[int index] + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "Sequence index out of range."); + } + + #endregion + + return tracks[index]; + } + } + + /// + /// Gets the Sequence's division value. + /// + public int Division + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return properties.Division; + } + } + + /// + /// Gets or sets the Sequence's format value. + /// + public int Format + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return properties.Format; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(IsBusy) + { + throw new InvalidOperationException(); + } + + #endregion + + properties.Format = value; + } + } + + /// + /// Gets the Sequence's type. + /// + public SequenceType SequenceType + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return properties.SequenceType; + } + } + + /// + /// If the loader is busy. + /// + public bool IsBusy + { + get + { + return loadWorker.IsBusy || saveWorker.IsBusy; + } + } + + #endregion + + #endregion + + #region ICollection Members + + /// + /// Adds an item to the sequence. + /// + public void Add(Track item) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + else if(item == null) + { + throw new ArgumentNullException("item"); + } + + #endregion + + tracks.Add(item); + + properties.TrackCount = tracks.Count; + } + + /// + /// Removes all items from the sequence. + /// + public void Clear() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + tracks.Clear(); + + properties.TrackCount = tracks.Count; + } + + /// + /// Determines whenever the sequence contains a specific value. + /// + /// + /// true, if the item is found in the sequence. Otherwise, it'll be false. + /// + public bool Contains(Track item) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return tracks.Contains(item); + } + + /// + /// Copies the elements of the sequence to an array, starting at a particular array index. + /// + public void CopyTo(Track[] array, int arrayIndex) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + tracks.CopyTo(array, arrayIndex); + } + + /// + /// Gets the number of elements contained in the sequence. + /// + /// + /// The number of elements in the sequence. + /// + public int Count + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return tracks.Count; + } + } + + /// + /// Gets a value indicating whenever the sequence is read-only. + /// + /// + /// true, if the sequence is read-only; otherwise, false. + /// + public bool IsReadOnly + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return false; + } + } + + /// + /// Removes the first occurrence of a specific object from the sequence. + /// + /// + /// true, if the item was successfully removed from the sequence; otherwise false. This method also returns false if the item is not found in the original sequence. + /// + public bool Remove(Track item) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + bool result = tracks.Remove(item); + + if(result) + { + properties.TrackCount = tracks.Count; + } + + return result; + } + + #endregion + + #region IEnumerable Members + + /// + /// Returns an enumerator that iterates through the sequence. + /// + public IEnumerator GetEnumerator() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return tracks.GetEnumerator(); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Sequence"); + } + + #endregion + + return tracks.GetEnumerator(); + } + + #endregion + + #region IComponent Members + + /// + /// Handles disposing of the sequence when the application is closed. + /// + public event EventHandler Disposed; + + /// + /// Gets or sets the site associated with the sequence. + /// + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Disposes the load when the application is closed. + /// + public void Dispose() + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + loadWorker.Dispose(); + saveWorker.Dispose(); + + disposed = true; + + EventHandler handler = Disposed; + + if(handler != null) + { + handler(this, EventArgs.Empty); + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequencer.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequencer.cs new file mode 100644 index 0000000..0073d25 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Sequencer.cs @@ -0,0 +1,446 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; + +namespace Sanford.Multimedia.Midi +{ + /// + /// This sequencer class allows for the sequencing of sequences. + /// + public class Sequencer : IComponent + { + private Sequence sequence = null; + + private List> enumerators = new List>(); + + private MessageDispatcher dispatcher = new MessageDispatcher(); + + private ChannelChaser chaser = new ChannelChaser(); + + private ChannelStopper stopper = new ChannelStopper(); + + private MidiInternalClock clock = new MidiInternalClock(); + + private int tracksPlayingCount; + + private readonly object lockObject = new object(); + + private bool playing = false; + + private bool disposed = false; + + private ISite site = null; + + #region Events + + /// + /// Handles the event when the sequencer has finished playing the sequence. + /// + public event EventHandler PlayingCompleted; + + /// + /// Handles the event when a channel message is displayed when a sequence is played. + /// + public event EventHandler ChannelMessagePlayed + { + add + { + dispatcher.ChannelMessageDispatched += value; + } + remove + { + dispatcher.ChannelMessageDispatched -= value; + } + } + + /// + /// Handles the event when a system ex message is displayed when a sequence is played. + /// + public event EventHandler SysExMessagePlayed + { + add + { + dispatcher.SysExMessageDispatched += value; + } + remove + { + dispatcher.SysExMessageDispatched -= value; + } + } + + /// + /// Handles the event when a metadata message is displayed when a sequence is played. + /// + public event EventHandler MetaMessagePlayed + { + add + { + dispatcher.MetaMessageDispatched += value; + } + remove + { + dispatcher.MetaMessageDispatched -= value; + } + } + + /// + /// Handles the chased event in the sequencer. + /// + public event EventHandler Chased + { + add + { + chaser.Chased += value; + } + remove + { + chaser.Chased -= value; + } + } + + /// + /// Handles the event when sequencer stops playing. + /// + public event EventHandler Stopped + { + add + { + stopper.Stopped += value; + } + remove + { + stopper.Stopped -= value; + } + } + + #endregion + + /// + /// The main sequencer function. + /// + public Sequencer() + { + dispatcher.MetaMessageDispatched += delegate(object sender, MetaMessageEventArgs e) + { + if(e.Message.MetaType == MetaType.EndOfTrack) + { + tracksPlayingCount--; + + if(tracksPlayingCount == 0) + { + Stop(); + + OnPlayingCompleted(EventArgs.Empty); + } + } + else + { + clock.Process(e.Message); + } + }; + + dispatcher.ChannelMessageDispatched += delegate(object sender, ChannelMessageEventArgs e) + { + stopper.Process(e.Message); + }; + + clock.Tick += delegate(object sender, EventArgs e) + { + lock(lockObject) + { + if(!playing) + { + return; + } + + foreach(IEnumerator enumerator in enumerators) + { + enumerator.MoveNext(); + } + } + }; + } + + /// + /// The function in which checks if the sequencer has been disposed. + /// + ~Sequencer() + { + Dispose(false); + } + + /// + /// The method for disposing the sequencer when the application is closed. + /// + protected virtual void Dispose(bool disposing) + { + if(disposing) + { + lock(lockObject) + { + Stop(); + + clock.Dispose(); + + disposed = true; + + GC.SuppressFinalize(this); + } + } + } + + /// + /// Starts the sequencer. + /// + public void Start() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(lockObject) + { + Stop(); + + Position = 0; + + Continue(); + } + } + + /// + /// Continues the sequencer. + /// + public void Continue() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + #region Guard + + if(Sequence == null) + { + return; + } + + #endregion + + lock(lockObject) + { + Stop(); + + enumerators.Clear(); + + foreach(Track t in Sequence) + { + enumerators.Add(t.TickIterator(Position, chaser, dispatcher).GetEnumerator()); + } + + tracksPlayingCount = Sequence.Count; + + playing = true; + clock.Ppqn = sequence.Division; + clock.Continue(); + } + } + + /// + /// Stops the sequencer. + /// + public void Stop() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(lockObject) + { + #region Guard + + if(!playing) + { + return; + } + + #endregion + + playing = false; + clock.Stop(); + stopper.AllSoundOff(); + } + } + + /// + /// Handles the event for when the sequencer is finished playing. + /// + protected virtual void OnPlayingCompleted(EventArgs e) + { + EventHandler handler = PlayingCompleted; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// Handles the event for when the sequencer is disposed. + /// + protected virtual void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// The sequencer's playing position of the sequence. + /// + public int Position + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + return clock.Ticks; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + else if(value < 0) + { + throw new ArgumentOutOfRangeException(); + } + + #endregion + + bool wasPlaying; + + lock(lockObject) + { + wasPlaying = playing; + + Stop(); + + clock.SetTicks(value); + } + + lock(lockObject) + { + if(wasPlaying) + { + Continue(); + } + } + } + } + + /// + /// The loaded sequence that represents a series of tracks. + /// + public Sequence Sequence + { + get + { + return sequence; + } + set + { + #region Require + + if(value == null) + { + throw new ArgumentNullException(); + } + else if(value.SequenceType == SequenceType.Smpte) + { + throw new NotSupportedException(); + } + + #endregion + + lock(lockObject) + { + Stop(); + sequence = value; + } + } + } + + #region IComponent Members + + /// + /// Handles the disposed event. + /// + public event EventHandler Disposed; + + /// + /// Gets the site and sets the site with a value. + /// + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region IDisposable Members + + /// + /// The dispose function for when the application is closed. + /// + public void Dispose() + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + Dispose(true); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Iterators.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Iterators.cs new file mode 100644 index 0000000..02bfbb1 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Iterators.cs @@ -0,0 +1,144 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Sanford.Multimedia.Midi +{ + public sealed partial class Track + { + #region Iterators + + /// + /// Main function for the track iterator. + /// + public IEnumerable Iterator() + { + MidiEvent current = head; + + while(current != null) + { + yield return current; + + current = current.Next; + } + + current = endOfTrackMidiEvent; + + yield return current; + } + + /// + /// Dispatches the track iterator. + /// + public IEnumerable DispatcherIterator(MessageDispatcher dispatcher) + { + IEnumerator enumerator = Iterator().GetEnumerator(); + + while(enumerator.MoveNext()) + { + yield return enumerator.Current.AbsoluteTicks; + + dispatcher.Dispatch(enumerator.Current, this); + } + } + + /// + /// A track iterator for the amount of ticks. + /// + public IEnumerable TickIterator(int startPosition, + ChannelChaser chaser, MessageDispatcher dispatcher) + { + #region Require + + if(startPosition < 0) + { + throw new ArgumentOutOfRangeException("startPosition", startPosition, + "Start position out of range."); + } + + #endregion + + IEnumerator enumerator = Iterator().GetEnumerator(); + + bool notFinished = enumerator.MoveNext(); + IMidiMessage message; + + while(notFinished && enumerator.Current.AbsoluteTicks < startPosition) + { + message = enumerator.Current.MidiMessage; + + if(message.MessageType == MessageType.Channel) + { + chaser.Process((ChannelMessage)message); + } + else if(message.MessageType == MessageType.Meta) + { + dispatcher.Dispatch(enumerator.Current, this); + } + + notFinished = enumerator.MoveNext(); + } + + chaser.Chase(); + + int ticks = startPosition; + + while(notFinished) + { + while(ticks < enumerator.Current.AbsoluteTicks) + { + yield return ticks; + + ticks++; + } + + yield return ticks; + + while(notFinished && enumerator.Current.AbsoluteTicks == ticks) + { + dispatcher.Dispatch(enumerator.Current, this); + + notFinished = enumerator.MoveNext(); + } + + ticks++; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Test.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Test.cs new file mode 100644 index 0000000..86f406e --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.Test.cs @@ -0,0 +1,131 @@ +using System; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + public sealed partial class Track + { + /// + /// Tests the tracks. + /// + [Conditional("DEBUG")] + public static void Test() + { + TestInsert(); + TestRemoveAt(); + TestMerge(); + } + + [Conditional("DEBUG")] + private static void TestInsert() + { + Track track = new Track(); + int midiEventCount = 2000; + int positionMax = 32000; + int endOfTrackOffset = 1000; + int length = 0; + int position = 0; + ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0); + Random r = new Random(); + + for(int i = 0; i < midiEventCount; i++) + { + position = r.Next(positionMax); + + if(position > length) + { + length = position; + } + + track.Insert(position, message); + } + + track.EndOfTrackOffset = endOfTrackOffset; + + length += track.EndOfTrackOffset; + + Debug.Assert(track.Count == midiEventCount + 1); + Debug.Assert(track.Length == length); + } + + [Conditional("DEBUG")] + private static void TestRemoveAt() + { + Track a = new Track(); + ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0); + + a.Insert(0, message); + a.Insert(10, message); + a.Insert(20, message); + a.Insert(30, message); + a.Insert(40, message); + + int count = a.Count; + + a.RemoveAt(0); + + Debug.Assert(a.Count == count - 1); + + a.RemoveAt(a.Count - 2); + + Debug.Assert(a.Count == count - 2); + Debug.Assert(a.GetMidiEvent(0).AbsoluteTicks == 10); + Debug.Assert(a.GetMidiEvent(a.Count - 2).AbsoluteTicks == 30); + + a.RemoveAt(0); + a.RemoveAt(0); + a.RemoveAt(0); + + Debug.Assert(a.Count == 1); + } + + [Conditional("DEBUG")] + private static void TestMerge() + { + Track a = new Track(); + Track b = new Track(); + + a.Merge(b); + + Debug.Assert(a.Count == 1); + + ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, 60, 0); + + b.Insert(0, message); + b.Insert(10, message); + b.Insert(20, message); + b.Insert(30, message); + b.Insert(40, message); + + a.Merge(b); + + Debug.Assert(a.Count == 1 + b.Count - 1); + + a.Clear(); + + Debug.Assert(a.Count == 1); + + a.Insert(0, message); + a.Insert(10, message); + a.Insert(20, message); + a.Insert(30, message); + a.Insert(40, message); + + int count = a.Count; + + a.Merge(b); + + Debug.Assert(a.Count == count + b.Count - 1); + Debug.Assert(a.GetMidiEvent(0).DeltaTicks == 0); + Debug.Assert(a.GetMidiEvent(1).DeltaTicks == 0); + Debug.Assert(a.GetMidiEvent(2).DeltaTicks == 10); + Debug.Assert(a.GetMidiEvent(3).DeltaTicks == 0); + Debug.Assert(a.GetMidiEvent(4).DeltaTicks == 10); + Debug.Assert(a.GetMidiEvent(5).DeltaTicks == 0); + Debug.Assert(a.GetMidiEvent(6).DeltaTicks == 10); + Debug.Assert(a.GetMidiEvent(7).DeltaTicks == 0); + Debug.Assert(a.GetMidiEvent(8).DeltaTicks == 10); + Debug.Assert(a.GetMidiEvent(9).DeltaTicks == 0); + } + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.cs new file mode 100644 index 0000000..9b94499 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/Track.cs @@ -0,0 +1,613 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Diagnostics; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Represents a collection of MidiEvents and a MIDI track within a + /// Sequence. + /// + public sealed partial class Track + { + #region Track Members + + #region Fields + + // The number of MidiEvents in the Track. Will always be at least 1 + // because the Track will always have an end of track message. + private int count = 1; + + // The number of ticks to offset the end of track message. + private int endOfTrackOffset = 0; + + // The first MidiEvent in the Track. + private MidiEvent head = null; + + // The last MidiEvent in the Track, not including the end of track + // message. + private MidiEvent tail = null; + + // The end of track MIDI event. + private MidiEvent endOfTrackMidiEvent; + + #endregion + + #region Construction + + /// + /// Main function that represents the end of track MIDI event. + /// + public Track() + { + endOfTrackMidiEvent = new MidiEvent(this, Length, MetaMessage.EndOfTrackMessage); + } + + #endregion + + #region Methods + + /// + /// Inserts an IMidiMessage at the specified position in absolute ticks. + /// + /// + /// The position in the Track in absolute ticks in which to insert the + /// IMidiMessage. + /// + /// + /// The IMidiMessage to insert. + /// + public void Insert(int position, IMidiMessage message) + { + #region Require + + if(position < 0) + { + throw new ArgumentOutOfRangeException("position", position, + "IMidiMessage position out of range."); + } + else if(message == null) + { + throw new ArgumentNullException("message"); + } + + #endregion + + MidiEvent newMidiEvent = new MidiEvent(this, position, message); + + if(head == null) + { + head = newMidiEvent; + tail = newMidiEvent; + } + else if (position < head.AbsoluteTicks) + { + newMidiEvent.Next = head; + head.Previous = newMidiEvent; + head = newMidiEvent; + } + else if (position >= tail.AbsoluteTicks) + { + newMidiEvent.Previous = tail; + tail.Next = newMidiEvent; + tail = newMidiEvent; + endOfTrackMidiEvent.SetAbsoluteTicks(Length); + endOfTrackMidiEvent.Previous = tail; + } + else + { + MidiEvent current = head; + + while (!(current.AbsoluteTicks > position)) + current = current.Next; + + newMidiEvent.Next = current; + newMidiEvent.Previous = current.Previous; + current.Previous.Next = newMidiEvent; + current.Previous = newMidiEvent; + } + + count++; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Clears all of the MidiEvents, with the exception of the end of track + /// message, from the Track. + /// + public void Clear() + { + head = tail = null; + + count = 1; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Merges the specified Track with the current Track. + /// + /// + /// The Track to merge with. + /// + public void Merge(Track trk) + { + #region Require + + if(trk == null) + { + throw new ArgumentNullException("trk"); + } + + #endregion + + #region Guard + + if(trk == this) + { + return; + } + else if(trk.Count == 1) + { + return; + } + + #endregion + +#if(DEBUG) + int oldCount = Count; +#endif + + count += trk.Count - 1; + + MidiEvent a = head; + MidiEvent b = trk.head; + MidiEvent current = null; + + Debug.Assert(b != null); + + if(a != null && a.AbsoluteTicks <= b.AbsoluteTicks) + { + current = new MidiEvent(this, a.AbsoluteTicks, a.MidiMessage); + a = a.Next; + } + else + { + current = new MidiEvent(this, b.AbsoluteTicks, b.MidiMessage); + b = b.Next; + } + + head = current; + + while(a != null && b != null) + { + while(a != null && a.AbsoluteTicks <= b.AbsoluteTicks) + { + current.Next = new MidiEvent(this, a.AbsoluteTicks, a.MidiMessage); + current.Next.Previous = current; + current = current.Next; + a = a.Next; + } + + if(a != null) + { + while(b != null && b.AbsoluteTicks <= a.AbsoluteTicks) + { + current.Next = new MidiEvent(this, b.AbsoluteTicks, b.MidiMessage); + current.Next.Previous = current; + current = current.Next; + b = b.Next; + } + } + } + + while(a != null) + { + current.Next = new MidiEvent(this, a.AbsoluteTicks, a.MidiMessage); + current.Next.Previous = current; + current = current.Next; + a = a.Next; + } + + while(b != null) + { + current.Next = new MidiEvent(this, b.AbsoluteTicks, b.MidiMessage); + current.Next.Previous = current; + current = current.Next; + b = b.Next; + } + + tail = current; + + endOfTrackMidiEvent.SetAbsoluteTicks(Length); + endOfTrackMidiEvent.Previous = tail; + + #region Ensure +#if(DEBUG) + Debug.Assert(count == oldCount + trk.Count - 1); +#endif + #endregion + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Removes the MidiEvent at the specified index. + /// + /// + /// The index into the Track at which to remove the MidiEvent. + /// + public void RemoveAt(int index) + { + #region Require + + if(index < 0) + { + throw new ArgumentOutOfRangeException("index", index, "Track index out of range."); + } + else if(index == Count - 1) + { + throw new ArgumentException("Cannot remove the end of track event.", "index"); + } + + #endregion + + MidiEvent current = GetMidiEvent(index); + + if(current.Previous != null) + { + current.Previous.Next = current.Next; + } + else + { + Debug.Assert(current == head); + + head = head.Next; + } + + if(current.Next != null) + { + current.Next.Previous = current.Previous; + } + else + { + Debug.Assert(current == tail); + + tail = tail.Previous; + + endOfTrackMidiEvent.SetAbsoluteTicks(Length); + endOfTrackMidiEvent.Previous = tail; + } + + current.Next = current.Previous = null; + + count--; + + #region Invariant + + AssertValid(); + + #endregion + } + + /// + /// Gets the MidiEvent at the specified index. + /// + /// + /// The index of the MidiEvent to get. + /// + /// + /// The MidiEvent at the specified index. + /// + public MidiEvent GetMidiEvent(int index) + { + #region Require + + if(index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException("index", index, + "Track index out of range."); + } + + #endregion + + MidiEvent result; + + if(index == Count - 1) + { + result = endOfTrackMidiEvent; + } + else + { + if(index < Count / 2) + { + result = head; + + for(int i = 0; i < index; i++) + { + result = result.Next; + } + } + else + { + result = tail; + + for(int i = Count - 2; i > index; i--) + { + result = result.Previous; + } + } + } + + #region Ensure + +#if(DEBUG) + if(index == Count - 1) + { + Debug.Assert(result.AbsoluteTicks == Length); + Debug.Assert(result.MidiMessage == MetaMessage.EndOfTrackMessage); + } + else + { + MidiEvent t = head; + + for(int i = 0; i < index; i++) + { + t = t.Next; + } + + Debug.Assert(t == result); + } +#endif + + #endregion + + return result; + } + + /// + /// A MIDI event that moves the track. + /// + public void Move(MidiEvent e, int newPosition) + { + #region Require + + if(e.Owner != this) + { + throw new ArgumentException("MidiEvent does not belong to this Track."); + } + else if(newPosition < 0) + { + throw new ArgumentOutOfRangeException("newPosition"); + } + else if(e == endOfTrackMidiEvent) + { + throw new InvalidOperationException( + "Cannot move end of track message. Use the EndOfTrackOffset property instead."); + } + + #endregion + + MidiEvent previous = e.Previous; + MidiEvent next = e.Next; + + if(e.Previous != null && e.Previous.AbsoluteTicks > newPosition) + { + e.Previous.Next = e.Next; + + if(e.Next != null) + { + e.Next.Previous = e.Previous; + } + + while(previous != null && previous.AbsoluteTicks > newPosition) + { + next = previous; + previous = previous.Previous; + } + } + else if(e.Next != null && e.Next.AbsoluteTicks < newPosition) + { + e.Next.Previous = e.Previous; + + if(e.Previous != null) + { + e.Previous.Next = e.Next; + } + + while(next != null && next.AbsoluteTicks < newPosition) + { + previous = next; + next = next.Next; + } + } + + if(previous != null) + { + previous.Next = e; + } + + if(next != null) + { + next.Previous = e; + } + + e.Previous = previous; + e.Next = next; + e.SetAbsoluteTicks(newPosition); + + if(newPosition < head.AbsoluteTicks) + { + head = e; + } + + if(newPosition > tail.AbsoluteTicks) + { + tail = e; + } + + endOfTrackMidiEvent.SetAbsoluteTicks(Length); + endOfTrackMidiEvent.Previous = tail; + + #region Invariant + + AssertValid(); + + #endregion + } + + [Conditional("DEBUG")] + private void AssertValid() + { + int c = 1; + MidiEvent current = head; + int ticks = 1; + + while(current != null) + { + ticks += current.DeltaTicks; + + if(current.Previous != null) + { + Debug.Assert(current.AbsoluteTicks >= current.Previous.AbsoluteTicks); + Debug.Assert(current.DeltaTicks == current.AbsoluteTicks - current.Previous.AbsoluteTicks); + } + + if(current.Next == null) + { + Debug.Assert(tail == current); + } + + current = current.Next; + + c++; + } + + ticks += EndOfTrackOffset; + + Debug.Assert(ticks == Length, "Length mismatch"); + Debug.Assert(c == Count, "Count mismatch"); + } + + #endregion + + #region Properties + + /// + /// Gets the number of MidiEvents in the Track. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets the length of the Track in ticks. + /// + public int Length + { + get + { + int length = EndOfTrackOffset; + + if (tail != null) + { + length += tail.AbsoluteTicks; + } + + return length; + } + } + + /// + /// Gets or sets the end of track meta message position offset. + /// + public int EndOfTrackOffset + { + get + { + return endOfTrackOffset; + } + set + { + #region Require + + if(value < 0) + { + throw new ArgumentOutOfRangeException("EndOfTrackOffset", value, + "End of track offset out of range."); + } + + #endregion + + endOfTrackOffset = value; + + endOfTrackMidiEvent.SetAbsoluteTicks(Length); + } + } + + /// + /// Gets an object that can be used to synchronize access to the Track. + /// + public object SyncRoot + { + get + { + return this; + } + } + + #endregion + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackReader.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackReader.cs new file mode 100644 index 0000000..863b963 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackReader.cs @@ -0,0 +1,448 @@ +#region License + +/* Copyright (c) 2005 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.IO; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Reads a track from a stream. + /// + internal class TrackReader + { + private Track track = new Track(); + + private Track newTrack = new Track(); + + private ChannelMessageBuilder cmBuilder = new ChannelMessageBuilder(); + + private SysCommonMessageBuilder scBuilder = new SysCommonMessageBuilder(); + + private Stream stream; + + private byte[] trackData; + + private int trackIndex; + + private int previousTicks; + + private int ticks; + + private int status; + + private int runningStatus; + + public TrackReader() + { + } + + public void Read(Stream strm) + { + stream = strm; + FindTrack(); + + int trackLength = GetTrackLength(); + trackData = new byte[trackLength]; + + int result = strm.Read(trackData, 0, trackLength); + + if(result < 0) + { + throw new MidiFileException("End of MIDI file unexpectedly reached."); + } + + newTrack = new Track(); + + ParseTrackData(); + + track = newTrack; + } + + private void FindTrack() + { + bool found = false; + int result; + + while(!found) + { + result = stream.ReadByte(); + + if(result == 'M') + { + result = stream.ReadByte(); + + if(result == 'T') + { + result = stream.ReadByte(); + + if(result == 'r') + { + result = stream.ReadByte(); + + if(result == 'k') + { + found = true; + } + } + } + } + + if(result < 0) + { + throw new MidiFileException("Unable to find track in MIDI file."); + } + } + } + + private int GetTrackLength() + { + byte[] trackLength = new byte[4]; + + int result = stream.Read(trackLength, 0, trackLength.Length); + + if(result < trackLength.Length) + { + throw new MidiFileException("End of MIDI file unexpectedly reached."); + } + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(trackLength); + } + + return BitConverter.ToInt32(trackLength, 0); + } + + private void ParseTrackData() + { + trackIndex = ticks = runningStatus = 0; + + while(trackIndex < trackData.Length) + { + previousTicks = ticks; + + ticks += ReadVariableLengthValue(); + + if((trackData[trackIndex] & 0x80) == 0x80) + { + status = trackData[trackIndex]; + trackIndex++; + } + else + { + status = runningStatus; + } + + ParseMessage(); + } + } + + private void ParseMessage() + { + // If this is a channel message. + if(status >= (int)ChannelCommand.NoteOff && + status <= (int)ChannelCommand.PitchWheel + + ChannelMessage.MidiChannelMaxValue) + { + ParseChannelMessage(); + } + // Else if this is a meta message. + else if(status == 0xFF) + { + ParseMetaMessage(); + } + // Else if this is the start of a system exclusive message. + else if(status == (int)SysExType.Start) + { + ParseSysExMessageStart(); + } + // Else if this is a continuation of a system exclusive message. + else if(status == (int)SysExType.Continuation) + { + ParseSysExMessageContinue(); + } + // Else if this is a system common message. + else if(status >= (int)SysCommonType.MidiTimeCode && + status <= (int)SysCommonType.TuneRequest) + { + ParseSysCommonMessage(); + } + // Else if this is a system realtime message. + else if(status >= (int)SysRealtimeType.Clock && + status <= (int)SysRealtimeType.Reset) + { + ParseSysRealtimeMessage(); + } + } + + private void ParseChannelMessage() + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + cmBuilder.Command = ChannelMessage.UnpackCommand(status); + cmBuilder.MidiChannel = ChannelMessage.UnpackMidiChannel(status); + cmBuilder.Data1 = trackData[trackIndex]; + + trackIndex++; + + if(ChannelMessage.DataBytesPerType(cmBuilder.Command) == 2) + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + cmBuilder.Data2 = trackData[trackIndex]; + + trackIndex++; + } + + cmBuilder.Build(); + newTrack.Insert(ticks, cmBuilder.Result); + runningStatus = status; + } + + private void ParseMetaMessage() + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + MetaType type = (MetaType)trackData[trackIndex]; + + trackIndex++; + + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + if(type == MetaType.EndOfTrack) + { + newTrack.EndOfTrackOffset = ticks - previousTicks; + + trackIndex++; + } + else + { + byte[] data = new byte[ReadVariableLengthValue()]; + Array.Copy(trackData, trackIndex, data, 0, data.Length); + newTrack.Insert(ticks, new MetaMessage(type, data)); + + trackIndex += data.Length; + } + } + + private void ParseSysExMessageStart() + { + // System exclusive cancels running status. + runningStatus = 0; + + byte[] data = new byte[ReadVariableLengthValue() + 1]; + data[0] = (byte)SysExType.Start; + + Array.Copy(trackData, trackIndex, data, 1, data.Length - 1); + newTrack.Insert(ticks, new SysExMessage(data)); + + trackIndex += data.Length - 1; + } + + private void ParseSysExMessageContinue() + { + trackIndex++; + + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + // System exclusive cancels running status. + runningStatus = 0; + + // If this is an escaped message rather than a system exclusive + // continuation message. + if((trackData[trackIndex] & 0x80) == 0x80) + { + status = trackData[trackIndex]; + trackIndex++; + + ParseMessage(); + } + else + { + byte[] data = new byte[ReadVariableLengthValue() + 1]; + data[0] = (byte)SysExType.Continuation; + + Array.Copy(trackData, trackIndex, data, 1, data.Length - 1); + newTrack.Insert(ticks, new SysExMessage(data)); + + trackIndex += data.Length - 1; + } + } + + private void ParseSysCommonMessage() + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + // System common cancels running status. + runningStatus = 0; + + scBuilder.Type = (SysCommonType)status; + + switch((SysCommonType)status) + { + case SysCommonType.MidiTimeCode: + scBuilder.Data1 = trackData[trackIndex]; + trackIndex++; + break; + + case SysCommonType.SongPositionPointer: + scBuilder.Data1 = trackData[trackIndex]; + trackIndex++; + + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + scBuilder.Data2 = trackData[trackIndex]; + trackIndex++; + break; + + case SysCommonType.SongSelect: + scBuilder.Data1 = trackData[trackIndex]; + trackIndex++; + break; + + case SysCommonType.TuneRequest: + // Nothing to do here. + break; + } + + scBuilder.Build(); + + newTrack.Insert(ticks, scBuilder.Result); + } + + private void ParseSysRealtimeMessage() + { + SysRealtimeMessage e = null; + + switch((SysRealtimeType)status) + { + case SysRealtimeType.ActiveSense: + e = SysRealtimeMessage.ActiveSenseMessage; + break; + + case SysRealtimeType.Clock: + e = SysRealtimeMessage.ClockMessage; + break; + + case SysRealtimeType.Continue: + e = SysRealtimeMessage.ContinueMessage; + break; + + case SysRealtimeType.Reset: + e = SysRealtimeMessage.ResetMessage; + break; + + case SysRealtimeType.Start: + e = SysRealtimeMessage.StartMessage; + break; + + case SysRealtimeType.Stop: + e = SysRealtimeMessage.StopMessage; + break; + + case SysRealtimeType.Tick: + e = SysRealtimeMessage.TickMessage; + break; + } + + newTrack.Insert(ticks, e); + } + + private int ReadVariableLengthValue() + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + int result = 0; + + result = trackData[trackIndex]; + + trackIndex++; + + if((result & 0x80) == 0x80) + { + result &= 0x7F; + + int temp; + + do + { + if(trackIndex >= trackData.Length) + { + throw new MidiFileException("End of track unexpectedly reached."); + } + + temp = trackData[trackIndex]; + trackIndex++; + result <<= 7; + result |= temp & 0x7F; + }while((temp & 0x80) == 0x80); + } + + return result; + } + + public Track Track + { + get + { + return track; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackWriter.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackWriter.cs new file mode 100644 index 0000000..470a90b --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Midi/Sequencing/Track Classes/TrackWriter.cs @@ -0,0 +1,256 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Sanford.Multimedia.Midi +{ + /// + /// Writes a Track to a Stream. + /// + internal class TrackWriter + { + private static readonly byte[] TrackHeader = + { + (byte)'M', + (byte)'T', + (byte)'r', + (byte)'k' + }; + + // The Track to write to the Stream. + private Track track = new Track(); + + // The Stream to write to. + private Stream stream; + + // Running status. + private int runningStatus = 0; + + // The Track data in raw bytes. + private List trackData = new List(); + + public void Write(Stream strm) + { + this.stream = strm; + + trackData.Clear(); + + stream.Write(TrackHeader, 0, TrackHeader.Length); + + foreach(MidiEvent e in track.Iterator()) + { + WriteVariableLengthValue(e.DeltaTicks); + + switch(e.MidiMessage.MessageType) + { + case MessageType.Channel: + Write((ChannelMessage)e.MidiMessage); + break; + + case MessageType.SystemExclusive: + Write((SysExMessage)e.MidiMessage); + break; + + case MessageType.Meta: + Write((MetaMessage)e.MidiMessage); + break; + + case MessageType.SystemCommon: + Write((SysCommonMessage)e.MidiMessage); + break; + + case MessageType.SystemRealtime: + Write((SysRealtimeMessage)e.MidiMessage); + break; + + case MessageType.Short: + Write((ShortMessage)e.MidiMessage); + break; + } + } + + byte[] trackLength = BitConverter.GetBytes(trackData.Count); + + if(BitConverter.IsLittleEndian) + { + Array.Reverse(trackLength); + } + + stream.Write(trackLength, 0, trackLength.Length); + + foreach(byte b in trackData) + { + stream.WriteByte(b); + } + } + + private void WriteVariableLengthValue(int value) + { + int v = value; + byte[] array = new byte[4]; + int count = 0; + + array[0] = (byte)(v & 0x7F); + + v >>= 7; + + while(v > 0) + { + count++; + array[count] = (byte)((v & 0x7F) | 0x80); + v >>= 7; + } + + while(count >= 0) + { + trackData.Add(array[count]); + count--; + } + } + + private void Write(ShortMessage message) + { + trackData.AddRange(message.GetBytes()); + } + + private void Write(ChannelMessage message) + { + if(runningStatus != message.Status) + { + trackData.Add((byte)message.Status); + runningStatus = message.Status; + } + + trackData.Add((byte)message.Data1); + + if(ChannelMessage.DataBytesPerType(message.Command) == 2) + { + trackData.Add((byte)message.Data2); + } + } + + private void Write(SysExMessage message) + { + // System exclusive message cancel running status. + runningStatus = 0; + + trackData.Add((byte)message.Status); + + WriteVariableLengthValue(message.Length - 1); + + for(int i = 1; i < message.Length; i++) + { + trackData.Add(message[i]); + } + } + + private void Write(MetaMessage message) + { + trackData.Add((byte)message.Status); + trackData.Add((byte)message.MetaType); + + WriteVariableLengthValue(message.Length); + + trackData.AddRange(message.GetBytes()); + } + + private void Write(SysCommonMessage message) + { + // Escaped messages cancel running status. + runningStatus = 0; + + // Escaped message. + trackData.Add((byte)0xF7); + + trackData.Add((byte)message.Status); + + switch(message.SysCommonType) + { + case SysCommonType.MidiTimeCode: + trackData.Add((byte)message.Data1); + break; + + case SysCommonType.SongPositionPointer: + trackData.Add((byte)message.Data1); + trackData.Add((byte)message.Data2); + break; + + case SysCommonType.SongSelect: + trackData.Add((byte)message.Data1); + break; + } + } + + private void Write(SysRealtimeMessage message) + { + // Escaped messages cancel running status. + runningStatus = 0; + + // Escaped message. + trackData.Add((byte)0xF7); + + trackData.Add((byte)message.Status); + } + + /// + /// Gets or sets the Track to write to the Stream. + /// + public Track Track + { + get + { + return track; + } + set + { + #region Require + + if(value == null) + { + throw new ArgumentNullException("Track"); + } + + #endregion + + runningStatus = 0; + trackData.Clear(); + + track = value; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ITimer.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ITimer.cs new file mode 100644 index 0000000..6804f33 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ITimer.cs @@ -0,0 +1,98 @@ +#region License + +/* Copyright (c) 2015 Andreas Grimme + * + * 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 System; +using System.ComponentModel; + +namespace Sanford.Multimedia.Timers +{ + /// + /// This provides the functionality for the timer. + /// + public interface ITimer : IComponent + { + /// + /// Gets a value indicating whether the Timer is running. + /// + bool IsRunning { get; } + + /// + /// Gets the timer mode. + /// + /// + /// If the timer has already been disposed. + /// + TimerMode Mode { get; set; } + + /// + /// Period between timer events in milliseconds. + /// + int Period { get; set; } + + /// + /// Resolution of the timer in milliseconds. + /// + int Resolution { get; set; } + + /// + /// Gets or sets the object used to marshal event-handler calls. + /// + ISynchronizeInvoke SynchronizingObject { get; set; } + + /// + /// Occurs when the Timer has started; + /// + event EventHandler Started; + + /// + /// Occurs when the Timer has stopped; + /// + event EventHandler Stopped; + + /// + /// Occurs when the time period has elapsed. + /// + event EventHandler Tick; + + /// + /// Starts the timer. + /// + /// + /// The timer has already been disposed. + /// + /// + /// The timer failed to start. + /// + void Start(); + + /// + /// Stops timer. + /// + /// + /// If the timer has already been disposed. + /// + void Stop(); + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimer.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimer.cs new file mode 100644 index 0000000..8545682 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimer.cs @@ -0,0 +1,387 @@ +#region License + +/* Copyright (c) 2015 Andreas Grimme + * + * 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 System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Text; +using System.Threading; + +namespace Sanford.Multimedia.Timers +{ + /// + /// Replacement for the Windows multimedia timer that also runs on Mono + /// + sealed class ThreadTimer : ITimer + { + ThreadTimerQueue queue; + + bool isRunning; + TimerMode mode; + TimeSpan period; + TimeSpan resolution; + + static object[] emptyArgs = new object[] { EventArgs.Empty }; + + public ThreadTimer() + : this(ThreadTimerQueue.Instance) + { + if (!Stopwatch.IsHighResolution) + { + throw new NotImplementedException("Stopwatch is not IsHighResolution"); + } + + isRunning = false; + mode = TimerMode.Periodic; + resolution = TimeSpan.FromMilliseconds(1); + period = resolution; + + tickRaiser = new EventRaiser(OnTick); + } + + ThreadTimer(ThreadTimerQueue queue) + { + this.queue = queue; + } + + internal void DoTick() + { + if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) + { + SynchronizingObject.BeginInvoke(tickRaiser, emptyArgs); + } + else + { + OnTick(EventArgs.Empty); + } + } + + // Represents methods that raise events. + private delegate void EventRaiser(EventArgs e); + + // Represents the method that raises the Tick event. + private EventRaiser tickRaiser; + + // The ISynchronizeInvoke object to use for marshaling events. + private ISynchronizeInvoke synchronizingObject = null; + + public bool IsRunning + { + get + { + return isRunning; + } + } + + public TimerMode Mode + { + get + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return mode; + } + + set + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + mode = value; + + if (IsRunning) + { + Stop(); + Start(); + } + } + } + + public int Period + { + get + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return (int) period.TotalMilliseconds; + } + set + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + var wasRunning = IsRunning; + + if (wasRunning) + { + Stop(); + } + + period = TimeSpan.FromMilliseconds(value); + + if (wasRunning) + { + Start(); + } + } + } + + public TimeSpan PeriodTimeSpan + { + get { return period; } + } + + public int Resolution + { + get + { + return (int) resolution.TotalMilliseconds; + } + + set + { + resolution = TimeSpan.FromMilliseconds(value); + } + } + + // For implementing IComponent. + private ISite site = null; + + public ISite Site + { + get + { + return site; + } + + set + { + site = value; + } + } + + /// + /// Gets or sets the object used to marshal event-handler calls. + /// + public ISynchronizeInvoke SynchronizingObject + { + get + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return synchronizingObject; + } + set + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + synchronizingObject = value; + } + } + + public event EventHandler Disposed; + public event EventHandler Started; + public event EventHandler Stopped; + public event EventHandler Tick; + + public void Dispose() + { + Stop(); + disposed = true; + OnDisposed(EventArgs.Empty); + } + + #region Event Raiser Methods + + // Raises the Disposed event. + private void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if (handler != null) + { + handler(this, e); + } + } + + // Raises the Started event. + private void OnStarted(EventArgs e) + { + EventHandler handler = Started; + + if (handler != null) + { + handler(this, e); + } + } + + // Raises the Stopped event. + private void OnStopped(EventArgs e) + { + EventHandler handler = Stopped; + + if (handler != null) + { + handler(this, e); + } + } + + // Raises the Tick event. + private void OnTick(EventArgs e) + { + EventHandler handler = Tick; + + if (handler != null) + { + handler(this, e); + } + } + + #endregion + + bool disposed = false; + + public void Start() + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + #region Guard + + if (IsRunning) + { + return; + } + + #endregion + + // If the periodic event callback should be used. + if (Mode == TimerMode.Periodic) + { + queue.Add(this); + isRunning = true; + } + // Else the one shot event callback should be used. + else + { + throw new NotImplementedException(); + } + + if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) + { + SynchronizingObject.BeginInvoke( + new EventRaiser(OnStarted), + new object[] { EventArgs.Empty }); + } + else + { + OnStarted(EventArgs.Empty); + } + } + + public void Stop() + { + #region Require + + if (disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + #region Guard + + if (!IsRunning) + { + return; + } + + #endregion + + queue.Remove(this); + isRunning = false; + + if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) + { + SynchronizingObject.BeginInvoke( + new EventRaiser(OnStopped), + new object[] { EventArgs.Empty }); + } + else + { + OnStopped(EventArgs.Empty); + } + } + + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimerQueue.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimerQueue.cs new file mode 100644 index 0000000..0956a6f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/ThreadTimerQueue.cs @@ -0,0 +1,175 @@ +#region License + +/* Copyright (c) 2015 Andreas Grimme + * + * 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 System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; + +namespace Sanford.Multimedia.Timers +{ + /// + /// Queues and executes timer events in an internal worker thread. + /// + class ThreadTimerQueue + { + Stopwatch watch = Stopwatch.StartNew(); + Thread loop; + List tickQueue = new List(); + + public static ThreadTimerQueue Instance + { + get + { + if (instance == null) + { + instance = new ThreadTimerQueue(); + } + return instance; + + } + } + static ThreadTimerQueue instance; + + private ThreadTimerQueue() + { + } + + public void Add(ThreadTimer timer) + { + lock (this) + { + var tick = new Tick + { + Timer = timer, + Time = watch.Elapsed + }; + tickQueue.Add(tick); + tickQueue.Sort(); + + if (loop == null) + { + loop = new Thread(TimerLoop); + loop.Start(); + } + Monitor.PulseAll(this); + } + } + + public void Remove(ThreadTimer timer) + { + lock (this) + { + int i = 0; + for (; i < tickQueue.Count; ++i) + { + if (tickQueue[i].Timer == timer) + { + break; + } + } + if (i < tickQueue.Count) + { + tickQueue.RemoveAt(i); + } + Monitor.PulseAll(this); + } + } + + class Tick : IComparable + { + public ThreadTimer Timer; + public TimeSpan Time; + + public int CompareTo(object obj) + { + var r = obj as Tick; + if (r == null) + { + return -1; + } + return Time.CompareTo(r.Time); + } + } + + static TimeSpan Min(TimeSpan x0, TimeSpan x1) + { + if (x0 > x1) + { + return x1; + } + else + { + return x0; + } + } + + /// + /// The thread to execute the timer events + /// + private void TimerLoop() + { + lock (this) + { + TimeSpan maxTimeout = TimeSpan.FromMilliseconds(500); + + for (int queueEmptyCount = 0; queueEmptyCount < 3; ++queueEmptyCount) + { + var waitTime = maxTimeout; + if (tickQueue.Count > 0) + { + waitTime = Min(tickQueue[0].Time - watch.Elapsed, waitTime); + queueEmptyCount = 0; + } + + if (waitTime > TimeSpan.Zero) + { + Monitor.Wait(this, waitTime); + } + + if (tickQueue.Count > 0) + { + var tick = tickQueue[0]; + var mode = tick.Timer.Mode; + Monitor.Exit(this); + tick.Timer.DoTick(); + Monitor.Enter(this); + if (mode == TimerMode.Periodic) + { + tick.Time += tick.Timer.PeriodTimeSpan; + tickQueue.Sort(); + } + else + { + tickQueue.RemoveAt(0); + } + } + } + loop = null; + } + } + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Time.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Time.cs new file mode 100644 index 0000000..f802bf7 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Time.cs @@ -0,0 +1,169 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Timers +{ + /// + /// Defines constants representing the timing format used by the Time struct. + /// + public enum TimeType + { + /// + /// Defined in milliseconds. + /// + Milliseconds = 0x0001, + /// + /// Defined in samples. + /// + Samples = 0x0002, + /// + /// Defined in bytes. + /// + Bytes = 0x0004, + /// + /// Defined in SMPTE. + /// + Smpte = 0x0008, + /// + /// Defined in MIDI. + /// + Midi = 0x0010, + /// + /// Defined in ticks. + /// + Ticks = 0x0020 + } + + /// + /// Represents the Windows Multimedia MMTIME structure. + /// + [StructLayout(LayoutKind.Explicit)] + public struct Time + { + /// + /// Type. + /// + [FieldOffset(0)] + public int type; + + /// + /// Milliseconds. + /// + [FieldOffset(4)] + public int milliseconds; + + /// + /// Samples. + /// + [FieldOffset(4)] + public int samples; + + /// + /// Byte count. + /// + [FieldOffset(4)] + public int byteCount; + + /// + /// Ticks. + /// + [FieldOffset(4)] + public int ticks; + + // + // SMPTE + // + + /// + /// SMPTE hours. + /// + [FieldOffset(4)] + public byte hours; + + /// + /// SMPTE minutes. + /// + [FieldOffset(5)] + public byte minutes; + + /// + /// SMPTE seconds. + /// + [FieldOffset(6)] + public byte seconds; + + /// + /// SMPTE frames. + /// + [FieldOffset(7)] + public byte frames; + + /// + /// SMPTE frames per second. + /// + [FieldOffset(8)] + public byte framesPerSecond; + + /// + /// SMPTE dummy. + /// + [FieldOffset(9)] + public byte dummy; + + /// + /// SMPTE pad 1. + /// + [FieldOffset(10)] + public byte pad1; + + /// + /// SMPTE pad 2. + /// + [FieldOffset(11)] + public byte pad2; + + // + // MIDI + // + + /// + /// MIDI song position pointer. + /// + [FieldOffset(4)] + public int songPositionPointer; + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Timer.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Timer.cs new file mode 100644 index 0000000..c09c4f9 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/Timer.cs @@ -0,0 +1,720 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace Sanford.Multimedia.Timers +{ + /// + /// Defines constants for the multimedia Timer's event types. + /// + public enum TimerMode + { + /// + /// Timer event occurs once. + /// + OneShot, + + /// + /// Timer event occurs periodically. + /// + Periodic + }; + + /// + /// Represents information about the multimedia Timer's capabilities. + /// + [StructLayout(LayoutKind.Sequential)] + public struct TimerCaps + { + /// + /// Minimum supported period in milliseconds. + /// + public int periodMin; + + /// + /// Maximum supported period in milliseconds. + /// + public int periodMax; + + /// + /// The default timer capabilities. + /// + public static TimerCaps Default + { + get + { + return new TimerCaps { periodMin = 1, periodMax = Int32.MaxValue }; + } + } + } + + /// + /// Represents the Windows multimedia timer. + /// + sealed class Timer : ITimer + { + #region Timer Members + + #region Delegates + + // Represents the method that is called by Windows when a timer event occurs. + private delegate void TimeProc(int id, int msg, int user, int param1, int param2); + + // Represents methods that raise events. + private delegate void EventRaiser(EventArgs e); + + #endregion + + #region Win32 Multimedia Timer Functions + + // Gets timer capabilities. + [DllImport("winmm.dll")] + private static extern int timeGetDevCaps(ref TimerCaps caps, + int sizeOfTimerCaps); + + // Creates and starts the timer. + [DllImport("winmm.dll")] + private static extern int timeSetEvent(int delay, int resolution, TimeProc proc, IntPtr user, int mode); + + // Stops and destroys the timer. + [DllImport("winmm.dll")] + private static extern int timeKillEvent(int id); + + // Indicates that the operation was successful. + private const int TIMERR_NOERROR = 0; + + #endregion + + #region Fields + + // Timer identifier. + private int timerID; + + // Timer mode. + private volatile TimerMode mode; + + // Period between timer events in milliseconds. + private volatile int period; + + // Timer resolution in milliseconds. + private volatile int resolution; + + // Called by Windows when a timer periodic event occurs. + private TimeProc timeProcPeriodic; + + // Called by Windows when a timer one shot event occurs. + private TimeProc timeProcOneShot; + + // Represents the method that raises the Tick event. + private EventRaiser tickRaiser; + + // The ISynchronizeInvoke object to use for marshaling events. + private ISynchronizeInvoke synchronizingObject = null; + + // Indicates whether or not the timer is running. + private bool running = false; + + // Indicates whether or not the timer has been disposed. + private volatile bool disposed = false; + + // For implementing IComponent. + private ISite site = null; + + // Multimedia timer capabilities. + private static TimerCaps caps; + + #endregion + + #region Events + + /// + /// Occurs when the Timer has started; + /// + public event EventHandler Started; + + /// + /// Occurs when the Timer has stopped; + /// + public event EventHandler Stopped; + + /// + /// Occurs when the time period has elapsed. + /// + public event EventHandler Tick; + + #endregion + + #region Construction + + /// + /// Initialize class. + /// + static Timer() + { + // Get multimedia timer capabilities. + timeGetDevCaps(ref caps, Marshal.SizeOf(caps)); + } + + /// + /// Initializes a new instance of the Timer class with the specified IContainer. + /// + /// + /// The IContainer to which the Timer will add itself. + /// + public Timer(IContainer container) + { + // Required for Windows.Forms Class Composition Designer support + container.Add(this); + + Initialize(); + } + + /// + /// Initializes a new instance of the Timer class. + /// + public Timer() + { + Initialize(); + } + + ~Timer() + { + if(IsRunning) + { + // Stop and destroy timer. + timeKillEvent(timerID); + } + } + + // Initialize timer with default values. + private void Initialize() + { + this.mode = TimerMode.Periodic; + this.period = Capabilities.periodMin; + this.resolution = 1; + + running = false; + + timeProcPeriodic = new TimeProc(TimerPeriodicEventCallback); + timeProcOneShot = new TimeProc(TimerOneShotEventCallback); + tickRaiser = new EventRaiser(OnTick); + } + + #endregion + + #region Methods + + /// + /// Starts the timer. + /// + /// + /// The timer has already been disposed. + /// + /// + /// The timer failed to start. + /// + public void Start() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + #region Guard + + if(IsRunning) + { + return; + } + + #endregion + + // If the periodic event callback should be used. + if(Mode == TimerMode.Periodic) + { + // Create and start timer. + timerID = timeSetEvent(Period, Resolution, timeProcPeriodic, IntPtr.Zero, (int)Mode); + } + // Else the one shot event callback should be used. + else + { + // Create and start timer. + timerID = timeSetEvent(Period, Resolution, timeProcOneShot, IntPtr.Zero, (int)Mode); + } + + // If the timer was created successfully. + if(timerID != 0) + { + running = true; + + if(SynchronizingObject != null && SynchronizingObject.InvokeRequired) + { + SynchronizingObject.BeginInvoke( + new EventRaiser(OnStarted), + new object[] { EventArgs.Empty }); + } + else + { + OnStarted(EventArgs.Empty); + } + } + else + { + throw new TimerStartException("Unable to start multimedia Timer."); + } + } + + /// + /// Stops timer. + /// + /// + /// If the timer has already been disposed. + /// + public void Stop() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + #region Guard + + if(!running) + { + return; + } + + #endregion + + // Stop and destroy timer. + int result = timeKillEvent(timerID); + + Debug.Assert(result == TIMERR_NOERROR); + + running = false; + + if(SynchronizingObject != null && SynchronizingObject.InvokeRequired) + { + SynchronizingObject.BeginInvoke( + new EventRaiser(OnStopped), + new object[] { EventArgs.Empty }); + } + else + { + OnStopped(EventArgs.Empty); + } + } + + #region Callbacks + + // Callback method called by the Win32 multimedia timer when a timer + // periodic event occurs. + private void TimerPeriodicEventCallback(int id, int msg, int user, int param1, int param2) + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + if(synchronizingObject != null) + { + synchronizingObject.BeginInvoke(tickRaiser, new object[] { EventArgs.Empty }); + } + else + { + OnTick(EventArgs.Empty); + } + } + + // Callback method called by the Win32 multimedia timer when a timer + // one shot event occurs. + private void TimerOneShotEventCallback(int id, int msg, int user, int param1, int param2) + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + if(synchronizingObject != null) + { + synchronizingObject.BeginInvoke(tickRaiser, new object[] { EventArgs.Empty }); + Stop(); + } + else + { + OnTick(EventArgs.Empty); + Stop(); + } + } + + #endregion + + #region Event Raiser Methods + + // Raises the Disposed event. + private void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if(handler != null) + { + handler(this, e); + } + } + + // Raises the Started event. + private void OnStarted(EventArgs e) + { + EventHandler handler = Started; + + if(handler != null) + { + handler(this, e); + } + } + + // Raises the Stopped event. + private void OnStopped(EventArgs e) + { + EventHandler handler = Stopped; + + if(handler != null) + { + handler(this, e); + } + } + + // Raises the Tick event. + private void OnTick(EventArgs e) + { + EventHandler handler = Tick; + + if(handler != null) + { + handler(this, e); + } + } + + #endregion + + #endregion + + #region Properties + + /// + /// Gets or sets the object used to marshal event-handler calls. + /// + public ISynchronizeInvoke SynchronizingObject + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return synchronizingObject; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + synchronizingObject = value; + } + } + + /// + /// Gets or sets the time between Tick events. + /// + /// + /// If the timer has already been disposed. + /// + public int Period + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return period; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + else if(value < Capabilities.periodMin || value > Capabilities.periodMax) + { + throw new ArgumentOutOfRangeException("Period", value, + "Multimedia Timer period out of range."); + } + + #endregion + + period = value; + + if(IsRunning) + { + Stop(); + Start(); + } + } + } + + /// + /// Gets or sets the timer resolution. + /// + /// + /// If the timer has already been disposed. + /// + /// + /// The resolution is in milliseconds. The resolution increases + /// with smaller values; a resolution of 0 indicates periodic events + /// should occur with the greatest possible accuracy. To reduce system + /// overhead, however, you should use the maximum value appropriate + /// for your application. + /// + public int Resolution + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return resolution; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + else if(value < 0) + { + throw new ArgumentOutOfRangeException("Resolution", value, + "Multimedia timer resolution out of range."); + } + + #endregion + + resolution = value; + + if(IsRunning) + { + Stop(); + Start(); + } + } + } + + /// + /// Gets the timer mode. + /// + /// + /// If the timer has already been disposed. + /// + public TimerMode Mode + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + return mode; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("Timer"); + } + + #endregion + + mode = value; + + if(IsRunning) + { + Stop(); + Start(); + } + } + } + + /// + /// Gets a value indicating whether the Timer is running. + /// + public bool IsRunning + { + get + { + return running; + } + } + + /// + /// Gets the timer capabilities. + /// + public static TimerCaps Capabilities + { + get + { + return caps; + } + } + + #endregion + + #endregion + + #region IComponent Members + + public event System.EventHandler Disposed; + + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Frees timer resources. + /// + public void Dispose() + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + disposed = true; + + if(running) + { + // Stop and destroy timer. + timeKillEvent(timerID); + } + + OnDisposed(EventArgs.Empty); + } + + #endregion + } + + /// + /// The exception that is thrown when a timer fails to start. + /// + public class TimerStartException : ApplicationException + { + /// + /// Initializes a new instance of the TimerStartException class. + /// + /// + /// The error message that explains the reason for the exception. + /// + public TimerStartException(string message) : base(message) + { + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/TimerFactory.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/TimerFactory.cs new file mode 100644 index 0000000..b7c617f --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia.Timers/TimerFactory.cs @@ -0,0 +1,58 @@ +#region License + +/* Copyright (c) 2015 Andreas Grimme + * + * 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 Sanford.Multimedia.Timers; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia.Timers +{ + /// + /// Use this factory to create ITimer instances. + /// + /// Caller is responsible for Dispose. + public static class TimerFactory + { + static bool IsRunningOnMono() + { + return Type.GetType("Mono.Runtime") != null; + } + + /// + /// Creates an instance of ITimer + /// + /// Newly created instance of ITimer + public static ITimer Create() + { + if (IsRunningOnMono()) + { + return new ThreadTimer(); + } + + return new Timer(); + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Device.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Device.cs new file mode 100644 index 0000000..85929b2 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Device.cs @@ -0,0 +1,166 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Sanford.Multimedia +{ + /// + /// Defines the public abstract 'Device' class to interface System.IDisposable. + /// + public abstract class Device : IDisposable + { + /// + /// This protected construct, uses a Callback Function integer if it's equal to value 0x30000. + /// + protected const int CALLBACK_FUNCTION = 0x30000; + + /// + /// This protected construct, uses a Callback Event integer if it's equal to value 0x50000. + /// + protected const int CALLBACK_EVENT = 0x50000; + + private int deviceID; + + /// + /// Synchronizes the context. + /// + protected SynchronizationContext context; + + // Indicates whether the device has been disposed. + private bool disposed = false; + + /// + /// Outputs an error via ErrorEventArgs, if the EventHandler encounters an issue. + /// + public event EventHandler Error; + + /// + /// This public function utilises the Device ID integer with SynchronizationContext. + /// + public Device(int deviceID) + { + this.deviceID = deviceID; + + if(SynchronizationContext.Current == null) + { + context = new SynchronizationContext(); + } + else + { + context = SynchronizationContext.Current; + } + } + + /// + /// Utilises system garbage collector (System.GC) to dispose memory when the boolean value is set to true. + /// + protected virtual void Dispose(bool disposing) + { + if(disposing) + { + disposed = true; + + GC.SuppressFinalize(this); + } + } + + /// + /// Error handling function. + /// + protected virtual void OnError(ErrorEventArgs e) + { + EventHandler handler = Error; + + if(handler != null) + { + context.Post(delegate(object dummy) + { + handler(this, e); + }, null); + } + } + + /// + /// Closes the MIDI device. + /// + public abstract void Close(); + + /// + /// Resets the device. + /// + public abstract void Reset(); + + /// + /// Gets the device handle. + /// + public abstract IntPtr Handle + { + get; + } + + /// + /// Calls the DeviceID public integer. + /// + public int DeviceID + { + get + { + return deviceID; + } + } + + /// + /// Declares the device as disposed. + /// + public bool IsDisposed + { + get + { + return disposed; + } + } + + #region IDisposable + + /// + /// Disposes of the device. + /// + public abstract void Dispose(); + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/DeviceException.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/DeviceException.cs new file mode 100644 index 0000000..e79bffc --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/DeviceException.cs @@ -0,0 +1,117 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; + +namespace Sanford.Multimedia +{ + /// + /// Refers the System.ApplicationException as DeviceException. + /// + public abstract class DeviceException : ApplicationException + { + #region Error Codes + /// No error. + public const int MMSYSERR_NOERROR = 0; + /// Unspecified error. + public const int MMSYSERR_ERROR = 1; + /// Device ID out of range. + public const int MMSYSERR_BADDEVICEID = 2; + /// Driver failed enable. + public const int MMSYSERR_NOTENABLED = 3; + /// Device already allocated. + public const int MMSYSERR_ALLOCATED = 4; + /// Device handle is invalid. + public const int MMSYSERR_INVALHANDLE = 5; + /// No device driver present. + public const int MMSYSERR_NODRIVER = 6; + /// Memory allocation error. + public const int MMSYSERR_NOMEM = 7; + /// Function isn't supported. + public const int MMSYSERR_NOTSUPPORTED = 8; + /// Error value out of range. + public const int MMSYSERR_BADERRNUM = 9; + /// Invalid flag passed. + public const int MMSYSERR_INVALFLAG = 10; + /// Invalid parameter passed. + public const int MMSYSERR_INVALPARAM = 11; + /// + /// Handle being used.

+ /// Simultaneously on another.

+ /// Thread (eg callback).

+ ///
+ public const int MMSYSERR_HANDLEBUSY = 12; + /// Specified alias not found. + public const int MMSYSERR_INVALIDALIAS = 13; + /// Bad registry database. + public const int MMSYSERR_BADDB = 14; + /// Registry key not found. + public const int MMSYSERR_KEYNOTFOUND = 15; + /// Registry read error. + public const int MMSYSERR_READERROR = 16; + /// Registry write error. + public const int MMSYSERR_WRITEERROR = 17; + /// Registry delete error. + public const int MMSYSERR_DELETEERROR = 18; + /// Registry value not found. + public const int MMSYSERR_VALNOTFOUND = 19; + /// Driver does not call DriverCallback. + public const int MMSYSERR_NODRIVERCB = 20; + /// Last error. + public const int MMSYSERR_LASTERROR = 20; + + #endregion + + private int errorCode; + + /// + /// Calls the Device Exception error code. + /// + public DeviceException(int errorCode) + { + this.errorCode = errorCode; + } + + /// + /// Public integer for the error code. + /// + public int ErrorCode + { + get + { + return errorCode; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/ErrorEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/ErrorEventArgs.cs new file mode 100644 index 0000000..b7fdd0c --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/ErrorEventArgs.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Sanford.Multimedia +{ + /// + /// This will handle any errors relating to Sanford.Multimedia. + /// + public class ErrorEventArgs : EventArgs + { + private Exception ex; + + /// + /// This represents the error itself. + /// + public ErrorEventArgs(Exception ex) + { + this.ex = ex; + } + + /// + /// Displays the error. + /// + /// + /// The error that is associated with the issue. + /// + public Exception Error + { + get + { + return ex; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Key.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Key.cs new file mode 100644 index 0000000..dfd313e --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Key.cs @@ -0,0 +1,192 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +namespace Sanford.Multimedia +{ + /// + /// Defines constants for all major and minor keys. + /// + public enum Key + { + /// + /// The A♭ (A-Flat) Minor sequenced note. + /// + AFlatMinor, + + /// + /// The E♭ (E-Flat) Minor sequenced note. + /// + EFlatMinor, + + /// + /// The B♭ (B-Flat) Minor sequenced note. + /// + BFlatMinor, + + /// + /// The F Minor sequenced note. + /// + FMinor, + + /// + /// The C Minor sequenced note. + /// + CMinor, + + /// + /// The G Minor sequenced note. + /// + GMinor, + + /// + /// The D Minor sequenced note. + /// + DMinor, + + /// + /// The A Minor sequenced note. + /// + AMinor, + + /// + /// The E Minor sequenced note. + /// + EMinor, + + /// + /// The B Minor sequenced note. + /// + BMinor, + + /// + /// The F♯ (F-Sharp) Minor sequenced note. + /// + FSharpMinor, + + /// + /// The C♯ (C-Sharp) Minor sequenced note. + /// + CSharpMinor, + + /// + /// The G♯ (G-Sharp) Minor sequenced note. + /// + GSharpMinor, + + /// + /// The D♯ (D-Sharp) Minor sequenced note. + /// + DSharpMinor, + + /// + /// The A♯ (A-Sharp) Minor sequenced note. + /// + ASharpMinor, + + /// + /// The C♭ (C-Flat) Major sequenced note. + /// + CFlatMajor, + + /// + /// The G♭ (G-Flat) Major sequenced note. + /// + GFlatMajor, + + /// + /// The D♭ (D-Flat) Major sequenced note. + /// + DFlatMajor, + + /// + /// The A♭ (A-Flat) Major sequenced note. + /// + AFlatMajor, + + /// + /// The E♭ (E-Flat) Major sequenced note. + /// + EFlatMajor, + + /// + /// The B♭ (B-Flat) Major sequenced note. + /// + BFlatMajor, + + /// + /// The F Major sequenced note. + /// + FMajor, + + /// + /// The C Major sequenced note. + /// + CMajor, + + /// + /// The G Major sequenced note. + /// + GMajor, + + /// + /// The D Major sequenced note. + /// + DMajor, + + /// + /// The A Major sequenced note. + /// + AMajor, + + /// + /// The E Major sequenced note. + /// + EMajor, + + /// + /// The B Major sequenced note. + /// + BMajor, + + /// + /// The F♯ (F-Sharp) Major sequenced note. + /// + FSharpMajor, + + /// + /// The C♯ (C-Sharp) Major sequenced note. + /// + CSharpMajor, + } +} \ No newline at end of file diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Note.cs b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Note.cs new file mode 100644 index 0000000..bfe32cf --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Multimedia/Note.cs @@ -0,0 +1,127 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +namespace Sanford.Multimedia +{ + /// + /// Defines constants representing the 12 Note of the chromatic scale. + /// + public enum Note + { + /// + /// C natural. + /// + C, + + /// + /// C sharp. + /// + CSharp, + + /// + /// D flat. + /// + DFlat = CSharp, + + /// + /// D natural. + /// + D, + + /// + /// D sharp. + /// + DSharp, + + /// + /// E flat. + /// + EFlat = DSharp, + + /// + /// E natural. + /// + E, + + /// + /// F natural. + /// + F, + + /// + /// F sharp. + /// + FSharp, + + /// + /// G flat. + /// + GFlat = FSharp, + + /// + /// G natural. + /// + G, + + /// + /// G sharp. + /// + GSharp, + + /// + /// A flat. + /// + AFlat = GSharp, + + /// + /// A natural. + /// + A, + + /// + /// A sharp. + /// + ASharp, + + /// + /// B flat. + /// + BFlat = ASharp, + + /// + /// B natural. + /// + B + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/AsyncResult.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/AsyncResult.cs new file mode 100644 index 0000000..ef8dd84 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/AsyncResult.cs @@ -0,0 +1,189 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Threading; + +namespace Sanford.Threading +{ + /// + /// Provides basic implementation of the IAsyncResult interface. + /// + public class AsyncResult : IAsyncResult + { + #region AsyncResult Members + + #region Fields + + // The owner of this AsyncResult object. + private object owner; + + // The callback to be invoked when the operation completes. + private AsyncCallback callback; + + // User state information. + private object state; + + // For signaling when the operation has completed. + private ManualResetEvent waitHandle = new ManualResetEvent(false); + + // A value indicating whether the operation completed synchronously. + private bool completedSynchronously; + + // A value indicating whether the operation has completed. + private bool isCompleted = false; + + // The ID of the thread this AsyncResult object originated on. + private int threadId; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the AsyncResult object with the + /// specified owner of the AsyncResult object, the optional callback + /// delegate, and optional state object. + /// + /// + /// The owner of the AsyncResult object. + /// + /// + /// An optional asynchronous callback, to be called when the + /// operation is complete. + /// + /// + /// A user-provided object that distinguishes this particular + /// asynchronous request from other requests. + /// + public AsyncResult(object owner, AsyncCallback callback, object state) + { + this.owner = owner; + this.callback = callback; + this.state = state; + + // Get the current thread ID. This will be used later to determine + // if the operation completed synchronously. + threadId = Thread.CurrentThread.ManagedThreadId; + } + + #endregion + + #region Methods + + /// + /// Signals that the operation has completed. + /// + public void Signal() + { + isCompleted = true; + + completedSynchronously = threadId == Thread.CurrentThread.ManagedThreadId; + + waitHandle.Set(); + + if(callback != null) + { + callback(this); + } + } + + #endregion + + #region Properties + + /// + /// Gets the owner of this AsyncResult object. + /// + public object Owner + { + get + { + return owner; + } + } + + #endregion + + #endregion + + #region IAsyncResult Members + + /// + /// This object provides the async state. + /// + public object AsyncState + { + get + { + return state; + } + } + + /// + /// This handles the waiting time for the async. + /// + public WaitHandle AsyncWaitHandle + { + get + { + return waitHandle; + } + } + + /// + /// Determines whenever the async completed synchronously or not. + /// + public bool CompletedSynchronously + { + get + { + return completedSynchronously; + } + } + + /// + /// Determines if the async has completed. + /// + public bool IsCompleted + { + get + { + return isCompleted; + } + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.AsyncResult.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.AsyncResult.cs new file mode 100644 index 0000000..7c0ca38 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.AsyncResult.cs @@ -0,0 +1,121 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace Sanford.Threading +{ + public partial class DelegateQueue + { + private enum NotificationType + { + None, + BeginInvokeCompleted, + PostCompleted + } + + /// + /// Implements the IAsyncResult interface for the DelegateQueue class. + /// + private class DelegateQueueAsyncResult : AsyncResult + { + // The delegate to be invoked. + private Delegate method; + + // Args to be passed to the delegate. + private object[] args; + + // The object returned from the delegate. + private object returnValue = null; + + // Represents a possible exception thrown by invoking the method. + private Exception error = null; + + private NotificationType notificationType; + + public DelegateQueueAsyncResult( + object owner, + Delegate method, + object[] args, + bool synchronously, + NotificationType notificationType) + : base(owner, null, null) + { + this.method = method; + this.args = args; + this.notificationType = notificationType; + } + + public DelegateQueueAsyncResult( + object owner, + AsyncCallback callback, + object state, + Delegate method, + object[] args, + bool synchronously, + NotificationType notificationType) + : base(owner, callback, state) + { + this.method = method; + this.args = args; + this.notificationType = notificationType; + } + + public void Invoke() + { + try + { + returnValue = method.DynamicInvoke(args); + } + catch(Exception ex) + { + error = ex; + } + finally + { + Signal(); + } + } + + public object[] GetArgs() + { + return args; + } + + public object ReturnValue + { + get + { + return returnValue; + } + } + + public Exception Error + { + get + { + return error; + } + set + { + error = value; + } + } + + public Delegate Method + { + get + { + return method; + } + } + + public NotificationType NotificationType + { + get + { + return notificationType; + } + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.cs new file mode 100644 index 0000000..3def8c6 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/DelegateQueue.cs @@ -0,0 +1,853 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; +using System.Threading; +using Sanford.Collections.Generic; + +namespace Sanford.Threading +{ + /// + /// Represents an asynchronous queue of delegates. + /// + public partial class DelegateQueue : SynchronizationContext, IComponent, ISynchronizeInvoke + { + #region DelegateQueue Members + + #region Fields + + // The thread for processing delegates. + private Thread delegateThread; + + // The deque for holding delegates. + private Deque delegateDeque = new Deque(); + + // The object to use for locking. + private readonly object lockObject = new object(); + + // The synchronization context in which this DelegateQueue was created. + private SynchronizationContext context; + + // Inidicates whether the delegate queue has been disposed. + private volatile bool disposed = false; + + // Thread ID counter for all DelegateQueues. + private volatile static uint threadID = 0; + + private ISite site = null; + + #endregion + + #region Events + + /// + /// Occurs after a method has been invoked as a result of a call to + /// the BeginInvoke or BeginInvokePriority methods. + /// + public event EventHandler InvokeCompleted; + + /// + /// Occurs after a method has been invoked as a result of a call to + /// the Post and PostPriority methods. + /// + public event EventHandler PostCompleted; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the DelegateQueue class. + /// + public DelegateQueue() + { + InitializeDelegateQueue(); + + if(SynchronizationContext.Current == null) + { + context = new SynchronizationContext(); + } + else + { + context = SynchronizationContext.Current; + } + } + + /// + /// Initializes a new instance of the DelegateQueue class with the specified IContainer object. + /// + /// + /// The IContainer to which the DelegateQueue will add itself. + /// + public DelegateQueue(IContainer container) + { + // Required for Windows.Forms Class Composition Designer support + container.Add(this); + + InitializeDelegateQueue(); + } + + /// + /// Checks if DelegateQueue has been disposed. + /// + ~DelegateQueue() + { + Dispose(false); + } + + // Initializes the DelegateQueue. + private void InitializeDelegateQueue() + { + // Create thread for processing delegates. + delegateThread = new Thread(DelegateProcedure); + + lock(lockObject) + { + // Increment to next thread ID. + threadID++; + + // Create name for thread. + delegateThread.Name = "Delegate Queue Thread: " + threadID.ToString(); + + // Start thread. + delegateThread.Start(); + + Debug.WriteLine(delegateThread.Name + " Started."); + + // Wait for signal from thread that it is running. + Monitor.Wait(lockObject); + } + } + + #endregion + + #region Methods + + /// + /// Disposes of DelegateQueue when closed. + /// + protected virtual void Dispose(bool disposing) + { + if(disposing) + { + lock(lockObject) + { + disposed = true; + + Monitor.Pulse(lockObject); + + GC.SuppressFinalize(this); + } + } + } + + /// + /// Executes the delegate on the main thread that this object executes on. + /// + /// + /// A Delegate to a method that takes parameters of the same number and + /// type that are contained in args. + /// + /// + /// An array of type Object to pass as arguments to the given method. + /// + /// + /// An IAsyncResult interface that represents the asynchronous operation + /// started by calling this method. + /// + /// + /// The delegate is placed at the beginning of the queue. Its invocation + /// takes priority over delegates already in the queue. + /// + public IAsyncResult BeginInvokePriority(Delegate method, params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(method == null) + { + throw new ArgumentNullException(); + } + + #endregion + + DelegateQueueAsyncResult result; + + // If BeginInvokePriority was called from a different thread than the one + // in which the DelegateQueue is running. + if(InvokeRequired) + { + result = new DelegateQueueAsyncResult(this, method, args, false, NotificationType.BeginInvokeCompleted); + + lock(lockObject) + { + // Put the method at the front of the queue. + delegateDeque.PushFront(result); + + Monitor.Pulse(lockObject); + } + } + // Else BeginInvokePriority was called from the same thread in which the + // DelegateQueue is running. + else + { + result = new DelegateQueueAsyncResult(this, method, args, true, NotificationType.None); + + // The method is invoked here instead of placing it in the + // queue. The reason for this is that if EndInvoke is called + // from the same thread in which the DelegateQueue is running and + // the method has not been invoked, deadlock will occur. + result.Invoke(); + } + + return result; + } + + /// + /// Executes the delegate on the main thread that this object executes on. + /// + /// + /// A Delegate to a method that takes parameters of the same number and + /// type that are contained in args. + /// + /// + /// An array of type Object to pass as arguments to the given method. + /// + /// + /// An IAsyncResult interface that represents the asynchronous operation + /// started by calling this method. + /// + /// + /// + /// The delegate is placed at the beginning of the queue. Its invocation + /// takes priority over delegates already in the queue. + /// + /// + /// Unlike BeginInvoke, this method operates synchronously, that is, it + /// waits until the process completes before returning. Exceptions raised + /// during the call are propagated back to the caller. + /// + /// + public object InvokePriority(Delegate method, params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(method == null) + { + throw new ArgumentNullException(); + } + + #endregion + + object returnValue = null; + + // If InvokePriority was called from a different thread than the one + // in which the DelegateQueue is running. + if(InvokeRequired) + { + DelegateQueueAsyncResult result = new DelegateQueueAsyncResult(this, method, args, false, NotificationType.None); + + lock(lockObject) + { + // Put the method at the back of the queue. + delegateDeque.PushFront(result); + + Monitor.Pulse(lockObject); + } + + // Wait for the result of the method invocation. + returnValue = EndInvoke(result); + } + // Else InvokePriority was called from the same thread in which the + // DelegateQueue is running. + else + { + // Invoke the method here rather than placing it in the queue. + returnValue = method.DynamicInvoke(args); + } + + return returnValue; + } + + /// + /// Executes the delegate on the main thread that this object executes on. + /// + /// + /// An optional asynchronous callback, to be called when the method is invoked. + /// + /// + /// A user-provided object that distinguishes this particular asynchronous invoke request from other requests. + /// + /// + /// A Delegate to a method that takes parameters of the same number and + /// type that are contained in args. + /// + /// + /// An array of type Object to pass as arguments to the given method. + /// + /// + /// An IAsyncResult interface that represents the asynchronous operation + /// started by calling this method. + /// + public IAsyncResult BeginInvoke(AsyncCallback callback, object state, Delegate method, params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(method == null) + { + throw new ArgumentNullException(); + } + + #endregion + + DelegateQueueAsyncResult result; + + if(InvokeRequired) + { + result = new DelegateQueueAsyncResult(this, callback, state, method, args, false, NotificationType.BeginInvokeCompleted); + + lock(lockObject) + { + delegateDeque.PushBack(result); + + Monitor.Pulse(lockObject); + } + } + else + { + result = new DelegateQueueAsyncResult(this, callback, state, method, args, false, NotificationType.None); + + result.Invoke(); + } + + return result; + } + + /// + /// Dispatches an asynchronous message to this synchronization context. + /// + /// + /// The SendOrPostCallback delegate to call. + /// + /// + /// The object passed to the delegate. + /// + /// + /// The Post method starts an asynchronous request to post a message. + /// + public void PostPriority(SendOrPostCallback d, object state) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(d == null) + { + throw new ArgumentNullException(); + } + + #endregion + + lock(lockObject) + { + DelegateQueueAsyncResult result = new DelegateQueueAsyncResult(this, d, new object[] { state }, false, NotificationType.PostCompleted); + + // Put the method at the front of the queue. + delegateDeque.PushFront(result); + + Monitor.Pulse(lockObject); + } + } + + /// + /// Dispatches an synchronous message to this synchronization context. + /// + /// + /// The SendOrPostCallback delegate to call. + /// + /// + /// The object passed to the delegate. + /// + public void SendPriority(SendOrPostCallback d, object state) + { + InvokePriority(d, state); + } + + // Processes and invokes delegates. + private void DelegateProcedure() + { + lock(lockObject) + { + // Signal the constructor that the thread is now running. + Monitor.Pulse(lockObject); + } + + // Set this DelegateQueue as the SynchronizationContext for this thread. + SynchronizationContext.SetSynchronizationContext(this); + + // Placeholder for DelegateQueueAsyncResult objects. + DelegateQueueAsyncResult result = null; + + // While the DelegateQueue has not been disposed. + while(true) + { + // Critical section. + lock(lockObject) + { + // If the DelegateQueue has been disposed, break out of loop; we're done. + if(disposed) + { + break; + } + + // If there are delegates waiting to be invoked. + if(delegateDeque.Count > 0) + { + result = delegateDeque.PopFront(); + } + // Else there are no delegates waiting to be invoked. + else + { + // Wait for next delegate. + Monitor.Wait(lockObject); + + // If the DelegateQueue has been disposed, break out of loop; we're done. + if(disposed) + { + break; + } + + Debug.Assert(delegateDeque.Count > 0); + + result = delegateDeque.PopFront(); + } + } + + Debug.Assert(result != null); + + // Invoke the delegate. + result.Invoke(); + + if(result.NotificationType == NotificationType.BeginInvokeCompleted) + { + InvokeCompletedEventArgs e = new InvokeCompletedEventArgs( + result.Method, + result.GetArgs(), + result.ReturnValue, + result.Error); + + OnInvokeCompleted(e); + } + else if(result.NotificationType == NotificationType.PostCompleted) + { + object[] args = result.GetArgs(); + + Debug.Assert(args.Length == 1); + Debug.Assert(result.Method is SendOrPostCallback); + + PostCompletedEventArgs e = new PostCompletedEventArgs( + (SendOrPostCallback)result.Method, + result.Error, + args[0]); + + OnPostCompleted(e); + } + else + { + Debug.Assert(result.NotificationType == NotificationType.None); + } + } + + Debug.WriteLine(delegateThread.Name + " Finished"); + } + + /// + /// Raises the InvokeCompleted event. + /// + protected virtual void OnInvokeCompleted(InvokeCompletedEventArgs e) + { + EventHandler handler = InvokeCompleted; + + if(handler != null) + { + context.Post(delegate(object state) + { + handler(this, e); + }, null); + } + } + + /// + /// Raises the PostCompleted event. + /// + protected virtual void OnPostCompleted(PostCompletedEventArgs e) + { + EventHandler handler = PostCompleted; + + if(handler != null) + { + context.Post(delegate(object state) + { + handler(this, e); + }, null); + } + } + + /// + /// Raises the Disposed event. + /// + protected virtual void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if(handler != null) + { + context.Post(delegate(object state) + { + handler(this, e); + }, null); + } + } + + #endregion + + #endregion + + #region SynchronizationContext Overrides + + /// + /// Dispatches a synchronous message to this synchronization context. + /// + /// + /// The SendOrPostCallback delegate to call. + /// + /// + /// The object passed to the delegate. + /// + /// + /// The Send method starts an synchronous request to send a message. + /// + public override void Send(SendOrPostCallback d, object state) + { + Invoke(d, state); + } + + /// + /// Dispatches an asynchronous message to this synchronization context. + /// + /// + /// The SendOrPostCallback delegate to call. + /// + /// + /// The object passed to the delegate. + /// + /// + /// The Post method starts an asynchronous request to post a message. + /// + public override void Post(SendOrPostCallback d, object state) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(d == null) + { + throw new ArgumentNullException(); + } + + #endregion + + lock(lockObject) + { + delegateDeque.PushBack(new DelegateQueueAsyncResult(this, d, new object[] { state }, false, NotificationType.PostCompleted)); + + Monitor.Pulse(lockObject); + } + } + + #endregion + + #region IComponent Members + + /// + /// Represents the method that handles the Disposed delegate of a DelegateQueue. + /// + public event System.EventHandler Disposed; + + /// + /// Gets or sets the ISite associated with the DelegateQueue. + /// + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region ISynchronizeInvoke Members + + /// + /// Executes the delegate on the main thread that this DelegateQueue executes on. + /// + /// + /// A Delegate to a method that takes parameters of the same number and type that + /// are contained in args. + /// + /// + /// An array of type Object to pass as arguments to the given method. This can be + /// a null reference (Nothing in Visual Basic) if no arguments are needed. + /// + /// + /// An IAsyncResult interface that represents the asynchronous operation started + /// by calling this method. + /// + /// + /// The delegate is called asynchronously, and this method returns immediately. + /// You can call this method from any thread. If you need the return value from a process + /// started with this method, call EndInvoke to get the value. + /// If you need to call the delegate synchronously, use the Invoke method instead. + /// + public IAsyncResult BeginInvoke(Delegate method, params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(method == null) + { + throw new ArgumentNullException(); + } + + #endregion + + DelegateQueueAsyncResult result; + + if(InvokeRequired) + { + result = new DelegateQueueAsyncResult(this, method, args, false, NotificationType.BeginInvokeCompleted); + + lock(lockObject) + { + delegateDeque.PushBack(result); + + Monitor.Pulse(lockObject); + } + } + else + { + result = new DelegateQueueAsyncResult(this, method, args, false, NotificationType.None); + + result.Invoke(); + } + + return result; + } + + /// + /// Waits until the process started by calling BeginInvoke completes, and then returns + /// the value generated by the process. + /// + /// + /// An IAsyncResult interface that represents the asynchronous operation started + /// by calling BeginInvoke. + /// + /// + /// An Object that represents the return value generated by the asynchronous operation. + /// + /// + /// This method gets the return value of the asynchronous operation represented by the + /// IAsyncResult passed by this interface. If the asynchronous operation has not completed, this method will wait until the result is available. + /// + public object EndInvoke(IAsyncResult result) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(!(result is DelegateQueueAsyncResult)) + { + throw new ArgumentException(); + } + else if(((DelegateQueueAsyncResult)result).Owner != this) + { + throw new ArgumentException(); + } + + #endregion + + result.AsyncWaitHandle.WaitOne(); + + DelegateQueueAsyncResult r = (DelegateQueueAsyncResult)result; + + if(r.Error != null) + { + throw r.Error; + } + + return r.ReturnValue; + } + + /// + /// Executes the delegate on the main thread that this DelegateQueue executes on. + /// + /// + /// A Delegate that contains a method to call, in the context of the thread for the DelegateQueue. + /// + /// + /// An array of type Object that represents the arguments to pass to the given method. + /// + /// + /// An Object that represents the return value from the delegate being invoked, or a + /// null reference (Nothing in Visual Basic) if the delegate has no return value. + /// + /// + /// Unlike BeginInvoke, this method operates synchronously, that is, it waits until + /// the process completes before returning. Exceptions raised during the call are propagated + /// back to the caller. + /// Use this method when calling a method from a different thread to marshal the call + /// to the proper thread. + /// + public object Invoke(Delegate method, params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateQueue"); + } + else if(method == null) + { + throw new ArgumentNullException(); + } + + #endregion + + object returnValue = null; + + if(InvokeRequired) + { + DelegateQueueAsyncResult result = new DelegateQueueAsyncResult(this, method, args, false, NotificationType.None); + + lock(lockObject) + { + delegateDeque.PushBack(result); + + Monitor.Pulse(lockObject); + } + + returnValue = EndInvoke(result); + } + else + { + // Invoke the method here rather than placing it in the queue. + returnValue = method.DynamicInvoke(args); + } + + return returnValue; + } + + /// + /// Gets a value indicating whether the caller must call Invoke. + /// + /// + /// true if the caller must call Invoke; otherwise, false. + /// + /// + /// This property determines whether the caller must call Invoke when making + /// method calls to this DelegateQueue. If you are calling a method from a different + /// thread, you must use the Invoke method to marshal the call to the proper thread. + /// + public bool InvokeRequired + { + get + { + return Thread.CurrentThread.ManagedThreadId != delegateThread.ManagedThreadId; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Disposes of the DelegateQueue. + /// + public void Dispose() + { + #region Guards + + if(disposed) + { + return; + } + + #endregion + + Dispose(true); + + OnDisposed(EventArgs.Empty); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/PostCompletedEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/PostCompletedEventArgs.cs new file mode 100644 index 0000000..26e7272 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateQueue/PostCompletedEventArgs.cs @@ -0,0 +1,68 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Threading; + +namespace Sanford.Threading +{ + /// + /// This class is used when the async events have been completed. + /// + public class PostCompletedEventArgs : AsyncCompletedEventArgs + { + private SendOrPostCallback callback; + + /// + /// Main function for post completed events. + /// + public PostCompletedEventArgs(SendOrPostCallback callback, Exception error, object state) + : base(error, false, state) + { + this.callback = callback; + } + + /// + /// Gets and returns the callback. + /// + public SendOrPostCallback Callback + { + get + { + return callback; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/DelegateScheduler.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/DelegateScheduler.cs new file mode 100644 index 0000000..8506657 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/DelegateScheduler.cs @@ -0,0 +1,585 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Threading; +using System.Timers; +using Sanford.Collections; + +namespace Sanford.Threading +{ + /// + /// Provides functionality for timestamped delegate invocation. + /// + public partial class DelegateScheduler : IDisposable, IComponent + { + #region DelegateScheduler Members + + #region Fields + + /// + /// A constant value representing an unlimited number of delegate invocations. + /// + public const int Infinite = -1; + + // Default polling interval. + private const int DefaultPollingInterval = 10; + + // For queuing the delegates in priority order. + private PriorityQueue queue = new PriorityQueue(); + + // Used for timing events for polling the delegate queue. + private System.Timers.Timer timer = new System.Timers.Timer(DefaultPollingInterval); + + // For storing tasks when the scheduler isn't running. + private List tasks = new List(); + + // A value indicating whether the DelegateScheduler is running. + private bool running = false; + + // A value indicating whether the DelegateScheduler has been disposed. + private bool disposed = false; + + private ISite site = null; + + #endregion + + #region Events + + /// + /// Raised when a delegate is invoked. + /// + public event EventHandler InvokeCompleted; + + #endregion + + #region Construction + + /// + /// Initializes a new instance of the DelegateScheduler class. + /// + public DelegateScheduler() + { + Initialize(); + } + + /// + /// Initializes a new instance of the DelegateScheduler class with the + /// specified IContainer. + /// + public DelegateScheduler(IContainer container) + { + // Required for Windows.Forms Class Composition Designer support + container.Add(this); + + Initialize(); + } + + // Initializes the DelegateScheduler. + private void Initialize() + { + timer.Elapsed += new ElapsedEventHandler(HandleElapsed); + } + + /// + /// Checks if the DelegateScheduler has been disposed. + /// + ~DelegateScheduler() + { + Dispose(false); + } + + #endregion + + #region Methods + + /// + /// Disposes of DelegateScheduler when closed. + /// + protected virtual void Dispose(bool disposing) + { + if(disposing) + { + Stop(); + + timer.Dispose(); + + Clear(); + + disposed = true; + + OnDisposed(EventArgs.Empty); + + GC.SuppressFinalize(this); + } + } + + /// + /// Adds a delegate to the DelegateScheduler. + /// + /// + /// The number of times the delegate should be invoked. + /// + /// + /// The time in milliseconds between delegate invocation. + /// + /// + /// + /// The delegate to invoke. + /// + /// The arguments to pass to the delegate when it is invoked. + /// + /// + /// A Task object representing the scheduled task. + /// + /// + /// If the DelegateScheduler has already been disposed. + /// + /// + /// If an unlimited count is desired, pass the DelegateScheduler.Infinity + /// constant as the count argument. + /// + public Task Add( + int count, + int millisecondsTimeout, + Delegate method, + params object[] args) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateScheduler"); + } + + #endregion + + Task t = new Task(count, millisecondsTimeout, method, args); + + lock(queue.SyncRoot) + { + // Only add the task to the DelegateScheduler if the count + // is greater than zero or set to Infinite. + if(count > 0 || count == DelegateScheduler.Infinite) + { + if(IsRunning) + { + queue.Enqueue(t); + } + else + { + tasks.Add(t); + } + } + } + + return t; + } + + /// + /// Removes the specified Task. + /// + /// + /// The Task to be removed. + /// + /// + /// If the DelegateScheduler has already been disposed. + /// + public void Remove(Task task) + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("DelegateScheduler"); + } + + #endregion + + #region Guard + + if(task == null) + { + return; + } + + #endregion + + lock(queue.SyncRoot) + { + if(IsRunning) + { + queue.Remove(task); + } + else + { + tasks.Remove(task); + } + } + } + + /// + /// Starts the DelegateScheduler. + /// + /// + /// If the DelegateScheduler has already been disposed. + /// + public void Start() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + #region Guard + + if(IsRunning) + { + return; + } + + #endregion + + lock(queue.SyncRoot) + { + Task t; + + while(tasks.Count > 0) + { + t = tasks[tasks.Count - 1]; + + tasks.RemoveAt(tasks.Count - 1); + + t.ResetNextTimeout(); + + queue.Enqueue(t); + } + + running = true; + + timer.Start(); + } + } + + /// + /// Stops the DelegateScheduler. + /// + /// + /// If the DelegateScheduler has already been disposed. + /// + public void Stop() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + #region Guard + + if(!IsRunning) + { + return; + } + + #endregion + + lock(queue.SyncRoot) + { + // While there are still tasks left in the queue. + while(queue.Count > 0) + { + // Remove task from queue and add it to the Task list + // to be used again next time the DelegateScheduler is run. + tasks.Add((Task)queue.Dequeue()); + } + + timer.Stop(); + + running = false; + } + } + + /// + /// Clears the DelegateScheduler of all tasks. + /// + /// + /// If the DelegateScheduler has already been disposed. + /// + public void Clear() + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + + #endregion + + lock(queue.SyncRoot) + { + queue.Clear(); + tasks.Clear(); + } + } + + // Responds to the timer's Elapsed event by running any tasks that are due. + private void HandleElapsed(object sender, ElapsedEventArgs e) + { + Debug.WriteLine("Signal time: " + e.SignalTime.ToString()); + + lock(queue.SyncRoot) + { + #region Guard + + if(queue.Count == 0) + { + return; + } + + #endregion + + // Take a look at the first task in the queue to see if it's + // time to run it. + Task tk = (Task)queue.Peek(); + + // The return value from the delegate that will be invoked. + object returnValue; + + // While there are still tasks in the queue and it is time + // to run one or more of them. + while(queue.Count > 0 && tk.NextTimeout <= e.SignalTime) + { + // Remove task from queue. + queue.Dequeue(); + + // While it's time for the task to run. + while((tk.Count == Infinite || tk.Count > 0) && tk.NextTimeout <= e.SignalTime) + { + try + { + Debug.WriteLine("Invoking delegate."); + Debug.WriteLine("Next timeout: " + tk.NextTimeout.ToString()); + + // Invoke delegate. + returnValue = tk.Invoke(e.SignalTime); + + OnInvokeCompleted( + new InvokeCompletedEventArgs( + tk.Method, + tk.GetArgs(), + returnValue, + null)); + } + catch(Exception ex) + { + OnInvokeCompleted( + new InvokeCompletedEventArgs( + tk.Method, + tk.GetArgs(), + null, + ex)); + } + } + + // If this task should run again. + if(tk.Count == Infinite || tk.Count > 0) + { + // Enqueue task back into priority queue. + queue.Enqueue(tk); + } + + // If there are still tasks in the queue. + if(queue.Count > 0) + { + // Take a look at the next task to see if it is + // time to run. + tk = (Task)queue.Peek(); + } + } + } + } + + /// + /// Raises the Disposed event. + /// + protected virtual void OnDisposed(EventArgs e) + { + EventHandler handler = Disposed; + + if(handler != null) + { + handler(this, e); + } + } + + /// + /// Raises the InvokeCompleted event. + /// + protected virtual void OnInvokeCompleted(InvokeCompletedEventArgs e) + { + EventHandler handler = InvokeCompleted; + + if(handler != null) + { + handler(this, e); + } + } + + #endregion + + #region Properties + + /// + /// Gets or sets the interval in milliseconds in which the + /// DelegateScheduler polls its queue of delegates in order to + /// determine when they should run. + /// + public double PollingInterval + { + get + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("PriorityQueue"); + } + + #endregion + + return timer.Interval; + } + set + { + #region Require + + if(disposed) + { + throw new ObjectDisposedException("PriorityQueue"); + } + + #endregion + + timer.Interval = value; + } + } + + /// + /// Gets a value indicating whether the DelegateScheduler is running. + /// + public bool IsRunning + { + get + { + return running; + } + } + + /// + /// Gets or sets the object used to marshal event-handler calls and delegate invocations. + /// + public ISynchronizeInvoke SynchronizingObject + { + get + { + return timer.SynchronizingObject; + } + set + { + timer.SynchronizingObject = value; + } + } + + #endregion + + #endregion + + #region IComponent Members + + /// + /// When the event has been disposed. + /// + public event System.EventHandler Disposed; + + /// + /// Gets and returns the site, sets the site with a value. + /// + public ISite Site + { + get + { + return site; + } + set + { + site = value; + } + } + + #endregion + + #region IDisposable Members + + /// + /// The main dispose function that occurs when disposed. + /// + public void Dispose() + { + #region Guard + + if(disposed) + { + return; + } + + #endregion + + Dispose(true); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/Task.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/Task.cs new file mode 100644 index 0000000..28af998 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/DelegateScheduler/Task.cs @@ -0,0 +1,201 @@ +#region License + +/* Copyright (c) 2007 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Sanford.Threading +{ + /// + /// Indicates the tasks to be compared. + /// + public class Task : IComparable + { + #region Task Members + + #region Fields + + // The number of times left to invoke the delegate associated with this Task. + private int count; + + // The interval between delegate invocation. + private int millisecondsTimeout; + + // The delegate to invoke. + private Delegate method; + + // The arguments to pass to the delegate when it is invoked. + private object[] args; + + // The time for the next timeout; + private DateTime nextTimeout; + + // For locking. + private readonly object lockObject = new object(); + + #endregion + + #region Construction + + internal Task( + int count, + int millisecondsTimeout, + Delegate method, + object[] args) + { + this.count = count; + this.millisecondsTimeout = millisecondsTimeout; + this.method = method; + this.args = args; + + ResetNextTimeout(); + } + + #endregion + + #region Methods + + internal void ResetNextTimeout() + { + nextTimeout = DateTime.Now.AddMilliseconds(millisecondsTimeout); + } + + internal object Invoke(DateTime signalTime) + { + Debug.Assert(count == DelegateScheduler.Infinite || count > 0); + + object returnValue = method.DynamicInvoke(args); + + if(count == DelegateScheduler.Infinite) + { + nextTimeout = nextTimeout.AddMilliseconds(millisecondsTimeout); + } + else + { + count--; + + if(count > 0) + { + nextTimeout = nextTimeout.AddMilliseconds(millisecondsTimeout); + } + } + + return returnValue; + } + + /// + /// Initializes returns the arguments. + /// + public object[] GetArgs() + { + return args; + } + + #endregion + + #region Properties + + /// + /// Gets and returns the next timeout. + /// + public DateTime NextTimeout + { + get + { + return nextTimeout; + } + } + + /// + /// Gets and returns the count. + /// + public int Count + { + get + { + return count; + } + } + + /// + /// Gets and returns the method. + /// + public Delegate Method + { + get + { + return method; + } + } + + /// + /// Gets and returns the timeout in milliseconds. + /// + public int MillisecondsTimeout + { + get + { + return millisecondsTimeout; + } + } + + #endregion + + #endregion + + #region IComparable Members + + + /// + /// Compares the current instance with another object of the same type and returns an integer indicates whenever the current instance precedes, follows, or occurs in the same position in the sort order as the other object. + /// + /// + /// Compares between the subtracted next timeout and the task. + /// + public int CompareTo(object obj) + { + Task t = obj as Task; + + if(t == null) + { + throw new ArgumentException("obj is not the same type as this instance."); + } + + return -nextTimeout.CompareTo(t.nextTimeout); + } + + #endregion + } +} diff --git a/Sanford.Multimedia.Midi.Core/Sanford.Threading/InvokeCompletedEventArgs.cs b/Sanford.Multimedia.Midi.Core/Sanford.Threading/InvokeCompletedEventArgs.cs new file mode 100644 index 0000000..83e0a11 --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/Sanford.Threading/InvokeCompletedEventArgs.cs @@ -0,0 +1,105 @@ +#region License + +/* Copyright (c) 2006 Leslie Sanford + * + * 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 + +#region Contact + +/* + * Leslie Sanford + * Email: jabberdabber@hotmail.com + */ + +#endregion + +using System; +using System.ComponentModel; +using System.Reflection; + +namespace Sanford.Threading +{ + /// + /// Represents information about the InvokeCompleted event. + /// + public class InvokeCompletedEventArgs : AsyncCompletedEventArgs + { + private Delegate method; + + private object[] args; + + private object result; + + /// + /// Represents the delegate, objects and exceptions for the InvokeCompleted event. + /// + /// + /// Represents the delegate method used. + /// + /// + /// For any args to be used. + /// + /// + /// For any results that occur. + /// + /// + /// For any errors that may occur. + /// + public InvokeCompletedEventArgs(Delegate method, object[] args, object result, Exception error) + : base(error, false, null) + { + this.method = method; + this.args = args; + this.result = result; + } + + /// + /// Initializes the args as an object. + /// + public object[] GetArgs() + { + return args; + } + + /// + /// Initializes method as a delegate. + /// + public Delegate Method + { + get + { + return method; + } + } + + /// + /// Initializes result as an object. + /// + public object Result + { + get + { + return result; + } + } + } +} diff --git a/Sanford.Multimedia.Midi.Core/docs/Sanford.Multimedia.Midi.XML b/Sanford.Multimedia.Midi.Core/docs/Sanford.Multimedia.Midi.XML new file mode 100644 index 0000000..97fe04c --- /dev/null +++ b/Sanford.Multimedia.Midi.Core/docs/Sanford.Multimedia.Midi.XML @@ -0,0 +1,8208 @@ + + + + Sanford.Multimedia.Midi.Core + + + + + Represents a simple double-ended-queue collection of objects. + + + + + Initializes a new instance of the Deque class. + + + + + Initializes a new instance of the Deque class that contains + elements copied from the specified collection. + + + The ICollection to copy elements from. + + + + + Removes all objects from the Deque. + + + + + Determines whether or not an element is in the Deque. + + + The Object to locate in the Deque. + + + true if obj if found in the Deque; otherwise, + false. + + + + + Inserts an object at the front of the Deque. + + + The object to push onto the deque; + + + + + Inserts an object at the back of the Deque. + + + The object to push onto the deque; + + + + + Removes and returns the object at the front of the Deque. + + + The object at the front of the Deque. + + + The Deque is empty. + + + + + Removes and returns the object at the back of the Deque. + + + The object at the back of the Deque. + + + The Deque is empty. + + + + + Returns the object at the front of the Deque without removing it. + + + The object at the front of the Deque. + + + The Deque is empty. + + + + + Returns the object at the back of the Deque without removing it. + + + The object at the back of the Deque. + + + The Deque is empty. + + + + + Copies the Deque to a new array. + + + A new array containing copies of the elements of the Deque. + + + + + Returns a synchronized (thread-safe) wrapper for the Deque. + + + The Deque to synchronize. + + + A synchronized wrapper around the Deque. + + + + + Gets a value indicating whether access to the Deque is synchronized + (thread-safe). + + + + + Gets the number of elements contained in the Deque. + + + + + Copies the Deque elements to an existing one-dimensional Array, + starting at the specified array index. + + + The one-dimensional Array that is the destination of the elements + copied from Deque. The Array must have zero-based indexing. + + + The zero-based index in array at which copying begins. + + + + + Gets an object that can be used to synchronize access to the Deque. + + + + + Returns an enumerator that can iterate through the Deque. + + + An IEnumerator for the Deque. + + + + + Creates a shallow copy of the Deque. + + + A shallow copy of the Deque. + + + + + Represents a simple double-ended-queue collection of objects. + + + + + Initializes a new instance of the Deque class. + + + + + Initializes a new instance of the Deque class that contains + elements copied from the specified collection. + + + The collection whose elements are copied to the new Deque. + + + + + Removes all objects from the Deque. + + + + + Determines whether or not an element is in the Deque. + + + The Object to locate in the Deque. + + + true if obj if found in the Deque; otherwise, + false. + + + + + Inserts an object at the front of the Deque. + + + The object to push onto the deque; + + + + + Inserts an object at the back of the Deque. + + + The object to push onto the deque; + + + + + Removes and returns the object at the front of the Deque. + + + The object at the front of the Deque. + + + The Deque is empty. + + + + + Removes and returns the object at the back of the Deque. + + + The object at the back of the Deque. + + + The Deque is empty. + + + + + Returns the object at the front of the Deque without removing it. + + + The object at the front of the Deque. + + + The Deque is empty. + + + + + Returns the object at the back of the Deque without removing it. + + + The object at the back of the Deque. + + + The Deque is empty. + + + + + Copies the Deque to a new array. + + + A new array containing copies of the elements of the Deque. + + + + + Returns a synchronized (thread-safe) wrapper for the Deque. + + + The Deque to synchronize. + + + A synchronized wrapper around the Deque. + + + + + Gets a value indicating whether access to the Deque is synchronized + (thread-safe). + + + + + Gets the number of elements contained in the Deque. + + + + + Copies the Deque elements to an existing one-dimensional Array, + starting at the specified array index. + + + The one-dimensional Array that is the destination of the elements + copied from Deque. The Array must have zero-based indexing. + + + The zero-based index in array at which copying begins. + + + + + Gets an object that can be used to synchronize access to the Deque. + + + + + Returns an enumerator that can iterate through the Deque. + + + An IEnumerator for the Deque. + + + + + Creates a shallow copy of the Deque. + + + A shallow copy of the Deque. + + + + + Gets and returns the Enumerator. + + + + + Returns an enumerator that can iterate through the Deque. + + + An IEnumerator for the Deque. + + + + + Represents a list with undo/redo functionality. + + + The type of elements in the list. + + + + + The undoable construction list. + + + + + The collection list of undoables. + + + + + The capacity list of undoables. + + + + + Undoes the last operation. + + + true if the last operation was undone, false if there + are no more operations left to undo. + + + + + Redoes the last operation. + + + true if the last operation was redone, false if there + are no more operations left to redo. + + + + + Clears the undo/redo history. + + + + + Searches the entire list for an element using the default comparer. + + + + + Searches the entire list for an element using a specified comparer. + + + + + Searches a range of elements in the sorted list for an element using a specified comparer. + + + + + Determines whenever the list contains the undo/redo option. + + + + + Converts all the data that is being read into the option chosen. + + + + + If the data exists and matches, it returns the value as true. + + + + + Initiates trying to find the data that matches. + + + + + Initiates trying to find all the data results that match. + + + + + Finds the index to the data. + + + + + Finds the index to the data based on the start of the index. + + + + + Finds the index to the data based on the start of the index and the count. + + + + + Searches for an element that matches the conditions defined by the T in Predicate, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + + + + + Searches for an element that matches the conditions defined by the T in Predicate and extended from the start of the index, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + + + + + Searches for an element that matches the conditions defined by the T in Predicate and extended from the start of the index and to show a specific number of options, then returns the zero-based index of the last occurrence that matches the data if found, otherwise will be -1. + + + + + Searches for an element that matches the conditions defined by T, then returns the last element that matches, otherwise it will be T by default. + + + + + Searches for the item, then returns the last occurrence of the item in the list. + + + + + Searches for the item, then returns the last occurrence of the item within the range of elements in the list. + + + + + Searches for the item, then returns the last occurrence of the item within the range of elements in the list and contains a specified number of elements and ends at the specific index. + + + + + Determines whenever every element in the list matches the conditions set by the Predicate. + + + + + Copies the elements of the list to a new array. + + + + + Sets the capacity to the actual number of elements in the list, if the number is less than a threshold value. + + + + + Adds a range of elements to insert from the list with the number of elements. + + + + + Inserts the range of elements from the list index into the undo/redo manager. + + + + + Removes a range of elements to insert from the list with the number of elements. + + + + + Reverts any added element or any removed element from the list. + + + + + Reverts any added element or any removed element from the list and shows the number of elements. + + + + + The number of operations left to undo. + + + + + The number of operations left to redo. + + + + + Searches for a list of undo/redo functions via an index. + + + + + Inserts the undo/redo listed options from the index. + + + + + Allows to remove the undo/redo options listed by command. + + + + + Gets or sets the undo/redo options from the list. + + + + + Adds an undo/redo option to the list of undo/redo options. + + + + + Clears an undo/redo option from the list of undo/redo options. + + + + + Copies an undo/redo option from the list to an array. + + + + + Counts the list of undo/redo options from the list. + + + + + Checks if the list is read only, and returns if it is false. + + + + + Removes an undo/redo option from the list. + + + + + Gets an enumerator and returns an enumerator that iterates through the list. + + + + + This is the main command that will test the UndoableList. + + + + + Undoes the last operation. + + + true if the last operation was undone, false if there + are no more operations left to undo. + + + + + Redoes the last operation. + + + true if the last operation was redone, false if there + are no more operations left to redo. + + + + + Clears the undo/redo history. + + + + + The number of operations left to undo. + + + + + The number of operations left to redo. + + + + + Represents an array data structure. + + + + + Initialize an instance of the Array class with the specified array + length. + + + The length of the array. + + + + + Initializes a new instance of the Array class with the specified + head of the random access list and the length of the array. + + + The head of the random access list. + + + The length of the array. + + + + + Gets the value of the specified element in the current Array. + + + An integer that represents the position of the Array element to + get. + + + The value at the specified position in the Array. + + + index is outside the range of valid indexes for the current Array. + + + + + Sets the specified element in the current Array to the specified + value. + + + The new value for the specified element. + + + An integer that represents the position of the Array element to set. + + + A new array with the element at the specified position set to the + specified value. + + + index is outside the range of valid indexes for the current Array. + + + + + Gets an integer that represents the total number of elements in all + the dimensions of the Array. + + + + + Returns an IEnumerator for the Array. + + + An IEnumerator for the Array. + + + + + Represents a collection of elements accessible by index and supports + insertion and deletion. + + + + + Initializes the ArrayList class. + + + + + Initializes a new instance of the ArrayList class. + + + + + Initializes a new instance of the ArrayList class that contains + elements copied from the specified collection. + + + The ICollection whose elements are copied to the new list. + + + + + Initializes a new instance of the ArrayList class with the + specified root and count. + + + The root of the tree. + + + The number of items in the ArrayList. + + + + + Adds an object to the end of the ArrayList. + + + The Object to be added to the end of the ArrayList. + + + A new ArrayList object with the specified value added at the end. + + + + + Determines whether an element is in the ArrayList. + + + The Object to locate in the ArrayList. + + + true if item is found in the ArrayList; otherwise, + false. + + + + + Returns the zero-based index of the first occurrence of a value in + the ArrayList. + + + The Object to locate in the ArrayList. + + + The zero-based index of the first occurrence of value within the + ArrayList, if found; otherwise, -1. + + + + + Inserts an element into the ArrayList at the specified index. + + + The zero-based index at which value should be inserted. + + + The Object to insert. + + + A new ArrayList with the specified object inserted at the specified + index. + + + index is less than zero or index is greater than Count. + + + + + Removes the first occurrence of a specified object from the + ArrayList. + + + The Object to remove from the ArrayList. + + + A new ArrayList with the first occurrent of the specified object + removed. + + + + + Removes the element at the specified index of the ArrayList. + + + The zero-based index of the element to remove. + + + A new ArrayList with the element at the specified index removed. + + + index is less than zero or index is equal to or greater than Count. + + + + + Gets the value at the specified index. + + + The zero-based index of the element to get. + + + The value at the specified index. + + + index is less than zero or index is equal to or greater than Count. + + + + + Sets the value at the specified index. + + + The zero-based index of the element to set. + + + The value to set at the specified index. + + + A new ArrayList with the specified value set at the specified index. + + + index is less than zero or index is equal to or greater than Count. + + + + + Gets the number of elements contained in the ArrayList. + + + + + Returns an enumerator that can iterate through the ArrayList. + + + An IEnumerator that can be used to iterate through the ArrayList. + + + + + Provides functionality for iterating over an AVL tree. + + + + + Initializes a new instance of the AvlEnumerator class. + + + The root of the AVL tree to iterate over. + + + + + Initializes a new instance of the AvlEnumerator class. + + + The root of the AVL tree to iterate over. + + + The number of nodes in the tree. + + + + + Sets the enumerator to its initial position, which is before + the first element in the AVL tree. + + + + + Gets the current element in the AVL tree. + + + The enumerator is positioned before the first element in the AVL + tree or after the last element. + + + + + Advances the enumerator to the next element of the AVL tree. + + + true if the enumerator was successfully advanced to the + next element; false if the enumerator has passed the end + of the collection. + + + + + Represents a node in an AVL tree. + + + + + Initializes a new instance of the AvlNode class with the specified + data and left and right children. + + + The data for the node. + + + The left child. + + + The right child. + + + + + Removes the current node from the AVL tree. + + + The node to in the tree to replace the current node. + + + + + Balances the subtree represented by the node. + + + The root node of the balanced subtree. + + + + + Indicates whether or not the subtree the node represents is in + balance. + + + true if the subtree is in balance; otherwise, false. + + + + + Gets the balance factor of the subtree the node represents. + + + + + Gets the number of nodes in the subtree. + + + + + Gets the node's data. + + + + + Gets the height of the subtree the node represents. + + + + + Gets the node's left child. + + + + + Gets the node's right child. + + + + + Represents the functionality and properties of AVL nodes. + + + + + Removes the current node from the AVL tree. + + + The node to in the tree to replace the current node. + + + + + Balances the subtree represented by the node. + + + The root node of the balanced subtree. + + + + + Indicates whether or not the subtree the node represents is in + balance. + + + true if the subtree is in balance; otherwise, false. + + + + + Gets the balance factor of the subtree the node represents. + + + + + Gets the number of nodes in the subtree. + + + + + Gets the node's data. + + + + + Gets the height of the subtree the node represents. + + + + + Gets the node's left child. + + + + + Gets the node's right child. + + + + + Represents a null AVL node. + + + + + Removes the current node from the AVL tree. + + + The node to in the tree to replace the current node. + + + + + Balances the subtree represented by the node. + + + The root node of the balanced subtree. + + + + + Indicates whether or not the subtree the node represents is in + balance. + + + true if the subtree is in balance; otherwise, false. + + + + + Gets the balance factor of the subtree the node represents. + + + + + Gets the number of nodes in the subtree. + + + + + Gets the node's data. + + + + + Gets the height of the subtree the node represents. + + + + + Gets the node's left child. + + + + + Gets the node's right child. + + + + + Provides functionality for enumerating a RandomAccessList. + + + + + Initializes a new instance of the Enumerator with the specified + head of the list and the number of nodes in the list. + + + The head of the list. + + + The number of nodes in the list. + + + + + Sets the enumerator to its initial position, which is before + the first element in the random access list. + + + + + Gets the current element in the random access list. + + + The enumerator is positioned before the first element in the + random access list or after the last element. + + + + + Advances the enumerator to the next element in the random access + list. + + + true if the enumerator was successfully advanced to the + next element; false if the enumerator has passed the end + of the collection. + + + + + Represents the top nodes in a RandomAccessList. + + + + + Initializes a new instance of the RalTopNode with the specified + root of the tree this node represents and the next top node in the + list. + + + The root node of the tree this top node represents. + + + The next top node in the list. + + + + + Gets the value at the specified element in the random access list. + + + An integer that represents the position of the random access list + element to get. + + + The value at the specified position in the random access list. + + + + + Sets the specified element in the current random access list to the + specified value. + + + The new value for the specified element. + + + An integer that represents the position of the random access list + element to set. + + + A new random access list top node with the element at the specified + position set to the specified value. + + + + + Gets the root node represented by the top node. + + + + + Gets the next top node in the random access list. + + + + + Represents subtree nodes within random access lists. + + + + + Initializes an instance of the RandomAccessListNode with the + specified value, left child, and right child. + + + The value to store in the node. + + + The left child. + + + The right child. + + + + + Gets the value at the specified element in the random access list + subtree. + + + An integer that represents the position of the random access list + subtree element to get. + + + The value at the specified position in the random access list + subtree. + + + + + Sets the specified element in the current random access list + subtree to the specified value. + + + The new value for the specified element. + + + An integer that represents the position of the random access list + subtree element to set. + + + A new random access list tree node with the element at the specified + position set to the specified value. + + + + + Gets the number of nodes in the tree. + + + + + Gets the left child. + + + + + Gets the right child. + + + + + Gets the value represented by this node. + + + + + Implements Chris Okasaki's random access list. + + + + + Represents an empty random access list. + + + + + Initializes a new instance of the RandomAccessList class. + + + + + Initializes a new instance of the RandomAccessList class with the + specified first top node and the number of elements in the list. + + + The first top node in the list. + + + The number of nodes in the list. + + + + + Prepends a value to the random access list. + + + The value to prepend to the list. + + + A new random access list with the specified value prepended to the + list. + + + + + Gets the value at the specified position in the current + RandomAccessList. + + + An integer that represents the position of the RandomAccessList + element to get. + + + The value at the specified position in the RandomAccessList. + + + index is outside the range of valid indexes for the current + RandomAccessList. + + + + + Sets the specified element in the current RandomAccessList to the + specified value. + + + The new value for the specified element. + + + An integer that represents the position of the RandomAccessList + element to set. + + + A new RandomAccessList with the element at the specified position + set to the specified value. + + + index is outside the range of valid indexes for the current + RandomAccessList. + + + + + Gets the number of elements in the RandomAccessList. + + + + + Gets a RandomAccessList with first element of the current + RandomAccessList. + + + If the RandomAccessList is empty. + + + + + Gets a RandomAccessList with all but the first element of the + current RandomAccessList. + + + If the RandomAccessList is empty. + + + + + Returns an IEnumerator for the RandomAccessList. + + + An IEnumerator for the RandomAccessList. + + + + + Represents a collection of key-and-value pairs that are sorted by the + keys and are accessible by key. + + + + + An empty SortedList. + + + + + Initializes a new instance of the SortedList class that is empty + and is sorted according to the IComparable interface implemented by + each key added to the SortedList. + + + + + Initializes a new instance of the SortedList class that is empty + and is sorted according to the specified IComparer interface. + + + The IComparer implementation to use when comparing keys, or a null + reference to use the IComparable implementation of each key. + + + + + Initializes a new instance of the SortedList class with the + specified root node and the IComparer interface to use for sorting + keys. + + + The root of the AVL tree. + + + The IComparer implementation to use when comparing keys, or a null + reference to use the IComparable implementation of each key. + + + + + Adds an element with the specified key and value to the SortedList. + + + The key of the element to add. + + + The value of the element to add. The value can be a null reference. + + + A new SortedList with the specified key and value added to the + previous SortedList. + + + key is a null reference. + + + An element with the specified key already exists in the SortedList, + or The SortedList is set to use the IComparable interface, and key + does not implement the IComparable interface. + + + + + Determines whether the SortedList contains a specific key. + + + The key to locate in the SortedList. + + + true if the SortedList contains an element with the + specified key; otherwise, false. + + + + + Returns an IDictionaryEnumerator that can iterate through the + SortedList. + + + An IDictionaryEnumerator for the SortedList. + + + + + Removes the element with the specified key from SortedList. + + + + + The key of the element to remove. + + + key is a null reference. + + + The SortedList is set to use the IComparable interface, and key + does not implement the IComparable interface. + + + + + Gets the value associated with the specified key. + + + + + Gets the number of elements contained in the SortedList. + + + + + Provides functionality for iterating through a SortedList. + + + + + Initializes a new instance of the SortedListEnumerator class + with the specified root of the AVL tree to iterate over. + + + The root of the AVL tree the SortedList uses internally. + + + + + Represents a simple last-in-first-out collection of objects. + + + + + An empty Stack. + + + + + Initializes a new instance of the Stack class. + + + + + Initializes a new instance of the Stack class with the + specified top node and the number of elements in the stack. + + + The top node in the stack. + + + The number of elements in the stack. + + + + + Inserts an object at the top of the Stack. + + + The Object to push onto the Stack. + + + A new stack with the specified object on the top of the stack. + + + + + Removes the object at the top of the Stack. + + + A new stack with top of the previous stack removed. + + + The Stack is empty. + + + + + Gets the number of elements in the Stack. + + + + + Gets the top of the stack. + + + The Stack is empty. + + + + + Represents a node in the stack. + + + + + Provides functionality for iterating over the Stack class. + + + + + Initializes a new instance of the StackEnumerator class with + the specified stack to iterate over. + + + The Stack to iterate over. + + + + + Sets the enumerator to its initial position, which is before + the first element in the Stack. + + + + + Gets the current element in the Stack. + + + The enumerator is positioned before the first element of the + Stack or after the last element. + + + + + Advances the enumerator to the next element of the Stack. + + + + + + Returns an IEnumerator for the Stack. + + + An IEnumerator for the Stack. + + + + + Represents the priority queue data structure. + + + + + Initializes a new instance of the PriorityQueue class. + + + The PriorityQueue will cast its elements to the IComparable + interface when making comparisons. + + + + + Initializes a new instance of the PriorityQueue class with the + specified IComparer. + + + The IComparer to use for comparing and ordering elements. + + + If the specified IComparer is null, the PriorityQueue will cast its + elements to the IComparable interface when making comparisons. + + + + + Enqueues the specified element into the PriorityQueue. + + + The element to enqueue into the PriorityQueue. + + + If element is null. + + + + + Removes the element at the head of the PriorityQueue. + + + The element at the head of the PriorityQueue. + + + If Count is zero. + + + + + Removes the specified element from the PriorityQueue. + + + The element to remove. + + + If element is null + + + + + Returns a value indicating whether the specified element is in the + PriorityQueue. + + + The element to test. + + + true if the element is in the PriorityQueue; otherwise + false. + + + + + Returns the element at the head of the PriorityQueue without + removing it. + + + The element at the head of the PriorityQueue. + + + + + Removes all elements from the PriorityQueue. + + + + + Returns a synchronized wrapper of the specified PriorityQueue. + + + The PriorityQueue to synchronize. + + + A synchronized PriorityQueue. + + + If queue is null. + + + + + Tests the methods in the Priority Queue. + + + + + Gets a value indicating whenever PriorityQueue is synchronized. + + + + + Gets the number of elements contained in PriorityQueue. + + + + + Copies the elements of the PriorityQueue to an array, starting at a particular array index. + + + + + Gets an object that can be used to synchronize access to the PriorityQueue. + + + + + Gets the enumerator for the Priority Queue, then returns the enumerator through a collection. + + + + + Represents a collection of key-and-value pairs. + + + The SkipList class is an implementation of the IDictionary interface. It + is based on the data structure created by William Pugh. + + + + + Initializes a new instance of the SkipList class that is empty and + is sorted according to the IComparable interface implemented by + each key added to the SkipList. + + + Each key must implement the IComparable interface to be capable of + comparisons with every other key in the SortedList. The elements + are sorted according to the IComparable implementation of each key + added to the SkipList. + + + + + Initializes a new instance of the SkipList class that is empty and + is sorted according to the specified IComparer interface. + + + The IComparer implementation to use when comparing keys. + + + The elements are sorted according to the specified IComparer + implementation. If comparer is a null reference, the IComparable + implementation of each key is used; therefore, each key must + implement the IComparable interface to be capable of comparisons + with every other key in the SkipList. + + + + + Destructor. + + + + + Initializes the SkipList. + + + + + Returns a level value for a new SkipList node. + + + The level value for a new SkipList node. + + + + + Searches for the specified key. + + + The key to search for. + + + Returns true if the specified key is in the SkipList. + + + + + Searches for the specified key. + + + The key to search for. + + + A SkipList node to hold the results of the search. + + + Returns true if the specified key is in the SkipList. + + + + + Searches for the specified key. + + + The key to search for. + + + An array of nodes holding references to the places in the SkipList + search in which the search dropped down one level. + + + Returns true if the specified key is in the SkipList. + + + + + Searches for the specified key. + + + The key to search for. + + + A SkipList node to hold the results of the search. + + + An array of nodes holding references to the places in the SkipList + search in which the search dropped down one level. + + + Returns true if the specified key is in the SkipList. + + + + + Search for the specified key using a comparer. + + + The key to search for. + + + A SkipList node to hold the results of the search. + + + An array of nodes holding references to the places in the SkipList + search in which the search dropped down one level. + + + Returns true if the specified key is in the SkipList. + + + + + Search for the specified key using the IComparable interface + implemented by each key. + + + The key to search for. + + + A SkipList node to hold the results of the search. + + + An array of nodes holding references to the places in the SkipList + search in which the search dropped down one level. + + + Returns true if the specified key is in the SkipList. + + + Assumes each key inserted into the SkipList implements the + IComparable interface. + + If the specified key is in the SkipList, the curr parameter will + reference the node with the key. If the specified key is not in the + SkipList, the curr paramater will either hold the node with the + first key value greater than the specified key or it will have the + same value as the header indicating that the search reached the end + of the SkipList. + + + + + Inserts a key/value pair into the SkipList. + + + The key to insert into the SkipList. + + + The value to insert into the SkipList. + + + An array of nodes holding references to places in the SkipList in + which the search for the place to insert the new key/value pair + dropped down one level. + + + + + Represents a node in the SkipList. + + + + + Initializes an instant of a Node with its node level. + + + The node level. + + + + + Initializes an instant of a Node with its node level and + key/value pair. + + + The node level. + + + The key for the node. + + + The value for the node. + + + + + Key property. + + + + + Value property. + + + + + Node dictionary Entry property - contains key/value pair. + + + + + Disposes the Node. + + + + + Enumerates the elements of a skip list. + + + + + Initializes an instance of a SkipListEnumerator. + + + + + + Gets both the key and the value of the current dictionary + entry. + + + + + Gets the key of the current dictionary entry. + + + + + Gets the value of the current dictionary entry. + + + + + Advances the enumerator to the next element of the skip list. + + + true if the enumerator was successfully advanced to the next + element; false if the enumerator has passed the end of the + skip list. + + + + + Sets the enumerator to its initial position, which is before + the first element in the skip list. + + + + + Gets the current element in the skip list. + + + + + Adds an element with the provided key and value to the SkipList. + + + The Object to use as the key of the element to add. + + + The Object to use as the value of the element to add. + + + + + Removes all elements from the SkipList. + + + + + Determines whether the SkipList contains an element with the + specified key. + + + The key to locate in the SkipList. + + + true if the SkipList contains an element with the key; otherwise, + false. + + + + + Returns an IDictionaryEnumerator for the SkipList. + + + An IDictionaryEnumerator for the SkipList. + + + + + Removes the element with the specified key from the SkipList. + + + The key of the element to remove. + + + + + Gets a value indicating whether the SkipList has a fixed size. + + + + + Gets a value indicating whether the IDictionary is read-only. + + + + + Gets or sets the element with the specified key. This is the + indexer for the SkipList. + + + + + Gets an ICollection containing the keys of the SkipList. + + + + + Gets an ICollection containing the values of the SkipList. + + + + + Copies the elements of the SkipList to an Array, starting at a + particular Array index. + + + The one-dimensional Array that is the destination of the elements + copied from SkipList. + + + The zero-based index in array at which copying begins. + + + + + Gets the number of elements contained in the SkipList. + + + + + Gets a value indicating whether access to the SkipList is + synchronized (thread-safe). + + + + + Gets an object that can be used to synchronize access to the + SkipList. + + + + + Returns an enumerator that can iterate through the SkipList. + + + An IEnumerator that can be used to iterate through the collection. + + + + + Represents functionality for generating events for driving Sequence playback. + + + + + Occurs when an IClock generates a tick. + + + + + Occurs when an IClock starts generating Ticks. + + + When an IClock is started, it resets itself and generates ticks to + drive playback from the beginning of the Sequence. + + + + + Occurs when an IClock continues generating Ticks. + + + When an IClock is continued, it generates ticks to drive playback + from the current position within the Sequence. + + + + + Occurs when an IClock is stopped. + + + + + Gets a value indicating whether the IClock is running. + + + + + Determines the number of ticks. + + + + + Generates clock events internally. + + + + + Initializes a new instance of the MidiInternalClock class. + + + + + Initializes a new instance of MidiInternalClock class with a specified base and a newly named integer. + + + The timer period in which the MidiInternalClock will use to determine the amount of time. + + + + + Initializes a new instance of the MidiInternalClock class with the + specified IContainer. + + + The IContainer to which the MidiInternalClock will add itself. + + + + + Starts the MidiInternalClock. + + + + + Resumes tick generation from the current position. + + + + + Stops the MidiInternalClock. + + + + + Sets the amount of ticks determined by the integer. + + + + + Processes with the meta message determined, along with the tempo. + + + + + Disposes of the MidiInternalClock when closed. + + + + + Gets or sets the tempo in microseconds per beat. + + + + + Gets the ticks in microseconds per beat. + + + + + Initializes the Disposed event. + + + + + Initializes the Site functionality using ISite. + + + + + Performs the main Dispose functionality for when the application is closed. + + + + + Provides basic functionality for generating tick events with pulses per + quarter note resolution. + + + + + The default tempo in microseconds: 120bpm. + + + + + The minimum pulses per quarter note value. + + + + + Indicates whether the clock is running. + + + + + The PpqnClock determines how many ticks and timer period is used for the PPQN format. + + + The timerPeriod integer determines the amount of time there is. + + + + + Gets the tempos per beat. + + + + + Sets the tempos to be used per beat. + + + + + Resets the amount of ticks. + + + + + Generates the amount of ticks. + + + + + Calculates the amount of time that the timer will have. + + + + + Calculates the amount of ticks per clock. + + + + + An event that handles the ticks. + + + + + An event that starts the PPQN Clock. + + + + + An event that stops the PPQN Clock. + + + + + An event that continues the PPQN Clock. + + + + + An integer that gets and sets the PPQN Clock value. + + + + + An abstract integer that gets the amount of ticks. + + + + + An integer that determines the ticks per clock. + + + The amount of ticks per clock. + + + + + This event occurs when PPQN Clock generates a tick. + + + + + This event occurs when PPQN Clock is started and starts generating ticks. + + + + + This event occurs when PPQN Clock continues generating ticks. + + + + + This event occurs when PPQN Clock has stopped. + + + + + Checks if PPQN Clock is running. + + + + + Represents a MIDI device capable of receiving MIDI events. + + + + + Initializes a new instance of the InputDevice class with the + specified device ID. + + + + + The Input Device handler. + + + + + Disposes the data when closed. + + + + + Gets or sets a value indicating whether the midi events should be posted on the same synchronization context as the device constructor was called. + Default is true. If set to false the events are fired on the driver callback or the thread of the driver callback delegate queue, depending on the PostDriverCallbackToDelegateQueue property. + + + true if midi events should be posted on the same synchronization context as the device constructor was called; otherwise, false. + + + + + Occurs when any message was received. The underlying type of the message is as specific as possible. + Channel, Common, Realtime or SysEx. + + + + + Occurs when a short message was received. + + + + + Occurs when a channel message was received. + + + + + Occurs when a system ex message was received. + + + + + Occurs when a system common message was received. + + + + + Occurs when a system realtime message was received. + + + + + Occurs when a invalid short message was received. + + + + + Occurs when a invalid system ex message message was received. + + + + + Occurs when a short message was sent. + + + + + Occurs when a message was received. + + + + + Occurs when a channel message is received. + + + + + Occurs when a system ex message is received. + + + + + Occurs when a system common message is received. + + + + + Occurs when a system realtime message is received. + + + + + Occurs when an invalid short message is received. + + + + + Occurs when an invalid system ex message is received. + + + + + Gets or sets a value indicating whether the midi input driver callback should be posted on a delegate queue with its own thread. + Default is true. If set to false the driver callback directly calls the events for lowest possible latency. + + + true if the midi input driver callback should be posted on a delegate queue with its own thread; otherwise, false. + + + + + Creates a system ex buffer for MIDI headers. + + + + + Gets the Input Device handle. + + + + + Gets and sets the system ex buffer size. + + + + + Determines how many Input Devices there are. + + + + + Closes the MIDI input device. + + + + + Starts recording from the MIDI input device. + + + + + Stops recording from the MIDI input device. + + + + + Resets the MIDI input device. + + + + + Initializes the MIDI input device capabilities. + + + This will show the device ID for the MIDI input device. + + + + + When closed, all connections to the MIDI input device are disposed. + + + + + The exception that is thrown when a error occurs with the InputDevice + class. + + + + + Initializes a new instance of the InputDeviceException class with + the specified error code. + + + The error code. + + + + + Gets a message that describes the current exception. + + + + + Handles the MIDI Message Events. + + + This provides the basic functionality for all MIDI messages. + + + + + Represents MIDI input device capabilities. + + + + + Manufacturer identifier of the device driver for the Midi output + device. + + + + + Product identifier of the Midi output device. + + + + + Version number of the device driver for the Midi output device. The + high-order byte is the major version number, and the low-order byte + is the minor version number. + + + + + Product name. + + + + + Optional functionality supported by the device. + + + + + The base abstract class for all MIDI devices. + + + + + Size of the MidiHeader structure. + + + + + The main function for all MIDI devices. + + + + + Connects a MIDI InputDevice to a MIDI thru or OutputDevice, or + connects a MIDI thru device to a MIDI OutputDevice. + + + Handle to a MIDI InputDevice or a MIDI thru device (for thru + devices, this handle must belong to a MIDI OutputDevice). + + + Handle to the MIDI OutputDevice or thru device. + + + If an error occurred while connecting the two devices. + + + + + Disconnects a MIDI InputDevice from a MIDI thru or OutputDevice, or + disconnects a MIDI thru device from a MIDI OutputDevice. + + + Handle to a MIDI InputDevice or a MIDI thru device. + + + Handle to the MIDI OutputDevice to be disconnected. + + + If an error occurred while disconnecting the two devices. + + + + + The base class for all MIDI device exception classes. + + + + + This error occurs when the header is not prepared. + + + + + This error occurs when the MIDI player is still playing something. + + + + + This error occurs when there are no configured instruments. + + + + + This error occurs when the hardware is still busy. + + + + + This error occurs when the port is no longer connected. + + + + + This error occurs when there is an invalid MIF. + + + + + This error occurs when the operation is unsupported with open mode. + + + + + This error occurs when the through device is eating up a message. + + + + + This error is the last error in range. + + + + + Initializes a new instance of the DeviceException class with the + specified error code. + + + The error code. + + + + + Represents the Windows Multimedia MIDIHDR structure. + + + + + Pointer to MIDI data. + + + + + Size of the buffer. + + + + + Actual amount of data in the buffer. This value should be less than + or equal to the value given in the dwBufferLength member. + + + + + Custom user data. + + + + + Flags giving information about the buffer. + + + + + Reserved; do not use. + + + + + Reserved; do not use. + + + + + Offset into the buffer when a callback is performed. (This + callback is generated because the MEVT_F_CALLBACK flag is + set in the dwEvent member of the MidiEventArgs structure.) + This offset enables an application to determine which + event caused the callback. + + + + + Reserved; do not use. + + + + + Builds a pointer to a MidiHeader structure. + + + + + Initializes a new instance of the MidiHeaderBuilder. + + + + + Builds the pointer to the MidiHeader structure. + + + + + Initializes the MidiHeaderBuilder with the specified SysExMessage. + + + The SysExMessage to use for initializing the MidiHeaderBuilder. + + + + + Releases the resources associated with the built MidiHeader pointer. + + + + + Releases the resources associated with the specified MidiHeader pointer. + + + The MidiHeader pointer. + + + + + The length of the system exclusive buffer. + + + + + Gets the pointer to the MidiHeader. + + + + + Represents MIDI output device capabilities. + + + + + Manufacturer identifier of the device driver for the Midi output + device. + + + + + Product identifier of the Midi output device. + + + + + Version number of the device driver for the Midi output device. The + high-order byte is the major version number, and the low-order byte + is the minor version number. + + + + + Product name. + + + + + Flags describing the type of the Midi output device. + + + + + Number of voices supported by an internal synthesizer device. If + the device is a port, this member is not meaningful and is set + to 0. + + + + + Maximum number of simultaneous notes that can be played by an + internal synthesizer device. If the device is a port, this member + is not meaningful and is set to 0. + + + + + Channels that an internal synthesizer device responds to, where the + least significant bit refers to channel 0 and the most significant + bit to channel 15. Port devices that transmit on all channels set + this member to 0xFFFF. + + + + + Optional functionality supported by the device. + + + + + The event args class for no operations. + + + + + The function for the no operation events. + + + + + Gets and returns the data. + + + + + Represents a device capable of sending MIDI messages. + + + + + Initializes a new instance of the OutputDevice class. + + + + + When closed, disposes of the MIDI output device. + + + + + Closes the OutputDevice. + + + If an error occurred while closing the OutputDevice. + + + + + Resets the OutputDevice. + + + + + Sends the MIDI output channel device message. + + + + + Sends a system ex MIDI output device message. + + + + + Sends a system common MIDI output device message. + + + + + Gets or sets a value indicating whether the OutputDevice uses + a running status. + + + + + The exception that is thrown when a error occurs with the OutputDevice + class. + + + + + Initializes a new instance of the OutputDeviceException class with + the specified error code. + + + The error code. + + + + + Gets a message that describes the current exception. + + + + + This is an abstract class for MIDI output devices. + + + + + Handles resetting the MIDI output device. + + + + + Handles the MIDI output device short messages. + + + + + Handles preparing the headers for the MIDI output device. + + + + + Handles unpreparing the headers for the MIDI output device. + + + + + Handles the MIDI output device long message. + + + + + Obtains the MIDI output device caps. + + + + + Obtains the number of MIDI output devices. + + + + + A construct integer that tells the compiler that hexadecimal value 0x3C7 means MOM_OPEN. + + + + + A construct integer that tells the compiler that hexadecimal value 0x3C8 means MOM_CLOSE. + + + + + A construct integer that tells the compiler that hexadecimal value 0x3C9 means MOM_DONE. + + + + + This delegate is a generic delegate for the MIDI output devices. + + + + + Represents the method that handles messages from Windows. + + + + + For releasing buffers. + + + + + This object remains locked in place. + + + + + The number of buffers still in the queue. + + + + + Builds MidiHeader structures for sending system exclusive messages. + + + + + The device handle. + + + + + Base class for output devices with an integer. + + + Device ID is used here. + + + + + Disposes when it has been closed. + + + + + This dispose function will dispose all delegates that are queued when closed. + + + + + Sends the MIDI output channel device message. + + + + + Sends a short MIDI output channel device message. + + + + + Sends a system ex MIDI output channel device message. + + + + + Sends a system common MIDI output device message. + + + + + Sends a system realtime MIDI output device message. + + + + + Resets the MIDI output device. + + + + + Sends a MIDI output device message. + + + + + Initializes the MIDI output device capabilities. + + + + + Handles Windows messages. + + + + + Releases buffers. + + + + + When closed, disposes the object that is locked in place. + + + + + Handles the MIDI output device pointer. + + + + + Counts the number of MIDI output devices. + + + + + Sealed class stream for MIDI output devices. + + + + + Handles the event for no operations. + + + + + Stream for MIDI output devices. + + + + + Disposes the streams when closed. + + + + + When the application is closed, this will dispose of any streams. + + + + + Starts playing the stream. + + + + + Pauses playing the stream. + + + + + Stops playing the stream. + + + + + Resets the MIDI output device playing the stream. + + + + + Writes to the MIDI output device stream. + + + + + Writes the no operation for MIDI output device streams. + + + + + Clears out all the MIDI output device streams when done. + + + + + Initializes the amount of time for the MIDI output device stream. + + + + + Handles the messages for the MIDI output device streams. + + + + + Gets the size of the MIDI output device stream and sets the amount to be divided. + + + + + Gets the amount of tempo, then sets the tempo for the MIDI output device stream. + + + + + Defines constants representing the General MIDI instrument set. + + + + + Instrument sample: Acoustic Grand Piano. + + + + + Instrument sample: Bright Acoustic Piano. + + + + + Instrument sample: Electric Grand Piano. + + + + + Instrument sample: Honky Tonk Piano. + + + + + Instrument sample: Electric Piano 1. + + + + + Instrument sample: Electric Piano 2. + + + + + Instrument sample: Harpsichord. + + + + + Instrument sample: Clavinet. + + + + + Instrument sample: Celesta. + + + + + Instrument sample: Glockenspiel. + + + + + Instrument sample: Music Box. + + + + + Instrument sample: Vibraphone. + + + + + Instrument sample: Marimba. + + + + + Instrument sample: Xylophone. + + + + + Instrument sample: Tubular Bells. + + + + + Instrument sample: Dulcimer. + + + + + Instrument sample: Drawbar Organ. + + + + + Instrument sample: Percussive Organ. + + + + + Instrument sample: Rock Organ. + + + + + Instrument sample: Church Organ. + + + + + Instrument sample: Reed Organ. + + + + + Instrument sample: Accordion. + + + + + Instrument sample: Harmonica. + + + + + Instrument sample: Tango Accordion. + + + + + Instrument sample: Acoustic Guitar Nylon. + + + + + Instrument sample: Acoustic Guitar Steel. + + + + + Instrument sample: Electric Guitar Jazz. + + + + + Instrument sample: Electric Guitar Clean. + + + + + Instrument sample: Electric Guitar Muted. + + + + + Instrument sample: Overdriven Guitar. + + + + + Instrument sample: Distortion Guitar. + + + + + Instrument sample: Guitar Harmonics. + + + + + Instrument sample: Acoustic Bass. + + + + + Instrument sample: Electric Bass Finger. + + + + + Instrument sample: Electric Bass Pick. + + + + + Instrument sample: Fretless Bass. + + + + + Instrument sample: Slap Bass 1. + + + + + Instrument sample: Slap Bass 2. + + + + + Instrument sample: Synth Bass 1. + + + + + Instrument sample: Synth Bass 2. + + + + + Instrument sample: Violin. + + + + + Instrument sample: Viola. + + + + + Instrument sample: Cello. + + + + + Instrument sample: Contrabass. + + + + + Instrument sample: Tremolo Strings. + + + + + Instrument sample: Pizzicato Strings. + + + + + Instrument sample: Orchestral Harp. + + + + + Instrument sample: Timpani. + + + + + Instrument sample: String Ensemble 1. + + + + + Instrument sample: String Ensemble 2. + + + + + Instrument sample: Synth Strings 1. + + + + + Instrument sample: Synth Strings 2. + + + + + Instrument sample: Aah (Choir). + + + + + Instrument sample: Ooh (Voice). + + + + + Instrument sample: Synth Voice. + + + + + Instrument sample: Orchestra Hit. + + + + + Instrument sample: Trumpet. + + + + + Instrument sample: Trombone. + + + + + Instrument sample: Tuba. + + + + + Instrument sample: Muted Trumpet. + + + + + Instrument sample: French Horn. + + + + + Instrument sample: Brass Section. + + + + + Instrument sample: Synth Brass 1. + + + + + Instrument sample: Synth Brass 2. + + + + + Instrument sample: Soprano Saxophone. + + + + + Instrument sample: Alto Saxophone. + + + + + Instrument sample: Tenor Saxophone. + + + + + Instrument sample: Baritone Saxophone. + + + + + Instrument sample: Oboe. + + + + + Instrument sample: English Horn. + + + + + Instrument sample: Bassoon. + + + + + Instrument sample: Clarinet. + + + + + Instrument sample: Piccolo. + + + + + Instrument sample: Flute. + + + + + Instrument sample: Recorder. + + + + + Instrument sample: Pan Flute. + + + + + Instrument sample: Blown Bottle. + + + + + Instrument sample: Shakuhachi. + + + + + Instrument sample: Whistle. + + + + + Instrument sample: Ocarina. + + + + + Instrument sample: Lead 1 (Square). + + + + + Instrument sample: Lead 2 (Sawtooth). + + + + + Instrument sample: Lead 3 (Calliope). + + + + + Instrument sample: Lead 4 (Chiff). + + + + + Instrument sample: Lead 5 (Charang). + + + + + Instrument sample: Lead 6 (Voice). + + + + + Instrument sample: Lead 7 (Fifths). + + + + + Instrument sample: Lead 8 (Bass And Lead). + + + + + Instrument sample: Pad 1 (New Age). + + + + + Instrument sample: Pad 2 (Warm). + + + + + Instrument sample: Pad 3 (Polysynth). + + + + + Instrument sample: Pad 4 (Choir). + + + + + Instrument sample: Pad 5 (Bowed). + + + + + Instrument sample: Pad 6 (Metallic). + + + + + Instrument sample: Pad 7 (Halo). + + + + + Instrument sample: Pad 8 (Sweep). + + + + + Instrument sample: Fx 1 (Rain). + + + + + Instrument sample: Fx 2 (Soundtrack). + + + + + Instrument sample: Fx 3 (Crystal). + + + + + Instrument sample: Fx 4 (Atmosphere). + + + + + Instrument sample: Fx 5 (Brightness). + + + + + Instrument sample: Fx 6 (Goblins). + + + + + Instrument sample: Fx 7 (Echoes). + + + + + Instrument sample: Fx 8 (Sci-Fi). + + + + + Instrument sample: Sitar. + + + + + Instrument sample: Banjo. + + + + + Instrument sample: Shamisen. + + + + + Instrument sample: Koto. + + + + + Instrument sample: Kalimba. + + + + + Instrument sample: Bag Pipe. + + + + + Instrument sample: Fiddle. + + + + + Instrument sample: Shanai. + + + + + Instrument sample: Tinkle Bell. + + + + + Instrument sample: Agogo. + + + + + Instrument sample: Steel Drums. + + + + + Instrument sample: Woodblock. + + + + + Instrument sample: Taiko Drum. + + + + + Instrument sample: Melodic Tom. + + + + + Instrument sample: Synth Drum. + + + + + Instrument sample: Reverse Cymbal. + + + + + Instrument sample: Guitar Fret Noise. + + + + + Instrument sample: Breath Noise. + + + + + Instrument sample: Seashore. + + + + + Instrument sample: Bird Tweet. + + + + + Instrument sample: Telephone Ring. + + + + + Instrument sample: Helicopter. + + + + + Instrument sample: Applause. + + + + + Instrument sample: Gunshot. + + + + + Defines constants for ChannelMessage types. + + + + + Represents the note-off command type. + + + + + Represents the note-on command type. + + + + + Represents the poly pressure (aftertouch) command type. + + + + + Represents the controller command type. + + + + + Represents the program change command type. + + + + + Represents the channel pressure (aftertouch) command + type. + + + + + Represents the pitch wheel command type. + + + + + Defines constants for controller types. + + + + + The Bank Select coarse. + + + + + The Modulation Wheel coarse. + + + + + The Breath Control coarse. + + + + + The Foot Pedal coarse. + + + + + The Portamento Time coarse. + + + + + The Data Entry Slider coarse. + + + + + The Volume coarse. + + + + + The Balance coarse. + + + + + The Pan position coarse. + + + + + The Expression coarse. + + + + + The Effect Control 1 coarse. + + + + + The Effect Control 2 coarse. + + + + + The General Puprose Slider 1 + + + + + The General Puprose Slider 2 + + + + + The General Puprose Slider 3 + + + + + The General Puprose Slider 4 + + + + + The Bank Select fine. + + + + + The Modulation Wheel fine. + + + + + The Breath Control fine. + + + + + The Foot Pedal fine. + + + + + The Portamento Time fine. + + + + + The Data Entry Slider fine. + + + + + The Volume fine. + + + + + The Balance fine. + + + + + The Pan position fine. + + + + + The Expression fine. + + + + + The Effect Control 1 fine. + + + + + The Effect Control 2 fine. + + + + + The Hold Pedal 1. + + + + + The Portamento. + + + + + The Sustenuto Pedal. + + + + + The Soft Pedal. + + + + + The Legato Pedal. + + + + + The Hold Pedal 2. + + + + + The Sound Variation. + + + + + The Sound Timbre. + + + + + The Sound Release Time. + + + + + The Sound Attack Time. + + + + + The Sound Brightness. + + + + + The Sound Control 6. + + + + + The Sound Control 7. + + + + + The Sound Control 8. + + + + + The Sound Control 9. + + + + + The Sound Control 10. + + + + + The General Purpose Button 1. + + + + + The General Purpose Button 2. + + + + + The General Purpose Button 3. + + + + + The General Purpose Button 4. + + + + + The Effects Level. + + + + + The Tremolo Level. + + + + + The Chorus Level. + + + + + The Celeste Level. + + + + + The Phaser Level. + + + + + The Data Button Increment. + + + + + The Data Button Decrement. + + + + + The NonRegistered Parameter Fine. + + + + + The NonRegistered Parameter Coarse. + + + + + The Registered Parameter Fine. + + + + + The Registered Parameter Coarse. + + + + + The All Sound Off. + + + + + The All Controllers Off. + + + + + The Local Keyboard. + + + + + The All Notes Off. + + + + + The Omni Mode Off. + + + + + The Omni Mode On. + + + + + The Mono Operation. + + + + + The Poly Operation. + + + + + Represents MIDI channel messages. + + + + + Maximum value allowed for MIDI channels. + + + + + Initializes a new instance of the ChannelEventArgs class with the + specified command, MIDI channel, and data 1 values. + + + The command value. + + + The MIDI channel. + + + The data 1 value. + + + If midiChannel is less than zero or greater than 15. Or if + data1 is less than zero or greater than 127. + + + + + Initializes a new instance of the ChannelEventArgs class with the + specified command, MIDI channel, data 1, and data 2 values. + + + The command value. + + + The MIDI channel. + + + The data 1 value. + + + The data 2 value. + + + If midiChannel is less than zero or greater than 15. Or if + data1 or data 2 is less than zero or greater than 127. + + + + + Returns a value for the current ChannelEventArgs suitable for use in + hashing algorithms. + + + A hash code for the current ChannelEventArgs. + + + + + Determines whether two ChannelEventArgs instances are equal. + + + The ChannelMessageEventArgs to compare with the current ChannelEventArgs. + + + true if the specified object is equal to the current + ChannelMessageEventArgs; otherwise, false. + + + + + Returns a value indicating how many bytes are used for the + specified ChannelCommand. + + + The ChannelCommand value to test. + + + The number of bytes used for the specified ChannelCommand. + + + + + Unpacks the command value from the specified integer channel + message. + + + The message to unpack. + + + The command value for the packed message. + + + + + Unpacks the MIDI channel from the specified integer channel + message. + + + The message to unpack. + + + The MIDI channel for the pack message. + + + + + Packs the MIDI channel into the specified integer message. + + + The message into which the MIDI channel is packed. + + + The MIDI channel to pack into the message. + + + An integer message. + + + If midiChannel is less than zero or greater than 15. + + + + + Packs the command value into an integer message. + + + The message into which the command is packed. + + + The command value to pack into the message. + + + An integer message. + + + + + Gets the channel command value. + + + + + Gets the MIDI channel. + + + + + Gets the first data value. + + + + + Gets the second data value. + + + + + Gets the EventType. + + + + + The class that contains events for channel messages. + + + + + The function that contains events for channel messages. + + + + + Gets the channel messages. + + + + + This class declares invalid short message events. + + + + + Main function for when the invalid short message event is declared. + + + + + Gets and returns the message. + + + + + This class declares invalid exclusive system message events. + + + + + Main function for declared invalid exclusive system message events. + + + + + Gets and returns the message data. + + + + + Class for declaring metadata message events. + + + + + Main function for declaring metadata message events. + + + + + Gets and returns the message. + + + + + Class for MIDI events. + + + + + Gets and sets the ticks for the MIDI events. + + + + + Raw short message as int or byte array, useful when working with VST. + + + + + A short message event that calculates the absolute ticks. + + + + + A short message event that uses a timestamp and calculates the absolute ticks. + + + + + A short message event that calculates the status byte, data 1 byte, data 2 byte, and absolute ticks. + + + + + Gets and returns the message. + + + + + Returns the channel message event. + + + + + Returns the common system message event. + + + + + Returns the realtime system message event. + + + + + Class for system common message events. + + + + + Main function for system common message events. + + + + + Gets and returns the message. + + + + + Class for exclusive system message events. + + + + + Main function for exclusive system message events. + + + + + Gets and returns the message. + + + + + Class for system realtime message events. + + + + + Requests the start for the system realtime message event. + + + + + Requests to continue for the system realtime message event. + + + + + Requests to stop for the system realtime message event. + + + + + Requests the clock for the system realtime message event. + + + + + Requests the ticks for the system realtime message event. + + + + + Requests the active sense for the system realtime message event. + + + + + Requests to restart for the system realtime message event. + + + + + Gets and returns the message. + + + + + Defines constants representing MIDI message types. + + + + + Channel messages. + + + + + Exclusive system messages. + + + + + Common system messages. + + + + + Realtime system messages. + + + + + Metadata messages. + + + + + Short messages. + + + + + Represents the basic functionality for all MIDI messages. + + + + + Gets a byte array representation of the MIDI message. + + + A byte array representation of the MIDI message. + + + + + Gets the MIDI message's status value. + + + + + Gets the MIDI event's type. + + + + + Delta samples when the event should be processed in the next audio buffer. + Leave at 0 for realtime input to play as fast as possible. + Set to the desired sample in the next buffer if you play a midi sequence synchronized to the audio callback + + + + + Provides functionality for building ChannelMessages. + + + + + Initializes a new instance of the ChannelMessageBuilder class. + + + + + Initializes a new instance of the ChannelMessageBuilder class with + the specified ChannelMessageEventArgs. + + + The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder. + + + The ChannelMessageBuilder uses the specified ChannelMessageEventArgs to + initialize its property values. + + + + + Initializes the ChannelMessageBuilder with the specified + ChannelMessageEventArgs. + + + The ChannelMessageEventArgs to use for initializing the ChannelMessageBuilder. + + + + + Clears the ChannelMessageEventArgs cache. + + + + + Gets the number of messages in the ChannelMessageEventArgs cache. + + + + + Gets the built ChannelMessageEventArgs. + + + + + Gets or sets the ChannelMessageEventArgs as a packed integer. + + + + + Gets or sets the Command value to use for building the + ChannelMessageEventArgs. + + + + + Gets or sets the MIDI channel to use for building the + ChannelMessageEventArgs. + + + MidiChannel is set to a value less than zero or greater than 15. + + + + + Gets or sets the first data value to use for building the + ChannelMessageEventArgs. + + + Data1 is set to a value less than zero or greater than 127. + + + + + Gets or sets the second data value to use for building the + ChannelMessageEventArgs. + + + Data2 is set to a value less than zero or greater than 127. + + + + + Builds a ChannelMessageEventArgs. + + + + + Represents functionality for building MIDI messages. + + + + + Builds the MIDI message. + + + + + Builds key signature MetaMessages. + + + + + Initializes a new instance of the KeySignatureBuilder class. + + + + + Initializes a new instance of the KeySignatureBuilder class with + the specified key signature MetaMessage. + + + The key signature MetaMessage to use for initializing the + KeySignatureBuilder class. + + + + + Initializes the KeySignatureBuilder with the specified MetaMessage. + + + The key signature MetaMessage to use for initializing the + KeySignatureBuilder. + + + + + Gets or sets the key. + + + + + The build key signature MetaMessage. + + + + + Builds the key signature MetaMessage. + + + + + Provides functionality for building meta text messages. + + + + + Initializes a new instance of the MetaMessageTextBuilder class. + + + + + Initializes a new instance of the MetaMessageTextBuilder class with the + specified type. + + + The type of MetaMessage. + + + If the MetaMessage type is not a text based type. + + + The MetaMessage type must be one of the following text based + types: + + + Copyright + + + Cuepoint + + + DeviceName + + + InstrumentName + + + Lyric + + + Marker + + + ProgramName + + + Text + + + TrackName + + + If the MetaMessage is not a text based type, an exception + will be thrown. + + + + + Initializes a new instance of the MetaMessageTextBuilder class with the + specified type. + + + The type of MetaMessage. + + + The text string of MetaMessage. + + + If the MetaMessage type is not a text based type. + + + The MetaMessage type must be one of the following text based + types: + + + Copyright + + + Cuepoint + + + DeviceName + + + InstrumentName + + + Lyric + + + Marker + + + ProgramName + + + Text + + + TrackName + + + If the MetaMessage is not a text based type, an exception + will be thrown. + + + + + Initializes a new instance of the MetaMessageTextBuilder class with the + specified MetaMessage. + + + The MetaMessage to use for initializing the MetaMessageTextBuilder. + + + If the MetaMessage is not a text based type. + + + The MetaMessage must be one of the following text based types: + + + Copyright + + + Cuepoint + + + DeviceName + + + InstrumentName + + + Lyric + + + Marker + + + ProgramName + + + Text + + + TrackName + + + If the MetaMessage is not a text based type, an exception will be + thrown. + + + + + Initializes the MetaMessageTextBuilder with the specified MetaMessage. + + + The MetaMessage to use for initializing the MetaMessageTextBuilder. + + + If the MetaMessage is not a text based type. + + + + + Indicates whether or not the specified MetaType is a text based + type. + + + The MetaType to test. + + + true if the MetaType is a text based type; + otherwise, false. + + + + + Gets or sets the text for the MetaMessage. + + + + + Gets or sets the MetaMessage type. + + + If the type is not a text based type. + + + + + Gets the built MetaMessage. + + + + + Builds the text MetaMessage. + + + + + Provides functionality for building song position pointer messages. + + + + + Initializes a new instance of the SongPositionPointerBuilder class. + + + + + Initializes a new instance of the SongPositionPointerBuilder class + with the specified song position pointer message. + + + The song position pointer message to use for initializing the + SongPositionPointerBuilder. + + + If message is not a song position pointer message. + + + + + Initializes the SongPositionPointerBuilder with the specified + SysCommonMessage. + + + The SysCommonMessage to use to initialize the + SongPositionPointerBuilder. + + + If the SysCommonMessage is not a song position pointer message. + + + + + Gets or sets the sequence position in ticks. + + + Value is set to less than zero. + + + Note: the position in ticks value is converted to the song position + pointer value. Since the song position pointer has a lower + resolution than the position in ticks, there is a probable loss of + resolution when setting the position in ticks value. + + + + + Gets or sets the PulsesPerQuarterNote object. + + + Value is not a multiple of 24. + + + + + Gets or sets the song position. + + + Value is set to less than zero. + + + + + Gets the built song position pointer message. + + + + + Builds a song position pointer message. + + + + + Provides functionality for building SysCommonMessages. + + + + + Initializes a new instance of the SysCommonMessageBuilder class. + + + + + Initializes a new instance of the SysCommonMessageBuilder class + with the specified SystemCommonMessage. + + + The SysCommonMessage to use for initializing the + SysCommonMessageBuilder. + + + The SysCommonMessageBuilder uses the specified SysCommonMessage to + initialize its property values. + + + + + Initializes the SysCommonMessageBuilder with the specified + SysCommonMessage. + + + The SysCommonMessage to use for initializing the + SysCommonMessageBuilder. + + + + + Clears the SysCommonMessageBuilder cache. + + + + + Gets the number of messages in the SysCommonMessageBuilder cache. + + + + + Gets the built SysCommonMessage. + + + + + Gets or sets the SysCommonMessage as a packed integer. + + + + + Gets or sets the type of SysCommonMessage. + + + + + Gets or sets the first data value to use for building the + SysCommonMessage. + + + Data1 is set to a value less than zero or greater than 127. + + + + + Gets or sets the second data value to use for building the + SysCommonMessage. + + + Data2 is set to a value less than zero or greater than 127. + + + + + Builds a SysCommonMessage. + + + + + Provides functionality for building tempo messages. + + + + + Initializes a new instance of the TempoChangeBuilder class. + + + + + Initialize a new instance of the TempoChangeBuilder class with the + specified MetaMessage. + + + The MetaMessage to use for initializing the TempoChangeBuilder class. + + + If the specified MetaMessage is not a tempo type. + + + The TempoChangeBuilder uses the specified MetaMessage to initialize + its property values. + + + + + Initializes the TempoChangeBuilder with the specified MetaMessage. + + + The MetaMessage to use for initializing the TempoChangeBuilder. + + + If the specified MetaMessage is not a tempo type. + + + + + Gets or sets the tempo. + + + Value is set to less than zero. + + + + + Gets the built message. + + + + + Builds the tempo change MetaMessage. + + + + + Provides easy to use functionality for time signature MetaMessages. + + + + + Initializes a new instance of the TimeSignatureBuilder class. + + + + + Initializes a new instance of the TimeSignatureBuilder class with the + specified MetaMessage. + + + The MetaMessage to use for initializing the TimeSignatureBuilder class. + + + If the specified MetaMessage is not a time signature type. + + + The TimeSignatureBuilder uses the specified MetaMessage to + initialize its property values. + + + + + Initializes the TimeSignatureBuilder with the specified MetaMessage. + + + The MetaMessage to use for initializing the TimeSignatureBuilder. + + + If the specified MetaMessage is not a time signature type. + + + + + Gets or sets the numerator. + + + Numerator is set to a value less than one. + + + + + Gets or sets the denominator. + + + Denominator is set to a value less than 2. + + + Denominator is set to a value that is not a power of 2. + + + + + Gets or sets the clocks per metronome click. + + + Clocks per metronome click determines how many MIDI clocks occur + for each metronome click. + + + + + Gets or sets how many thirty second notes there are for each + quarter note. + + + + + Gets the built message. + + + + + Builds the time signature MetaMessage. + + + + + Dispatches IMidiMessages to their corresponding sink. + + + + + Handles dispatching the channel message. + + + + + Handles dispatching the system ex message. + + + + + Handles dispatching the system common message. + + + + + Handles dispatching the system realtime message. + + + + + Handles dispatching the metadata message. + + + + + Dispatches IMidiMessages to their corresponding sink. + + + The MidiEvent to dispatch. + + + The Track to dispatch. + + + + + Dispatches the channel message. + + + + + Dispatches the system ex message. + + + + + Dispatches the system common message. + + + + + Dispatches the system realtime message. + + + + + Dispatches the metadata message. + + + + + Represents MetaMessage types. + + + + + Represents sequencer number type. + + + + + Represents the text type. + + + + + Represents the copyright type. + + + + + Represents the track name type. + + + + + Represents the instrument name type. + + + + + Represents the lyric type. + + + + + Represents the marker type. + + + + + Represents the cue point type. + + + + + Represents the program name type. + + + + + Represents the device name type. + + + + + Represents then end of track type. + + + + + Represents the tempo type. + + + + + Represents the Smpte offset type. + + + + + Represents the time signature type. + + + + + Represents the key signature type. + + + + + Represents the proprietary event type. + + + + + Represents MIDI meta messages. + + + Meta messages are MIDI messages that are stored in MIDI files. These + messages are not sent or received via MIDI but are read and + interpretted from MIDI files. They provide information that describes + a MIDI file's properties. For example, tempo changes are implemented + using meta messages. + + + + + The amount to shift data bytes when calculating the hash code. + + + + + Length in bytes for tempo meta message data. + + + + + Length in bytes for SMPTE offset meta message data. + + + + + Length in bytes for time signature meta message data. + + + + + Length in bytes for key signature meta message data. + + + + + End of track meta message. + + + + + Initializes a new instance of the MetaMessage class. + + + The type of MetaMessage. + + + The MetaMessage data. + + + The length of the MetaMessage is not valid for the MetaMessage type. + + + Each MetaMessage has type and length properties. For certain + types, the length of the message data must be a specific value. For + example, tempo messages must have a data length of exactly three. + Some MetaMessage types can have any data length. Text messages are + an example of a MetaMessage that can have a variable data length. + When a MetaMessage is created, the length of the data is checked + to make sure that it is valid for the specified type. If it is not, + an exception is thrown. + + + + + Gets a copy of the data bytes for this meta message. + + + A copy of the data bytes for this meta message. + + + + + Returns a value for the current MetaMessage suitable for use in + hashing algorithms. + + + A hash code for the current MetaMessage. + + + + + Determines whether two MetaMessage instances are equal. + + + The MetaMessage to compare with the current MetaMessage. + + + true if the specified MetaMessage is equal to the current + MetaMessage; otherwise, false. + + + + + Validates data length. + + + The MetaMessage type. + + + The length of the MetaMessage data. + + + true if the data length is valid for this type of + MetaMessage; otherwise, false. + + + + + Gets the element at the specified index. + + + index is less than zero or greater than or equal to Length. + + + + + Gets the length of the meta message. + + + + + Gets the type of meta message. + + + + + Gets the status value. + + + + + Gets the MetaMessage's MessageType. + + + + + MidiSignal provides all midi events from an input device. + + + + + Gets the device ID. + + + + + Create Midisignal with an input device which fires the events + + + + + + Disposes the input device when closed. + + + + + Initializes the MIDI events from device ID. + + + + + All incoming midi messages in short format + + + + + All incoming midi messages in short format + + + + + Channel messages like, note, controller, program, ... + + + + + SysEx messages + + + + + Midi timecode, song position, song select, tune request + + + + + Timing events, midi clock, start, stop, reset, active sense, tick + + + + + Takes a number of MidiEvents and merges them into a new single MidiEvent source + + + + + Gets the device ID and returns with a value of -3. + + + + + Merges the MIDI events. + + + + + Gets and returns the MIDI event sources from the events list. + + + + + Disposes of the MergeMidiEvents when closed. + + + + + Handles the event for when a MIDI message is received. + + + + + Handles the event for when a short message is received. + + + + + Handles the event for when a channel message is received. + + + + + Handles the event for when an exclusive system message is received. + + + + + Handles the event for when a common system message is received. + + + + + Handles the event for when a realtime system message is received. + + + + + An event source that combines all possible midi events + + + + + Gets the device identifier of the input devive. + Set it to any negative value for custom event sources. + + + + + Occurs when any message was received. The underlying type of the message should be as specific as possible. + Channel, Common, Realtime or SysEx. + + + + + All incoming midi short messages + + + + + Channel messages like, note, controller, program, ... + + + + + SysEx messages + + + + + Midi timecode, song position, song select, tune request + + + + + Timing events, midi clock, start, stop, reset, active sense, tick + + + + + Event sink that sends midi messages to an output device + + + + + Gets the device ID and returns with a value of -1. + + + + + Initializes and registers the MIDI output device events. + + + + + Disposes the underying output device and removes the events from the source + + + + + Sources and initializes the events for the MIDI output device. + + + + + Base abstract class for delta frames for MIDI messages. + + + + + Delta samples when the event should be processed in the next audio buffer. + Leave at 0 for realtime input to play as fast as possible. + Set to the desired sample in the next buffer if you play a midi sequence synchronized to the audio callback + + + + + Represents the basic class for all MIDI short messages. + + + MIDI short messages represent all MIDI messages except meta messages + and system exclusive messages. This includes channel messages, system + realtime messages, and system common messages. + + + + + The maximum value for data. + + + + + The maximum value for statuses. + + + + + Bit manipulation constant for data mask. + + + + + The message is set at 0. + + + + + Gets and returns the bytes for the MIDI short message. + + + + + Main function for MIDI short messages. + + + + + Initializes the message for the MIDI short message function. + + + + + Initializes the short message based on status and two bytes of data. + + + + + Gets the timestamp of the midi input driver in milliseconds since the midi input driver was started. + + + The timestamp in milliseconds since the midi input driver was started. + + + + + Gets the short message as a packed integer. + + + The message is packed into an integer value with the low-order byte + of the low-word representing the status value. The high-order byte + of the low-word represents the first data value, and the low-order + byte of the high-word represents the second data value. + + + + + Gets the messages's status value. + + + + + Gets the bytes for the MIDI short message. + + + The message for the short message. + + + + + Gets the message type and returns the message type with a short message. + + + + + Defines constants representing the various system common message types. + + + + + Represents the MTC system common message type. + + + + + Represents the song position pointer type. + + + + + Represents the song select type. + + + + + Represents the tune request type. + + + + + Represents MIDI system common messages. + + + + + Initializes a new instance of the SysCommonMessage class with the + specified type. + + + The type of SysCommonMessage. + + + + + Initializes a new instance of the SysCommonMessage class with the + specified type and the first data value. + + + The type of SysCommonMessage. + + + The first data value. + + + If data1 is less than zero or greater than 127. + + + + + Initializes a new instance of the SysCommonMessage class with the + specified type, first data value, and second data value. + + + The type of SysCommonMessage. + + + The first data value. + + + The second data value. + + + If data1 or data2 is less than zero or greater than 127. + + + + + Returns a value for the current SysCommonMessage suitable for use + in hashing algorithms. + + + A hash code for the current SysCommonMessage. + + + + + Determines whether two SysCommonMessage instances are equal. + + + The SysCommonMessage to compare with the current SysCommonMessage. + + + true if the specified SysCommonMessage is equal to the + current SysCommonMessage; otherwise, false. + + + + + Gets the SysCommonType. + + + + + Gets the first data value. + + + + + Gets the second data value. + + + + + Gets the MessageType. + + + + + Defines constants representing various system exclusive message types. + + + + + Represents the start of system exclusive message type. + + + + + Represents the continuation of a system exclusive message. + + + + + Represents MIDI system exclusive messages. + + + + + Maximum value for system exclusive channels. + + + + + Initializes a new instance of the SysExMessageEventArgs class with the + specified system exclusive data. + + + The system exclusive data. + + + The system exclusive data's status byte, the first byte in the + data, must have a value of 0xF0 or 0xF7. + + + + + Gets a byte array representation for the exclusive system message. + + + A clone of the byte array. + + + + + Copies the data to a byte array buffer and index. + + + + + Determines whenever the specified object is equal to the current object. + + + + + Returns the hash code for the current object. + + + + + Gets the timestamp of the midi input driver in milliseconds since the midi input driver was started. + + + The timestamp in milliseconds since the midi input driver was started. + + + + + Gets the element at the specified index. + + + If index is less than zero or greater than or equal to the length + of the message. + + + + + Gets the length of the system exclusive data. + + + + + Gets the system exclusive type. + + + + + Gets the status value. + + + + + Gets the MessageType. + + + + + Returns an enumerator for the exclusive system message. + + + + + Defines constants representing the various system realtime message types. + + + + + Represents the clock system realtime type. + + + + + Represents the tick system realtime type. + + + + + Represents the start system realtime type. + + + + + Represents the continue system realtime type. + + + + + Represents the stop system realtime type. + + + + + Represents the active sense system realtime type. + + + + + Represents the reset system realtime type. + + + + + Represents MIDI system realtime messages. + + + System realtime messages are MIDI messages that are primarily concerned + with controlling and synchronizing MIDI devices. + + + + + The instance of the system realtime start message. + + + + + The instance of the system realtime continue message. + + + + + The instance of the system realtime stop message. + + + + + The instance of the system realtime clock message. + + + + + The instance of the system realtime tick message. + + + + + The instance of the system realtime active sense message. + + + + + The instance of the system realtime reset message. + + + + + Returns a value for the current SysRealtimeMessage suitable for use in + hashing algorithms. + + + A hash code for the current SysRealtimeMessage. + + + + + Determines whether two SysRealtimeMessage instances are equal. + + + The SysRealtimeMessage to compare with the current SysRealtimeMessage. + + + true if the specified SysRealtimeMessage is equal to the current + SysRealtimeMessage; otherwise, false. + + + + + Gets the SysRealtimeType. + + + + + Gets the MessageType. + + + + + Converts a MIDI note number to its corresponding frequency. + + + + + The minimum value a note ID can have. + + + + + The maximum value a note ID can have. + + + + + Converts the specified note to a frequency. + + + The ID of the note to convert. + + + The frequency of the specified note. + + + + + Converts the specified frequency to a note. + + + The frequency to convert. + + + The ID of the note closest to the specified frequency. + + + + + The class that contains the channel chaser functionality. + + + + + Handles the chased events. + + + + + The main functions for ChannelChaser. + + + + + For processing channel messages. + + + + + Chases messages to an array so that it can determine between the MIDI channel value and data value, then detect the program change messages, pitch bend messages, channel pressure messages and poly pressure messages. + + + + + Resets all the channel chaser values. + + + + + Handles the chased event. + + + + + The ChannelStopper class, which provides pedal messages and sustenuto messages. + + + + + Handles the stopped event. + + + + + This function contains the pedal messages and sustenuto messages. + + + + + Processes the channel message. + + + + + Switches all sound off when stopped. + + + + + Resets all the messages. + + + + + Handles the event when the channels are stopped. + + + + + A class for chased events. + + + + + Main function for chased events. + + + + + Gets and returns messages. + + + + + A class for stopped events. + + + + + Main function for stopped events. + + + + + Gets and returns messages. + + + + + A class for MIDI events. + + + + + Gets and returns the amount of absolute ticks. + + + + + Gets the amount of delta ticks from absolute ticks, subtracted from the previous absolute ticks, if the previous tick is not null; otherwise, obtains the amount of absolute ticks. + + + + + Gets and returns the MIDI message. + + + + + Defintes constants representing SMPTE frame rates. + + + + + 24 SMPTE Frames. + + + + + 25 SMPTE Frames. + + + + + 29 SMPTE Frames. + + + + + 30 SMPTE Frames. + + + + + The different types of sequences. + + + + + The PPQN Sequence Type. + + + + + The SMPTE Sequence Type. + + + + + Represents MIDI file properties. + + + + + MIDI File Exception handles errors relating to the application being unable to read or write to a MIDI or Sequence. + + + + + The message that will display when an error occurs with a MIDI or Sequence format + + + + + This class initializes the recording sessions. + + + + + Main function for the recording sessions. + + + + + Builds the tracks, sorts and compares between a buffer and a timestamp, then creates a timestamped message with the amount of ticks. + + + + + Removes all elements from the list. + + + + + Gets and returns the track result for the recording session. + + + + + Records a channel message if the clock is running. + + + + + Records an external system message if the clock is running. + + + + + Represents a collection of Tracks. + + + + + When the loading of the sequence is complete. + + + + + When the loading of the sequence has changed. + + + + + When the sequence is saved. + + + + + When the save progress for the sequence has changed. + + + + + Initializes a new instance of the Sequence class. + + + + + Initializes a new instance of the Sequence class with the specified division. + + + The Sequence's division value. + + + + + Initializes a new instance of the Sequence class with the specified + file name of the MIDI file to load. + + + The name of the MIDI file to load. + + + + + Initializes a new instance of the Sequence class with the specified + file stream of the MIDI file to load. + + + The stream of the MIDI file to load. + + + + + Loads a MIDI file into the Sequence. + + + The MIDI file's name. + + + + + Loads a MIDI stream into the Sequence. + + + The MIDI file's stream. + + + + + Loads the sequence asynchronously. + + + + + Cancels loading the sequence asynchronously. + + + + + Saves the Sequence as a MIDI file. + + + The name to use for saving the MIDI file. + + + + + Saves the Sequence as a Stream. + + + The stream to use for saving the sequence. + + + + + Saves the sequence asynchronously. + + + + + Cancels saving the sequence asynchronously. + + + + + Gets the length in ticks of the Sequence. + + + The length in ticks of the Sequence. + + + The length in ticks of the Sequence is represented by the Track + with the longest length. + + + + + Gets the Track at the specified index. + + + The index of the Track to get. + + + The Track at the specified index. + + + + + Gets the Sequence's division value. + + + + + Gets or sets the Sequence's format value. + + + + + Gets the Sequence's type. + + + + + If the loader is busy. + + + + + Adds an item to the sequence. + + + + + Removes all items from the sequence. + + + + + Determines whenever the sequence contains a specific value. + + + true, if the item is found in the sequence. Otherwise, it'll be false. + + + + + Copies the elements of the sequence to an array, starting at a particular array index. + + + + + Gets the number of elements contained in the sequence. + + + The number of elements in the sequence. + + + + + Gets a value indicating whenever the sequence is read-only. + + + true, if the sequence is read-only; otherwise, false. + + + + + Removes the first occurrence of a specific object from the sequence. + + + true, if the item was successfully removed from the sequence; otherwise false. This method also returns false if the item is not found in the original sequence. + + + + + Returns an enumerator that iterates through the sequence. + + + + + Handles disposing of the sequence when the application is closed. + + + + + Gets or sets the site associated with the sequence. + + + + + Disposes the load when the application is closed. + + + + + This sequencer class allows for the sequencing of sequences. + + + + + Handles the event when the sequencer has finished playing the sequence. + + + + + Handles the event when a channel message is displayed when a sequence is played. + + + + + Handles the event when a system ex message is displayed when a sequence is played. + + + + + Handles the event when a metadata message is displayed when a sequence is played. + + + + + Handles the chased event in the sequencer. + + + + + Handles the event when sequencer stops playing. + + + + + The main sequencer function. + + + + + The function in which checks if the sequencer has been disposed. + + + + + The method for disposing the sequencer when the application is closed. + + + + + Starts the sequencer. + + + + + Continues the sequencer. + + + + + Stops the sequencer. + + + + + Handles the event for when the sequencer is finished playing. + + + + + Handles the event for when the sequencer is disposed. + + + + + The sequencer's playing position of the sequence. + + + + + The loaded sequence that represents a series of tracks. + + + + + Handles the disposed event. + + + + + Gets the site and sets the site with a value. + + + + + The dispose function for when the application is closed. + + + + + Represents a collection of MidiEvents and a MIDI track within a + Sequence. + + + + + Main function that represents the end of track MIDI event. + + + + + Inserts an IMidiMessage at the specified position in absolute ticks. + + + The position in the Track in absolute ticks in which to insert the + IMidiMessage. + + + The IMidiMessage to insert. + + + + + Clears all of the MidiEvents, with the exception of the end of track + message, from the Track. + + + + + Merges the specified Track with the current Track. + + + The Track to merge with. + + + + + Removes the MidiEvent at the specified index. + + + The index into the Track at which to remove the MidiEvent. + + + + + Gets the MidiEvent at the specified index. + + + The index of the MidiEvent to get. + + + The MidiEvent at the specified index. + + + + + A MIDI event that moves the track. + + + + + Gets the number of MidiEvents in the Track. + + + + + Gets the length of the Track in ticks. + + + + + Gets or sets the end of track meta message position offset. + + + + + Gets an object that can be used to synchronize access to the Track. + + + + + Main function for the track iterator. + + + + + Dispatches the track iterator. + + + + + A track iterator for the amount of ticks. + + + + + Tests the tracks. + + + + + Reads a track from a stream. + + + + + Writes a Track to a Stream. + + + + + Gets or sets the Track to write to the Stream. + + + + + This provides the functionality for the timer. + + + + + Gets a value indicating whether the Timer is running. + + + + + Gets the timer mode. + + + If the timer has already been disposed. + + + + + Period between timer events in milliseconds. + + + + + Resolution of the timer in milliseconds. + + + + + Gets or sets the object used to marshal event-handler calls. + + + + + Occurs when the Timer has started; + + + + + Occurs when the Timer has stopped; + + + + + Occurs when the time period has elapsed. + + + + + Starts the timer. + + + The timer has already been disposed. + + + The timer failed to start. + + + + + Stops timer. + + + If the timer has already been disposed. + + + + + Replacement for the Windows multimedia timer that also runs on Mono + + + + + Gets or sets the object used to marshal event-handler calls. + + + + + Queues and executes timer events in an internal worker thread. + + + + + The thread to execute the timer events + + + + + Defines constants representing the timing format used by the Time struct. + + + + + Defined in milliseconds. + + + + + Defined in samples. + + + + + Defined in bytes. + + + + + Defined in SMPTE. + + + + + Defined in MIDI. + + + + + Defined in ticks. + + + + + Represents the Windows Multimedia MMTIME structure. + + + + + Type. + + + + + Milliseconds. + + + + + Samples. + + + + + Byte count. + + + + + Ticks. + + + + + SMPTE hours. + + + + + SMPTE minutes. + + + + + SMPTE seconds. + + + + + SMPTE frames. + + + + + SMPTE frames per second. + + + + + SMPTE dummy. + + + + + SMPTE pad 1. + + + + + SMPTE pad 2. + + + + + MIDI song position pointer. + + + + + Defines constants for the multimedia Timer's event types. + + + + + Timer event occurs once. + + + + + Timer event occurs periodically. + + + + + Represents information about the multimedia Timer's capabilities. + + + + + Minimum supported period in milliseconds. + + + + + Maximum supported period in milliseconds. + + + + + The default timer capabilities. + + + + + Represents the Windows multimedia timer. + + + + + Occurs when the Timer has started; + + + + + Occurs when the Timer has stopped; + + + + + Occurs when the time period has elapsed. + + + + + Initialize class. + + + + + Initializes a new instance of the Timer class with the specified IContainer. + + + The IContainer to which the Timer will add itself. + + + + + Initializes a new instance of the Timer class. + + + + + Starts the timer. + + + The timer has already been disposed. + + + The timer failed to start. + + + + + Stops timer. + + + If the timer has already been disposed. + + + + + Gets or sets the object used to marshal event-handler calls. + + + + + Gets or sets the time between Tick events. + + + If the timer has already been disposed. + + + + + Gets or sets the timer resolution. + + + If the timer has already been disposed. + + + The resolution is in milliseconds. The resolution increases + with smaller values; a resolution of 0 indicates periodic events + should occur with the greatest possible accuracy. To reduce system + overhead, however, you should use the maximum value appropriate + for your application. + + + + + Gets the timer mode. + + + If the timer has already been disposed. + + + + + Gets a value indicating whether the Timer is running. + + + + + Gets the timer capabilities. + + + + + Frees timer resources. + + + + + The exception that is thrown when a timer fails to start. + + + + + Initializes a new instance of the TimerStartException class. + + + The error message that explains the reason for the exception. + + + + + Use this factory to create ITimer instances. + + Caller is responsible for Dispose. + + + + Creates an instance of ITimer + + Newly created instance of ITimer + + + + Defines the public abstract 'Device' class to interface System.IDisposable. + + + + + This protected construct, uses a Callback Function integer if it's equal to value 0x30000. + + + + + This protected construct, uses a Callback Event integer if it's equal to value 0x50000. + + + + + Synchronizes the context. + + + + + Outputs an error via ErrorEventArgs, if the EventHandler encounters an issue. + + + + + This public function utilises the Device ID integer with SynchronizationContext. + + + + + Utilises system garbage collector (System.GC) to dispose memory when the boolean value is set to true. + + + + + Error handling function. + + + + + Closes the MIDI device. + + + + + Resets the device. + + + + + Gets the device handle. + + + + + Calls the DeviceID public integer. + + + + + Declares the device as disposed. + + + + + Disposes of the device. + + + + + Refers the System.ApplicationException as DeviceException. + + + + No error. + + + Unspecified error. + + + Device ID out of range. + + + Driver failed enable. + + + Device already allocated. + + + Device handle is invalid. + + + No device driver present. + + + Memory allocation error. + + + Function isn't supported. + + + Error value out of range. + + + Invalid flag passed. + + + Invalid parameter passed. + + + + Handle being used.

+ Simultaneously on another.

+ Thread (eg callback).

+
+
+ + Specified alias not found. + + + Bad registry database. + + + Registry key not found. + + + Registry read error. + + + Registry write error. + + + Registry delete error. + + + Registry value not found. + + + Driver does not call DriverCallback. + + + Last error. + + + + Calls the Device Exception error code. + + + + + Public integer for the error code. + + + + + This will handle any errors relating to Sanford.Multimedia. + + + + + This represents the error itself. + + + + + Displays the error. + + + The error that is associated with the issue. + + + + + Defines constants for all major and minor keys. + + + + + The A♭ (A-Flat) Minor sequenced note. + + + + + The E♭ (E-Flat) Minor sequenced note. + + + + + The B♭ (B-Flat) Minor sequenced note. + + + + + The F Minor sequenced note. + + + + + The C Minor sequenced note. + + + + + The G Minor sequenced note. + + + + + The D Minor sequenced note. + + + + + The A Minor sequenced note. + + + + + The E Minor sequenced note. + + + + + The B Minor sequenced note. + + + + + The F♯ (F-Sharp) Minor sequenced note. + + + + + The C♯ (C-Sharp) Minor sequenced note. + + + + + The G♯ (G-Sharp) Minor sequenced note. + + + + + The D♯ (D-Sharp) Minor sequenced note. + + + + + The A♯ (A-Sharp) Minor sequenced note. + + + + + The C♭ (C-Flat) Major sequenced note. + + + + + The G♭ (G-Flat) Major sequenced note. + + + + + The D♭ (D-Flat) Major sequenced note. + + + + + The A♭ (A-Flat) Major sequenced note. + + + + + The E♭ (E-Flat) Major sequenced note. + + + + + The B♭ (B-Flat) Major sequenced note. + + + + + The F Major sequenced note. + + + + + The C Major sequenced note. + + + + + The G Major sequenced note. + + + + + The D Major sequenced note. + + + + + The A Major sequenced note. + + + + + The E Major sequenced note. + + + + + The B Major sequenced note. + + + + + The F♯ (F-Sharp) Major sequenced note. + + + + + The C♯ (C-Sharp) Major sequenced note. + + + + + Defines constants representing the 12 Note of the chromatic scale. + + + + + C natural. + + + + + C sharp. + + + + + D flat. + + + + + D natural. + + + + + D sharp. + + + + + E flat. + + + + + E natural. + + + + + F natural. + + + + + F sharp. + + + + + G flat. + + + + + G natural. + + + + + G sharp. + + + + + A flat. + + + + + A natural. + + + + + A sharp. + + + + + B flat. + + + + + B natural. + + + + + Provides basic implementation of the IAsyncResult interface. + + + + + Initializes a new instance of the AsyncResult object with the + specified owner of the AsyncResult object, the optional callback + delegate, and optional state object. + + + The owner of the AsyncResult object. + + + An optional asynchronous callback, to be called when the + operation is complete. + + + A user-provided object that distinguishes this particular + asynchronous request from other requests. + + + + + Signals that the operation has completed. + + + + + Gets the owner of this AsyncResult object. + + + + + This object provides the async state. + + + + + This handles the waiting time for the async. + + + + + Determines whenever the async completed synchronously or not. + + + + + Determines if the async has completed. + + + + + Represents an asynchronous queue of delegates. + + + + + Implements the IAsyncResult interface for the DelegateQueue class. + + + + + Occurs after a method has been invoked as a result of a call to + the BeginInvoke or BeginInvokePriority methods. + + + + + Occurs after a method has been invoked as a result of a call to + the Post and PostPriority methods. + + + + + Initializes a new instance of the DelegateQueue class. + + + + + Initializes a new instance of the DelegateQueue class with the specified IContainer object. + + + The IContainer to which the DelegateQueue will add itself. + + + + + Checks if DelegateQueue has been disposed. + + + + + Disposes of DelegateQueue when closed. + + + + + Executes the delegate on the main thread that this object executes on. + + + A Delegate to a method that takes parameters of the same number and + type that are contained in args. + + + An array of type Object to pass as arguments to the given method. + + + An IAsyncResult interface that represents the asynchronous operation + started by calling this method. + + + The delegate is placed at the beginning of the queue. Its invocation + takes priority over delegates already in the queue. + + + + + Executes the delegate on the main thread that this object executes on. + + + A Delegate to a method that takes parameters of the same number and + type that are contained in args. + + + An array of type Object to pass as arguments to the given method. + + + An IAsyncResult interface that represents the asynchronous operation + started by calling this method. + + + + The delegate is placed at the beginning of the queue. Its invocation + takes priority over delegates already in the queue. + + + Unlike BeginInvoke, this method operates synchronously, that is, it + waits until the process completes before returning. Exceptions raised + during the call are propagated back to the caller. + + + + + + Executes the delegate on the main thread that this object executes on. + + + An optional asynchronous callback, to be called when the method is invoked. + + + A user-provided object that distinguishes this particular asynchronous invoke request from other requests. + + + A Delegate to a method that takes parameters of the same number and + type that are contained in args. + + + An array of type Object to pass as arguments to the given method. + + + An IAsyncResult interface that represents the asynchronous operation + started by calling this method. + + + + + Dispatches an asynchronous message to this synchronization context. + + + The SendOrPostCallback delegate to call. + + + The object passed to the delegate. + + + The Post method starts an asynchronous request to post a message. + + + + + Dispatches an synchronous message to this synchronization context. + + + The SendOrPostCallback delegate to call. + + + The object passed to the delegate. + + + + + Raises the InvokeCompleted event. + + + + + Raises the PostCompleted event. + + + + + Raises the Disposed event. + + + + + Dispatches a synchronous message to this synchronization context. + + + The SendOrPostCallback delegate to call. + + + The object passed to the delegate. + + + The Send method starts an synchronous request to send a message. + + + + + Dispatches an asynchronous message to this synchronization context. + + + The SendOrPostCallback delegate to call. + + + The object passed to the delegate. + + + The Post method starts an asynchronous request to post a message. + + + + + Represents the method that handles the Disposed delegate of a DelegateQueue. + + + + + Gets or sets the ISite associated with the DelegateQueue. + + + + + Executes the delegate on the main thread that this DelegateQueue executes on. + + + A Delegate to a method that takes parameters of the same number and type that + are contained in args. + + + An array of type Object to pass as arguments to the given method. This can be + a null reference (Nothing in Visual Basic) if no arguments are needed. + + + An IAsyncResult interface that represents the asynchronous operation started + by calling this method. + + + The delegate is called asynchronously, and this method returns immediately. + You can call this method from any thread. If you need the return value from a process + started with this method, call EndInvoke to get the value. + If you need to call the delegate synchronously, use the Invoke method instead. + + + + + Waits until the process started by calling BeginInvoke completes, and then returns + the value generated by the process. + + + An IAsyncResult interface that represents the asynchronous operation started + by calling BeginInvoke. + + + An Object that represents the return value generated by the asynchronous operation. + + + This method gets the return value of the asynchronous operation represented by the + IAsyncResult passed by this interface. If the asynchronous operation has not completed, this method will wait until the result is available. + + + + + Executes the delegate on the main thread that this DelegateQueue executes on. + + + A Delegate that contains a method to call, in the context of the thread for the DelegateQueue. + + + An array of type Object that represents the arguments to pass to the given method. + + + An Object that represents the return value from the delegate being invoked, or a + null reference (Nothing in Visual Basic) if the delegate has no return value. + + + Unlike BeginInvoke, this method operates synchronously, that is, it waits until + the process completes before returning. Exceptions raised during the call are propagated + back to the caller. + Use this method when calling a method from a different thread to marshal the call + to the proper thread. + + + + + Gets a value indicating whether the caller must call Invoke. + + + true if the caller must call Invoke; otherwise, false. + + + This property determines whether the caller must call Invoke when making + method calls to this DelegateQueue. If you are calling a method from a different + thread, you must use the Invoke method to marshal the call to the proper thread. + + + + + Disposes of the DelegateQueue. + + + + + This class is used when the async events have been completed. + + + + + Main function for post completed events. + + + + + Gets and returns the callback. + + + + + Provides functionality for timestamped delegate invocation. + + + + + A constant value representing an unlimited number of delegate invocations. + + + + + Raised when a delegate is invoked. + + + + + Initializes a new instance of the DelegateScheduler class. + + + + + Initializes a new instance of the DelegateScheduler class with the + specified IContainer. + + + + + Checks if the DelegateScheduler has been disposed. + + + + + Disposes of DelegateScheduler when closed. + + + + + Adds a delegate to the DelegateScheduler. + + + The number of times the delegate should be invoked. + + + The time in milliseconds between delegate invocation. + + + + The delegate to invoke. + + The arguments to pass to the delegate when it is invoked. + + + A Task object representing the scheduled task. + + + If the DelegateScheduler has already been disposed. + + + If an unlimited count is desired, pass the DelegateScheduler.Infinity + constant as the count argument. + + + + + Removes the specified Task. + + + The Task to be removed. + + + If the DelegateScheduler has already been disposed. + + + + + Starts the DelegateScheduler. + + + If the DelegateScheduler has already been disposed. + + + + + Stops the DelegateScheduler. + + + If the DelegateScheduler has already been disposed. + + + + + Clears the DelegateScheduler of all tasks. + + + If the DelegateScheduler has already been disposed. + + + + + Raises the Disposed event. + + + + + Raises the InvokeCompleted event. + + + + + Gets or sets the interval in milliseconds in which the + DelegateScheduler polls its queue of delegates in order to + determine when they should run. + + + + + Gets a value indicating whether the DelegateScheduler is running. + + + + + Gets or sets the object used to marshal event-handler calls and delegate invocations. + + + + + When the event has been disposed. + + + + + Gets and returns the site, sets the site with a value. + + + + + The main dispose function that occurs when disposed. + + + + + Indicates the tasks to be compared. + + + + + Initializes returns the arguments. + + + + + Gets and returns the next timeout. + + + + + Gets and returns the count. + + + + + Gets and returns the method. + + + + + Gets and returns the timeout in milliseconds. + + + + + Compares the current instance with another object of the same type and returns an integer indicates whenever the current instance precedes, follows, or occurs in the same position in the sort order as the other object. + + + Compares between the subtracted next timeout and the task. + + + + + Represents information about the InvokeCompleted event. + + + + + Represents the delegate, objects and exceptions for the InvokeCompleted event. + + + Represents the delegate method used. + + + For any args to be used. + + + For any results that occur. + + + For any errors that may occur. + + + + + Initializes the args as an object. + + + + + Initializes method as a delegate. + + + + + Initializes result as an object. + + +
+
diff --git a/SoundFont2/SF2.cs b/SoundFont2/SF2.cs new file mode 100644 index 0000000..3bc550c --- /dev/null +++ b/SoundFont2/SF2.cs @@ -0,0 +1,150 @@ +using Kermalis.EndianBinaryIO; +using System.IO; + +namespace Kermalis.SoundFont2 +{ + public sealed class SF2 + { + private uint _size; + public InfoListChunk InfoChunk { get; } + public SdtaListChunk SoundChunk { get; } + public PdtaListChunk HydraChunk { get; } + + /// For creating + public SF2() + { + InfoChunk = new InfoListChunk(this); + SoundChunk = new SdtaListChunk(this); + HydraChunk = new PdtaListChunk(this); + } + + /// For reading + public SF2(string path) + { + var reader = new EndianBinaryReader(File.Open(path, FileMode.Open)); + string str = reader.ReadString(4, false); + if (str != "RIFF") + { + throw new InvalidDataException("RIFF header was not found at the start of the file."); + } + _size = reader.ReadUInt32(); + str = reader.ReadString(4, false); + if (str != "sfbk") + { + throw new InvalidDataException("sfbk header was not found at the expected offset."); + } + InfoChunk = new InfoListChunk(this, reader); + SoundChunk = new SdtaListChunk(this, reader); + HydraChunk = new PdtaListChunk(this, reader); + } + + public void Save(string path) + { + var writer = new EndianBinaryWriter(File.Open(path, FileMode.Create)); + { + AddTerminals(); + + writer.Write("RIFF", 4); + writer.Write(_size); + writer.Write("sfbk", 4); + + InfoChunk.Write(writer); + SoundChunk.Write(writer); + HydraChunk.Write(writer); + } + } + + + /// Returns sample index + public uint AddSample(short[] pcm16, string name, bool bLoop, uint loopPos, uint sampleRate, byte originalKey, sbyte pitchCorrection) + { + uint start = SoundChunk.SMPLSubChunk.AddSample(pcm16, bLoop, loopPos); + // If the sample is looped the standard requires us to add the 8 bytes from the start of the loop to the end + uint end, loopEnd, loopStart; + + uint len = (uint)pcm16.Length; + if (bLoop) + { + end = start + len + 8; + loopStart = start + loopPos; loopEnd = start + len; + } + else + { + end = start + len; + loopStart = 0; loopEnd = 0; + } + + return AddSampleHeader(name, start, end, loopStart, loopEnd, sampleRate, originalKey, pitchCorrection); + } + /// Returns instrument index + public uint AddInstrument(string name) + { + return HydraChunk.INSTSubChunk.AddInstrument(new SF2Instrument(name, (ushort)HydraChunk.IBAGSubChunk.Count)); + } + public void AddInstrumentBag() + { + HydraChunk.IBAGSubChunk.AddBag(new SF2Bag(this, false)); + } + public void AddInstrumentModulator() + { + HydraChunk.IMODSubChunk.AddModulator(new SF2ModulatorList()); + } + public void AddInstrumentGenerator() + { + HydraChunk.IGENSubChunk.AddGenerator(new SF2GeneratorList()); + } + public void AddInstrumentGenerator(SF2Generator generator, SF2GeneratorAmount amount) + { + HydraChunk.IGENSubChunk.AddGenerator(new SF2GeneratorList(generator, amount)); + } + public void AddPreset(string name, ushort preset, ushort bank) + { + HydraChunk.PHDRSubChunk.AddPreset(new SF2PresetHeader(name, preset, bank, (ushort)HydraChunk.PBAGSubChunk.Count)); + } + public void AddPresetBag() + { + HydraChunk.PBAGSubChunk.AddBag(new SF2Bag(this, true)); + } + public void AddPresetModulator() + { + HydraChunk.PMODSubChunk.AddModulator(new SF2ModulatorList()); + } + public void AddPresetGenerator() + { + HydraChunk.PGENSubChunk.AddGenerator(new SF2GeneratorList()); + } + public void AddPresetGenerator(SF2Generator generator, SF2GeneratorAmount amount) + { + HydraChunk.PGENSubChunk.AddGenerator(new SF2GeneratorList(generator, amount)); + } + + private uint AddSampleHeader(string name, uint start, uint end, uint loopStart, uint loopEnd, uint sampleRate, byte originalKey, sbyte pitchCorrection) + { + return HydraChunk.SHDRSubChunk.AddSample(new SF2SampleHeader(name, start, end, loopStart, loopEnd, sampleRate, originalKey, pitchCorrection)); + } + private void AddTerminals() + { + AddSampleHeader("EOS", 0, 0, 0, 0, 0, 0, 0); + AddInstrument("EOI"); + AddInstrumentBag(); + AddInstrumentGenerator(); + AddInstrumentModulator(); + AddPreset("EOP", 0xFF, 0xFF); + AddPresetBag(); + AddPresetGenerator(); + AddPresetModulator(); + } + + internal void UpdateSize() + { + if (InfoChunk == null || SoundChunk == null || HydraChunk == null) + { + return; + } + _size = 4 + + InfoChunk.UpdateSize() + 8 + + SoundChunk.UpdateSize() + 8 + + HydraChunk.UpdateSize() + 8; + } + } +} diff --git a/SoundFont2/SF2Chunks.cs b/SoundFont2/SF2Chunks.cs new file mode 100644 index 0000000..9601304 --- /dev/null +++ b/SoundFont2/SF2Chunks.cs @@ -0,0 +1,1105 @@ +using Kermalis.EndianBinaryIO; +using System; +using System.Collections.Generic; + +namespace Kermalis.SoundFont2 +{ + public class SF2Chunk + { + protected readonly SF2 _sf2; + + /// Length 4 + public string ChunkName { get; } + /// Size in bytes + public uint Size { get; protected set; } + + protected SF2Chunk(SF2 inSf2, string name) + { + _sf2 = inSf2; + ChunkName = name; + } + protected SF2Chunk(SF2 inSf2, EndianBinaryReader reader) + { + _sf2 = inSf2; + ChunkName = reader.ReadString(4, false); + Size = reader.ReadUInt32(); + } + + internal virtual void Write(EndianBinaryWriter writer) + { + writer.Write(ChunkName, 4); + writer.Write(Size); + } + } + + public abstract class SF2ListChunk : SF2Chunk + { + ///Length 4 + public string ListChunkName { get; } + + protected SF2ListChunk(SF2 inSf2, string name) : base(inSf2, "LIST") + { + ListChunkName = name; + Size = 4; + } + protected SF2ListChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + ListChunkName = reader.ReadString(4, false); + } + + internal abstract uint UpdateSize(); + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(ListChunkName, 4); + } + } + + public sealed class SF2PresetHeader + { + public const uint Size = 38; + + /// Length 20 + public string PresetName { get; set; } + public ushort Preset { get; set; } + public ushort Bank { get; set; } + public ushort PresetBagIndex { get; set; } + // Reserved for future implementations + private readonly uint _library; + private readonly uint _genre; + private readonly uint _morphology; + + internal SF2PresetHeader(string name, ushort preset, ushort bank, ushort index) + { + PresetName = name; + Preset = preset; + Bank = bank; + PresetBagIndex = index; + } + internal SF2PresetHeader(EndianBinaryReader reader) + { + PresetName = reader.ReadString(20, true); + Preset = reader.ReadUInt16(); + Bank = reader.ReadUInt16(); + PresetBagIndex = reader.ReadUInt16(); + _library = reader.ReadUInt32(); + _genre = reader.ReadUInt32(); + _morphology = reader.ReadUInt32(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(PresetName, 20); + writer.Write(Preset); + writer.Write(Bank); + writer.Write(PresetBagIndex); + writer.Write(_library); + writer.Write(_genre); + writer.Write(_morphology); + } + + public override string ToString() + { + return $"Preset Header - Bank = {Bank}" + + $",\nPreset = {Preset}" + + $",\nName = \"{PresetName}\""; + } + } + + /// Covers sfPresetBag and sfInstBag + public sealed class SF2Bag + { + public const uint Size = 4; + + /// Index in list of generators + public ushort GeneratorIndex { get; set; } + /// Index in list of modulators + public ushort ModulatorIndex { get; set; } + + internal SF2Bag(SF2 inSf2, bool isPresetBag) + { + if (isPresetBag) + { + GeneratorIndex = (ushort)inSf2.HydraChunk.PGENSubChunk.Count; + ModulatorIndex = (ushort)inSf2.HydraChunk.PMODSubChunk.Count; + } + else + { + GeneratorIndex = (ushort)inSf2.HydraChunk.IGENSubChunk.Count; + ModulatorIndex = (ushort)inSf2.HydraChunk.IMODSubChunk.Count; + } + } + internal SF2Bag(EndianBinaryReader reader) + { + GeneratorIndex = reader.ReadUInt16(); + ModulatorIndex = reader.ReadUInt16(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(GeneratorIndex); + writer.Write(ModulatorIndex); + } + + public override string ToString() + { + return $"Bag - Generator index = {GeneratorIndex}" + + $",\nModulator index = {ModulatorIndex}"; + } + } + + /// Covers sfModList and sfInstModList + public sealed class SF2ModulatorList + { + public const uint Size = 10; + + public SF2Modulator ModulatorSource { get; set; } + public SF2Generator ModulatorDestination { get; set; } + public short ModulatorAmount { get; set; } + public SF2Modulator ModulatorAmountSource { get; set; } + public SF2Transform ModulatorTransform { get; set; } + + internal SF2ModulatorList() { } + internal SF2ModulatorList(EndianBinaryReader reader) + { + ModulatorSource = reader.ReadEnum(); + ModulatorDestination = reader.ReadEnum(); + ModulatorAmount = reader.ReadInt16(); + ModulatorAmountSource = reader.ReadEnum(); + ModulatorTransform = reader.ReadEnum(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(ModulatorSource); + writer.Write(ModulatorDestination); + writer.Write(ModulatorAmount); + writer.Write(ModulatorAmountSource); + writer.Write(ModulatorTransform); + } + + public override string ToString() + { + return $"Modulator List - Modulator source = {ModulatorSource}" + + $",\nModulator destination = {ModulatorDestination}" + + $",\nModulator amount = {ModulatorAmount}" + + $",\nModulator amount source = {ModulatorAmountSource}" + + $",\nModulator transform = {ModulatorTransform}"; + } + } + + public sealed class SF2GeneratorList + { + public const uint Size = 4; + + public SF2Generator Generator { get; set; } + public SF2GeneratorAmount GeneratorAmount { get; set; } + + internal SF2GeneratorList() { } + internal SF2GeneratorList(SF2Generator generator, SF2GeneratorAmount amount) + { + Generator = generator; + GeneratorAmount = amount; + } + internal SF2GeneratorList(EndianBinaryReader reader) + { + Generator = reader.ReadEnum(); + GeneratorAmount = new SF2GeneratorAmount { Amount = reader.ReadInt16() }; + } + + public void Write(EndianBinaryWriter writer) + { + writer.Write(Generator); + writer.Write(GeneratorAmount.Amount); + } + + public override string ToString() + { + return $"Generator List - Generator = {Generator}" + + $",\nGenerator amount = \"{GeneratorAmount}\""; + } + } + + public sealed class SF2Instrument + { + public const uint Size = 22; + + /// Length 20 + public string InstrumentName { get; set; } + public ushort InstrumentBagIndex { get; set; } + + internal SF2Instrument(string name, ushort index) + { + InstrumentName = name; + InstrumentBagIndex = index; + } + internal SF2Instrument(EndianBinaryReader reader) + { + InstrumentName = reader.ReadString(20, true); + InstrumentBagIndex = reader.ReadUInt16(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(InstrumentName, 20); + writer.Write(InstrumentBagIndex); + } + + public override string ToString() + { + return $"Instrument - Name = \"{InstrumentName}\""; + } + } + + public sealed class SF2SampleHeader + { + public const uint Size = 46; + + /// Length 20 + public string SampleName { get; set; } + public uint Start { get; set; } + public uint End { get; set; } + public uint LoopStart { get; set; } + public uint LoopEnd { get; set; } + public uint SampleRate { get; set; } + public byte OriginalKey { get; set; } + public sbyte PitchCorrection { get; set; } + public ushort SampleLink { get; set; } + public SF2SampleLink SampleType { get; set; } + + internal SF2SampleHeader(string name, uint start, uint end, uint loopStart, uint loopEnd, uint sampleRate, byte originalKey, sbyte pitchCorrection) + { + SampleName = name; + Start = start; + End = end; + LoopStart = loopStart; + LoopEnd = loopEnd; + SampleRate = sampleRate; + OriginalKey = originalKey; + PitchCorrection = pitchCorrection; + SampleType = SF2SampleLink.MonoSample; + } + internal SF2SampleHeader(EndianBinaryReader reader) + { + SampleName = reader.ReadString(20, true); + Start = reader.ReadUInt32(); + End = reader.ReadUInt32(); + LoopStart = reader.ReadUInt32(); + LoopEnd = reader.ReadUInt32(); + SampleRate = reader.ReadUInt32(); + OriginalKey = reader.ReadByte(); + PitchCorrection = reader.ReadSByte(); + SampleLink = reader.ReadUInt16(); + SampleType = reader.ReadEnum(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(SampleName, 20); + writer.Write(Start); + writer.Write(End); + writer.Write(LoopStart); + writer.Write(LoopEnd); + writer.Write(SampleRate); + writer.Write(OriginalKey); + writer.Write(PitchCorrection); + writer.Write(SampleLink); + writer.Write(SampleType); + } + + public override string ToString() + { + return $"Sample - Name = \"{SampleName}\"" + + $",\nType = {SampleType}"; + } + } + + #region Sub-Chunks + + public sealed class VersionSubChunk : SF2Chunk + { + public SF2VersionTag Version { get; set; } + + internal VersionSubChunk(SF2 inSf2, string subChunkName) : base(inSf2, subChunkName) + { + Size = SF2VersionTag.Size; + inSf2.UpdateSize(); + } + internal VersionSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + Version = new SF2VersionTag(reader); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + Version.Write(writer); + } + + public override string ToString() + { + return $"Version Chunk - Revision = {Version}"; + } + } + + public sealed class HeaderSubChunk : SF2Chunk + { + public int MaxSize { get; } + private int _fieldTargetLength; + private string _field; + /// Length + public string Field + { + get => _field; + set + { + if (value.Length >= MaxSize) // Input too long; cut it down + { + _fieldTargetLength = MaxSize; + } + else if (value.Length % 2 == 0) // Even amount of characters + { + _fieldTargetLength = value.Length + 2; // Add two null-terminators to keep the byte count even + } + else // Odd amount of characters + { + _fieldTargetLength = value.Length + 1; // Add one null-terminator since that would make byte the count even + } + _field = value; + Size = (uint)_fieldTargetLength; + _sf2.UpdateSize(); + } + } + + internal HeaderSubChunk(SF2 inSf2, string subChunkName, int maxSize = 0x100) : base(inSf2, subChunkName) + { + MaxSize = maxSize; + } + internal HeaderSubChunk(SF2 inSf2, EndianBinaryReader reader, int maxSize = 0x100) : base(inSf2, reader) + { + MaxSize = maxSize; + _field = reader.ReadString((int)Size, true); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + writer.Write(_field, _fieldTargetLength); + } + + public override string ToString() + { + return $"Header Chunk - Name = \"{ChunkName}\"" + + $",\nField Max Size = {MaxSize}" + + $",\nField = \"{Field}\""; + } + } + + public sealed class SMPLSubChunk : SF2Chunk + { + private readonly List _samples = new List(); // Block of sample data + + internal SMPLSubChunk(SF2 inSf2) : base(inSf2, "smpl") { } + internal SMPLSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / sizeof(short); i++) + { + _samples.Add(reader.ReadInt16()); + } + } + + // Returns index of the start of the sample + internal uint AddSample(short[] pcm16, bool bLoop, uint loopPos) + { + uint start = (uint)_samples.Count; + + // Write wave + _samples.AddRange(pcm16); + + // If looping is enabled, write 8 samples from the loop point + if (bLoop) + { + // In case (loopPos + i) is greater than the sample length + uint max = (uint)pcm16.Length - loopPos; + for (uint i = 0; i < 8; i++) + { + _samples.Add(pcm16[loopPos + (i % max)]); + } + } + + // Write 46 empty samples + _samples.AddRange(new short[46]); + + Size = (uint)_samples.Count * sizeof(short); + _sf2.UpdateSize(); + return start; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + foreach (short s in _samples) + { + writer.Write(s); + } + } + + public override string ToString() + { + return $"Sample Data Chunk"; + } + } + + public sealed class PHDRSubChunk : SF2Chunk + { + private readonly List _presets = new List(); + public uint Count => (uint)_presets.Count; + + internal PHDRSubChunk(SF2 inSf2) : base(inSf2, "phdr") { } + internal PHDRSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2PresetHeader.Size; i++) + { + _presets.Add(new SF2PresetHeader(reader)); + } + } + + internal void AddPreset(SF2PresetHeader preset) + { + _presets.Add(preset); + Size = Count * SF2PresetHeader.Size; + _sf2.UpdateSize(); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _presets[i].Write(writer); + } + } + + public override string ToString() + { + return $"Preset Header Chunk - Preset count = {Count}"; + } + } + + public sealed class INSTSubChunk : SF2Chunk + { + private readonly List _instruments = new List(); + public uint Count => (uint)_instruments.Count; + + internal INSTSubChunk(SF2 inSf2) : base(inSf2, "inst") { } + internal INSTSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2Instrument.Size; i++) + { + _instruments.Add(new SF2Instrument(reader)); + } + } + + internal uint AddInstrument(SF2Instrument instrument) + { + _instruments.Add(instrument); + Size = Count * SF2Instrument.Size; + _sf2.UpdateSize(); + return Count - 1; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _instruments[i].Write(writer); + } + } + + public override string ToString() + { + return $"Instrument Chunk - Instrument count = {Count}"; + } + } + + public sealed class BAGSubChunk : SF2Chunk + { + private readonly List _bags = new List(); + public uint Count => (uint)_bags.Count; + + internal BAGSubChunk(SF2 inSf2, bool preset) : base(inSf2, preset ? "pbag" : "ibag") { } + internal BAGSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2Bag.Size; i++) + { + _bags.Add(new SF2Bag(reader)); + } + } + + internal void AddBag(SF2Bag bag) + { + _bags.Add(bag); + Size = Count * SF2Bag.Size; + _sf2.UpdateSize(); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _bags[i].Write(writer); + } + } + + public override string ToString() + { + return $"Bag Chunk - Name = \"{ChunkName}\"" + + $",\nBag count = {Count}"; + } + } + + public sealed class MODSubChunk : SF2Chunk + { + private readonly List _modulators = new List(); + public uint Count => (uint)_modulators.Count; + + internal MODSubChunk(SF2 inSf2, bool preset) : base(inSf2, preset ? "pmod" : "imod") { } + internal MODSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2ModulatorList.Size; i++) + { + _modulators.Add(new SF2ModulatorList(reader)); + } + } + + internal void AddModulator(SF2ModulatorList modulator) + { + _modulators.Add(modulator); + Size = Count * SF2ModulatorList.Size; + _sf2.UpdateSize(); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _modulators[i].Write(writer); + } + } + + public override string ToString() + { + return $"Modulator Chunk - Name = \"{ChunkName}\"" + + $",\nModulator count = {Count}"; + } + } + + public sealed class GENSubChunk : SF2Chunk + { + private readonly List _generators = new List(); + public uint Count => (uint)_generators.Count; + + internal GENSubChunk(SF2 inSf2, bool preset) : base(inSf2, preset ? "pgen" : "igen") { } + internal GENSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2GeneratorList.Size; i++) + { + _generators.Add(new SF2GeneratorList(reader)); + } + } + + internal void AddGenerator(SF2GeneratorList generator) + { + _generators.Add(generator); + Size = Count * SF2GeneratorList.Size; + _sf2.UpdateSize(); + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _generators[i].Write(writer); + } + } + + public override string ToString() + { + return $"Generator Chunk - Name = \"{ChunkName}\"" + + $",\nGenerator count = {Count}"; + } + } + + public sealed class SHDRSubChunk : SF2Chunk + { + private readonly List _samples = new List(); + public uint Count => (uint)_samples.Count; + + internal SHDRSubChunk(SF2 inSf2) : base(inSf2, "shdr") { } + internal SHDRSubChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + for (int i = 0; i < Size / SF2SampleHeader.Size; i++) + { + _samples.Add(new SF2SampleHeader(reader)); + } + } + + internal uint AddSample(SF2SampleHeader sample) + { + _samples.Add(sample); + Size = Count * SF2SampleHeader.Size; + _sf2.UpdateSize(); + return Count - 1; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + for (int i = 0; i < Count; i++) + { + _samples[i].Write(writer); + } + } + + public override string ToString() + { + return $"Sample Header Chunk - Sample header count = {Count}"; + } + } + + #endregion + + #region Main Chunks + + public sealed class InfoListChunk : SF2ListChunk + { + private readonly List _subChunks = new List(); + private const string DefaultEngine = "EMU8000"; + public string Engine + { + get + { + if (_subChunks.Find(s => s.ChunkName == "isng") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "isng") { Field = DefaultEngine }); + return DefaultEngine; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "isng") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "isng") { Field = value }); + } + } + } + + private const string DefaultBank = "General MIDI"; + public string Bank + { + get + { + if (_subChunks.Find(s => s.ChunkName == "INAM") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "INAM") { Field = DefaultBank }); + return DefaultBank; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "INAM") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "INAM") { Field = value }); + } + } + } + public string ROM + { + get + { + if (_subChunks.Find(s => s.ChunkName == "irom") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "irom") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "irom") { Field = value }); + } + } + } + public SF2VersionTag ROMVersion + { + get + { + if (_subChunks.Find(s => s.ChunkName == "iver") is VersionSubChunk chunk) + { + return chunk.Version; + } + else + { + return null; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "iver") is VersionSubChunk chunk) + { + chunk.Version = value; + } + else + { + _subChunks.Add(new VersionSubChunk(_sf2, "iver") { Version = value }); + } + } + } + public string Date + { + get + { + if (_subChunks.Find(s => s.ChunkName == "ICRD") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "ICRD") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "ICRD") { Field = value }); + } + } + } + public string Designer + { + get + { + if (_subChunks.Find(s => s.ChunkName == "IENG") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "IENG") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "IENG") { Field = value }); + } + } + } + public string Products + { + get + { + if (_subChunks.Find(s => s.ChunkName == "IPRD") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "IPRD") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "IPRD") { Field = value }); + } + } + } + public string Copyright + { + get + { + if (_subChunks.Find(s => s.ChunkName == "ICOP") is HeaderSubChunk icop) + { + return icop.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "ICOP") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "ICOP") { Field = value }); + } + } + } + + private const int CommentMaxSize = 0x10000; + public string Comment + { + get + { + if (_subChunks.Find(s => s.ChunkName == "ICMT") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "ICMT") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "ICMT", maxSize: CommentMaxSize) { Field = value }); + } + } + } + public string Tools + { + get + { + if (_subChunks.Find(s => s.ChunkName == "ISFT") is HeaderSubChunk chunk) + { + return chunk.Field; + } + else + { + return string.Empty; + } + } + set + { + if (_subChunks.Find(s => s.ChunkName == "ISFT") is HeaderSubChunk chunk) + { + chunk.Field = value; + } + else + { + _subChunks.Add(new HeaderSubChunk(_sf2, "ISFT") { Field = value }); + } + } + } + + internal InfoListChunk(SF2 inSf2) : base(inSf2, "INFO") + { + // Mandatory sub-chunks + _subChunks.Add(new VersionSubChunk(inSf2, "ifil") { Version = new SF2VersionTag(2, 1) }); + _subChunks.Add(new HeaderSubChunk(inSf2, "isng") { Field = DefaultEngine }); + _subChunks.Add(new HeaderSubChunk(inSf2, "INAM") { Field = DefaultBank }); + inSf2.UpdateSize(); + } + internal InfoListChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + long startOffset = reader.BaseStream.Position; + while (reader.BaseStream.Position < startOffset + Size - 4) // The 4 represents the INFO that was already read + { + // Peek 4 chars for the chunk name + string name = reader.ReadString(4, false); + reader.BaseStream.Position -= 4; + switch (name) + { + case "ICMT": _subChunks.Add(new HeaderSubChunk(inSf2, reader, maxSize: CommentMaxSize)); break; + case "ifil": + case "iver": _subChunks.Add(new VersionSubChunk(inSf2, reader)); break; + case "isng": + case "INAM": + case "ICRD": + case "IENG": + case "IPRD": + case "ICOP": + case "ISFT": + case "irom": _subChunks.Add(new HeaderSubChunk(inSf2, reader)); break; + default: throw new NotSupportedException($"Unsupported chunk name at 0x{reader.BaseStream.Position:X}: \"{name}\""); + } + } + } + + internal override uint UpdateSize() + { + Size = 4; + foreach (SF2Chunk sub in _subChunks) + { + Size += sub.Size + 8; + } + + return Size; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + foreach (SF2Chunk sub in _subChunks) + { + sub.Write(writer); + } + } + + public override string ToString() + { + return $"Info List Chunk - Sub-chunk count = {_subChunks.Count}"; + } + } + + public sealed class SdtaListChunk : SF2ListChunk + { + public SMPLSubChunk SMPLSubChunk { get; } + + internal SdtaListChunk(SF2 inSf2) : base(inSf2, "sdta") + { + SMPLSubChunk = new SMPLSubChunk(inSf2); + inSf2.UpdateSize(); + } + internal SdtaListChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + SMPLSubChunk = new SMPLSubChunk(inSf2, reader); + } + + internal override uint UpdateSize() + { + return Size = 4 + + SMPLSubChunk.Size + 8; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + SMPLSubChunk.Write(writer); + } + + public override string ToString() + { + return $"Sample Data List Chunk"; + } + } + + public sealed class PdtaListChunk : SF2ListChunk + { + public PHDRSubChunk PHDRSubChunk { get; } + public BAGSubChunk PBAGSubChunk { get; } + public MODSubChunk PMODSubChunk { get; } + public GENSubChunk PGENSubChunk { get; } + public INSTSubChunk INSTSubChunk { get; } + public BAGSubChunk IBAGSubChunk { get; } + public MODSubChunk IMODSubChunk { get; } + public GENSubChunk IGENSubChunk { get; } + public SHDRSubChunk SHDRSubChunk { get; } + + internal PdtaListChunk(SF2 inSf2) : base(inSf2, "pdta") + { + PHDRSubChunk = new PHDRSubChunk(inSf2); + PBAGSubChunk = new BAGSubChunk(inSf2, true); + PMODSubChunk = new MODSubChunk(inSf2, true); + PGENSubChunk = new GENSubChunk(inSf2, true); + INSTSubChunk = new INSTSubChunk(inSf2); + IBAGSubChunk = new BAGSubChunk(inSf2, false); + IMODSubChunk = new MODSubChunk(inSf2, false); + IGENSubChunk = new GENSubChunk(inSf2, false); + SHDRSubChunk = new SHDRSubChunk(inSf2); + inSf2.UpdateSize(); + } + internal PdtaListChunk(SF2 inSf2, EndianBinaryReader reader) : base(inSf2, reader) + { + PHDRSubChunk = new PHDRSubChunk(inSf2, reader); + PBAGSubChunk = new BAGSubChunk(inSf2, reader); + PMODSubChunk = new MODSubChunk(inSf2, reader); + PGENSubChunk = new GENSubChunk(inSf2, reader); + INSTSubChunk = new INSTSubChunk(inSf2, reader); + IBAGSubChunk = new BAGSubChunk(inSf2, reader); + IMODSubChunk = new MODSubChunk(inSf2, reader); + IGENSubChunk = new GENSubChunk(inSf2, reader); + SHDRSubChunk = new SHDRSubChunk(inSf2, reader); + } + + internal override uint UpdateSize() + { + return Size = 4 + + PHDRSubChunk.Size + 8 + + PBAGSubChunk.Size + 8 + + PMODSubChunk.Size + 8 + + PGENSubChunk.Size + 8 + + INSTSubChunk.Size + 8 + + IBAGSubChunk.Size + 8 + + IMODSubChunk.Size + 8 + + IGENSubChunk.Size + 8 + + SHDRSubChunk.Size + 8; + } + + internal override void Write(EndianBinaryWriter writer) + { + base.Write(writer); + PHDRSubChunk.Write(writer); + PBAGSubChunk.Write(writer); + PMODSubChunk.Write(writer); + PGENSubChunk.Write(writer); + INSTSubChunk.Write(writer); + IBAGSubChunk.Write(writer); + IMODSubChunk.Write(writer); + IGENSubChunk.Write(writer); + SHDRSubChunk.Write(writer); + } + + public override string ToString() + { + return $"Hydra List Chunk"; + } + } + + #endregion +} diff --git a/SoundFont2/SF2Types.cs b/SoundFont2/SF2Types.cs new file mode 100644 index 0000000..b297d80 --- /dev/null +++ b/SoundFont2/SF2Types.cs @@ -0,0 +1,142 @@ +using Kermalis.EndianBinaryIO; +using System.Runtime.InteropServices; + +namespace Kermalis.SoundFont2 +{ + /// SF2 v2.1 spec page 16 + public sealed class SF2VersionTag + { + public const uint Size = 4; + + public ushort Major { get; } + public ushort Minor { get; } + + public SF2VersionTag(ushort major, ushort minor) + { + Major = major; + Minor = minor; + } + internal SF2VersionTag(EndianBinaryReader reader) + { + Major = reader.ReadUInt16(); + Minor = reader.ReadUInt16(); + } + + internal void Write(EndianBinaryWriter writer) + { + writer.Write(Major); + writer.Write(Minor); + } + + public override string ToString() + { + return $"v{Major}.{Minor}"; + } + } + + /// SF2 spec v2.1 page 19 - Two bytes that can handle either two 8-bit values or a single 16-bit value + [StructLayout(LayoutKind.Explicit)] + public struct SF2GeneratorAmount + { + [FieldOffset(0)] public byte LowByte; + [FieldOffset(1)] public byte HighByte; + [FieldOffset(0)] public short Amount; + [FieldOffset(0)] public ushort UAmount; + + public override string ToString() + { + return $"BLo = {LowByte}, BHi = {HighByte}, Sh = {Amount}, U = {UAmount}"; + } + } + + /// SF2 v2.1 spec page 20 + public enum SF2SampleLink : ushort + { + MonoSample = 1, + RightSample = 2, + LeftSample = 4, + LinkedSample = 8, + RomMonoSample = 0x8001, + RomRightSample = 0x8002, + RomLeftSample = 0x8004, + RomLinkedSample = 0x8008 + } + + /// SF2 v2.1 spec page 38 + public enum SF2Generator : ushort + { + StartAddrsOffset = 0, + EndAddrsOffset = 1, + StartloopAddrsOffset = 2, + EndloopAddrsOffset = 3, + StartAddrsCoarseOffset = 4, + ModLfoToPitch = 5, + VibLfoToPitch = 6, + ModEnvToPitch = 7, + InitialFilterFc = 8, + InitialFilterQ = 9, + ModLfoToFilterFc = 10, + ModEnvToFilterFc = 11, + EndAddrsCoarseOffset = 12, + ModLfoToVolume = 13, + ChorusEffectsSend = 15, + ReverbEffectsSend = 16, + Pan = 17, + DelayModLFO = 21, + FreqModLFO = 22, + DelayVibLFO = 23, + FreqVibLFO = 24, + DelayModEnv = 25, + AttackModEnv = 26, + HoldModEnv = 27, + DecayModEnv = 28, + SustainModEnv = 29, + ReleaseModEnv = 30, + KeynumToModEnvHold = 31, + KeynumToModEnvDecay = 32, + DelayVolEnv = 33, + AttackVolEnv = 34, + HoldVolEnv = 35, + DecayVolEnv = 36, + SustainVolEnv = 37, + ReleaseVolEnv = 38, + KeynumToVolEnvHold = 39, + KeynumToVolEnvDecay = 40, + Instrument = 41, + KeyRange = 43, + VelRange = 44, + StartloopAddrsCoarseOffset = 45, + Keynum = 46, + Velocity = 47, + InitialAttenuation = 48, + EndloopAddrsCoarseOffset = 50, + CoarseTune = 51, + FineTune = 52, + SampleID = 53, + SampleModes = 54, + ScaleTuning = 56, + ExclusiveClass = 57, + OverridingRootKey = 58, + EndOper = 60 + } + + /// SF2 v2.1 spec page 50 + public enum SF2Modulator : ushort + { + None = 0, + NoteOnVelocity = 1, + NoteOnKey = 2, + PolyPressure = 10, + ChnPressure = 13, + PitchWheel = 14, + PitchWheelSensivity = 16 + } + + /// SF2 v2.1 spec page 52 + public enum SF2Transform : ushort + { + Linear = 0, + Concave = 1, + Convex = 2 + } +} diff --git a/SoundFont2/SoundFont2.csproj b/SoundFont2/SoundFont2.csproj new file mode 100644 index 0000000..8b7d4a4 --- /dev/null +++ b/SoundFont2/SoundFont2.csproj @@ -0,0 +1,29 @@ + + + + Kermalis + + SoundFont2 + SoundFont2 + SoundFont2 + Kermalis.SoundFont2 + 1.0.0.0 + ..\Build + + + + netcoreapp3.1 + + + + netcoreapp3.1 + Auto + none + false + + + + + + + diff --git a/VG Music Studio.sln b/VG Music Studio.sln index 660de87..5d96e60 100644 --- a/VG Music Studio.sln +++ b/VG Music Studio.sln @@ -1,9 +1,19 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27428.2002 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32804.467 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VG Music Studio", "VG Music Studio\VG Music Studio.csproj", "{97C8ACF8-66A3-4321-91D6-3E94EACA577F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VG Music Studio", "VG Music Studio\VG Music Studio.csproj", "{97C8ACF8-66A3-4321-91D6-3E94EACA577F}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sanford.Multimedia.Midi.Core", "Sanford.Multimedia.Midi.Core\Sanford.Multimedia.Midi.Core.csproj", "{C54D7E26-82EC-43BA-9CE7-A5BA1F851EDA}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EndianBinaryIO", "EndianBinaryIO\EndianBinaryIO.csproj", "{32FDD6E5-60A9-4FE4-AE73-AE6C41D81D26}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DLS2", "DLS2\DLS2.csproj", "{4DEFE207-7C02-4AF5-9710-06536A1EB2AB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoundFont2", "SoundFont2\SoundFont2.csproj", "{53B52F18-AEB4-47C8-A07B-9F3082A45964}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObjectListView2019", "ObjectListView\ObjectListView2019.csproj", "{6220611C-85D7-45B5-9857-45C0F0FE62A8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +25,26 @@ Global {97C8ACF8-66A3-4321-91D6-3E94EACA577F}.Debug|Any CPU.Build.0 = Debug|Any CPU {97C8ACF8-66A3-4321-91D6-3E94EACA577F}.Release|Any CPU.ActiveCfg = Release|Any CPU {97C8ACF8-66A3-4321-91D6-3E94EACA577F}.Release|Any CPU.Build.0 = Release|Any CPU + {C54D7E26-82EC-43BA-9CE7-A5BA1F851EDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C54D7E26-82EC-43BA-9CE7-A5BA1F851EDA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C54D7E26-82EC-43BA-9CE7-A5BA1F851EDA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C54D7E26-82EC-43BA-9CE7-A5BA1F851EDA}.Release|Any CPU.Build.0 = Release|Any CPU + {32FDD6E5-60A9-4FE4-AE73-AE6C41D81D26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {32FDD6E5-60A9-4FE4-AE73-AE6C41D81D26}.Debug|Any CPU.Build.0 = Debug|Any CPU + {32FDD6E5-60A9-4FE4-AE73-AE6C41D81D26}.Release|Any CPU.ActiveCfg = Release|Any CPU + {32FDD6E5-60A9-4FE4-AE73-AE6C41D81D26}.Release|Any CPU.Build.0 = Release|Any CPU + {4DEFE207-7C02-4AF5-9710-06536A1EB2AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4DEFE207-7C02-4AF5-9710-06536A1EB2AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4DEFE207-7C02-4AF5-9710-06536A1EB2AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4DEFE207-7C02-4AF5-9710-06536A1EB2AB}.Release|Any CPU.Build.0 = Release|Any CPU + {53B52F18-AEB4-47C8-A07B-9F3082A45964}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53B52F18-AEB4-47C8-A07B-9F3082A45964}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53B52F18-AEB4-47C8-A07B-9F3082A45964}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53B52F18-AEB4-47C8-A07B-9F3082A45964}.Release|Any CPU.Build.0 = Release|Any CPU + {6220611C-85D7-45B5-9857-45C0F0FE62A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6220611C-85D7-45B5-9857-45C0F0FE62A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6220611C-85D7-45B5-9857-45C0F0FE62A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6220611C-85D7-45B5-9857-45C0F0FE62A8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/VG Music Studio/Core/GBA/AlphaDream/Config.cs b/VG Music Studio/Core/GBA/AlphaDream/Config.cs index c168930..a925dc6 100644 --- a/VG Music Studio/Core/GBA/AlphaDream/Config.cs +++ b/VG Music Studio/Core/GBA/AlphaDream/Config.cs @@ -13,6 +13,7 @@ internal class Config : Core.Config { public readonly byte[] ROM; public readonly EndianBinaryReader Reader; + public readonly MemoryStream Stream; public readonly string GameCode; public readonly byte Version; @@ -214,7 +215,7 @@ public override string GetSongName(long index) public override void Dispose() { - Reader.Dispose(); + Stream.Dispose(); } } } diff --git a/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_DLS.cs b/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_DLS.cs index 222ee3f..b281c3d 100644 --- a/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_DLS.cs +++ b/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_DLS.cs @@ -1,5 +1,4 @@ using Kermalis.DLS2; -using System; using System.Collections.Generic; using System.Diagnostics; @@ -8,16 +7,16 @@ namespace Kermalis.VGMusicStudio.Core.GBA.AlphaDream internal sealed class SoundFontSaver_DLS { // Since every key will use the same articulation data, just store one instance - private static readonly Level2ArticulatorChunk _art2 = new Level2ArticulatorChunk + private static readonly Level2ArticulatorChunk _art2 = new Level2ArticulatorChunk() { - new Level2ArticulatorConnectionBlock { Destination = Level2ArticulatorDestination.LFOFrequency, Scale = 2786 }, - new Level2ArticulatorConnectionBlock { Destination = Level2ArticulatorDestination.VIBFrequency, Scale = 2786 }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.KeyNumber, Destination = Level2ArticulatorDestination.Pitch }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.Vibrato, Control = Level2ArticulatorSource.Modulation_CC1, Destination = Level2ArticulatorDestination.Pitch, BipolarSource = true, Scale = 0x320000 }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.Vibrato, Control = Level2ArticulatorSource.ChannelPressure, Destination = Level2ArticulatorDestination.Pitch, BipolarSource = true, Scale = 0x320000 }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.Pan_CC10, Destination = Level2ArticulatorDestination.Pan, BipolarSource = true, Scale = 0xFE0000 }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.ChorusSend_CC91, Destination = Level2ArticulatorDestination.Reverb, Scale = 0xC80000 }, - new Level2ArticulatorConnectionBlock { Source = Level2ArticulatorSource.Reverb_SendCC93, Destination = Level2ArticulatorDestination.Chorus, Scale = 0xC80000 } + new Level2ArticulatorConnectionBlock() { Destination = Level2ArticulatorDestination.LFOFrequency, Scale = 2786 }, + new Level2ArticulatorConnectionBlock() { Destination = Level2ArticulatorDestination.VIBFrequency, Scale = 2786 }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.KeyNumber, Destination = Level2ArticulatorDestination.Pitch }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.Vibrato, Control = Level2ArticulatorSource.Modulation_CC1, Destination = Level2ArticulatorDestination.Pitch, BipolarSource = true, Scale = 0x320000 }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.Vibrato, Control = Level2ArticulatorSource.ChannelPressure, Destination = Level2ArticulatorDestination.Pitch, BipolarSource = true, Scale = 0x320000 }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.Pan_CC10, Destination = Level2ArticulatorDestination.Pan, BipolarSource = true, Scale = 0xFE0000 }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.ChorusSend_CC91, Destination = Level2ArticulatorDestination.Reverb, Scale = 0xC80000 }, + new Level2ArticulatorConnectionBlock() { Source = Level2ArticulatorSource.Reverb_SendCC93, Destination = Level2ArticulatorDestination.Chorus, Scale = 0xC80000 } }; public static void Save(Config config, string path) @@ -62,7 +61,7 @@ private static void AddInfo(Config config, DLS dls) fmt.WaveInfo.BlockAlign = 1; fmt.FormatInfo.BitsPerSample = 8; // Create wave sample chunk and add loop if there is one - var wsmp = new WaveSampleChunk + var wsmp = new WaveSampleChunk() { UnityNote = 60, Options = WaveSampleOptions.NoTruncation | WaveSampleOptions.NoCompression @@ -78,7 +77,7 @@ private static void AddInfo(Config config, DLS dls) } // Get PCM sample byte[] pcm = new byte[sh.Length]; - Array.Copy(config.ROM, ofs + 0x10, pcm, 0, sh.Length); + System.Array.Copy(config.ROM, ofs + 0x10, pcm, 0, sh.Length); // Add int dlsIndex = waves.Count; @@ -145,13 +144,13 @@ void Add(ushort low, ushort high, ushort baseKey) lrgn.Add(new ListChunk("rgn2") { rgnh, - new WaveSampleChunk + new WaveSampleChunk() { UnityNote = baseKey, Options = WaveSampleOptions.NoTruncation | WaveSampleOptions.NoCompression, Loop = value.Item1.Loop }, - new WaveLinkChunk + new WaveLinkChunk() { Channels = WaveLinkChannels.Left, TableIndex = (uint)value.Item2 diff --git a/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_SF2.cs b/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_SF2.cs index 8fda0b9..6e0aa02 100644 --- a/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_SF2.cs +++ b/VG Music Studio/Core/GBA/AlphaDream/SoundFontSaver_SF2.cs @@ -10,17 +10,17 @@ internal sealed class SoundFontSaver_SF2 public static void Save(Config config, string path) { var sf2 = new SF2(); - AddInfo(config, sf2.InfoChunk); + AddInfo(config, sf2); Dictionary sampleDict = AddSamples(config, sf2); AddInstruments(config, sf2, sampleDict); sf2.Save(path); } - private static void AddInfo(Config config, InfoListChunk chunk) + private static void AddInfo(Config config, SF2 sf2) { - chunk.Bank = config.Name; - //chunk.Copyright = config.Creator; - chunk.Tools = Util.Utils.ProgramName + " by Kermalis"; + sf2.InfoChunk.Bank = config.Name; + //sf2.InfoChunk.Copyright = config.Creator; + sf2.InfoChunk.Tools = Util.Utils.ProgramName + " by Kermalis"; } private static Dictionary AddSamples(Config config, SF2 sf2) diff --git a/VG Music Studio/Core/GBA/MP2K/Config.cs b/VG Music Studio/Core/GBA/MP2K/Config.cs index 9a0ea23..4574393 100644 --- a/VG Music Studio/Core/GBA/MP2K/Config.cs +++ b/VG Music Studio/Core/GBA/MP2K/Config.cs @@ -13,6 +13,7 @@ internal class Config : Core.Config { public readonly byte[] ROM; public readonly EndianBinaryReader Reader; + public readonly MemoryStream Stream; public readonly string GameCode; public readonly byte Version; @@ -236,7 +237,7 @@ public override string GetSongName(long index) public override void Dispose() { - Reader.Dispose(); + Stream.Dispose(); } } } diff --git a/VG Music Studio/Core/GBA/MP2K/Player.cs b/VG Music Studio/Core/GBA/MP2K/Player.cs index b070842..e00bd21 100644 --- a/VG Music Studio/Core/GBA/MP2K/Player.cs +++ b/VG Music Studio/Core/GBA/MP2K/Player.cs @@ -842,7 +842,7 @@ public void SaveAsMIDI(string fileName, MIDISaveArgs args) } case TuneCommand tune: { - track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, trackIndex, 24, tune.Tune + 0x40)); + track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, trackIndex, 24, tune.Tune)); break; } case VoiceCommand voice: diff --git a/VG Music Studio/Core/Mixer.cs b/VG Music Studio/Core/Mixer.cs index e0a242f..d6766ae 100644 --- a/VG Music Studio/Core/Mixer.cs +++ b/VG Music Studio/Core/Mixer.cs @@ -1,4 +1,5 @@ using Kermalis.VGMusicStudio.UI; +using Kermalis.VGMusicStudio.Properties; using NAudio.CoreAudioApi; using NAudio.CoreAudioApi.Interfaces; using NAudio.Wave; @@ -11,6 +12,7 @@ internal abstract class Mixer : IAudioSessionEventsHandler, IDisposable public readonly bool[] Mutes = new bool[SongInfoControl.SongInfo.MaxTracks]; private IWavePlayer _out; private AudioSessionControl _appVolume; + private DeviceState _device = DeviceState.Unplugged; protected void Init(IWaveProvider waveProvider) { @@ -69,7 +71,31 @@ public void OnStateChanged(AudioSessionState state) } public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) { - throw new NotImplementedException(); + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonDeviceRemoval) + { + Exception ex = new Exception(); + FlexibleMessageBox.Show(ex, string.Format(Strings.AudioDeviceRemoved, _device)); + } + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonExclusiveModeOverride) + { + + } + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonFormatChanged) + { + + } + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonServerShutdown) + { + + } + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonSessionDisconnected) + { + + } + if (disconnectReason == AudioSessionDisconnectReason.DisconnectReasonSessionLogoff) + { + + } } public void SetVolume(float volume) { diff --git a/VG Music Studio/Core/NDS/DSE/Config.cs b/VG Music Studio/Core/NDS/DSE/Config.cs index 25f856c..6d4e4ca 100644 --- a/VG Music Studio/Core/NDS/DSE/Config.cs +++ b/VG Music Studio/Core/NDS/DSE/Config.cs @@ -22,8 +22,9 @@ public Config(string bgmPath) var songs = new Song[BGMFiles.Length]; for (int i = 0; i < BGMFiles.Length; i++) { - using (var reader = new EndianBinaryReader(File.OpenRead(BGMFiles[i]))) + using (var readfile = File.OpenRead(BGMFiles[i])) { + var reader = new EndianBinaryReader(readfile); SMD.Header header = reader.ReadObject(); songs[i] = new Song(i, $"{Path.GetFileNameWithoutExtension(BGMFiles[i])} - {new string(header.Label.TakeWhile(c => c != '\0').ToArray())}"); } diff --git a/VG Music Studio/Core/NDS/DSE/Player.cs b/VG Music Studio/Core/NDS/DSE/Player.cs index 4fa2b81..a534281 100644 --- a/VG Music Studio/Core/NDS/DSE/Player.cs +++ b/VG Music Studio/Core/NDS/DSE/Player.cs @@ -119,8 +119,9 @@ public void LoadSong(long index) string bgm = _config.BGMFiles[index]; _localSWD = new SWD(Path.ChangeExtension(bgm, "swd")); _smdFile = File.ReadAllBytes(bgm); - using (var reader = new EndianBinaryReader(new MemoryStream(_smdFile))) + using (var stream = new MemoryStream(_smdFile)) { + var reader = new EndianBinaryReader(stream); SMD.Header header = reader.ReadObject(); SMD.ISongChunk songChunk; switch (header.Version) diff --git a/VG Music Studio/Core/NDS/DSE/SWD.cs b/VG Music Studio/Core/NDS/DSE/SWD.cs index 4e9f984..9d62be7 100644 --- a/VG Music Studio/Core/NDS/DSE/SWD.cs +++ b/VG Music Studio/Core/NDS/DSE/SWD.cs @@ -323,8 +323,9 @@ public class LFOInfo public SWD(string path) { - using (var reader = new EndianBinaryReader(new MemoryStream(File.ReadAllBytes(path)))) + using (var stream = new MemoryStream(File.ReadAllBytes(path))) { + var reader = new EndianBinaryReader(stream); Type = reader.ReadString(4, false); Unknown = reader.ReadBytes(4); Length = reader.ReadUInt32(); diff --git a/VG Music Studio/Core/NDS/SDAT/SBNK.cs b/VG Music Studio/Core/NDS/SDAT/SBNK.cs index c0b016d..716fbd7 100644 --- a/VG Music Studio/Core/NDS/SDAT/SBNK.cs +++ b/VG Music Studio/Core/NDS/SDAT/SBNK.cs @@ -125,8 +125,9 @@ public void Write(EndianBinaryWriter ew) public SBNK(byte[] bytes) { - using (var er = new EndianBinaryReader(new MemoryStream(bytes))) + using (var stream = new MemoryStream(bytes)) { + var er = new EndianBinaryReader(stream); er.ReadIntoObject(this); } } diff --git a/VG Music Studio/Core/NDS/SDAT/SDAT.cs b/VG Music Studio/Core/NDS/SDAT/SDAT.cs index 0f4c4c7..b1df0a5 100644 --- a/VG Music Studio/Core/NDS/SDAT/SDAT.cs +++ b/VG Music Studio/Core/NDS/SDAT/SDAT.cs @@ -209,8 +209,9 @@ public void Write(EndianBinaryWriter ew) public SDAT(byte[] bytes) { - using (var er = new EndianBinaryReader(new MemoryStream(bytes))) + using (var stream = new MemoryStream(bytes)) { + var er = new EndianBinaryReader(stream); FileHeader = er.ReadObject(); SYMBOffset = er.ReadInt32(); SYMBLength = er.ReadInt32(); diff --git a/VG Music Studio/Core/NDS/SDAT/SSEQ.cs b/VG Music Studio/Core/NDS/SDAT/SSEQ.cs index 3d97b1e..e5ab386 100644 --- a/VG Music Studio/Core/NDS/SDAT/SSEQ.cs +++ b/VG Music Studio/Core/NDS/SDAT/SSEQ.cs @@ -14,8 +14,9 @@ internal class SSEQ public SSEQ(byte[] bytes) { - using (var er = new EndianBinaryReader(new MemoryStream(bytes))) + using (var stream = new MemoryStream(bytes)) { + var er = new EndianBinaryReader(stream); FileHeader = er.ReadObject(); BlockType = er.ReadString(4, false); BlockSize = er.ReadInt32(); diff --git a/VG Music Studio/Core/NDS/SDAT/SWAR.cs b/VG Music Studio/Core/NDS/SDAT/SWAR.cs index c7a982c..3a92651 100644 --- a/VG Music Studio/Core/NDS/SDAT/SWAR.cs +++ b/VG Music Studio/Core/NDS/SDAT/SWAR.cs @@ -45,8 +45,9 @@ public void Write(EndianBinaryWriter ew) public SWAR(byte[] bytes) { - using (var er = new EndianBinaryReader(new MemoryStream(bytes))) + using (var stream = new MemoryStream(bytes)) { + var er = new EndianBinaryReader(stream); FileHeader = er.ReadObject(); BlockType = er.ReadString(4, false); BlockSize = er.ReadInt32(); diff --git a/VG Music Studio/Core/VGMSDebug.cs b/VG Music Studio/Core/VGMSDebug.cs index 91bc091..0d73ae3 100644 --- a/VG Music Studio/Core/VGMSDebug.cs +++ b/VG Music Studio/Core/VGMSDebug.cs @@ -88,8 +88,9 @@ public static void GBAGameCodeScan(string path) { try { - using (var reader = new EndianBinaryReader(File.OpenRead(file))) + using (var readfile = File.OpenRead(file)) { + var reader = new EndianBinaryReader(readfile); string gameCode = reader.ReadString(3, false, 0xAC); char regionCode = reader.ReadChar(0xAF); byte version = reader.ReadByte(0xBC); diff --git a/VG Music Studio/Dependencies/DLS2.dll b/VG Music Studio/Dependencies/DLS2.dll deleted file mode 100644 index 1d3bc0c..0000000 Binary files a/VG Music Studio/Dependencies/DLS2.dll and /dev/null differ diff --git a/VG Music Studio/Dependencies/Sanford.Multimedia.Midi.dll b/VG Music Studio/Dependencies/Sanford.Multimedia.Midi.dll deleted file mode 100644 index 4e31c6b..0000000 Binary files a/VG Music Studio/Dependencies/Sanford.Multimedia.Midi.dll and /dev/null differ diff --git a/VG Music Studio/Dependencies/SoundFont2.dll b/VG Music Studio/Dependencies/SoundFont2.dll deleted file mode 100644 index f3f8008..0000000 Binary files a/VG Music Studio/Dependencies/SoundFont2.dll and /dev/null differ diff --git a/VG Music Studio/Properties/Strings.Designer.cs b/VG Music Studio/Properties/Strings.Designer.cs index 7153b37..6882a80 100644 --- a/VG Music Studio/Properties/Strings.Designer.cs +++ b/VG Music Studio/Properties/Strings.Designer.cs @@ -59,7 +59,18 @@ internal Strings() { resourceCulture = value; } } - + + /// + /// Informs whenever an audio output device was removed. + /// + internal static string AudioDeviceRemoved + { + get + { + return ResourceManager.GetString("AudioDeviceRemoved", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} key. /// diff --git a/VG Music Studio/Properties/Strings.resx b/VG Music Studio/Properties/Strings.resx index 8e4ae4a..228bc16 100644 --- a/VG Music Studio/Properties/Strings.resx +++ b/VG Music Studio/Properties/Strings.resx @@ -373,4 +373,8 @@ VoiceTable saved to {0}. {0} is the file name. + + An audio output device was {0}. {1} was disconnected. + {0} is the status of the device. {1} is the device itself + \ No newline at end of file diff --git a/VG Music Studio/UI/MainForm.cs b/VG Music Studio/UI/MainForm.cs index 761394f..71e452e 100644 --- a/VG Music Studio/UI/MainForm.cs +++ b/VG Music Studio/UI/MainForm.cs @@ -1,15 +1,19 @@ using Kermalis.VGMusicStudio.Core; using Kermalis.VGMusicStudio.Properties; using Kermalis.VGMusicStudio.Util; -using Microsoft.WindowsAPICodePack.Dialogs; -using Microsoft.WindowsAPICodePack.Taskbar; +//using Microsoft.WindowsAPICodePack.Dialogs; +//using Microsoft.WindowsAPICodePack.Taskbar; using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; using System.Windows.Forms; +using System.Windows.Interop; namespace Kermalis.VGMusicStudio.UI { @@ -45,7 +49,7 @@ internal class MainForm : ThemedForm private readonly ColorSlider _volumeBar, _positionBar; private readonly SongInfoControl _songInfo; private readonly ImageComboBox _songsComboBox; - private readonly ThumbnailToolBarButton _prevTButton, _toggleTButton, _nextTButton; + //private readonly ThumbnailToolBarButton _prevTButton, _toggleTButton, _nextTButton; #endregion @@ -149,17 +153,17 @@ private MainForm() Text = Utils.ProgramName; // Taskbar Buttons - if (TaskbarManager.IsPlatformSupported) + /*if (TaskbarManager.IsPlatformSupported) { - _prevTButton = new ThumbnailToolBarButton(Resources.IconPrevious, Strings.PlayerPreviousSong); + _prevTButton = new ToolStripButton(Resources.IconPrevious, Strings.PlayerPreviousSong); _prevTButton.Click += PlayPreviousSong; - _toggleTButton = new ThumbnailToolBarButton(Resources.IconPlay, Strings.PlayerPlay); + _toggleTButton = new ToolStripButton(Resources.IconPlay, Strings.PlayerPlay); _toggleTButton.Click += TogglePlayback; - _nextTButton = new ThumbnailToolBarButton(Resources.IconNext, Strings.PlayerNextSong); + _nextTButton = new ToolStripButton(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); } @@ -220,11 +224,19 @@ private void SongNumerical_ValueChanged(object sender, EventArgs e) 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); + + // When the song isn't a null value and is played if (song != null) { - Text = $"{Utils.ProgramName} - {song.Name}"; + Text = $"{Utils.ProgramName} - {song.Name}"; // Reads the song name from the .yaml file _songsComboBox.SelectedIndex = songs.IndexOf(song) + 1; // + 1 because the "Music" playlist is first in the combobox } + + // When the song is a null value and is played + if (song == null) + { + return; // Resets the music player and prevents the song from playing + } _positionBar.Maximum = Engine.Instance.Player.MaxTicks; _positionBar.LargeChange = _positionBar.Maximum / 10; _positionBar.SmallChange = _positionBar.LargeChange / 4; @@ -317,22 +329,22 @@ 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) + //var f = File.OpenRead(d.SelectedPath); + if (d.ShowDialog() == DialogResult.OK) { DisposeEngine(); bool success; - try - { - new Engine(Engine.EngineType.NDS_DSE, d.FileName); - success = true; - } - catch (Exception ex) + + new Engine(Engine.EngineType.NDS_DSE, d.SelectedPath); + success = true; + if (success != true) { + Exception ex = new Exception(); FlexibleMessageBox.Show(ex, Strings.ErrorOpenDSE); success = false; } @@ -349,12 +361,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 = "Game Boy Advance ROM (*.gba, *.srl)|*.gba;*.srl|All files (*.*)|*.*", + FilterIndex = 2, + RestoreDirectory = true }; - if (d.ShowDialog() == CommonFileDialogResult.Ok) + if (d.ShowDialog() == DialogResult.OK) { DisposeEngine(); bool success; @@ -381,12 +395,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 = "Game Boy Advance ROM (*.gba, *.srl)|*.gba;*.srl|All files (*.*)|*.*", + FilterIndex = 1, + RestoreDirectory = true }; - if (d.ShowDialog() == CommonFileDialogResult.Ok) + if (d.ShowDialog() == DialogResult.OK) { DisposeEngine(); bool success; @@ -413,12 +429,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 = "Nitro Soundmaker Sound Data Archive (*.sdat)|*.sdat|All files (*.*)|*.*", + FilterIndex = 1, + RestoreDirectory = true }; - if (d.ShowDialog() == CommonFileDialogResult.Ok) + if (d.ShowDialog() == DialogResult.OK) { DisposeEngine(); bool success; @@ -446,15 +464,15 @@ private void OpenSDAT(object sender, EventArgs e) private void ExportDLS(object sender, EventArgs e) { - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = Engine.Instance.Config.GetGameName(), - DefaultExtension = ".dls", - EnsureValidNames = true, - Title = Strings.MenuSaveDLS, - Filters = { new CommonFileDialogFilter(Strings.FilterSaveDLS, ".dls") } + FileName = Engine.Instance.Config.GetGameName(), + Filter = Strings.FilterSaveDLS, + FilterIndex = 1, + ValidateNames = true, + Title = Strings.MenuSaveDLS }; - if (d.ShowDialog() == CommonFileDialogResult.Ok) + if (d.ShowDialog() == DialogResult.OK) { try { @@ -469,15 +487,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) { var p = (Core.GBA.MP2K.Player)Engine.Instance.Player; var args = new Core.GBA.MP2K.Player.MIDISaveArgs @@ -502,15 +520,15 @@ private void ExportMIDI(object sender, EventArgs e) } private void ExportSF2(object sender, EventArgs e) { - var d = new CommonSaveFileDialog + var d = new SaveFileDialog { - DefaultFileName = Engine.Instance.Config.GetGameName(), - DefaultExtension = ".sf2", - EnsureValidNames = true, + FileName = Engine.Instance.Config.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) { try { @@ -525,15 +543,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) { Stop(); bool oldFade = Engine.Instance.Player.ShouldFadeOut; @@ -563,8 +581,8 @@ public void LetUIKnowPlayerIsPlaying() _pauseButton.Text = Strings.PlayerPause; _timer.Interval = (int)(1_000d / GlobalConfig.Instance.RefreshRate); _timer.Start(); - UpdateTaskbarState(); - UpdateTaskbarButtons(); + //UpdateTaskbarState(); + //UpdateTaskbarButtons(); } } private void Play() @@ -585,8 +603,8 @@ private void Pause() _pauseButton.Text = Strings.PlayerPause; _timer.Start(); } - UpdateTaskbarState(); - UpdateTaskbarButtons(); + //UpdateTaskbarState(); + //UpdateTaskbarButtons(); } private void Stop() { @@ -597,8 +615,8 @@ private void Stop() _songInfo.DeleteData(); _piano.UpdateKeys(_songInfo.Info, PianoTracks); UpdatePositionIndicators(0L); - UpdateTaskbarState(); - UpdateTaskbarButtons(); + //UpdateTaskbarState(); + //UpdateTaskbarButtons(); } private void TogglePlayback(object sender, EventArgs e) { @@ -655,7 +673,7 @@ 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(); + //UpdateTaskbarButtons(); } private void DisposeEngine() { @@ -665,13 +683,13 @@ private void DisposeEngine() Engine.Instance.Dispose(); } _trackViewer?.UpdateTracks(); - _prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = _positionBar.Enabled = false; + //_prevTButton.Enabled = _toggleTButton.Enabled = _nextTButton.Enabled = _songsComboBox.Enabled = _songNumerical.Enabled = _playButton.Enabled = _volumeBar.Enabled = _positionBar.Enabled = false; Text = Utils.ProgramName; _songInfo.SetNumTracks(0); _songInfo.ResetMutes(); ResetPlaylistStuff(false); UpdatePositionIndicators(0L); - UpdateTaskbarState(); + //UpdateTaskbarState(); _songsComboBox.SelectedIndexChanged -= SongsComboBox_SelectedIndexChanged; _songNumerical.ValueChanged -= SongNumerical_ValueChanged; _songNumerical.Visible = false; @@ -713,17 +731,22 @@ private void SongEnded() { _stopUI = true; } + private void UpdatePositionIndicators(long ticks) { if (_positionBarFree) { _positionBar.Value = ticks; } + /* if (GlobalConfig.Instance.TaskbarProgress && TaskbarManager.IsPlatformSupported) { TaskbarManager.Instance.SetProgressValue((int)ticks, (int)_positionBar.Maximum); } + */ } + + /* private void UpdateTaskbarState() { if (GlobalConfig.Instance.TaskbarProgress && TaskbarManager.IsPlatformSupported) @@ -760,7 +783,7 @@ private void UpdateTaskbarButtons() } _toggleTButton.Enabled = true; } - } + }*/ private void OpenTrackViewer(object sender, EventArgs e) { diff --git a/VG Music Studio/VG Music Studio.csproj b/VG Music Studio/VG Music Studio.csproj index de7ee46..9c3031a 100644 --- a/VG Music Studio/VG Music Studio.csproj +++ b/VG Music Studio/VG Music Studio.csproj @@ -1,17 +1,8 @@ - - - + - Debug - AnyCPU - {97C8ACF8-66A3-4321-91D6-3E94EACA577F} + net6.0-windows WinExe Kermalis.VGMusicStudio - VG Music Studio - v4.8 - 512 - true - false publish\ true @@ -27,28 +18,17 @@ 1.0.0.%2a false true + false + true + true + true - AnyCPU - true - full - false ..\Build\ - DEBUG;TRACE - prompt - 4 Off - false - AnyCPU - pdbonly - true ..\Build\ - TRACE - prompt - 4 - false On @@ -58,195 +38,30 @@ Kermalis.VGMusicStudio.Program - - Dependencies\DLS2.dll - - - ..\packages\EndianBinaryIO.1.1.2\lib\netstandard2.0\EndianBinaryIO.dll - - - ..\packages\Microsoft.WindowsAPICodePack-Core.1.1.0.2\lib\Microsoft.WindowsAPICodePack.dll - - - ..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.Shell.dll - - - ..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.ShellExtensions.dll - - - ..\packages\NAudio.Core.2.0.0\lib\netstandard2.0\NAudio.Core.dll - - - ..\packages\NAudio.Wasapi.2.0.0\lib\netstandard2.0\NAudio.Wasapi.dll - - - ..\packages\ObjectListView.Official.2.9.1\lib\net20\ObjectListView.dll - - - - - False - Dependencies\Sanford.Multimedia.Midi.dll - - - False - Dependencies\SoundFont2.dll - - - - - - - - - - - - - ..\packages\YamlDotNet.11.2.1\lib\net45\YamlDotNet.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Strings.resx - - - - + Component - - - - + Component - - - - - - - - - - + Always - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - + Always - - - Always - - - Always - - + + Always - - - - - ResXFileCodeGenerator - Strings.Designer.cs - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - True - Settings.settings - True - - - - + + - - False - Microsoft .NET Framework 4.7.1 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - + + + + - \ No newline at end of file