DotNet 4.8.1 build of DotNetBar

This commit is contained in:
2025-02-07 10:35:23 -05:00
parent 33439b63a0
commit 6b0a5d60f4
2609 changed files with 989814 additions and 7 deletions

View File

@@ -0,0 +1,375 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Globalization;
namespace DevComponents.DotNetBar.Layout
{
[TypeConverter(typeof(BackgroundConvertor))]
public class Background : INotifyPropertyChanged
{
#region Constructor
/// <summary>
/// Initializes a new instance of the Background class.
/// </summary>
public Background()
{
}
/// <summary>
/// Initializes a new instance of the Background class with single solid backgruond color.
/// </summary>
public Background(Color backColor)
{
_Colors = new Color[] { backColor };
}
/// <summary>
/// Initializes a new instance of the Background class.
/// </summary>
/// <param name="colors"></param>
public Background(Color[] colors)
{
_Colors = colors;
}
/// <summary>
/// Initializes a new instance of the Background class.
/// </summary>
/// <param name="colors"></param>
/// <param name="positions"></param>
public Background(Color[] colors, float[] positions)
{
_Colors = colors;
_Positions = positions;
}
/// <summary>
/// Initializes a new instance of the Background class.
/// </summary>
/// <param name="colors"></param>
/// <param name="positions"></param>
/// <param name="gradientType"></param>
public Background(Color[] colors, float[] positions, eGradientType gradientType)
{
_Colors = colors;
_Positions = positions;
_GradientType = gradientType;
}
/// <summary>
/// Initializes a new instance of the Background class.
/// </summary>
/// <param name="colors"></param>
/// <param name="positions"></param>
/// <param name="gradientType"></param>
/// <param name="linearGradientAngle"></param>
public Background(Color[] colors, float[] positions, eGradientType gradientType, int linearGradientAngle)
{
_Colors = colors;
_Positions = positions;
_GradientType = gradientType;
_LinearGradientAngle = linearGradientAngle;
}
#endregion
#region Implementation
/// <summary>
/// Gets whether class is empty.
/// </summary>
[Browsable(false)]
public bool IsEmpty
{
get
{
return (_Colors == null || _Colors.Length == 0) &&
(_Positions == null || _Positions.Length == 0);
}
}
/// <summary>
/// Gets whether background is visible, i.e. colors are assigned.
/// </summary>
[Browsable(false)]
public bool IsBackgroundSet
{
get
{
return !(_Colors == null || _Colors.Length == 0);
}
}
/// <summary>
/// Creates the brush which represents the background.
/// </summary>
/// <param name="r">Bounds for the brush.</param>
/// <returns>New instance of the brush or null if brush cannot be created.</returns>
public Brush CreateBrush(Rectangle r)
{
if (!IsBackgroundSet)
return null;
if (_Colors.Length == 1)
return new SolidBrush(_Colors[0]);
if (_GradientType == eGradientType.LinearGradient)
{
LinearGradientBrush brush = null;
if (_Colors.Length == 2)
{
brush = new LinearGradientBrush(r, _Colors[0], _Colors[1], _LinearGradientAngle);
if (_Positions != null && _Positions.Length != 2) return brush;
}
else
brush = new LinearGradientBrush(r, _Colors[0], _Colors[_Colors.Length - 1], _LinearGradientAngle);
ColorBlend cb = GetColorBlend();
if (cb != null)
brush.InterpolationColors = cb;
return brush;
}
else
{
int n = (int)Math.Sqrt(r.Width * r.Width + r.Height * r.Height) + 4;
using (GraphicsPath path = new GraphicsPath())
{
path.AddEllipse(r.X - (n - r.Width) / 2, r.Y - (n - r.Height) / 2, n, n);
PathGradientBrush pbr = new PathGradientBrush(path);
pbr.CenterColor = _Colors[0];
pbr.SurroundColors = new Color[] { _Colors[_Colors.Length - 1] };
ColorBlend cb = GetColorBlend();
if (cb != null)
pbr.InterpolationColors = cb;
return (pbr);
}
}
}
private ColorBlend GetColorBlend()
{
if (_Colors != null &&
_Colors != null && _Colors.Length > 0)
{
ColorBlend cb = new ColorBlend(_Colors.Length);
cb.Colors = _Colors;
cb.Positions = GetPositions();
return (cb);
}
return (null);
}
private float[] GetPositions()
{
float[] cp = _Positions;
if (cp == null || cp.Length != _Colors.Length)
{
cp = new float[_Colors.Length];
float f = 1f / _Colors.Length;
for (int i = 0; i < cp.Length; i++)
cp[i] = i * f;
cp[_Colors.Length - 1] = 1;
}
return (cp);
}
private Color[] _Colors = null;
/// <summary>
/// Indicates the array of colors that make up background.
/// </summary>
[DefaultValue(null), Category("Appearance"), Description("Indicates the array of colors that make up background."), TypeConverter(typeof(ArrayConverter))]
public Color[] Colors
{
get
{
return _Colors;
}
set
{
if (_Colors != value)
{
_Colors = value;
OnPropertyChanged(new PropertyChangedEventArgs("Colors"));
}
}
}
private float[] _Positions = null;
/// <summary>
/// Indicates the positions for the gradient colors when multiple colors are set to Colors property. When not set
/// the gradient color positions are evenly distributed.
/// </summary>
[DefaultValue(null), Category("Appearance"), Description("Indicates the positions for the gradient colors when multiple colors are set to Colors property."), TypeConverter(typeof(ArrayConverter))]
public float[] Positions
{
get
{
return _Positions;
}
set
{
_Positions = value;
OnPropertyChanged(new PropertyChangedEventArgs("Positions"));
}
}
private eGradientType _GradientType = eGradientType.LinearGradient;
/// <summary>
/// Indicates the gradient type used when multiple Colors are specified.
/// </summary>
[DefaultValue(eGradientType.LinearGradient), Category("Appearance"), Description("Indicates the gradient type used when multiple Colors are specified.")]
public eGradientType GradientType
{
get { return _GradientType; }
set { _GradientType = value; OnPropertyChanged(new PropertyChangedEventArgs("GradientType")); }
}
private int _LinearGradientAngle = 90;
/// <summary>
/// Indicates the linear gradient angle.
/// </summary>
[DefaultValue(90), Description("Indicates the linear gradient angle."), Category("Appearance")]
public int LinearGradientAngle
{
get { return _LinearGradientAngle; }
set { _LinearGradientAngle = value; OnPropertyChanged(new PropertyChangedEventArgs("LinearGradientAngle")); }
}
#endregion
#region INotifyPropertyChanged Members
/// <summary>
/// Occurs when property value has changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler eh = PropertyChanged;
if (eh != null)
eh(this, e);
}
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="s">Event arguments</param>
protected virtual void OnPropertyChangedEx(string s)
{
PropertyChangedEventHandler eh = PropertyChanged;
if (eh != null)
{
PropertyChangedEventArgs e =
new PropertyChangedEventArgs(s);
eh(this, e);
}
}
#endregion
}
public enum eGradientType
{
LinearGradient,
RadialGradient
}
#region BackgroundConvertor
///<summary>
/// BackgroundConvertor
///</summary>
public class BackgroundConvertor : ExpandableObjectConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
}
public override object ConvertTo(
ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
Background gc = value as Background;
if (gc != null)
{
if (gc.IsEmpty)
return "(Empty)";
if (gc.Colors != null && gc.Colors.Length == 1)
return ColorHelpers.ToArgbString(gc.Colors[0]);
if (gc.Colors != null && gc.Colors.Length > 1)
return ("Blended");
return "";
}
}
return (base.ConvertTo(context, culture, value, destinationType));
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string str = value as string;
if (string.IsNullOrEmpty(str))
{
return new BorderColors();
}
string str2 = str.Trim();
if (str2.Length == 0)
{
return null;
}
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
if (str2.IndexOf(culture.TextInfo.ListSeparator[0]) == -1)
{
Color c = Color.FromName(str2);
if (c.IsEmpty)
c = ColorHelpers.GetColor(str2);
return new Background(c);
}
throw new ArgumentException("Text Parsing Failed");
//char ch = culture.TextInfo.ListSeparator[0];
//string[] strArray = str2.Split(new char[] { ch });
//Color[] numArray = new Color[strArray.Length];
////TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
//for (int i = 0; i < numArray.Length; i++)
//{
// numArray[i] = ColorHelpers.GetColor(strArray[i]);// (Color)converter.ConvertFromString(context, culture, strArray[i]);
//}
//if (numArray.Length == 1)
//{
// return new BorderColors(numArray[0]);
//}
//if (numArray.Length != 4)
//{
// throw new ArgumentException("Text Parsing Failed");
//}
//return new BorderColors(numArray[0], numArray[1], numArray[2], numArray[3]);
}
}
#endregion
}

View File

@@ -0,0 +1,339 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Collections;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Defines BorderColors structure used to define border colors.
/// </summary>
[StructLayout(LayoutKind.Sequential), TypeConverter(typeof(BorderColorsConverter))]
public struct BorderColors : IEquatable<BorderColors>
{
#region Constructor
private Color _Left;
private Color _Top;
private Color _Right;
private Color _Bottom;
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="uniformLength">Uniform BorderColors</param>
public BorderColors(Color uniformBorderColors)
{
_Left = _Top = _Right = _Bottom = uniformBorderColors;
}
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="left">Left BorderColors</param>
/// <param name="top">Top BorderColors</param>
/// <param name="right">Right BorderColors</param>
/// <param name="bottom">Bottom BorderColors</param>
public BorderColors(Color left, Color top, Color right, Color bottom)
{
_Left = left;
_Top = top;
_Right = right;
_Bottom = bottom;
}
#endregion
#region Implementation
/// <summary>
/// Gets whether object equals to this instance.
/// </summary>
/// <param name="obj">object to test.</param>
/// <returns>returns whether objects are Equals</returns>
public override bool Equals(object obj)
{
if (obj is BorderColors)
{
BorderColors BorderColors = (BorderColors)obj;
return (this == BorderColors);
}
return false;
}
/// <summary>
/// Gets whether object equals to this instance.
/// </summary>
/// <param name="BorderColors">object to test.</param>
/// <returns>returns whether objects are Equals</returns>
public bool Equals(BorderColors BorderColors)
{
return (this == BorderColors);
}
/// <summary>
/// Returns hash code for object.
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
return (((_Left.GetHashCode() ^ _Top.GetHashCode()) ^ _Right.GetHashCode()) ^ _Bottom.GetHashCode());
}
const string StringValueSeparator = ",";
/// <summary>
/// Returns string representation of object.
/// </summary>
/// <returns>string representing BorderColors</returns>
public override string ToString()
{
return Convert.ToString(_Left) + StringValueSeparator + Convert.ToString(_Top) + StringValueSeparator + Convert.ToString(_Right) + StringValueSeparator + Convert.ToString(_Bottom);
}
/// <summary>
/// Gets string representation of object.
/// </summary>
/// <param name="cultureInfo">Culture info.</param>
/// <returns>string representing BorderColors</returns>
internal string ToString(CultureInfo cultureInfo)
{
return Convert.ToString(_Left, cultureInfo) + StringValueSeparator + Convert.ToString(_Top, cultureInfo) + StringValueSeparator + Convert.ToString(_Right, cultureInfo) + StringValueSeparator + Convert.ToString(_Bottom, cultureInfo);
}
/// <summary>
/// Returns whether all values are empty.
/// </summary>
[Browsable(false)]
public bool IsEmpty
{
get
{
return (this.Left.IsEmpty && this.Top.IsEmpty && this.Right.IsEmpty && this.Bottom.IsEmpty);
}
}
/// <summary>
/// Returns whether all values are the same.
/// </summary>
[Browsable(false)]
public bool IsUniform
{
get
{
return (this.Left == this.Top && this.Top == this.Right && this.Right == this.Bottom);
}
}
public static bool operator ==(BorderColors t1, BorderColors t2)
{
return (t1._Left == t2._Left && t1._Top == t2._Top && t1._Right == t2._Right && t1._Bottom == t2._Bottom);
}
public static bool operator !=(BorderColors t1, BorderColors t2)
{
return !(t1 == t2);
}
/// <summary>
/// Gets or sets the left BorderColors.
/// </summary>
public Color Left
{
get
{
return _Left;
}
set
{
_Left = value;
}
}
/// <summary>
/// Gets or sets the top BorderColors.
/// </summary>
public Color Top
{
get
{
return _Top;
}
set
{
_Top = value;
}
}
/// <summary>
/// Gets or sets the Right BorderColors.
/// </summary>
public Color Right
{
get
{
return _Right;
}
set
{
_Right = value;
}
}
/// <summary>
/// Gets or sets the Bottom BorderColors.
/// </summary>
public Color Bottom
{
get
{
return _Bottom;
}
set
{
_Bottom = value;
}
}
#endregion
}
#region BorderColorsConverter
/// <summary>
/// Provides BorderColors TypeConverter.
/// </summary>
public class BorderColorsConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return ((destinationType == typeof(InstanceDescriptor)) || base.CanConvertTo(context, destinationType));
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string str = value as string;
if (string.IsNullOrEmpty(str))
{
return new BorderColors();
}
string str2 = str.Trim();
if (str2.Length == 0)
{
return null;
}
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
if (str2.IndexOf(culture.TextInfo.ListSeparator[0]) == -1)
{
Color c = Color.FromName(str2);
if(c.IsEmpty)
c = ColorHelpers.GetColor(str2);
return new BorderColors(c);
}
char ch = culture.TextInfo.ListSeparator[0];
string[] strArray = str2.Split(new char[] { ch });
Color[] numArray = new Color[strArray.Length];
//TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
for (int i = 0; i < numArray.Length; i++)
{
numArray[i] = ColorHelpers.GetColor(strArray[i]);// (Color)converter.ConvertFromString(context, culture, strArray[i]);
}
if (numArray.Length == 1)
{
return new BorderColors(numArray[0]);
}
if (numArray.Length != 4)
{
throw new ArgumentException("Text Parsing Failed");
}
return new BorderColors(numArray[0], numArray[1], numArray[2], numArray[3]);
}
private string ToArgbString(Color color)
{
if (color.IsEmpty) return "";
if (color.A == 255)
return color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
return color.A.ToString("X2") + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if (value is BorderColors)
{
if (destinationType == typeof(string))
{
BorderColors colors = (BorderColors)value;
if (colors.IsEmpty) return "";
if (colors.IsUniform) return ToArgbString(colors.Left);
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
string separator = culture.TextInfo.ListSeparator + " ";
//TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
string[] strArray = new string[4];
int num = 0;
//strArray[num++] = converter.ConvertToString(context, culture, BorderColors.Left);
//strArray[num++] = converter.ConvertToString(context, culture, BorderColors.Top);
//strArray[num++] = converter.ConvertToString(context, culture, BorderColors.Right);
//strArray[num++] = converter.ConvertToString(context, culture, BorderColors.Bottom);
strArray[num++] = ToArgbString(colors.Left);
strArray[num++] = ToArgbString(colors.Top);
strArray[num++] = ToArgbString(colors.Right);
strArray[num++] = ToArgbString(colors.Bottom);
return string.Join(separator, strArray);
}
if (destinationType == typeof(InstanceDescriptor))
{
BorderColors BorderColors2 = (BorderColors)value;
ConstructorInfo constructor = typeof(BorderColors).GetConstructor(new Type[] { typeof(Color), typeof(Color), typeof(Color), typeof(Color) });
if (constructor != null)
{
return new InstanceDescriptor(constructor, new object[] { BorderColors2.Left, BorderColors2.Top, BorderColors2.Right, BorderColors2.Bottom });
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
if (propertyValues == null)
{
throw new ArgumentNullException("propertyValues");
}
object left = propertyValues["Left"];
object top = propertyValues["Top"];
object right = propertyValues["Right"];
object bottom = propertyValues["Bottom"];
if ((((left == null) || (top == null)) || ((right == null) || (bottom == null))) || ((!(left is Color) || !(top is Color)) || (!(right is Color) || !(bottom is Color))))
{
throw new ArgumentException(string.Format("Property Value Invalid: left={0}, top={1}, right={2}, bottom={3}", left, top, right, bottom));
}
return new BorderColors((Color)left, (Color)top, (Color)right, (Color)bottom);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(typeof(BorderColors), attributes).Sort(new string[] { "Left", "Top", "Right", "Bottom" });
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
}
#endregion
}

View File

@@ -0,0 +1,493 @@
using System;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Globalization;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Defines Thickness class.
/// </summary>
[TypeConverter(typeof(BlankExpandableObjectConverter))]
public class BorderPattern : IEquatable<BorderPattern>, INotifyPropertyChanged
{
#region Static data
/// <summary>
/// Returns Empty instance of BorderPattern.
/// </summary>
public static BorderPattern Empty
{
get { return (new BorderPattern()); }
}
#endregion
#region Private variables
private LinePattern _Bottom = LinePattern.NotSet;
private LinePattern _Left = LinePattern.NotSet;
private LinePattern _Right = LinePattern.NotSet;
private LinePattern _Top = LinePattern.NotSet;
#endregion
#region Constructors
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="left">Left BorderPatternStyle.</param>
/// <param name="top">Top BorderPatternStyle.</param>
/// <param name="right">Right BorderPatternStyle.</param>
/// <param name="bottom">Bottom BorderPatternStyle.</param>
public BorderPattern(LinePattern left,
LinePattern top, LinePattern right, LinePattern bottom)
{
_Left = left;
_Top = top;
_Right = right;
_Bottom = bottom;
PropertyChanged = null;
}
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="all">Specifies uniform Thickness.</param>
public BorderPattern(LinePattern all)
: this(all, all, all, all)
{
}
///<summary>
/// Creates new instance of the object.
///</summary>
public BorderPattern()
{
}
#endregion
#region Public properties
#region All
/// <summary>
/// Gets or sets the thickness of all sides.
/// </summary>
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public LinePattern All
{
set { _Top = _Left = _Bottom = _Right = value; }
}
#endregion
#region Bottom
/// <summary>
/// Gets or sets the bottom Border Pattern
/// </summary>
[DefaultValue(LinePattern.NotSet)]
[Description("Indicates the bottom Border Pattern")]
public LinePattern Bottom
{
get { return (_Bottom); }
set
{
if (_Bottom != value)
{
_Bottom = value;
OnPropertyChanged(new PropertyChangedEventArgs("Bottom"));
}
}
}
#endregion
#region Left
/// <summary>
/// Gets or sets the left Border Pattern
/// </summary>
[DefaultValue(LinePattern.NotSet)]
[Description("Indicates the left Border Pattern")]
public LinePattern Left
{
get { return (_Left); }
set
{
if (_Left != value)
{
_Left = value;
OnPropertyChanged(new PropertyChangedEventArgs("Left"));
}
}
}
#endregion
#region Right
/// <summary>
/// Gets or sets the Right Border Pattern
/// </summary>
[DefaultValue(LinePattern.NotSet)]
[Description("Indicates the Right Border Pattern")]
public LinePattern Right
{
get { return (_Right); }
set
{
if (_Right != value)
{
_Right = value;
OnPropertyChanged(new PropertyChangedEventArgs("Right"));
}
}
}
#endregion
#region Top
/// <summary>
/// Gets or sets the Top Border Pattern
/// </summary>
[Browsable(true), DefaultValue(LinePattern.NotSet)]
[Description("Indicates the Top Border Pattern")]
public LinePattern Top
{
get { return (_Top); }
set
{
if (_Top != value)
{
_Top = value;
OnPropertyChanged(new PropertyChangedEventArgs("Top"));
}
}
}
#endregion
#region IsEmpty
/// <summary>
/// Gets whether the item is empty
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsEmpty
{
get
{
return (_Left == LinePattern.NotSet &&
_Right == LinePattern.NotSet &&
_Top == LinePattern.NotSet &&
_Bottom == LinePattern.NotSet);
}
}
/// <summary>
/// Gets whether left border is visible.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsLeftVisible
{
get
{
return (_Left != LinePattern.NotSet && _Left != LinePattern.None);
}
}
/// <summary>
/// Gets whether right border is visible.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsRightVisible
{
get
{
return (_Right != LinePattern.NotSet && _Right != LinePattern.None);
}
}
/// <summary>
/// Gets whether top border is visible.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsTopVisible
{
get
{
return (_Top != LinePattern.NotSet && _Top != LinePattern.None);
}
}
/// <summary>
/// Gets whether bottom border is visible.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsBottomVisible
{
get
{
return (_Bottom != LinePattern.NotSet && _Bottom != LinePattern.None);
}
}
#endregion
#endregion
#region Internal properties
#region IsUniform
internal bool IsUniform
{
get
{
return (_Left == _Top &&
_Left == _Right && _Left == _Bottom);
}
}
#endregion
#endregion
#region Equals
/// <summary>
/// Gets whether two instances are equal.
/// </summary>
/// <param name="obj">Instance to compare to.</param>
/// <returns>true if equal otherwise false.</returns>
public override bool Equals(object obj)
{
if (obj is BorderPattern)
return (this == (BorderPattern)obj);
return (false);
}
/// <summary>
/// Gets whether two instances are equal.
/// </summary>
/// <param name="borderPattern">Instance to compare to</param>
/// <returns>true if equal otherwise false</returns>
public bool Equals(BorderPattern borderPattern)
{
return (this == borderPattern);
}
#endregion
#region GetHashCode
/// <summary>
/// Returns hash-code.
/// </summary>
/// <returns>hash-code</returns>
public override int GetHashCode()
{
return (((_Left.GetHashCode() ^ _Top.GetHashCode()) ^
_Right.GetHashCode()) ^ _Bottom.GetHashCode());
}
#endregion
#region Operators
#region "==" operator
/// <summary>
/// Implements == operator.
/// </summary>
/// <param name="t1">Object 1</param>
/// <param name="t2">Object 2</param>
/// <returns>true if equals</returns>
public static bool operator ==(BorderPattern t1, BorderPattern t2)
{
if (ReferenceEquals(t1, t2))
return (true);
if (((object)t1 == null) || ((object)t2 == null))
return (false);
return (t1._Left == t2._Left && t1._Right == t2._Right &&
t1._Top == t2._Top && t1._Bottom == t2._Bottom);
}
#endregion
#region "!=" operator
/// <summary>
/// Implements != operator
/// </summary>
/// <param name="t1">Object 1</param>
/// <param name="t2">Object 2</param>
/// <returns>true if different</returns>
public static bool operator !=(BorderPattern t1, BorderPattern t2)
{
return ((t1 == t2) == false);
}
#endregion
#endregion
#region ApplyPattern
/// <summary>
/// Applies the pattern to instance of this pattern.
/// </summary>
/// <param name="pattern">Pattern to apply.</param>
public void ApplyPattern(BorderPattern pattern)
{
if (pattern != null)
{
if (pattern.Top != LinePattern.NotSet)
_Top = pattern.Top;
if (pattern.Left != LinePattern.NotSet)
_Left = pattern.Left;
if (pattern.Bottom != LinePattern.NotSet)
_Bottom = pattern.Bottom;
if (pattern.Right != LinePattern.NotSet)
_Right = pattern.Right;
}
}
#endregion
#region Copy
/// <summary>
/// Creates an exact copy of the BorderPattern.
/// </summary>
/// <returns>Copy of the BorderPattern.</returns>
public BorderPattern Copy()
{
BorderPattern copy = new BorderPattern(_Left, _Top, _Right, _Bottom);
return (copy);
}
#endregion
#region INotifyPropertyChanged Members
/// <summary>
/// Occurs when property value has changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="e">Event arguments</param>
void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler eh = PropertyChanged;
if (eh != null)
eh(this, e);
}
#endregion
}
#region enums
#region LinePattern
///<summary>
/// LinePattern
///</summary>
public enum LinePattern
{
///<summary>
/// None
///</summary>
None = -2,
///<summary>
/// NotSet
///</summary>
NotSet = -1,
///<summary>
/// Solid
///</summary>
Solid = DashStyle.Solid,
///<summary>
/// Dash
///</summary>
Dash = DashStyle.Dash,
///<summary>
/// Dot
///</summary>
Dot = DashStyle.Dot,
///<summary>
/// DashDot
///</summary>
DashDot = DashStyle.DashDot,
///<summary>
/// DashDotDot
///</summary>
DashDotDot = DashStyle.DashDotDot,
}
#endregion
#endregion
#region BlankExpandableObjectConverter
///<summary>
/// BlankExpandableObjectConverter
///</summary>
public class BlankExpandableObjectConverter : ExpandableObjectConverter
{
///<summary>
/// ConvertTo
///</summary>
///<param name="context"></param>
///<param name="culture"></param>
///<param name="value"></param>
///<param name="destinationType"></param>
///<returns></returns>
public override object ConvertTo(
ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return (" ");
return (base.ConvertTo(context, culture, value, destinationType));
}
}
#endregion
}

View File

@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
internal static class ColorHelpers
{
/// <summary>
/// Converts hex string to Color type.
/// </summary>
/// <param name="rgbHex">Hexadecimal color representation.</param>
/// <returns>Reference to Color object.</returns>
public static Color GetColor(string rgbHex)
{
if (string.IsNullOrEmpty(rgbHex))
return Color.Empty;
if (rgbHex.Length == 8)
return Color.FromArgb(Convert.ToInt32(rgbHex.Substring(0, 2), 16),
Convert.ToInt32(rgbHex.Substring(2, 2), 16),
Convert.ToInt32(rgbHex.Substring(4, 2), 16),
Convert.ToInt32(rgbHex.Substring(6, 2), 16));
return Color.FromArgb(Convert.ToInt32(rgbHex.Substring(0, 2), 16),
Convert.ToInt32(rgbHex.Substring(2, 2), 16),
Convert.ToInt32(rgbHex.Substring(4, 2), 16));
}
/// <summary>
/// Converts hex string to Color type.
/// </summary>
/// <param name="rgb">Color representation as 32-bit RGB value.</param>
/// <returns>Reference to Color object.</returns>
public static Color GetColor(int rgb)
{
if (rgb == -1) return Color.Empty;
return Color.FromArgb((rgb & 0xFF0000) >> 16, (rgb & 0xFF00) >> 8, rgb & 0xFF);
}
/// <summary>
/// Converts hex string to Color type.
/// </summary>
/// <param name="rgb">Color representation as 32-bit RGB value.</param>
/// <returns>Reference to Color object.</returns>
public static Color GetColor(int alpha, int rgb)
{
if (rgb == -1) return Color.Empty;
return Color.FromArgb(alpha, (rgb & 0xFF0000) >> 16, (rgb & 0xFF00) >> 8, rgb & 0xFF);
}
public static string ToArgbString(Color color)
{
if (color.IsEmpty) return "";
if (color.A == 255)
return color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
return color.A.ToString("X2") + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}
}
}

View File

@@ -0,0 +1,46 @@
using System.Collections;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Represents block layout manager responsible for sizing the content blocks.
/// </summary>
public abstract class BlockLayoutManager
{
private Graphics m_Graphics;
/// <summary>
/// Resizes the content block and sets it's Bounds property to reflect new size.
/// </summary>
/// <param name="block">Content block to resize.</param>
/// <param name="availableSize">Content size available for the block in the given line.</param>
public abstract void Layout(IBlock block, Size availableSize);
/// <summary>
/// Performs layout finalization
/// </summary>
/// <param name="containerBounds"></param>
/// <param name="blocksBounds"></param>
/// <param name="lines"></param>
/// <returns></returns>
public abstract Rectangle FinalizeLayout(Rectangle containerBounds, Rectangle blocksBounds, ArrayList lines);
/// <summary>
/// Gets or sets the graphics object used by layout manager.
/// </summary>
public System.Drawing.Graphics Graphics
{
get {return m_Graphics;}
set {m_Graphics=value;}
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Specifies orientation of content.
/// </summary>
public enum eContentOrientation
{
/// <summary>
/// Indicates Horizontal orientation of the content.
/// </summary>
Horizontal,
/// <summary>
/// Indicates Vertical orientation of the content.
/// </summary>
Vertical
}
/// <summary>
/// Specifies content horizontal alignment.
/// </summary>
public enum eContentAlignment
{
/// <summary>
/// Content is left aligned.UI
/// </summary>
Left,
/// <summary>
/// Content is right aligned.
/// </summary>
Right,
/// <summary>
/// Content is centered.
/// </summary>
Center
}
/// <summary>
/// Specifies content vertical alignment.
/// </summary>
public enum eContentVerticalAlignment
{
/// <summary>
/// Content is top aligned.
/// </summary>
Top,
/// <summary>
/// Content is bottom aligned.
/// </summary>
Bottom,
/// <summary>
/// Content is in the middle.
/// </summary>
Middle
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Drawing;
using DevComponents.DotNetBar;
using System.Windows.Forms;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Represents a content block interface.
/// </summary>
public interface IBlock
{
/// <summary>
/// Gets or sets the bounds of the content block.
/// </summary>
Rectangle Bounds {get;set;}
/// <summary>
/// Gets or sets whether content block is visible.
/// </summary>
bool Visible {get;set;}
/// <summary>
/// Gets or sets the block margins.
/// </summary>
Padding Margin { get;set;}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Text;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Represents a extended content block interface for advanced layout information.
/// </summary>
public interface IBlockExtended : IBlock
{
bool IsBlockElement { get;}
bool IsNewLineAfterElement { get;}
bool CanStartNewLine { get; }
/// <summary>
/// Returns whether element is an container so it receives full available size of parent control for layout.
/// </summary>
bool IsBlockContainer { get; }
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Represents interface for block layout.
/// </summary>
public interface IContentLayout
{
/// <summary>
/// Performs layout of the content block.
/// </summary>
/// <param name="containerBounds">Container bounds to layout content blocks in.</param>
/// <param name="contentBlocks">Content blocks to layout.</param>
/// <param name="blockLayout">Block layout manager that resizes the content blocks.</param>
/// <returns>The bounds of the content blocks within the container bounds.</returns>
Rectangle Layout(Rectangle containerBounds, IBlock[] contentBlocks, BlockLayoutManager blockLayout);
}
}

View File

@@ -0,0 +1,659 @@
using System;
using System.Collections;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.UI.ContentManager
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
/// <summary>
/// Represents the serial content layout manager that arranges content blocks in series next to each other.
/// </summary>
public class SerialContentLayoutManager:IContentLayout
{
#region Events
/// <summary>
/// Occurs when X, Y position of next block is calcualted.
/// </summary>
public event LayoutManagerPositionEventHandler NextPosition;
/// <summary>
/// Occurs before new block is layed out.
/// </summary>
public event LayoutManagerLayoutEventHandler BeforeNewBlockLayout;
#endregion
#region Private Variables
private int m_BlockSpacing=0;
private bool m_FitContainerOversize=false;
private bool m_FitContainer = false;
private bool m_VerticalFitContainerWidth = false;
private bool m_HorizontalFitContainerHeight = false;
private eContentOrientation m_ContentOrientation=eContentOrientation.Horizontal;
private eContentAlignment m_ContentAlignment=eContentAlignment.Left;
private eContentVerticalAlignment m_ContentVerticalAlignment=eContentVerticalAlignment.Middle;
private eContentVerticalAlignment m_BlockLineAlignment = eContentVerticalAlignment.Middle;
private bool m_EvenHeight=false;
private bool m_MultiLine=false;
private bool m_RightToLeft = false;
private bool m_OversizeDistribute = false;
#endregion
/// <summary>
/// Creates new instance of the class.
/// </summary>
public SerialContentLayoutManager()
{
}
#region IContentLayout Members
/// <summary>
/// Performs layout of the content block.
/// </summary>
/// <param name="containerBounds">Container bounds to layout content blocks in.</param>
/// <param name="contentBlocks">Content blocks to layout.</param>
/// <param name="blockLayout">Block layout manager that resizes the content blocks.</param>
/// <returns>The bounds of the content blocks within the container bounds.</returns>
public virtual Rectangle Layout(Rectangle containerBounds, IBlock[] contentBlocks, BlockLayoutManager blockLayout)
{
Rectangle blocksBounds=Rectangle.Empty;
Point position=containerBounds.Location;
ArrayList lines=new ArrayList();
lines.Add(new BlockLineInfo());
BlockLineInfo currentLine=lines[0] as BlockLineInfo;
bool switchToNewLine = false;
bool canStartOnNewLine = true;
int visibleIndex = 0;
foreach(IBlock block in contentBlocks)
{
if(!block.Visible)
{
block.Bounds = Rectangle.Empty;
continue;
}
if (BeforeNewBlockLayout != null)
{
LayoutManagerLayoutEventArgs e = new LayoutManagerLayoutEventArgs(block, position, visibleIndex);
BeforeNewBlockLayout(this, e);
position = e.CurrentPosition;
if (e.CancelLayout)
continue;
}
visibleIndex++;
Size availableSize = containerBounds.Size;
bool isBlockElement = false;
bool isNewLineTriggger = false;
bool isContainer = false;
if (block is IBlockExtended)
{
IBlockExtended ex = block as IBlockExtended;
isBlockElement = ex.IsBlockElement;
isNewLineTriggger = ex.IsNewLineAfterElement;
canStartOnNewLine = ex.CanStartNewLine;
isContainer = ex.IsBlockContainer;
}
else
canStartOnNewLine = true;
if (!isBlockElement && !isContainer)
{
if (m_ContentOrientation == eContentOrientation.Horizontal)
availableSize.Width = (containerBounds.Right - position.X);
else
availableSize.Height = (containerBounds.Bottom - position.Y);
}
// Resize the content block
blockLayout.Layout(block, availableSize);
if(m_MultiLine && currentLine.Blocks.Count > 0)
{
if (m_ContentOrientation == eContentOrientation.Horizontal && (position.X + block.Bounds.Width > containerBounds.Right && canStartOnNewLine || isBlockElement || switchToNewLine))
{
position.X=containerBounds.X;
position.Y+=(currentLine.LineSize.Height+m_BlockSpacing);
currentLine=new BlockLineInfo();
currentLine.Line=lines.Count;
lines.Add(currentLine);
}
else if (m_ContentOrientation == eContentOrientation.Vertical && (position.Y + block.Bounds.Height > containerBounds.Bottom && canStartOnNewLine || isBlockElement || switchToNewLine))
{
position.Y=containerBounds.Y;
position.X+=(currentLine.LineSize.Width+m_BlockSpacing);
currentLine=new BlockLineInfo();
currentLine.Line=lines.Count;
lines.Add(currentLine);
}
}
if(m_ContentOrientation==eContentOrientation.Horizontal)
{
if(block.Bounds.Height>currentLine.LineSize.Height)
currentLine.LineSize.Height=block.Bounds.Height;
currentLine.LineSize.Width=position.X+block.Bounds.Width-containerBounds.X;
}
else if(m_ContentOrientation==eContentOrientation.Vertical)
{
if(block.Bounds.Width>currentLine.LineSize.Width)
currentLine.LineSize.Width=block.Bounds.Width;
currentLine.LineSize.Height=position.Y+block.Bounds.Height-containerBounds.Y;
}
currentLine.Blocks.Add(block);
if (block.Visible) currentLine.VisibleItemsCount++;
Rectangle r = new Rectangle(position, block.Bounds.Size);
r.X += block.Margin.Left;
r.Y += block.Margin.Top;
block.Bounds = r;
if (blocksBounds.IsEmpty)
{
r = block.Bounds; // Make sure that blocks bounds take in account any margin
r.X -= block.Margin.Left;
r.Y -= block.Margin.Top;
r.Width += block.Margin.Horizontal;
r.Height += block.Margin.Vertical;
blocksBounds = r;
}
else
blocksBounds = Rectangle.Union(blocksBounds, block.Bounds);
switchToNewLine = isBlockElement | isNewLineTriggger;
position=GetNextPosition(block, position);
}
blocksBounds=AlignResizeBlocks(containerBounds, blocksBounds, lines);
if (m_RightToLeft)
blocksBounds = MirrorContent(containerBounds, blocksBounds, contentBlocks);
blocksBounds = blockLayout.FinalizeLayout(containerBounds, blocksBounds, lines);
return blocksBounds;
}
#endregion
#region Internals
private struct SizeExtended
{
public int Width;
public int Height;
public float WidthReduction;
public float HeightReduction;
public bool UseAbsoluteWidth;
}
private Rectangle AlignResizeBlocks(Rectangle containerBounds,Rectangle blocksBounds,ArrayList lines)
{
Rectangle newBounds=Rectangle.Empty;
if(containerBounds.IsEmpty || blocksBounds.IsEmpty || ((BlockLineInfo)lines[0]).Blocks.Count==0)
return newBounds;
if(m_ContentAlignment==eContentAlignment.Left && m_ContentVerticalAlignment==eContentVerticalAlignment.Top &&
!m_FitContainer && !m_FitContainerOversize && !m_EvenHeight && m_BlockLineAlignment==eContentVerticalAlignment.Top)
return blocksBounds;
Point[] offset=new Point[lines.Count];
SizeExtended[] sizeOffset = new SizeExtended[lines.Count];
foreach(BlockLineInfo lineInfo in lines)
{
if(m_ContentOrientation==eContentOrientation.Horizontal)
{
if(m_FitContainer && containerBounds.Width>lineInfo.LineSize.Width ||
m_FitContainerOversize && lineInfo.LineSize.Width>containerBounds.Width)
{
if (m_OversizeDistribute && containerBounds.Width < lineInfo.LineSize.Width * .75)
{
sizeOffset[lineInfo.Line].Width = (int)Math.Floor((float)(containerBounds.Width - lineInfo.VisibleItemsCount * m_BlockSpacing) / (float)lineInfo.VisibleItemsCount);
sizeOffset[lineInfo.Line].UseAbsoluteWidth = true;
}
else
sizeOffset[lineInfo.Line].Width = ((containerBounds.Width - lineInfo.VisibleItemsCount * m_BlockSpacing) - lineInfo.LineSize.Width) / lineInfo.VisibleItemsCount;
sizeOffset[lineInfo.Line].WidthReduction = (float)(containerBounds.Width - lineInfo.VisibleItemsCount * m_BlockSpacing) / (float)lineInfo.LineSize.Width;
blocksBounds.Width=containerBounds.Width;
}
if (m_HorizontalFitContainerHeight && containerBounds.Height > blocksBounds.Height)
sizeOffset[lineInfo.Line].Height = (containerBounds.Height - lineInfo.LineSize.Height) / lines.Count;
}
else
{
if(m_FitContainer && containerBounds.Height>lineInfo.LineSize.Height ||
m_FitContainerOversize && lineInfo.LineSize.Height>containerBounds.Height)
{
if (m_OversizeDistribute && containerBounds.Width < lineInfo.LineSize.Width * .75)
{
sizeOffset[lineInfo.Line].Height = (int)Math.Floor((float)(containerBounds.Height - lineInfo.VisibleItemsCount * m_BlockSpacing) / (float)lineInfo.VisibleItemsCount);
sizeOffset[lineInfo.Line].UseAbsoluteWidth = true;
}
else
sizeOffset[lineInfo.Line].Height = ((containerBounds.Height - lineInfo.VisibleItemsCount * m_BlockSpacing) - lineInfo.LineSize.Height) / lineInfo.VisibleItemsCount;
sizeOffset[lineInfo.Line].HeightReduction = (float)(containerBounds.Height - lineInfo.VisibleItemsCount * m_BlockSpacing) / (float)lineInfo.LineSize.Height;
blocksBounds.Height=containerBounds.Height;
}
if (m_VerticalFitContainerWidth && containerBounds.Width > blocksBounds.Width)
sizeOffset[lineInfo.Line].Width = (containerBounds.Width - lineInfo.LineSize.Width) / lines.Count;
}
if(m_ContentOrientation==eContentOrientation.Horizontal && !m_FitContainer)
{
if(containerBounds.Width>blocksBounds.Width && m_FitContainerOversize || !m_FitContainerOversize)
{
switch(m_ContentAlignment)
{
case eContentAlignment.Right:
if (containerBounds.Width > lineInfo.LineSize.Width)
offset[lineInfo.Line].X = containerBounds.Width - lineInfo.LineSize.Width;
break;
case eContentAlignment.Center:
if (containerBounds.Width > lineInfo.LineSize.Width)
offset[lineInfo.Line].X = (containerBounds.Width - lineInfo.LineSize.Width) / 2;
break;
}
}
}
if(m_ContentOrientation==eContentOrientation.Vertical && !m_FitContainer)
{
if(containerBounds.Height>blocksBounds.Height && m_FitContainerOversize || !m_FitContainerOversize)
{
switch(m_ContentVerticalAlignment)
{
case eContentVerticalAlignment.Bottom:
if (containerBounds.Height > lineInfo.LineSize.Height)
offset[lineInfo.Line].Y = containerBounds.Height - lineInfo.LineSize.Height;
break;
case eContentVerticalAlignment.Middle:
if (containerBounds.Height > lineInfo.LineSize.Height)
offset[lineInfo.Line].Y = (containerBounds.Height - lineInfo.LineSize.Height) / 2;
break;
}
}
}
}
if (m_VerticalFitContainerWidth && containerBounds.Width > blocksBounds.Width && m_ContentOrientation==eContentOrientation.Vertical)
blocksBounds.Width = containerBounds.Width;
else if(m_HorizontalFitContainerHeight && containerBounds.Height>blocksBounds.Height && m_ContentOrientation==eContentOrientation.Horizontal)
blocksBounds.Height = containerBounds.Height;
if(m_ContentOrientation==eContentOrientation.Horizontal)
{
foreach(BlockLineInfo lineInfo in lines)
{
foreach(IBlock block in lineInfo.Blocks)
{
if(!block.Visible)
continue;
Rectangle r=block.Bounds;
if(m_EvenHeight && lineInfo.LineSize.Height>0)
r.Height=lineInfo.LineSize.Height;
r.Offset(offset[lineInfo.Line]);
if(m_ContentVerticalAlignment==eContentVerticalAlignment.Middle)
{
// Takes care of offset rounding error when both content is vertically centered and blocks in line are centered
if (m_BlockLineAlignment == eContentVerticalAlignment.Middle)
r.Offset(0,((containerBounds.Height-blocksBounds.Height)+(lineInfo.LineSize.Height-r.Height))/2);
else
r.Offset(0,(containerBounds.Height-blocksBounds.Height)/2);
// Line alignment of the block
if (m_BlockLineAlignment == eContentVerticalAlignment.Bottom)
r.Offset(0, lineInfo.LineSize.Height - r.Height);
}
else if(m_ContentVerticalAlignment==eContentVerticalAlignment.Bottom)
r.Offset(0,containerBounds.Height-blocksBounds.Height);
// To avoid rounding offset errors when dividing this is split see upper part
if(m_ContentVerticalAlignment!=eContentVerticalAlignment.Middle)
{
// Line alignment of the block
if (m_BlockLineAlignment == eContentVerticalAlignment.Middle)
r.Offset(0, (lineInfo.LineSize.Height - r.Height) / 2);
else if (m_BlockLineAlignment == eContentVerticalAlignment.Bottom)
r.Offset(0, lineInfo.LineSize.Height - r.Height);
}
if(sizeOffset[lineInfo.Line].Width!=0)
{
if (m_OversizeDistribute)
{
int nw = sizeOffset[lineInfo.Line].UseAbsoluteWidth ? sizeOffset[lineInfo.Line].Width : (int)Math.Floor(r.Width * sizeOffset[lineInfo.Line].WidthReduction);
offset[lineInfo.Line].X += nw - r.Width;
r.Width = nw;
}
else
{
r.Width += sizeOffset[lineInfo.Line].Width;
offset[lineInfo.Line].X += sizeOffset[lineInfo.Line].Width;
}
}
r.Height+=sizeOffset[lineInfo.Line].Height;
block.Bounds=r;
if(newBounds.IsEmpty)
newBounds=block.Bounds;
else
newBounds=Rectangle.Union(newBounds,block.Bounds);
}
// Adjust for left-over size adjustment for odd difference between container width and the total block width
if (!m_OversizeDistribute && sizeOffset[lineInfo.Line].Width != 0 && containerBounds.Width - (lineInfo.LineSize.Width + sizeOffset[lineInfo.Line].Width * lineInfo.Blocks.Count) != 0)
{
Rectangle r=((IBlock)lineInfo.Blocks[lineInfo.Blocks.Count-1]).Bounds;
r.Width+=containerBounds.Width-(lineInfo.LineSize.Width+sizeOffset[lineInfo.Line].Width*lineInfo.Blocks.Count);
((IBlock)lineInfo.Blocks[lineInfo.Blocks.Count-1]).Bounds=r;
}
}
}
else
{
foreach(BlockLineInfo lineInfo in lines)
{
foreach(IBlock block in lineInfo.Blocks)
{
if(!block.Visible)
continue;
Rectangle r=block.Bounds;
if(m_EvenHeight && lineInfo.LineSize.Width>0)
r.Width=lineInfo.LineSize.Width - block.Margin.Horizontal;
r.Offset(offset[lineInfo.Line]);
if(m_ContentAlignment==eContentAlignment.Center)
r.Offset(((containerBounds.Width-blocksBounds.Width)+(lineInfo.LineSize.Width-r.Width))/2,0); //r.Offset((containerBounds.Width-blocksBounds.Width)/2+(lineInfo.LineSize.Width-r.Width)/2,0);
else if(m_ContentAlignment==eContentAlignment.Right)
r.Offset((containerBounds.Width-blocksBounds.Width)+lineInfo.LineSize.Width-r.Width,0);
r.Width+=sizeOffset[lineInfo.Line].Width;
if(sizeOffset[lineInfo.Line].Height!=0)
{
if (m_OversizeDistribute)
{
int nw = sizeOffset[lineInfo.Line].UseAbsoluteWidth ? sizeOffset[lineInfo.Line].Height : (int)Math.Floor(r.Height * sizeOffset[lineInfo.Line].HeightReduction);
offset[lineInfo.Line].Y += nw - r.Height;
r.Height = nw;
}
else
{
r.Height += sizeOffset[lineInfo.Line].Height;
offset[lineInfo.Line].Y += sizeOffset[lineInfo.Line].Height;
}
}
block.Bounds=r;
if (newBounds.IsEmpty)
{
r.Y -= block.Margin.Top; // Account for any margin set on first element
r.X -= block.Margin.Left;
r.Width += block.Margin.Horizontal;
r.Height += block.Margin.Vertical;
newBounds = r;
}
else
newBounds = Rectangle.Union(newBounds, block.Bounds);
}
if (!m_OversizeDistribute && sizeOffset[lineInfo.Line].Height != 0 && containerBounds.Height - (lineInfo.LineSize.Height + sizeOffset[lineInfo.Line].Height * lineInfo.Blocks.Count) != 0)
{
Rectangle r=((IBlock)lineInfo.Blocks[lineInfo.Blocks.Count-1]).Bounds;
r.Height+=containerBounds.Height-(lineInfo.LineSize.Height+sizeOffset[lineInfo.Line].Height*lineInfo.Blocks.Count);
((IBlock)lineInfo.Blocks[lineInfo.Blocks.Count-1]).Bounds=r;
}
}
}
return newBounds;
}
private Point GetNextPosition(IBlock block, Point position)
{
if (NextPosition != null)
{
LayoutManagerPositionEventArgs e = new LayoutManagerPositionEventArgs();
e.Block = block;
e.CurrentPosition = position;
NextPosition(this, e);
if (e.Cancel)
return e.NextPosition;
}
if (m_ContentOrientation == eContentOrientation.Horizontal)
position.X += block.Bounds.Width + m_BlockSpacing + block.Margin.Horizontal;
else
position.Y += block.Bounds.Height + m_BlockSpacing + block.Margin.Vertical;
return position;
}
internal class BlockLineInfo
{
public BlockLineInfo() {}
public ArrayList Blocks=new ArrayList();
public Size LineSize=Size.Empty;
public int Line=0;
public int VisibleItemsCount = 0;
}
private Rectangle MirrorContent(Rectangle containerBounds, Rectangle blockBounds, IBlock[] contentBlocks)
{
int xOffset = (blockBounds.X - containerBounds.X);
if (blockBounds.Width < containerBounds.Width)
blockBounds.X = containerBounds.Right - ((blockBounds.X - containerBounds.X) + blockBounds.Width);
else if (blockBounds.Width > containerBounds.Width)
containerBounds.Width = blockBounds.Width;
foreach (IBlock block in contentBlocks)
{
if (!block.Visible)
continue;
Rectangle r = block.Bounds;
block.Bounds = new Rectangle(containerBounds.Right - ((r.X - containerBounds.X) + r.Width), r.Y, r.Width, r.Height);
}
return blockBounds;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the spacing in pixels between content blocks. Default value is 0.
/// </summary>
public virtual int BlockSpacing
{
get {return m_BlockSpacing;}
set {m_BlockSpacing=value;}
}
/// <summary>
/// Gets or sets whether content blocks are forced to fit the container bounds if they
/// occupy more space than it is available by container. Default value is false.
/// </summary>
public virtual bool FitContainerOversize
{
get {return m_FitContainerOversize;}
set {m_FitContainerOversize=value;}
}
/// <summary>
/// Gets or sets whether content blocks are resized to fit the container bound if they
/// occupy less space than it is available by container. Default value is false.
/// </summary>
public virtual bool FitContainer
{
get {return m_FitContainer;}
set {m_FitContainer=value;}
}
/// <summary>
/// Gets or sets whether content blocks are resized (Width) to fit container bounds if they
/// occupy less space than the actual container width. Applies to the Vertical orientation only. Default value is false.
/// </summary>
public virtual bool VerticalFitContainerWidth
{
get { return m_VerticalFitContainerWidth; }
set { m_VerticalFitContainerWidth = value; }
}
/// <summary>
/// Gets or sets whether content blocks are resized (Height) to fit container bounds if they
/// occupy less space than the actual container height. Applies to the Horizontal orientation only. Default value is false.
/// </summary>
public virtual bool HorizontalFitContainerHeight
{
get { return m_HorizontalFitContainerHeight; }
set { m_HorizontalFitContainerHeight = value; }
}
/// <summary>
/// Gets or sets the content orientation. Default value is Horizontal.
/// </summary>
public virtual eContentOrientation ContentOrientation
{
get {return m_ContentOrientation;}
set {m_ContentOrientation=value;}
}
/// <summary>
/// Gets or sets the content vertical alignment. Default value is Middle.
/// </summary>
public virtual eContentVerticalAlignment ContentVerticalAlignment
{
get {return m_ContentVerticalAlignment;}
set {m_ContentVerticalAlignment=value;}
}
/// <summary>
/// Gets or sets the block line vertical alignment. Default value is Middle.
/// </summary>
public virtual eContentVerticalAlignment BlockLineAlignment
{
get { return m_BlockLineAlignment; }
set { m_BlockLineAlignment = value; }
}
/// <summary>
/// Gets or sets the content horizontal alignment. Default value is Left.
/// </summary>
public virtual eContentAlignment ContentAlignment
{
get {return m_ContentAlignment;}
set {m_ContentAlignment=value;}
}
/// <summary>
/// Gets or sets whether all content blocks are resized so they have same height which is height of the tallest content block. Default value is false.
/// </summary>
public virtual bool EvenHeight
{
get {return m_EvenHeight;}
set {m_EvenHeight=value;}
}
/// <summary>
/// Gets or sets whether oversized blocks are resized based on the percentage reduction instead of based on equal pixel distribution. Default value is false.
/// </summary>
public virtual bool OversizeDistribute
{
get { return m_OversizeDistribute; }
set { m_OversizeDistribute = value; }
}
/// <summary>
/// Gets or sets whether content is wrapped into new line if it exceeds the width of the container.
/// </summary>
public bool MultiLine
{
get {return m_MultiLine;}
set {m_MultiLine=value;}
}
/// <summary>
/// Gets or sets whether layout is right-to-left.
/// </summary>
public bool RightToLeft
{
get { return m_RightToLeft; }
set { m_RightToLeft = value; }
}
#endregion
}
/// <summary>
/// Represents event arguments for SerialContentLayoutManager.NextPosition event.
/// </summary>
public class LayoutManagerPositionEventArgs : EventArgs
{
/// <summary>
/// Gets or sets the block that is layed out.
/// </summary>
public IBlock Block = null;
/// <summary>
/// Gets or sets the current block position.
/// </summary>
public Point CurrentPosition = Point.Empty;
/// <summary>
/// Gets or sets the calculated next block position.
/// </summary>
public Point NextPosition = Point.Empty;
/// <summary>
/// Cancels default position calculation.
/// </summary>
public bool Cancel = false;
}
/// <summary>
/// Represents event arguments for the SerialContentLayoutManager layout events.
/// </summary>
public class LayoutManagerLayoutEventArgs : EventArgs
{
/// <summary>
/// Gets or sets the reference block object.
/// </summary>
public IBlock Block = null;
/// <summary>
/// Gets or sets the position block will assume.
/// </summary>
public Point CurrentPosition = Point.Empty;
/// <summary>
/// Cancel the layout of the block, applies only to BeforeXXX layout event.
/// </summary>
public bool CancelLayout = false;
/// <summary>
/// Gets or sets the visibility index of the block.
/// </summary>
public int BlockVisibleIndex = 0;
/// <summary>
/// Creates new instance of the class and initializes it with default values.
/// </summary>
public LayoutManagerLayoutEventArgs(IBlock block, Point currentPosition, int visibleIndex)
{
this.Block = block;
this.CurrentPosition = currentPosition;
this.BlockVisibleIndex = visibleIndex;
}
}
/// <summary>
/// Delegate for SerialContentLayoutManager.NextPosition event.
/// </summary>
public delegate void LayoutManagerPositionEventHandler(object sender, LayoutManagerPositionEventArgs e);
/// <summary>
/// Delegate for the SerialContentLayoutManager layout events.
/// </summary>
public delegate void LayoutManagerLayoutEventHandler(object sender, LayoutManagerLayoutEventArgs e);
}

View File

@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1641B2CE-259C-4A52-A460-48C936B13951}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DevComponents.DotNetBar.Layout</RootNamespace>
<AssemblyName>DevComponents.DotNetBar.Layout</AssemblyName>
<StartupObject>
</StartupObject>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>dotnetbar.snk</AssemblyOriginatorKeyFile>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>2.0</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;LAYOUT</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;LAYOUT</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Release\DevComponents.DotNetBar.Layout.XML</DocumentationFile>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'ReleaseLayout|AnyCPU' ">
<OutputPath>bin\ReleaseLayout\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'ReleaseTrialLayout|AnyCPU' ">
<OutputPath>bin\ReleaseTrialLayout\</OutputPath>
<DefineConstants>TRACE;LAYOUT;TRIAL</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Design" />
<Reference Include="System.Drawing" />
<Reference Include="System.Drawing.Design" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Background.cs" />
<Compile Include="BorderColors.cs" />
<Compile Include="BorderPattern.cs" />
<Compile Include="ColorHelpers.cs" />
<Compile Include="ContentManager\BlockLayoutManager.cs" />
<Compile Include="ContentManager\Enums.cs" />
<Compile Include="ContentManager\IBlock.cs" />
<Compile Include="ContentManager\IBlockExtended.cs" />
<Compile Include="ContentManager\IContentLayoutManager.cs" />
<Compile Include="ContentManager\SerialContentLayoutManager.cs" />
<Compile Include="DotNetBarResourcesAttribute.cs" />
<Compile Include="LayoutLabelItem.cs" />
<Compile Include="Symbols.cs" />
<Compile Include="TextDrawing.cs" />
<Compile Include="TextMarkup\BarUtilities.cs" />
<Compile Include="TextMarkup\DisplayHelp.cs" />
<Compile Include="DoubleHelpers.cs" />
<Compile Include="DrawingHelpers.cs" />
<Compile Include="Helpers.cs" />
<Compile Include="InsertMarker.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ItemLayout.cs" />
<Compile Include="LayoutContext.cs" />
<Compile Include="LayoutControl.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="LayoutControlItem.cs" />
<Compile Include="LayoutGroup.cs" />
<Compile Include="LayoutItemBase.cs">
</Compile>
<Compile Include="LayoutItemCollection.cs" />
<Compile Include="LayoutSpacerItem.cs" />
<Compile Include="PaintContext.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="dotnetbar.snk" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<EmbeddedResource Include="SystemImages\FontAwesome.ttf" />
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="SimpleStyle.cs" />
<Compile Include="TextMarkup\BodyElement.cs" />
<Compile Include="TextMarkup\ContainerElement.cs" />
<Compile Include="TextMarkup\Div.cs" />
<Compile Include="TextMarkup\EndMarkupElement.cs" />
<Compile Include="TextMarkup\ExpandElement.cs" />
<Compile Include="TextMarkup\FontChangeElement.cs" />
<Compile Include="TextMarkup\FontElement.cs" />
<Compile Include="TextMarkup\Heading.cs" />
<Compile Include="TextMarkup\HyperLink.cs" />
<Compile Include="TextMarkup\IActiveMarkupElement.cs" />
<Compile Include="TextMarkup\ImageElement.cs" />
<Compile Include="TextMarkup\Italic.cs" />
<Compile Include="TextMarkup\MarkupDrawContext.cs" />
<Compile Include="TextMarkup\MarkupElement.cs" />
<Compile Include="TextMarkup\MarkupElementCollection.cs" />
<Compile Include="TextMarkup\MarkupLayoutManager.cs" />
<Compile Include="TextMarkup\MarkupParser.cs" />
<Compile Include="TextMarkup\MarkupSettings.cs" />
<Compile Include="TextMarkup\NewLine.cs" />
<Compile Include="TextMarkup\Paragraph.cs" />
<Compile Include="TextMarkup\Span.cs" />
<Compile Include="TextMarkup\Strike.cs" />
<Compile Include="TextMarkup\Strong.cs" />
<Compile Include="TextMarkup\SymbolElement.cs" />
<Compile Include="TextMarkup\TextElement.cs" />
<Compile Include="TextMarkup\Underline.cs" />
<Compile Include="Thickness.cs" />
<Compile Include="WinApi.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DotNetBar.csproj">
<Project>{36546CE3-335C-4AB6-A2F3-40F8C818BC66}</Project>
<Name>DotNetBar</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="LayoutControl.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,22 @@
using System;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Summary description for DotNetBarResourcesAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public class DotNetBarLayoutResourcesAttribute:System.Attribute
{
private string m_NamespacePrefix="";
public DotNetBarLayoutResourcesAttribute(string namespacePrefix)
{
m_NamespacePrefix=namespacePrefix;
}
public virtual string NamespacePrefix
{
get {return m_NamespacePrefix;}
}
}
}

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace DevComponents.DotNetBar.Layout
{
internal static class DoubleHelpers
{
/// <summary>
/// Gets whether values are close.
/// </summary>
/// <param name="value1">First value.</param>
/// <param name="value2">Second value</param>
/// <returns>true if values are close enough</returns>
public static bool AreClose(double value1, double value2)
{
if (value1 == value2)
{
return true;
}
double num2 = ((Math.Abs(value1) + Math.Abs(value2)) + 10.0) * 2.2204460492503131E-16;
double num = value1 - value2;
return ((-num2 < num) && (num2 > num));
}
/// <summary>
/// Gets whether value is zero
/// </summary>
/// <param name="value">value to check</param>
/// <returns>true if value is considered zero</returns>
public static bool IsZero(double value)
{
return (Math.Abs(value) < 2.2204460492503131E-15);
}
/// <summary>
/// Gets whether value is not an number.
/// </summary>
/// <param name="value">value to test</param>
/// <returns>true if value is not an number</returns>
public static bool IsNaN(double value)
{
NanUnion union = new NanUnion();
union.DoubleValue = value;
ulong num = union.UintValue & 18442240474082181120L;
ulong num2 = union.UintValue & ((ulong)0xfffffffffffffL);
if ((num != 0x7ff0000000000000L) && (num != 18442240474082181120L))
{
return false;
}
return (num2 != 0L);
}
[StructLayout(LayoutKind.Explicit)]
private struct NanUnion
{
// Fields
[FieldOffset(0)]
internal double DoubleValue;
[FieldOffset(0)]
internal ulong UintValue;
}
}
}

View File

@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
internal static class DrawingHelpers
{
/// <summary>
/// Draws the border.
/// </summary>
/// <param name="g">Graphics canvas.</param>
/// <param name="bounds">Bounds for border.</param>
/// <param name="borderThickness">Border thickness.</param>
/// <param name="borderPattern">Border pattern.</param>
/// <param name="borderColor">Border color.</param>
public static void DrawBorder(Graphics g, RectangleF bounds, Thickness borderThickness, BorderPattern borderPattern, BorderColors borderColor)
{
if (borderColor.IsEmpty || borderThickness.IsZero || borderPattern.IsEmpty) return;
Region oldClip = g.Clip;
g.SetClip(bounds, System.Drawing.Drawing2D.CombineMode.Intersect);
bounds.Width -= Math.Max(1, (float)borderThickness.Horizontal / 2);
bounds.Height -= Math.Max(1, (float)borderThickness.Vertical / 2);
if (borderThickness.Left > 1)
bounds.X += (float)borderThickness.Left / 2;
if (borderThickness.Top > 1)
bounds.Y += (float)borderThickness.Top / 2;
if (borderThickness.Left > 0d && !borderColor.Left.IsEmpty && borderPattern.IsLeftVisible)
{
using (Pen pen = new Pen(borderColor.Left, (float)borderThickness.Left))
{
pen.DashStyle = (System.Drawing.Drawing2D.DashStyle)borderPattern.Left;
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawLine(pen, bounds.X, bounds.Y - (float)(borderThickness.Top / 2), bounds.X, bounds.Bottom + (float)(borderThickness.Bottom / 2));
}
}
if (borderThickness.Right > 0d && !borderColor.Right.IsEmpty && borderPattern.IsRightVisible)
{
using (Pen pen = new Pen(borderColor.Right, (float)borderThickness.Right))
{
pen.DashStyle = (System.Drawing.Drawing2D.DashStyle)borderPattern.Right;
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawLine(pen, bounds.Right, bounds.Y - (float)(borderThickness.Top / 2), bounds.Right, bounds.Bottom + (float)(borderThickness.Bottom / 2));
}
}
if (borderThickness.Top > 0d && !borderColor.Top.IsEmpty && borderPattern.IsTopVisible)
{
using (Pen pen = new Pen(borderColor.Top, (float)borderThickness.Top))
{
pen.DashStyle = (System.Drawing.Drawing2D.DashStyle)borderPattern.Top;
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawLine(pen, bounds.X, bounds.Y, bounds.Right, bounds.Y);
}
}
if (borderThickness.Bottom > 0d && !borderColor.Bottom.IsEmpty && borderPattern.IsBottomVisible)
{
using (Pen pen = new Pen(borderColor.Bottom, (float)borderThickness.Bottom))
{
pen.DashStyle = (System.Drawing.Drawing2D.DashStyle)borderPattern.Bottom;
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawLine(pen, bounds.X, bounds.Bottom, bounds.Right, bounds.Bottom);
}
}
g.Clip = oldClip;
if (oldClip != null) oldClip.Dispose();
}
public static void PaintStyle(Graphics g, SimpleStyle style, Rectangle bounds)
{
if (style.IsPainted && !bounds.IsEmpty)
{
if (style.Background.IsBackgroundSet)
{
using (Brush brush = style.Background.CreateBrush(bounds))
g.FillRectangle(brush, bounds);
}
if (!style.BorderColors.IsEmpty && !style.BorderThickness.IsZero)
{
DrawingHelpers.DrawBorder(g, bounds, style.BorderThickness, style.BorderPattern, style.BorderColors);
}
}
}
}
}

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace DevComponents.DotNetBar.Layout
{
internal static class Helpers
{
public static Size Max(Size s1, Size s2)
{
return new Size(Math.Max(s1.Width, s2.Width), Math.Max(s1.Height, s2.Height));
}
public static Rectangle Deflate(Rectangle r, System.Windows.Forms.Padding padding)
{
r.X += padding.Left;
r.Width -= padding.Horizontal;
r.Y += padding.Top;
r.Height -= padding.Vertical;
return r;
}
public static Rectangle Deflate(Rectangle r, DevComponents.DotNetBar.Padding padding)
{
r.X += padding.Left;
r.Width -= padding.Horizontal;
r.Y += padding.Top;
r.Height -= padding.Vertical;
return r;
}
public static int GetTextBaseline(Control ctrl, ContentAlignment alignment)
{
return GetTextBaseline(ctrl, ctrl.Font, alignment);
}
public static int GetTextBaseline(Control ctrl, Font font, ContentAlignment alignment)
{
Rectangle clientRect = ctrl.ClientRectangle;
int ascent = 0;
int height = 0;
using (Graphics g = ctrl.CreateGraphics())
{
IntPtr hdc = g.GetHdc();
IntPtr hFont = font.ToHfont();
try
{
IntPtr oldObject = WinApi.SelectObject(hdc, hFont);
WinApi.TEXTMETRIC tm = new WinApi.TEXTMETRIC();
WinApi.GetTextMetrics(new HandleRef(ctrl, hdc), tm);
ascent = tm.tmAscent + 1;
height = tm.tmHeight;
WinApi.SelectObject(hdc, oldObject);
}
finally
{
WinApi.DeleteObject(hFont);
g.ReleaseHdc(hdc);
}
}
if ((alignment & (ContentAlignment.TopRight | ContentAlignment.TopCenter | ContentAlignment.TopLeft)) != (ContentAlignment)0)
{
return (clientRect.Top + ascent);
}
if ((alignment & (ContentAlignment.MiddleRight | ContentAlignment.MiddleCenter | ContentAlignment.MiddleLeft)) != (ContentAlignment)0)
{
return (((clientRect.Top + (clientRect.Height / 2)) - (height / 2)) + ascent);
}
return ((clientRect.Bottom - height) + ascent);
}
public static bool IsEmpty(System.Windows.Forms.Padding p)
{
return p.Left == 0 && p.Right == 0 && p.Top == 0 && p.Bottom == 0;
}
}
}

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace DevComponents.DotNetBar.Layout
{
internal class InsertMarker : Control
{
#region Constructor
/// <summary>
/// Initializes a new instance of the InsertMarker class.
/// </summary>
public InsertMarker()
{
this.SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
}
#endregion
#region Implementation
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
using (SolidBrush brush = new SolidBrush(this.ForeColor))
{
g.FillRectangle(brush, new Rectangle(0, 0, this.Width, 2));
g.FillRectangle(brush, new Rectangle(0, this.Height - 2, this.Width, 2));
g.FillRectangle(brush, this.Width / 2 - 1, 0, 2, this.Height);
}
base.OnPaint(e);
}
protected override void OnHandleCreated(EventArgs e)
{
UpdateRegion();
base.OnHandleCreated(e);
}
protected override void OnResize(EventArgs e)
{
UpdateRegion();
base.OnResize(e);
}
private void UpdateRegion()
{
GraphicsPath path = new GraphicsPath();
path.AddLine(0, 0, this.Width, 0);
path.AddLine(this.Width, 0, this.Width, 2);
path.AddLine(this.Width, 2, this.Width / 2 - 1, 2);
path.AddLine(this.Width / 2 + 1, 2, this.Width / 2 + 1, this.Height-2);
path.AddLine(this.Width / 2 + 1, this.Height - 2, this.Width, this.Height-2);
path.AddLine(this.Width, this.Height - 2, this.Width, this.Height);
path.AddLine(this.Width, this.Height, 0, this.Height);
path.AddLine(0, this.Height, 0, this.Height-2);
path.AddLine(0, this.Height - 2, this.Width/2-1, this.Height-2);
path.AddLine(this.Width / 2 - 1, this.Height - 2, this.Width/2-1, 2);
path.AddLine(this.Width / 2 - 1, 2, 0, 2);
path.CloseAllFigures();
Region reg = new Region();
reg.MakeEmpty();
reg.Union(path);
path.Widen(SystemPens.Control);
//Region r2 = new Region(path);
reg.Union(path);
this.Region = reg;
}
#endregion
}
}

View File

@@ -0,0 +1,371 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
internal class ItemLayout
{
public void Layout(LayoutGroup group, Rectangle clientBounds, LayoutContext context)
{
if (clientBounds.IsEmpty) return;
List<LayoutItemStrip> strips = SliceItemsInStrips(group, clientBounds, context);
ResizeStrips(strips, clientBounds);
Rectangle totalBounds = FinalizeItemSize(strips, clientBounds, context);
group.ActualBounds = totalBounds;
//Console.WriteLine("{0} -> {1}", clientBounds, totalBounds);
}
private LayoutContext CreateLayoutContext(LayoutContext context, int startAbsoluteIndex)
{
LayoutContext newContext = new LayoutContext(context.LayoutControl, context.Graphics, context.Font);
newContext.RightToLeft = context.RightToLeft;
newContext.AbsoluteIndex = startAbsoluteIndex;
return newContext;
}
private Rectangle FinalizeItemSize(List<LayoutItemStrip> strips, Rectangle clientBounds, LayoutContext context)
{
int sizeLimit = GetSizeLimit(clientBounds);
int stripSizeLimit = GetStripsSizeLimit(clientBounds);
Rectangle totalBounds = new Rectangle(clientBounds.Location, Size.Empty);
Point loc = clientBounds.Location;
Rectangle fullClientBounds = clientBounds;
int absIndex = context.AbsoluteIndex;
foreach (LayoutItemStrip strip in strips)
{
LayoutItemBase layoutItem = strip.Items[0];
int clientBoundsWidth = clientBounds.Width;
if (strip.IsLeftSpanStrip)
{
Size size = new Size(Math.Max(MinItemSize(layoutItem), ActualItemSize(layoutItem, fullClientBounds.Width)),
Math.Max(strip.MinStripHeightAbsolute, clientBounds.Height));
Rectangle r = new Rectangle(loc, size);
clientBounds.X += size.Width;
clientBounds.Width -= size.Width;
loc = clientBounds.Location;
layoutItem.SetBounds(r, (layoutItem.SharedTextSizeEnabled ? context.LargestTextSize : layoutItem.RealTextSize));
if (layoutItem is LayoutGroup)
{
LayoutContext groupContext = CreateLayoutContext(context, absIndex++);
((LayoutGroup)layoutItem).Layout(groupContext);
absIndex = groupContext.AbsoluteIndex;
}
totalBounds = Rectangle.Union(r, totalBounds);
layoutItem.AbsoluteIndex = absIndex++;
continue;
}
else if (strip.IsRightSpanStrip)
{
Size size = new Size(Math.Max(MinItemSize(layoutItem), ActualItemSize(layoutItem, fullClientBounds.Width)),
Math.Max(strip.MinStripHeightAbsolute, clientBounds.Height));
Rectangle r = new Rectangle(clientBounds.Right - size.Width, clientBounds.Y, size.Width, size.Height);
clientBounds.Width -= size.Width;
layoutItem.SetBounds(r, layoutItem.SharedTextSizeEnabled ? context.LargestTextSize : layoutItem.RealTextSize);
if (layoutItem is LayoutGroup)
{
LayoutContext groupContext = CreateLayoutContext(context, 10000/*absIndex++*/); // Pushing the tab index for right span strip to the right most
((LayoutGroup)layoutItem).Layout(groupContext);
//absIndex = groupContext.AbsoluteIndex;
}
totalBounds = Rectangle.Union(r, totalBounds);
layoutItem.AbsoluteIndex = absIndex++;
//layoutItem.ActualTextSize = layoutItem.SharedTextSizeEnabled ? context.LargestTextSize : layoutItem.RealTextSize;
continue;
}
bool repeat = false;
int repeatCount = 0;
int startAbsIndex = absIndex;
do
{
loc.X = clientBounds.X;
repeatCount++;
absIndex = startAbsIndex;
int totalPercentWidth = 0;
foreach (LayoutItemBase item in strip.Items)
{
Size size = new Size(Math.Max(MinItemSize(item), ActualItemSize(item, clientBoundsWidth - strip.TotalFixedWidth)),
strip.StripHeightAbsolute);
if (item.WidthType == eLayoutSizeType.Percent)
totalPercentWidth += item.Width;
if (strip.Items.Count == 1 && size.Width < clientBoundsWidth && clientBoundsWidth >= MinItemSize(item) && item.WidthType == eLayoutSizeType.Percent)
size.Width = clientBoundsWidth;
else if (loc.X + size.Width > clientBounds.X + clientBoundsWidth && strip.Items.Count > 1)
{
if (strip.Items[strip.Items.Count - 1] == item && MinItemSize(item) <= clientBoundsWidth - (loc.X - clientBounds.X))
size.Width = clientBoundsWidth - (loc.X - clientBounds.X);
else
{
clientBoundsWidth -= (loc.X + size.Width) - (clientBounds.X + clientBoundsWidth);
repeat = true;
break;
}
}
else if(strip.TotalFixedWidth == 0 && totalPercentWidth == 100 && strip.Items[strip.Items.Count - 1] == item && size.Width<clientBoundsWidth - (loc.X - clientBounds.X))
size.Width = clientBoundsWidth - (loc.X - clientBounds.X);
Rectangle r = new Rectangle(loc, size);
item.StripTextBaseline = strip.LargestTextBaseline;
item.SetBounds(r, item.SharedTextSizeEnabled ? context.LargestTextSize : item.RealTextSize);
if (item is LayoutGroup)
{
LayoutContext groupContext = CreateLayoutContext(context, absIndex++);
((LayoutGroup)item).Layout(groupContext);
absIndex = groupContext.AbsoluteIndex;
}
item.AbsoluteIndex = absIndex++;
totalBounds = Rectangle.Union(r, totalBounds);
loc.X += size.Width;
}
} while (repeat && repeatCount < 2);
loc.Y += strip.StripHeightAbsolute;
loc.X = clientBounds.X;
}
context.AbsoluteIndex = absIndex;
return totalBounds;
}
private void ResizeStrips(List<LayoutItemStrip> strips, Rectangle clientBounds)
{
int totalFixedSize = 0;
List<LayoutItemStrip> percenageStrips = new List<LayoutItemStrip>();
foreach (LayoutItemStrip strip in strips)
{
if (strip.StripHeightPercentage == 0)
totalFixedSize += strip.StripHeightAbsolute;
else
percenageStrips.Add(strip);
}
if (percenageStrips.Count > 0)
{
int sizeLimit = GetStripsSizeLimit(clientBounds);
if (totalFixedSize < sizeLimit)
sizeLimit -= totalFixedSize;
foreach (LayoutItemStrip strip in percenageStrips)
{
strip.StripHeightAbsolute = Math.Max(strip.StripHeightAbsolute, (sizeLimit * strip.StripHeightPercentage) / 100);
strip.StripHeightAbsolute = Math.Max(strip.StripHeightAbsolute, strip.MinStripHeightAbsolute);
}
}
}
private List<LayoutItemStrip> SliceItemsInStrips(LayoutGroup group, Rectangle clientBounds, LayoutContext context)
{
LayoutItemCollection items = group.Items;
List<LayoutItemStrip> strips = new List<LayoutItemStrip>();
if (items.Count == 0) return strips;
int sizeLimit = GetSizeLimit(clientBounds);
int currentPercent = 0;
int currentFixedSize = 0;
int currentTotalMinSize = 0;
int start = 0, end = items.Count;
Size largestTextSize = Size.Empty;
LayoutItemStrip currentStrip = new LayoutItemStrip();
// Check whether first or last item spans total client bounds effectively reducing the client width
int firstVisibleIndex = GetFirstVisibleItemIndex(items);
int lastVisibleIndex = GetLastVisibleItemIndex(items);
LayoutItemBase spanItem = null;
if (firstVisibleIndex >= 0) spanItem = items[firstVisibleIndex];
if (spanItem != null && !IsFixedStripSize(spanItem) && ItemStripSize(spanItem) >= 100)
{
if (spanItem.IsTextSizeShared)
largestTextSize = Helpers.Max(largestTextSize, spanItem.MeasureText(context));
else
spanItem.MeasureText(context);
sizeLimit -= ActualItemSize(spanItem, clientBounds.Width);
currentStrip.IsLeftSpanStrip = true;
currentStrip.StripHeightPercentage = 100;
currentStrip.MinStripHeightAbsolute = spanItem.MinSize.Height;
currentStrip.Items.Add(spanItem);
strips.Add(currentStrip);
currentStrip = new LayoutItemStrip();
start = firstVisibleIndex + 1;
}
if (firstVisibleIndex != lastVisibleIndex && lastVisibleIndex > 0)
{
spanItem = items[lastVisibleIndex];
if (!IsFixedStripSize(spanItem) && ItemStripSize(spanItem) >= 100 && !(!IsFixedSize(spanItem) && ItemSize(spanItem) >= 100))
{
if (spanItem.IsTextSizeShared)
largestTextSize = Helpers.Max(largestTextSize, spanItem.MeasureText(context));
else
spanItem.MeasureText(context);
sizeLimit -= ActualItemSize(spanItem, clientBounds.Width);
currentStrip.IsRightSpanStrip = true;
currentStrip.StripHeightPercentage = 100;
currentStrip.MinStripHeightAbsolute = spanItem.MinSize.Height;
currentStrip.Items.Add(spanItem);
strips.Add(currentStrip);
currentStrip = new LayoutItemStrip();
end = lastVisibleIndex;
}
}
for (int i = start; i < end; i++)
{
LayoutItemBase item = items[i];
if (!item.Visible) continue;
int itemSize = ItemSize(item);
if (item.IsTextSizeShared)
largestTextSize = Helpers.Max(largestTextSize, item.MeasureText(context));
else
item.MeasureText(context);
if (IsFixedSize(item))
{
if (currentTotalMinSize + itemSize > sizeLimit && currentTotalMinSize > 0 || currentPercent >= 100)
{
// Trigger new line
currentStrip.TotalFixedWidth = currentFixedSize;
strips.Add(currentStrip);
currentStrip = new LayoutItemStrip();
currentFixedSize = Math.Max(itemSize, MinItemSize(item)); ;
currentTotalMinSize = itemSize;
currentPercent = 0;
}
else
{
currentFixedSize += Math.Max(itemSize, MinItemSize(item));
currentTotalMinSize += itemSize;
}
if (item.HeightType == eLayoutSizeType.Percent)
currentStrip.StripHeightPercentage = Math.Max(currentStrip.StripHeightPercentage, item.Height);
else
currentStrip.StripHeightAbsolute = Math.Max(currentStrip.StripHeightAbsolute, item.Height);
}
else
{
int minItemSize = MinItemSize(item);
if (currentPercent + itemSize > 100 && currentPercent > 0 || (currentTotalMinSize + minItemSize > sizeLimit || itemSize > 100) && currentTotalMinSize > 0)
{
// Trigger new line
currentStrip.TotalFixedWidth = currentFixedSize;
strips.Add(currentStrip);
currentStrip = new LayoutItemStrip();
currentFixedSize = 0;
currentTotalMinSize = 0;
currentPercent = 0;
}
//else
//{
currentPercent += itemSize;
currentTotalMinSize += minItemSize;
//}
if (item.HeightType == eLayoutSizeType.Percent)
currentStrip.StripHeightPercentage = Math.Max(currentStrip.StripHeightPercentage, item.Height);
else
currentStrip.StripHeightAbsolute = Math.Max(currentStrip.StripHeightAbsolute, item.Height);
}
currentStrip.MinStripHeightAbsolute = Math.Max(currentStrip.MinStripHeightAbsolute, item.MinSize.Height);
if (item.IsTextBaselineShared)
currentStrip.LargestTextBaseline = Math.Max(currentStrip.LargestTextBaseline, item.TextBaseline);
currentStrip.Items.Add(item);
}
if (currentStrip.Items.Count > 0)
{
strips.Add(currentStrip);
currentStrip.TotalFixedWidth = currentFixedSize;
}
context.LargestTextSize = largestTextSize;
return strips;
}
private int GetFirstVisibleItemIndex(LayoutItemCollection items)
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].Visible) return i;
}
return -1;
}
private int GetLastVisibleItemIndex(LayoutItemCollection items)
{
for (int i = items.Count - 1; i >= 0; i--)
{
if (items[i].Visible) return i;
}
return -1;
}
private int ActualItemSize(LayoutItemBase item, int clientSize)
{
if (item.WidthType == eLayoutSizeType.Absolute)
return item.Width;
else
return (Math.Min(100, (item.Width == 99 ? 100 : item.Width)) * clientSize) / 100; // 99% is special case where we have relative size item inside of fixed size items on single line
}
private int MinItemSize(LayoutItemBase item)
{
return item.MinSize.Width;
}
private int GetSizeLimit(Rectangle clientBounds)
{
return clientBounds.Width;
}
private int GetStripsSizeLimit(Rectangle clientBounds)
{
return clientBounds.Height;
}
private int ItemSize(LayoutItemBase item)
{
return item.Width;
}
private int ItemStripSize(LayoutItemBase item)
{
return item.Height;
}
private bool IsFixedSize(LayoutItemBase item)
{
return item.IsWidthFixed;
}
private bool IsFixedStripSize(LayoutItemBase item)
{
return item.IsHeightFixed;
}
}
internal class LayoutItemStrip
{
/// <summary>
/// Collection of items inside of strip.
/// </summary>
public List<LayoutItemBase> Items = new List<LayoutItemBase>();
/// <summary>
/// Total width of all items with fixed width in the strip.
/// </summary>
public int TotalFixedWidth = 0;
/// <summary>
/// True if this is left most strip in group which spans whole group height.
/// </summary>
public bool IsLeftSpanStrip = false;
/// <summary>
/// True if this is right most strip in group which spans whole group height.
/// </summary>
public bool IsRightSpanStrip = false;
/// <summary>
/// Strip height determined as maximum height of items in it.
/// </summary>
public int StripHeightAbsolute = 0;
/// <summary>
/// Minimum strip height according to the larges MinSize of contained items.
/// </summary>
public int MinStripHeightAbsolute = 0;
/// <summary>
/// Maximum percentage strip height for all items in it.
/// </summary>
public int StripHeightPercentage = 0;
/// <summary>
/// The largest text-baseline for all items in strip.
/// </summary>
public int LargestTextBaseline = 0;
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
public class LayoutContext
{
/// <summary>
/// Initializes a new instance of the LayoutContext class.
/// </summary>
/// <param name="layoutControl"></param>
/// <param name="graphics"></param>
/// <param name="font"></param>
public LayoutContext(LayoutControl layoutControl, Graphics graphics, Font font)
{
LayoutControl = layoutControl;
Graphics = graphics;
Font = font;
FontBaseline = Helpers.GetTextBaseline(layoutControl, font, ContentAlignment.TopLeft);
RightToLeft = (layoutControl.RightToLeft == System.Windows.Forms.RightToLeft.Yes);
}
public LayoutControl LayoutControl = null;
public Graphics Graphics = null;
public Font Font = null;
public Size LargestTextSize = Size.Empty;
public int FontBaseline = 0;
public bool RightToLeft = false;
public int AbsoluteIndex = 0;
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,484 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Represents layout item which hosts a Windows Forms Control.
/// </summary>
[Designer("DevComponents.DotNetBar.Layout.Design.LayoutControlItemDesigner, DevComponents.DotNetBar.Layout.Design, Version=14.1.0.37, Culture=neutral, PublicKeyToken=7eb7c3a35b91de04")]
public class LayoutControlItem : LayoutItemBase
{
#region Constructor
protected override void OnDispose()
{
UnhookControlEventHandlers(_Control);
base.OnDispose();
}
#endregion
#region Implementation
protected override void OnUpdateLayout()
{
base.OnUpdateLayout();
if (_Control != null)
{
Rectangle bounds = Helpers.Deflate(this.Bounds, this.Padding);
Rectangle r = bounds;
if (this.TextVisible && !string.IsNullOrEmpty(this.Text))
{
Rectangle actualTextBounds = this.ActualTextBounds;
if (IsImageVisible)
actualTextBounds = Rectangle.Union(actualTextBounds, this.ActualImageBounds);
if (this.TextPosition == eLayoutPosition.Default || this.TextPosition == eLayoutPosition.Left)
{
r.X = actualTextBounds.Right + _TextControlSpacing;
r.Width = bounds.Right - r.X;
}
else if (this.TextPosition == eLayoutPosition.Top)
{
r.Y = actualTextBounds.Bottom + _TextControlSpacing;
r.Height = bounds.Bottom - r.Y;
}
else if (this.TextPosition == eLayoutPosition.Bottom)
{
r.Height = actualTextBounds.Y - bounds.Y - _TextControlSpacing;
}
else if (this.TextPosition == eLayoutPosition.Right)
{
r.Width = actualTextBounds.X - r.X - _TextControlSpacing;
}
}
if (_Control.Margin.Horizontal > 0 || _Control.Margin.Vertical > 0)
{
r.X += _Control.Margin.Left;
r.Width -= _Control.Margin.Horizontal;
r.Y += _Control.Margin.Top;
r.Height -= _Control.Margin.Vertical;
}
if (!_ControlSize.IsEmpty && _Control.Dock != DockStyle.Fill && (_ControlSize.Width > 0 && r.Width > _ControlSize.Width) || (_ControlSize.Height > 0 && r.Height > _ControlSize.Height))
{
Size controlSize = new Size(_ControlSize.Width > 0 ? Math.Min(r.Width, _ControlSize.Width) : r.Width,
_ControlSize.Height > 0 ? Math.Min(r.Height, _ControlSize.Height) : r.Height);
if (_Control.Dock != DockStyle.None)
{
if (_Control.Dock == DockStyle.Left)
r = new Rectangle(r.X, r.Y, controlSize.Width, r.Height);
else if (_Control.Dock == DockStyle.Right)
r = new Rectangle(r.Right - controlSize.Width, r.Y, controlSize.Width, r.Height);
else if (_Control.Dock == DockStyle.Top)
r = new Rectangle(r.X, r.Y, r.Width, controlSize.Height);
else if (_Control.Dock == DockStyle.Bottom)
r = new Rectangle(r.X, r.Bottom - controlSize.Height, r.Width, controlSize.Height);
}
else
{
if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom))
{
// Center into the bounding box
r.X += (r.Width - controlSize.Width) / 2;
r.Y += (r.Height - controlSize.Height) / 2;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Top))
{
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right))
{
r.X += (r.Width - controlSize.Width) / 2;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom))
{
r.Y += (r.Height - controlSize.Height) / 2;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Bottom))
{
r.Y = r.Bottom - controlSize.Height;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right))
{
r.Y = r.Bottom - controlSize.Height;
r.X += (r.Width - controlSize.Width) / 2;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Right | AnchorStyles.Top))
{
r.X = r.Right - controlSize.Width;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Right | AnchorStyles.Bottom))
{
r.X = r.Right - controlSize.Width;
r.Y = r.Bottom - controlSize.Height;
r.Size = controlSize;
}
else if (_Control.Anchor == (AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Top))
{
r.X = r.Right - controlSize.Width;
r.Y += (r.Height - controlSize.Height) / 2;
r.Size = controlSize;
}
else
r.Size = controlSize;
}
}
_Control.Bounds = r;
}
}
protected override void OnPaintBackground(PaintContext context)
{
base.OnPaintBackground(context);
if (IsKeyboardFocusWithin && context.FocusStyle != null)
{
DrawingHelpers.PaintStyle(context.Graphics, context.FocusStyle, this.Bounds);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ScaleItem(SizeF factor)
{
base.ScaleItem(factor);
bool widthChanged = factor.Width != 1f;
bool heightChanged = factor.Height != 1f;
if (!_ControlSize.IsEmpty && (widthChanged || heightChanged))
{
Size newSize = new Size();
if (widthChanged)
newSize.Width = (int)(_ControlSize.Width * factor.Width);
else
newSize.Width = _ControlSize.Width;
if (heightChanged)
newSize.Height = (int)(_ControlSize.Height * factor.Height);
else
newSize.Height = _ControlSize.Height;
ControlSize = newSize;
}
}
internal override void UpdateScrollBounds(int xScroll, int yScroll, bool moveControls)
{
base.UpdateScrollBounds(xScroll, yScroll, moveControls);
if (moveControls && _Control != null)
_Control.Location = new Point(_Control.Location.X + xScroll, _Control.Location.Y + yScroll);
}
protected override Size OnMeasureText(LayoutContext c)
{
if (_Control is TextBoxBase && this.TextPosition == eLayoutPosition.Default)
{
TextBoxBase textBox = (TextBoxBase)_Control;
int textBaseLine = Helpers.GetTextBaseline(_Control, ContentAlignment.TopLeft);
if (textBox is DevComponents.DotNetBar.Controls.TextBoxX)
textBaseLine += 3;
else if (textBox.BorderStyle == BorderStyle.FixedSingle || textBox.BorderStyle == BorderStyle.None)
textBaseLine += 2;
else if (textBox.BorderStyle == BorderStyle.Fixed3D)
textBaseLine += 3;
_ControlTextBaseline = textBaseLine;
}
else
_ControlTextBaseline = 0;
return base.OnMeasureText(c);
}
internal override int TextBaseline
{
get
{
if (_ControlTextBaseline > 0 && _ControlTextBaseline > base.TextBaseline)
return _ControlTextBaseline;
return base.TextBaseline;
}
set
{
base.TextBaseline = value;
}
}
private int _ControlTextBaseline = 0;
private Control _Control = null;
/// <summary>
/// Gets or sets the control managed by layout item.
/// </summary>
[DefaultValue(null), Category("Data"), Description("Indicates control managed by layout item.")]
public Control Control
{
get { return _Control; }
set
{
if (value != _Control)
{
Control oldValue = _Control;
_Control = value;
OnControlChanged(oldValue, value);
}
}
}
private void UnhookControlEventHandlers(Control control)
{
if (control == null) return;
control.Enter -= ControlEnter;
control.Leave -= ControlLeave;
control.MouseHover -= ControlMouseHover;
control.MouseDown -= ControlMouseDown;
control.MouseMove -= ControlMouseMove;
control.MouseLeave -= ControlMouseLeave;
}
/// <summary>
/// Called when Control property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnControlChanged(Control oldValue, Control newValue)
{
if (oldValue != null)
{
UnhookControlEventHandlers(oldValue);
}
OnPropertyChanged(new PropertyChangedEventArgs("Control"));
if (_Control != null)
{
_Control.Enter += ControlEnter;
_Control.Leave += ControlLeave;
_Control.MouseHover += ControlMouseHover;
_Control.MouseDown += ControlMouseDown;
_Control.MouseMove += ControlMouseMove;
_Control.MouseLeave += ControlMouseLeave;
if (_Control.Visible != this.Visible)
_Control.Visible = this.Visible;
}
InvalidateLayout();
}
private Point _MouseTooltipLocation = Point.Empty;
void ControlMouseLeave(object sender, EventArgs e)
{
_MouseTooltipLocation = Point.Empty;
if (ToolTipVisible)
HideToolTip();
}
void ControlMouseMove(object sender, MouseEventArgs e)
{
if (!_MouseTooltipLocation.IsEmpty && ToolTipVisible && (Math.Abs(_MouseTooltipLocation.X - e.X) > 1 || Math.Abs(_MouseTooltipLocation.Y - e.Y) > 1))
HideToolTip();
}
void ControlMouseDown(object sender, MouseEventArgs e)
{
if (ToolTipVisible)
HideToolTip();
}
void ControlMouseHover(object sender, EventArgs e)
{
if (_EnableControlTooltip)
{
ShowToolTip();
_MouseTooltipLocation = _Control.PointToClient(Control.MousePosition);
}
}
private void ControlLeave(object sender, EventArgs e)
{
IsKeyboardFocusWithin = false;
}
private void ControlEnter(object sender, EventArgs e)
{
IsKeyboardFocusWithin = true;
}
private bool _EnableControlTooltip = true;
/// <summary>
/// Indicates whether Tooltip for the item is shown when mouse is over the control.
/// </summary>
[DefaultValue(true), Category("Behavior"), Description("Indicates whether Tooltip for the item is shown when mouse is over the control.")]
public bool EnableControlTooltip
{
get { return _EnableControlTooltip; }
set
{
if (value != _EnableControlTooltip)
{
bool oldValue = _EnableControlTooltip;
_EnableControlTooltip = value;
OnEnableControlTooltipChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when EnableControlTooltip property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnEnableControlTooltipChanged(bool oldValue, bool newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("EnableControlTooltip"));
}
private int _TextControlSpacing = 3;
/// <summary>
/// Indicates spacing between text and the control.
/// </summary>
[DefaultValue(3), Category("Appearance"), Description("Indicates spacing between text and the control."), RefreshProperties(RefreshProperties.All)]
public int TextControlSpacing
{
get { return _TextControlSpacing; }
set
{
if (value != _TextControlSpacing)
{
int oldValue = _TextControlSpacing;
_TextControlSpacing = value;
OnTextControlSpacingChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when TextControlSpacing property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnTextControlSpacingChanged(int oldValue, int newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("TextControlSpacing"));
InvalidateLayout();
}
/// <summary>
/// Processes accelerator key for the item.
/// </summary>
/// <param name="charCode"></param>
internal override bool ProcessMnemonic(char charCode)
{
if (MnemonicsEnabled && _Control != null && _Control.CanSelect)
{
_Control.Select();
return true;
}
return false;
}
private Size _ControlSize = Size.Empty;
/// <summary>
/// Indicates suggested control size which is used only if calculated layout size for the control exceeds the size specified here. Either width or height may be set or both.
/// ControlSize property can be used in conjuction with Dock and Anchor properties on the Control. When available space for the Control
/// exceeds ControlSize the Dock and Anchor properties will indicate the control position inside of the control box.
/// </summary>
[Category("Appearance"), Description("Indicates suggested control size which is used only if calculated layout size for the control exceeds the size specified here. Either width or height may be set or both.")]
public Size ControlSize
{
get { return _ControlSize; }
set
{
if (value != _ControlSize)
{
Size oldValue = _ControlSize;
_ControlSize = value;
OnControlSizeChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when ControlSize property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnControlSizeChanged(Size oldValue, Size newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("ControlSize"));
InvalidateLayout();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeControlSize()
{
return !_ControlSize.IsEmpty;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetControlSize()
{
ControlSize = Size.Empty;
}
private bool _AutoSetTabIndex = true;
/// <summary>
/// Indicates whether Control TabIndex is automatically set based on the position of the item inside of the layout.
/// </summary>
[DefaultValue(true), Category("Behavior"), Description("Indicates whether Control TabIndex is automatically set based on the position of the item inside of the layout.")]
public bool AutoSetTabIndex
{
get { return _AutoSetTabIndex; }
set
{
if (value != _AutoSetTabIndex)
{
bool oldValue = _AutoSetTabIndex;
_AutoSetTabIndex = value;
OnAutoSetTabIndexChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when AutoSetTabIndex property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnAutoSetTabIndexChanged(bool oldValue, bool newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("AutoSetTabIndex"));
}
protected override void OnAbsoluteIndexChanged(int oldValue, int newValue)
{
if (_Control != null && _AutoSetTabIndex) _Control.TabIndex = newValue;
base.OnAbsoluteIndexChanged(oldValue, newValue);
}
private bool _FocusVisualStyleEnabled = true;
/// <summary>
/// Indicates whether LayoutControl.FocusStyle is used to paint background of item when control has input focus.
/// </summary>
[DefaultValue(true), Category("Behavior"), Description("Indicates whether LayoutControl.FocusStyle is used to paint background of item when control has input focus.")]
public bool FocusVisualStyleEnabled
{
get { return _FocusVisualStyleEnabled; }
set
{
if (_FocusVisualStyleEnabled == value)
return;
_FocusVisualStyleEnabled = value;
if (this.IsKeyboardFocusWithin)
this.Invalidate();
OnPropertyChanged(new PropertyChangedEventArgs("FocusVisualStyleEnabled"));
}
}
protected override void OnVisibleChanged(bool oldValue, bool newValue)
{
if (_Control != null)
_Control.Visible = newValue;
base.OnVisibleChanged(oldValue, newValue);
}
#endregion
}
}

View File

@@ -0,0 +1,805 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
[Designer("DevComponents.DotNetBar.Layout.Design.LayoutGroupDesigner, DevComponents.DotNetBar.Layout.Design, Version=14.1.0.37, Culture=neutral, PublicKeyToken=7eb7c3a35b91de04")]
public class LayoutGroup : LayoutItemBase
{
#region Constructor
/// <summary>
/// Initializes a new instance of the LayoutGroup class.
/// </summary>
public LayoutGroup()
{
_CaptionStyle = new SimpleStyle();
_CaptionStyle.PropertyChanged += CaptionStylePropertyChanged;
_Items = new LayoutItemCollection();
_Items.SetParentItem(this);
}
protected override void OnDispose()
{
_CaptionStyle.PropertyChanged -= CaptionStylePropertyChanged;
base.OnDispose();
}
#endregion
#region Implementation
private Rectangle _ActualBounds = Rectangle.Empty;
/// <summary>
/// Gets actual bounds of elements inside of group. The actual bounds may differ from requested layout bounds due to minium
/// size constraint.
/// </summary>
internal Rectangle ActualBounds
{
get
{
return _ActualBounds;
}
set
{
_ActualBounds = value;
}
}
protected override void OnPaint(PaintContext context)
{
OnPaintBackground(context);
if (!_CaptionBounds.IsEmpty)
{
bool isImageVisible = this.IsImageVisible;
Graphics g = context.Graphics;
//context.Graphics.FillRectangle(Brushes.Aqua, _CaptionBounds);
Color textColor = context.LabelTextColor;
bool dispose = false;
Brush textBrush = context.LabelTextBrush;
if (_Appearance == eGroupAppearance.Panel)
{
textColor = PaintPanelCaption(context);
textBrush = new SolidBrush(textColor);
dispose = true;
}
else if (_Appearance == eGroupAppearance.GroupPanel)
{
textColor = PaintGroupPanelCaption(context);
textBrush = new SolidBrush(textColor);
dispose = true;
}
else if (_CaptionStyle.IsPainted)
{
DrawingHelpers.PaintStyle(g, _CaptionStyle, _CaptionBounds);
}
if (!_CaptionStyle.TextColor.IsEmpty)
{
textColor = _CaptionStyle.TextColor;
textBrush = new SolidBrush(textColor);
dispose = true;
}
if (this.TextPosition == eLayoutPosition.Top || this.TextPosition == eLayoutPosition.Bottom)
{
PaintText(context, isImageVisible, textColor, ActualTextBounds, textBrush);
}
else
{
// Rotate rendering
g.RotateTransform(-90);
//Rectangle r = new Rectangle(_CaptionBounds.Top, -_CaptionBounds.Right, _CaptionBounds.Height, _CaptionBounds.Width);
//Rectangle r = new Rectangle(-_CaptionBounds.Bottom, _CaptionBounds.X, _CaptionBounds.Height, _CaptionBounds.Width);
Rectangle r = new Rectangle(-ActualTextBounds.Bottom, ActualTextBounds.X, ActualTextBounds.Height, ActualTextBounds.Width);
PaintText(context, isImageVisible, textColor, r, textBrush);
g.ResetTransform();
}
if (dispose)
textBrush.Dispose();
if (isImageVisible)
PaintImage(context, textColor);
}
foreach (LayoutItemBase item in _Items)
{
if (!item.Visible) continue;
item.Paint(context);
}
//context.Graphics.DrawRectangle(Pens.Green, ActualBounds);
}
private Color PaintPanelCaption(PaintContext context)
{
Rectangle bounds = _CaptionBounds;
if (!this.CaptionStyle.Margin.IsEmpty)
bounds = Helpers.Deflate(bounds, this.CaptionStyle.Margin);
Graphics g = context.Graphics;
DevComponents.DotNetBar.Rendering.Office2007ColorTable table = ((DevComponents.DotNetBar.Rendering.Office2007Renderer)DevComponents.DotNetBar.Rendering.GlobalManager.Renderer).ColorTable;
Color border = table.LegacyColors.PanelBorder;
Color back1 = table.LegacyColors.PanelBackground;
Color back2 = table.LegacyColors.PanelBackground2;
Color textColor = table.LegacyColors.PanelText;
int backAngle = table.LegacyColors.PanelBackgroundGradientAngle;
PaintRectangle(bounds, g, border, back1, back2, backAngle);
return textColor;
}
private Color PaintGroupPanelCaption(PaintContext context)
{
Rectangle r = _CaptionBounds;
Graphics g = context.Graphics;
ElementStyleDisplayInfo info = new ElementStyleDisplayInfo(_GroupPanelStyle, g, r);
ElementStyleDisplay.Paint(info);
return _GroupPanelStyle.TextColor;
}
const int CaptionEdgeDistance = 4;
private Rectangle GetGroupPanelCaptionBounds(Rectangle r)
{
eLayoutPosition textPosition = TextPosition;
eTextAlignment textAlignment = TextAlignment;
Size imageSize = GetImageSize();
if (!imageSize.IsEmpty) imageSize.Width += this.ImageTextSpacing;
int captionWidth = this.RealTextSize.Width + TextPadding.Horizontal + imageSize.Width;
if (textPosition == eLayoutPosition.Top || textPosition == eLayoutPosition.Bottom)
{
if (textAlignment == eTextAlignment.Left || textAlignment == eTextAlignment.Default)
{
r.Width = captionWidth;
r.X += CaptionEdgeDistance;
}
else if (textAlignment == eTextAlignment.Right)
{
r.X = r.Right - (captionWidth) - CaptionEdgeDistance;
r.Width = captionWidth;
}
else if (textAlignment == eTextAlignment.Center)
{
r.X += (r.Width - captionWidth) / 2;
r.Width = captionWidth;
}
}
else // Left/Right
{
if (textAlignment == eTextAlignment.Left || textAlignment == eTextAlignment.Default)
{
r.Y = r.Bottom - captionWidth - CaptionEdgeDistance;
r.Height = captionWidth;
}
else if (textAlignment == eTextAlignment.Right)
{
r.Height = captionWidth;
r.Y += CaptionEdgeDistance;
}
else if (textAlignment == eTextAlignment.Center)
{
r.Y += (r.Height - captionWidth) / 2;
r.Height = captionWidth;
}
}
return r;
}
/// <summary>
/// Paints the background of the item.
/// </summary>
/// <param name="context"></param>
protected override void OnPaintBackground(PaintContext context)
{
if (_Appearance == eGroupAppearance.Panel)
PaintPanelBackground(context);
else if (_Appearance == eGroupAppearance.GroupPanel)
PaintGroupPanelBackground(context);
else
base.OnPaintBackground(context);
}
private void PaintPanelBackground(PaintContext context)
{
Rectangle bounds = this.Bounds;
if (!this.Style.Margin.IsEmpty)
bounds = Helpers.Deflate(bounds, this.Style.Margin);
Graphics g = context.Graphics;
DevComponents.DotNetBar.Rendering.Office2007ColorTable table = ((DevComponents.DotNetBar.Rendering.Office2007Renderer)DevComponents.DotNetBar.Rendering.GlobalManager.Renderer).ColorTable;
Color border = table.LegacyColors.PanelBorder;
Color back1 = table.LegacyColors.PanelBackground;
Color back2 = table.LegacyColors.PanelBackground2;
int backAngle = table.LegacyColors.PanelBackgroundGradientAngle;
PaintRectangle(bounds, g, border, back1, back2, backAngle);
}
private static void PaintRectangle(Rectangle bounds, Graphics g, Color border, Color back1, Color back2, int backAngle)
{
if (bounds.Width <= 0 || bounds.Height <= 0)
return;
if (back2.IsEmpty)
{
if (!back1.IsEmpty)
{
using (SolidBrush brush = new SolidBrush(back1))
g.FillRectangle(brush, bounds);
}
}
else
{
using (System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(bounds, back1, back2, backAngle))
g.FillRectangle(brush, bounds);
}
if (!border.IsEmpty)
{
Rectangle borderBounds = bounds;
borderBounds.Width--; borderBounds.Height--;
using (Pen pen = new Pen(border))
g.DrawRectangle(pen, borderBounds);
}
}
private ElementStyle _GroupPanelStyle = null;
private void PaintGroupPanelBackground(PaintContext context)
{
InitializeGroupPanelStyle();
DevComponents.DotNetBar.Rendering.Office2007ColorTable table = ((DevComponents.DotNetBar.Rendering.Office2007Renderer)DevComponents.DotNetBar.Rendering.GlobalManager.Renderer).ColorTable;
_GroupPanelStyle.SetColorScheme(table.LegacyColors);
Rectangle bounds = this.Bounds;
if (!_CaptionBounds.IsEmpty)
{
eLayoutPosition tp = this.TextPosition;
if (tp == eLayoutPosition.Top)
{
bounds.Y += _CaptionBounds.Height / 2;
bounds.Height -= _CaptionBounds.Height / 2;
}
else if (tp == eLayoutPosition.Bottom)
bounds.Height -= _CaptionBounds.Height / 2;
else if (tp == eLayoutPosition.Left || tp == eLayoutPosition.Default)
{
bounds.X += _CaptionBounds.Width / 2;
bounds.Width -= _CaptionBounds.Width / 2;
}
else // Right
bounds.Width -= _CaptionBounds.Width / 2;
}
if (!this.Style.Margin.IsEmpty)
bounds = Helpers.Deflate(bounds, this.Style.Margin);
Graphics g = context.Graphics;
ElementStyleDisplayInfo info = new ElementStyleDisplayInfo(_GroupPanelStyle, g, bounds);
ElementStyleDisplay.Paint(info);
}
private void InitializeGroupPanelStyle()
{
if (_GroupPanelStyle != null) return;
_GroupPanelStyle = new ElementStyle();
_GroupPanelStyle.BackColorSchemePart = eColorSchemePart.PanelBackground;
_GroupPanelStyle.BackColor2SchemePart = eColorSchemePart.PanelBackground2;
_GroupPanelStyle.BorderColorSchemePart = eColorSchemePart.PanelBorder;
_GroupPanelStyle.BackColorGradientAngle = 90;
_GroupPanelStyle.CornerDiameter = 4;
_GroupPanelStyle.BorderWidth = 1;
_GroupPanelStyle.Border = DevComponents.DotNetBar.eStyleBorderType.Solid;
_GroupPanelStyle.CornerType = DevComponents.DotNetBar.eCornerType.Rounded;
_GroupPanelStyle.TextColorSchemePart = eColorSchemePart.PanelText;
}
protected override void OnUpdateLayout()
{
base.OnUpdateLayout();
}
private Rectangle _ContentBounds = Rectangle.Empty;
private ItemLayout _Layout = new ItemLayout();
/// <summary>
/// Performs group layout.
/// </summary>
/// <param name="context">Layout context information.</param>
public void Layout(LayoutContext context)
{
Rectangle r = this.Bounds;
// Calculate text-position
r = LayoutGroupCaption(context, r);
if (!_IsRootGroup)
r = Helpers.Deflate(r, this.Padding);
_ContentBounds = r;
_Layout.Layout(this, r, context);
}
private int _CaptionHeight = 0;
/// <summary>
/// Indicates explicit caption height in pixels.
/// </summary>
[DefaultValue(0), Category("Appearance"), Description("Indicates caption height in pixels.")]
public int CaptionHeight
{
get { return _CaptionHeight; }
set
{
if (value != _CaptionHeight)
{
int oldValue = _CaptionHeight;
_CaptionHeight = value;
OnCaptionHeightChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when CaptionHeight property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnCaptionHeightChanged(int oldValue, int newValue)
{
this.InvalidateLayout();
OnPropertyChanged(new PropertyChangedEventArgs("CaptionHeight"));
}
protected override Font GetTextFont(Font defaultFont)
{
Font font = defaultFont;
if (_CaptionStyle.Font != null)
font = _CaptionStyle.Font;
return font;
}
/// <summary>
/// Updates the layout of the text inside of item.
/// </summary>
protected override void UpdateTextBounds()
{
if (_CaptionBounds.IsEmpty) return;
Rectangle actualTextBounds = Helpers.Deflate(_CaptionBounds, this.TextPadding);
Rectangle actualImageBounds = Rectangle.Empty;
bool isImageVisible = IsImageVisible;
Size imageSize = Size.Empty;
if (isImageVisible)
imageSize = GetImageSize();
eTextAlignment textAlignment = this.TextAlignment;
Size realTextSize = this.RealTextSize;
if (isImageVisible)
{
eLayoutPosition imagePosition = ImagePosition;
int imageTextSpacing = ImageTextSpacing;
if (TextPosition == eLayoutPosition.Top || TextPosition == eLayoutPosition.Bottom)
{
if (imagePosition == eLayoutPosition.Default || imagePosition == eLayoutPosition.Right)
{
if (textAlignment == eTextAlignment.Right)
actualImageBounds = new Rectangle(actualTextBounds.Right - imageSize.Width - imageTextSpacing, actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
else if (textAlignment == eTextAlignment.Center)
{
if (Appearance == eGroupAppearance.GroupPanel)
{
actualImageBounds = new Rectangle(actualTextBounds.Right - (imageSize.Width + CaptionEdgeDistance), actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
actualTextBounds.Width = realTextSize.Width;
}
else
actualImageBounds = new Rectangle(actualTextBounds.X + actualTextBounds.Width / 2 + realTextSize.Width / 2 + this.ImageTextSpacing, actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
}
else
{
actualImageBounds = new Rectangle(actualTextBounds.X + imageTextSpacing + realTextSize.Width, actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
if (Appearance == eGroupAppearance.GroupPanel)
actualImageBounds.X -= CaptionEdgeDistance;
}
}
else if (imagePosition == eLayoutPosition.Left)
{
if (textAlignment == eTextAlignment.Right)
{
actualImageBounds = new Rectangle(actualTextBounds.Right - (realTextSize.Width + imageSize.Width + imageTextSpacing), actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
if (Appearance == eGroupAppearance.GroupPanel)
actualImageBounds.X += CaptionEdgeDistance;
}
else if (textAlignment == eTextAlignment.Center)
{
if (Appearance == eGroupAppearance.GroupPanel)
{
actualImageBounds = new Rectangle(actualTextBounds.X + CaptionEdgeDistance, actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
actualTextBounds.X = actualImageBounds.Right;
actualTextBounds.Width = realTextSize.Width;
}
else
actualImageBounds = new Rectangle(actualTextBounds.X + actualTextBounds.Width / 2 - (realTextSize.Width / 2 + this.ImageTextSpacing + imageSize.Width), actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
}
else
{
actualImageBounds = new Rectangle(actualTextBounds.X, actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2, imageSize.Width, imageSize.Height);
actualTextBounds.X += actualImageBounds.Width + imageTextSpacing;
actualTextBounds.Width -= actualImageBounds.Width + imageTextSpacing;
}
}
else if (imagePosition == eLayoutPosition.Top)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2,
actualTextBounds.Y - (imageSize.Height + imageTextSpacing),
imageSize.Width,
imageSize.Height);
}
else if (imagePosition == eLayoutPosition.Bottom)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2,
actualTextBounds.Bottom + imageTextSpacing,
imageSize.Width,
imageSize.Height);
}
}
else
{
if (imagePosition == eLayoutPosition.Default || imagePosition == eLayoutPosition.Right)
{
if (textAlignment == eTextAlignment.Right)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Y + imageTextSpacing, imageSize.Width, imageSize.Height);
actualTextBounds.Y += imageTextSpacing;
actualImageBounds.Height -= imageTextSpacing;
if (Appearance == eGroupAppearance.GroupPanel)
{
actualTextBounds.Y = actualImageBounds.Bottom - 10;
actualTextBounds.Height = (_CaptionBounds.Bottom - actualTextBounds.Y)+4;
}
}
else if (textAlignment == eTextAlignment.Center)
{
if (Appearance == eGroupAppearance.GroupPanel)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Y + CaptionEdgeDistance, imageSize.Width, imageSize.Height);
actualTextBounds.Y = actualImageBounds.Bottom;
actualTextBounds.Height = _CaptionBounds.Bottom - actualTextBounds.Y;
}
else
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Y + actualTextBounds.Height / 2 - (realTextSize.Width / 2 + imageTextSpacing + imageSize.Height), imageSize.Width, imageSize.Height);
}
else
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Bottom - (realTextSize.Width + imageTextSpacing + imageSize.Height), imageSize.Width, imageSize.Height);
if (Appearance == eGroupAppearance.GroupPanel)
actualImageBounds.Y += CaptionEdgeDistance;
}
}
else if (imagePosition == eLayoutPosition.Left)
{
if (textAlignment == eTextAlignment.Right)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Y + imageTextSpacing, imageSize.Width, imageSize.Height);
actualTextBounds.Y += imageTextSpacing;
actualImageBounds.Height -= imageTextSpacing;
if (Appearance == eGroupAppearance.GroupPanel)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Bottom - (CaptionEdgeDistance+imageSize.Width), imageSize.Width, imageSize.Height);
actualTextBounds.Height = actualImageBounds.Y - _CaptionBounds.Y;
}
}
else if (textAlignment == eTextAlignment.Center)
{
if (Appearance == eGroupAppearance.GroupPanel)
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Bottom - (imageSize.Height + CaptionEdgeDistance), imageSize.Width, imageSize.Height);
actualTextBounds.Height -= realTextSize.Height;
}
else
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Y + actualTextBounds.Height / 2 + realTextSize.Width / 2 + this.ImageTextSpacing, imageSize.Width, imageSize.Height);
}
else
{
actualImageBounds = new Rectangle(actualTextBounds.X + (actualTextBounds.Width - imageSize.Width) / 2, actualTextBounds.Bottom - imageSize.Height - imageTextSpacing, imageSize.Width, imageSize.Height);
actualTextBounds.Height -= actualImageBounds.Height + imageTextSpacing;
}
}
else if (imagePosition == eLayoutPosition.Top)
{
actualImageBounds = new Rectangle(actualTextBounds.X + imageTextSpacing,
actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2,
imageSize.Width,
imageSize.Height);
actualTextBounds.X += imageSize.Width + imageTextSpacing;
actualTextBounds.Width -= imageSize.Width + imageTextSpacing;
}
else if (imagePosition == eLayoutPosition.Bottom)
{
actualImageBounds = new Rectangle(actualTextBounds.Right - (imageSize.Width + imageTextSpacing),
actualTextBounds.Y + (actualTextBounds.Height - imageSize.Height) / 2,
imageSize.Width,
imageSize.Height);
actualTextBounds.Width -= imageSize.Width + imageTextSpacing;
}
}
}
this.ActualTextBounds = actualTextBounds;
this.ActualImageBounds = actualImageBounds;
}
private Rectangle _CaptionBounds = Rectangle.Empty;
protected virtual Rectangle LayoutGroupCaption(LayoutContext context, Rectangle r)
{
_CaptionBounds = Rectangle.Empty;
if (string.IsNullOrEmpty(this.Text) || !this.TextVisible)
return r;
eLayoutPosition textPosition = this.TextPosition;
Size textSize = new Size();
if (_CaptionHeight > 0)
{
textSize.Width = r.Width;
textSize.Height = _CaptionHeight;
}
else
{
textSize = MeasureText(context);
if (IsImageVisible)
{
Size imageSize = GetImageSize();
textSize.Height = Math.Max(textSize.Height, imageSize.Height);
}
}
if (textPosition == eLayoutPosition.Top)
{
_CaptionBounds = new Rectangle(r.X, r.Y, r.Width, textSize.Height);
r.Y += _CaptionBounds.Height;
r.Height -= _CaptionBounds.Height;
}
else if (textPosition == eLayoutPosition.Bottom)
{
_CaptionBounds = new Rectangle(r.X, r.Bottom - textSize.Height, r.Width, textSize.Height);
r.Height -= _CaptionBounds.Height;
}
else if (textPosition == eLayoutPosition.Left || textPosition == eLayoutPosition.Default) // Text rotated to the side
{
_CaptionBounds = new Rectangle(r.X, r.Y, textSize.Height, r.Height);
r.X += _CaptionBounds.Width;
r.Width -= _CaptionBounds.Width;
}
else if (textPosition == eLayoutPosition.Right) // Text rotated to the side
{
_CaptionBounds = new Rectangle(r.Right - textSize.Height, r.Y, textSize.Height, r.Height);
r.Width -= _CaptionBounds.Width;
}
if (Appearance == eGroupAppearance.GroupPanel)
_CaptionBounds = GetGroupPanelCaptionBounds(_CaptionBounds);
UpdateTextBounds();
//if (Appearance == eGroupAppearance.GroupPanel && !ActualImageBounds.IsEmpty)
//{
// if (textPosition == eLayoutPosition.Top || textPosition == eLayoutPosition.Bottom || textPosition == eLayoutPosition.Default)
// {
// if (TextAlignment != eTextAlignment.Center)
// ActualImageBounds = new Rectangle(ActualImageBounds.X + CaptionEdgeDistance, ActualImageBounds.Y, ActualImageBounds.Width, ActualImageBounds.Height);
// }
// else
// {
// ActualImageBounds = new Rectangle(ActualImageBounds.X, ActualImageBounds.Y + CaptionEdgeDistance, ActualImageBounds.Width, ActualImageBounds.Height);
// }
//}
return r;
}
private LayoutItemCollection _Items = null;
/// <summary>
/// Gets the collection of layout items objects assigned to the current group.
/// </summary>
[Browsable(true), Category("Items"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public LayoutItemCollection Items
{
get
{
return _Items;
}
}
//private eLayoutType _LayoutType = eLayoutType.Horizontal;
///// <summary>
///// Indicates layout type performed by the group.
///// </summary>
//[DefaultValue(eLayoutType.Horizontal), Category("Appearance"), Description("Indicates layout type performed by the group.")]
//public eLayoutType LayoutType
//{
// get { return _LayoutType; }
// set
// {
// if (value != _LayoutType)
// {
// eLayoutType oldValue = _LayoutType;
// _LayoutType = value;
// OnLayoutTypeChanged(oldValue, value);
// }
// }
//}
///// <summary>
///// Called when LayoutType property has changed.
///// </summary>
///// <param name="oldValue">Old property value</param>
///// <param name="newValue">New property value</param>
//protected virtual void OnLayoutTypeChanged(eLayoutType oldValue, eLayoutType newValue)
//{
// OnPropertyChanged(new PropertyChangedEventArgs("LayoutType"));
//}
internal override void UpdateScrollBounds(int xScroll, int yScroll, bool moveControls)
{
base.UpdateScrollBounds(xScroll, yScroll, moveControls);
_ActualBounds.Offset(xScroll, yScroll);
_CaptionBounds.Offset(xScroll, yScroll);
_ContentBounds.Offset(xScroll, yScroll);
foreach (LayoutItemBase item in this.Items)
{
item.UpdateScrollBounds(xScroll, yScroll, moveControls);
}
}
private bool _IsRootGroup = false;
/// <summary>
/// Indicates whether group is used as a root group in LayoutControl.
/// </summary>
[Browsable(false)]
public bool IsRootGroup
{
get { return _IsRootGroup; }
internal set
{
if (_IsRootGroup == value)
return;
_IsRootGroup = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsRootGroup"));
}
}
private SimpleStyle _CaptionStyle;
/// <summary>
/// Gets the style for the group caption represented by Text property.
/// </summary>
[Browsable(true), Category("Appearance"), Description("Gets the style for the group caption represented by Text property"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public SimpleStyle CaptionStyle
{
get { return _CaptionStyle; }
}
private void CaptionStylePropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.Invalidate();
//throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Returns whether item is contained as child item by this item or one of its children.
/// </summary>
/// <param name="value">Item to check.</param>
/// <returns>true if item is contained otherwise false</returns>
public override bool IsChildItem(LayoutItemBase value)
{
foreach (LayoutItemBase item in _Items)
{
if (item == value) return true;
if (item.IsChildItem(value)) return true;
}
return false;
}
private eGroupAppearance _Appearance = eGroupAppearance.None;
/// <summary>
/// Indicates the built-in appearance of group. When set group is painted using one of the pre-defined styles.
/// When set to None, default value, you can use Style and CaptionStyle properties to change the group appearance.
/// </summary>
[DefaultValue(eGroupAppearance.None), Category("Appearance"), Description("Indicates the built-in appearance of group.")]
public eGroupAppearance Appearance
{
get { return _Appearance; }
set
{
if (value != _Appearance)
{
eGroupAppearance oldValue = _Appearance;
_Appearance = value;
OnAppearanceChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when Appearance property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnAppearanceChanged(eGroupAppearance oldValue, eGroupAppearance newValue)
{
this.Invalidate();
this.InvalidateLayout();
OnPropertyChanged(new PropertyChangedEventArgs("Appearance"));
}
/// <summary>
/// Scales item in response to the scaling of the LayoutControl. Should never be called directly.
/// </summary>
/// <param name="factor"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ScaleItem(SizeF factor)
{
base.ScaleItem(factor);
if (_CaptionHeight > 0)
{
bool widthChanged = factor.Width != 1f;
bool heightChanged = factor.Height != 1f;
if (heightChanged)
{
_CaptionHeight = (int)(_CaptionHeight * factor.Height);
}
}
}
/// <summary>
/// Gets whether this item text-size is shared with other items inside of its parent group.
/// </summary>
[Browsable(false)]
public override bool IsTextSizeShared
{
get
{
return false;
}
}
/// <summary>
/// Gets whether this item's text-baseline is shared with other items inside of its parent group.
/// </summary>
[Browsable(false)]
public override bool IsTextBaselineShared
{
get
{
return false;
}
}
protected override void OnVisibleChanged(bool oldValue, bool newValue)
{
foreach (LayoutItemBase item in _Items)
{
item.Visible = newValue;
}
base.OnVisibleChanged(oldValue, newValue);
}
#endregion
}
/// <summary>
/// Specifies the layout type.
/// </summary>
public enum eLayoutType
{
/// <summary>
/// Horizontal layout type where items are first ordered from left to right then wrapped to next line.
/// </summary>
Horizontal,
/// <summary>
/// Vertical layout type where items are ordered first from top to bottom then wrapped onto the next column.
/// </summary>
Vertical
}
/// <summary>
/// Specifies built-in appearance for the LayoutGroup.
/// </summary>
public enum eGroupAppearance
{
/// <summary>
/// Group does not use any built-in appearance.
/// </summary>
None,
/// <summary>
/// Group is rendered like standard DotNetBar Panel control.
/// </summary>
Panel,
/// <summary>
/// Group is rendered like GroupPanel control.
/// </summary>
GroupPanel
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,371 @@
using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Represents collection for LayoutItemBase objects.
/// </summary>
public class LayoutItemCollection : CollectionBase
{
#region Private Variables
private LayoutItemBase _ParentItem = null;
#endregion
#region Internal Implementation
public LayoutItemCollection()
{
}
/// <summary>
/// Gets or sets the item this collection is associated with.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public LayoutItemBase ParentItem
{
get { return _ParentItem; }
}
/// <summary>
/// Sets the item collection belongs to.
/// </summary>
/// <param name="parent">Item that is parent of this collection.</param>
internal void SetParentItem(LayoutItemBase parent)
{
_ParentItem = parent;
}
/// <summary>
/// Adds new object to the collection.
/// </summary>
/// <param name="item">Object to add.</param>
/// <returns>Index of newly added object.</returns>
public virtual int Add(LayoutItemBase item)
{
if (this.List.Contains(item))
return IndexOf(item); // throw new InvalidOperationException("Item already contained in collection");
return List.Add(item);
}
/// <summary>
/// Adds an array of objects to the collection.
/// </summary>
/// <param name="items">Array of item objects.</param>
public virtual void AddRange(LayoutItemBase[] items)
{
foreach (LayoutItemBase item in items)
this.Add(item);
}
/// <summary>
/// Returns reference to the object in collection based on it's index.
/// </summary>
public LayoutItemBase this[int index]
{
get { return (LayoutItemBase)(List[index]); }
set { List[index] = value; }
}
/// <summary>
/// Inserts new object into the collection.
/// </summary>
/// <param name="index">Position of the object.</param>
/// <param name="value">Object to insert.</param>
public virtual void Insert(int index, LayoutItemBase value)
{
List.Insert(index, value);
}
/// <summary>
/// Returns index of the object inside of the collection.
/// </summary>
/// <param name="value">Reference to the object.</param>
/// <returns>Index of the object.</returns>
public int IndexOf(LayoutItemBase value)
{
return List.IndexOf(value);
}
/// <summary>
/// Returns whether collection contains specified object.
/// </summary>
/// <param name="value">Object to look for.</param>
/// <returns>true if object is part of the collection, otherwise false.</returns>
public bool Contains(LayoutItemBase value)
{
return List.Contains(value);
}
/// <summary>
/// Removes specified object from the collection.
/// </summary>
/// <param name="value"></param>
public virtual void Remove(LayoutItemBase value)
{
List.Remove(value);
}
protected override void OnRemove(int index, object value)
{
//if (!_PassiveCollection)
//{
// AdvTree tree = GetTreeControl();
// if (tree != null)
// tree.InvokeBeforeNodeRemove(m_SourceAction, value as Node, m_ParentNode);
//}
base.OnRemove(index, value);
}
protected override void OnRemoveComplete(int index, object value)
{
base.OnRemoveComplete(index, value);
if(!_MovingItem)
ItemRemoveComplete(index, value);
}
private void ItemRemoveComplete(int index, object value)
{
LayoutItemBase item = value as LayoutItemBase;
item.Parent = null;
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
base.OnSetComplete(index, oldValue, newValue);
if (!_MovingItem)
{
ItemRemoveComplete(index, oldValue);
ItemInsertComplete(newValue);
}
}
protected override void OnSet(int index, object oldValue, object newValue)
{
//if (!_PassiveCollection)
//{
// AdvTree tree = GetTreeControl();
// if (tree != null)
// tree.InvokeBeforeNodeRemove(m_SourceAction, oldValue as Node, m_ParentNode);
// if (tree != null)
// tree.InvokeBeforeNodeInsert(m_SourceAction, newValue as Node, m_ParentNode);
//}
base.OnSet(index, oldValue, newValue);
}
private bool _MovingItem = false;
/// <summary>
/// Moves an item in collection from its current location to new location.
/// </summary>
/// <param name="item"></param>
/// <param name="moveToIndex"></param>
public void Move(DevComponents.DotNetBar.Layout.LayoutItemBase item, int moveToIndex)
{
_MovingItem = true;
try
{
if (moveToIndex > this.Count - 1) moveToIndex = this.Count - 1;
if (moveToIndex < 0) moveToIndex = 0;
List.Remove(item);
List.Insert(moveToIndex, item);
//LayoutItemBase temp = this[moveToIndex];
//int index = List.IndexOf(item);
//List[moveToIndex] = item;
//List[index] = temp;
}
finally
{
_MovingItem = false;
}
}
protected override void OnInsert(int index, object value)
{
//if (!_PassiveCollection)
//{
// AdvTree tree = GetTreeControl();
// if (tree != null)
// tree.InvokeBeforeNodeInsert(m_SourceAction, value as Node, m_ParentNode);
//}
base.OnInsert(index, value);
}
protected override void OnInsertComplete(int index, object value)
{
base.OnInsertComplete(index, value);
if(!_MovingItem)
ItemInsertComplete(value);
}
private void ItemInsertComplete(object value)
{
LayoutItemBase item = value as LayoutItemBase;
item.Parent = _ParentItem;
//if (!_PassiveCollection)
//{
// Node node = value as Node;
// if (m_ParentNode != null)
// {
// if (node.Parent != null && node.Parent != m_ParentNode)
// node.Remove();
// node.SetParent(m_ParentNode);
// if (m_ParentNode.NodesColumns.IsSorted)
// {
// AdvTree parentTree = m_TreeControl;
// if (parentTree == null) parentTree = m_ParentNode.TreeControl;
// if (parentTree != null)
// parentTree.PushSortRequest(m_ParentNode);
// }
// }
// else
// {
// if (node.Parent != null)
// node.Remove();
// else
// node.InvokeOnParentChanged();
// if (m_TreeControl != null && m_TreeControl.Columns.IsSorted)
// {
// m_TreeControl.PushSortRequest();
// }
// }
// node.internalTreeControl = m_TreeControl;
// if (m_ParentNode != null)
// m_ParentNode.OnChildNodeInserted(node);
// else
// node.SizeChanged = true;
// AdvTree tree = GetTreeControl();
// if (tree != null)
// tree.InvokeAfterNodeInsert(m_SourceAction, value as Node, m_ParentNode);
//}
//m_SourceAction = eTreeAction.Code;
}
/// <summary>
/// Copies collection into the specified array.
/// </summary>
/// <param name="array">Array to copy collection to.</param>
/// <param name="index">Starting index.</param>
public void CopyTo(LayoutItemBase[] array, int index)
{
List.CopyTo(array, index);
}
/// <summary>
/// Copies contained items to the item array.
/// </summary>
/// <param name="array">Array to copy to.</param>
public void CopyTo(LayoutItemBase[] array)
{
List.CopyTo(array, 0);
}
/// <summary>
/// Copies contained items to the item array.
/// </summary>
/// <param name="array">Array to copy to.</param>
public void CopyTo(List<LayoutItemBase> list)
{
foreach (LayoutItemBase item in this.List)
{
list.Add(item);
}
}
protected override void OnClear()
{
foreach (LayoutItemBase item in this.List)
{
item.Parent = null;
}
base.OnClear();
}
protected override void OnClearComplete()
{
if (_ParentItem is LayoutGroup && ((LayoutGroup)_ParentItem).IsRootGroup)
{
// Remove all the controls as well from layout control
List<Control> controlsToRemove = new List<Control>();
LayoutControl lc = ((LayoutGroup)_ParentItem).LayoutControl;
if (lc != null)
{
lc.SuspendLayout();
foreach (Control c in lc.Controls)
{
if (!lc.IsSystemControl(c))
controlsToRemove.Add(c);
}
foreach (Control c in controlsToRemove)
{
lc.Controls.Remove(c);
if (lc.DisposeControlsOnRootGroupClear)
c.Dispose();
}
lc.ResumeLayout();
}
}
base.OnClearComplete();
}
/// <summary>
/// Sorts the elements in the entire collection using the IComparable implementation of each element.
/// </summary>
public virtual void Sort()
{
this.Sort(0, this.Count, Comparer.Default);
}
/// <summary>
/// Sorts the elements in the entire collection using the specified comparer.
/// </summary>
/// <param name="comparer">The IComparer implementation to use when comparing elements.-or- null to use the IComparable implementation of each element.</param>
public virtual void Sort(IComparer comparer)
{
this.Sort(0, this.Count, comparer);
}
/// <summary>
/// Sorts the elements in a range of elements in collection using the specified comparer.
/// </summary>
/// <param name="index"></param>
/// <param name="count"></param>
/// <param name="comparer"></param>
public virtual void Sort(int index, int count, IComparer comparer)
{
//AdvTree tree = GetTreeControl();
//if (!_PassiveCollection && tree != null)
// tree.BeginUpdate();
this.InnerList.Sort(index, count, comparer);
//if (tree != null && tree.DeepSort)
//{
// foreach (Node node in this.InnerList)
// {
// node.Nodes.Sort(0, node.Nodes.Count, comparer);
// }
//}
//if (!_PassiveCollection && tree != null)
// tree.EndUpdate();
}
/// <summary>
/// Finds the items with specified key, optionally searching sub-nodes.
/// </summary>
/// <param name="name">The name of the tree node to search for.</param>
/// <param name="searchAllChildren">true to search child nodes of tree nodes; otherwise, false. </param>
/// <returns>An array of Node objects whose Name property matches the specified key.</returns>
//public LayoutItemBase[] Find(string name, bool searchAllChildren)
//{
// ArrayList list = new ArrayList();
// NodeOperations.FindNodesByName(this, name, searchAllChildren, list);
// Node[] nodes = new Node[list.Count];
// if (list.Count > 0) list.CopyTo(nodes);
// return nodes;
//}
#endregion
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Represents the label item.
/// </summary>
internal class LayoutLabelItem : LayoutItemBase
{
#region Constructor
#endregion
#region Implementation
#endregion
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Represents the item used as empty spacer element.
/// </summary>
public class LayoutSpacerItem : LayoutItemBase
{
#region Constructor
#endregion
#region Implementation
protected override void OnPaintBackground(PaintContext context)
{
base.OnPaintBackground(context);
if (this.DesignMode && !this.IsSelected && this.Bounds.Width > 0 && this.Bounds.Height > 0)
{
using (Pen borderPen = this.DesignTimeBorderPen)
{
Rectangle clientRectangle = this.Bounds;
clientRectangle.Width--;
clientRectangle.Height--;
context.Graphics.DrawRectangle(borderPen, clientRectangle);
}
}
}
protected Pen DesignTimeBorderPen
{
get
{
Color color = (SystemColors.Control.GetBrightness() < 0.5) ? ControlPaint.Light(SystemColors.Control) : ControlPaint.Dark(SystemColors.Control);
LayoutControl lc = GetLayoutControl();
if (lc != null)
color = (lc.BackColor.GetBrightness() < 0.5) ? ControlPaint.Light(lc.BackColor) : ControlPaint.Dark(lc.BackColor);
Pen pen = new Pen(color);
pen.DashStyle = DashStyle.Dash;
return pen;
}
}
#endregion
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
public class PaintContext : IDisposable
{
/// <summary>
/// Initializes a new instance of the PaintContext class.
/// </summary>
/// <param name="control"></param>
/// <param name="graphics"></param>
public PaintContext(LayoutControl control, Graphics graphics, System.Drawing.Text.HotkeyPrefix hotkeyPrefix)
{
Control = control;
Graphics = graphics;
DefaultFont = control.LabelFont ?? control.Font;
HotkeyPrefix = hotkeyPrefix;
if (control.FocusStyle != null && control.FocusStyle.IsPainted)
this.FocusStyle = control.FocusStyle;
if (control.LabelTextColor.IsEmpty)
LabelTextColor = control.ForeColor;
else
LabelTextColor = control.LabelTextColor;
LabelTextBrush = new SolidBrush(LabelTextColor);
TextAlignment = control.LabelTextAlignment;
}
public LayoutControl Control = null;
public Graphics Graphics = null;
public Font DefaultFont = null;
public System.Drawing.Text.HotkeyPrefix HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
public SimpleStyle FocusStyle = null;
public Color LabelTextColor = Color.Empty;
public Brush LabelTextBrush = null;
public eTextAlignment TextAlignment = eTextAlignment.Default;
#region IDisposable Members
public void Dispose()
{
if (LabelTextBrush != null)
{
LabelTextBrush.Dispose();
LabelTextBrush = null;
}
}
#endregion
}
}

View File

@@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DevComponents.DotNetBar.Layout.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[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("DevComponents.DotNetBar.Layout.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DevComponents.DotNetBar.Layout.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,321 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DevComponents.DotNetBar.Layout
{
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class SimpleStyle : INotifyPropertyChanged, IDisposable
{
#region Constructor
/// <summary>
/// Initializes a new instance of the SimpleStyle class.
/// </summary>
public SimpleStyle()
{
_Background.PropertyChanged += BackgroundPropertyChanged;
_BorderPattern.PropertyChanged += BorderPatternPropertyChanged;
}
#endregion
#region Implementation
/// <summary>
/// Gets whether any properties on the style have been set that would cause style to be painted.
/// </summary>
[Browsable(false)]
public bool IsPainted
{
get
{
return _Background.IsBackgroundSet || !_BorderColors.IsEmpty && !_BorderThickness.IsZero || _Font != null;
}
}
private Background _Background = new Background();
/// <summary>
/// Gets or sets the style background.
/// </summary>
[Description("Indicates the style background")]
public Background Background
{
get
{
return _Background;
}
set
{
if (_Background != value)
{
if (_Background != null)
_Background.PropertyChanged -= BackgroundPropertyChanged;
_Background = value;
if (_Background != null)
_Background.PropertyChanged += BackgroundPropertyChanged;
OnPropertyChanged(new PropertyChangedEventArgs("Background"));
}
}
}
private void BackgroundPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(new PropertyChangedEventArgs("Background." + e.PropertyName));
}
/// <summary>
/// Gets whether property should be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeBackground()
{
return (_Background != null && !_Background.IsEmpty);
}
/// <summary>
/// Resets property to its default value.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private void ResetBackground()
{
Background = new Background();
}
private Color _TextColor = Color.Empty;
/// <summary>
/// Gets or sets text color.
/// </summary>
[Category("Appearance"), Description("Indicates text color.")]
public Color TextColor
{
get { return _TextColor; }
set { _TextColor = value; OnPropertyChanged(new PropertyChangedEventArgs("TextColor")); }
}
/// <summary>
/// Gets whether property should be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTextColor()
{
return !_TextColor.IsEmpty;
}
/// <summary>
/// Resets property to its default value.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetTextColor()
{
this.TextColor = Color.Empty;
}
private Font _Font = null;
/// <summary>
/// Indicates the text font.
/// </summary>
[DefaultValue(null), Category("Appearance"), Description("Indicates the text font.")]
public Font Font
{
get { return _Font; }
set
{
if (value != _Font)
{
Font oldValue = _Font;
_Font = value;
OnFontChanged(oldValue, value);
}
}
}
/// <summary>
/// Called when Font property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnFontChanged(Font oldValue, Font newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("Font"));
}
private BorderPattern _BorderPattern = new BorderPattern();
/// <summary>
/// Indicates the border line pattern.
/// </summary>
[Category("Appearance"), Description("Indicates the border line pattern.")]
public BorderPattern BorderPattern
{
get { return _BorderPattern; }
set
{
if (value != _BorderPattern)
{
BorderPattern oldValue = _BorderPattern;
_BorderPattern = value;
OnBorderPatternChanged(oldValue, value);
}
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeBorderPattern()
{
return !_BorderPattern.IsEmpty;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetBorderPattern()
{
this.BorderPattern = new BorderPattern();
}
/// <summary>
/// Called when BorderPattern property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnBorderPatternChanged(BorderPattern oldValue, BorderPattern newValue)
{
if (oldValue != null)
oldValue.PropertyChanged -= BorderPatternPropertyChanged;
if (newValue != null)
newValue.PropertyChanged += BorderPatternPropertyChanged;
OnPropertyChanged(new PropertyChangedEventArgs("BorderPattern"));
}
private void BorderPatternPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(new PropertyChangedEventArgs("BorderPattern" + e.PropertyName));
}
private BorderColors _BorderColors = new BorderColors();
/// <summary>
/// Gets or sets the border color.
/// </summary>
[Category("Appearance"), Description("Indicates border color.")]
public BorderColors BorderColors
{
get { return _BorderColors; }
set { _BorderColors = value; OnPropertyChanged(new PropertyChangedEventArgs("BorderColors")); }
}
/// <summary>
/// Gets whether property should be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeBorderColors()
{
return !_BorderColors.IsEmpty;
}
/// <summary>
/// Resets property to its default value.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetBorderColors()
{
this.BorderColors = new BorderColors();
}
private Thickness _BorderThickness = new Thickness();
/// <summary>
/// Indicates the border thickness.
/// </summary>
[Category("Appearance"), Description("Indicates the border thickness")]
public Thickness BorderThickness
{
get { return _BorderThickness; }
set
{
if (value != _BorderThickness)
{
Thickness oldValue = _BorderThickness;
_BorderThickness = value;
OnBorderThicknessChanged(oldValue, value);
}
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeBorderThickness()
{
return _BorderThickness.Bottom != 0 || _BorderThickness.Top != 0 || _BorderThickness.Left != 0 || _BorderThickness.Right != 0;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetBorderThickness()
{
_BorderThickness = new Thickness(0);
}
/// <summary>
/// Called when BorderThickness property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnBorderThicknessChanged(Thickness oldValue, Thickness newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("BorderThickness"));
}
private Padding _Margin = new Padding(0);
/// <summary>
/// Gets or sets spacing between the edge of the item and the border and background. This does not influence the actual layout or size of the item rather applies to rendering of the style only.
/// </summary>
[Browsable(true), Category("Appearance"), Description("Indicates spacing between the edge of the item and the border and background. This does not influence the actual layout or size of the item rather applies to rendering of the style only."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Padding Margin
{
get { return _Margin; }
set
{
if (_Margin != value)
{
Padding oldValue = _Margin;
_Margin = value;
OnMarginChanged(oldValue, value);
}
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeMargin()
{
return _Margin.Bottom != 0 || _Margin.Top != 0 || _Margin.Left != 0 || _Margin.Right != 0;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetMargin()
{
_Margin = new Padding(0);
}
/// <summary>
/// Called when Margin property has changed.
/// </summary>
/// <param name="oldValue">Old property value</param>
/// <param name="newValue">New property value</param>
protected virtual void OnMarginChanged(Padding oldValue, Padding newValue)
{
OnPropertyChanged(new PropertyChangedEventArgs("Margin"));
}
#endregion
#region IDisposable Members
protected virtual void OnDispose()
{
}
public void Dispose()
{
OnDispose();
}
#endregion
#region INotifyPropertyChanged Members
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="e">Provides event arguments.</param>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
/// <summary>
/// Occurs when property on object has changed.
/// </summary>
[Description("Occurs when property on object has changed.")]
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}

View File

@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.ComponentModel;
using System.IO;
using System.Reflection;
#if LAYOUT
namespace DevComponents.DotNetBar.Layout
#else
namespace DevComponents.DotNetBar
#endif
{
// Uses Font Awesome - http://fortawesome.github.com/Font-Awesome
[EditorBrowsable(EditorBrowsableState.Never)]
public static class Symbols
{
#region WinApi
[DllImport("gdi32")]
static extern IntPtr AddFontMemResourceEx(IntPtr pbFont,
uint cbFont,
IntPtr pdv,
[In] ref uint pcFonts);
[DllImport("gdi32")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RemoveFontMemResourceEx(IntPtr fh);
#endregion
#region Internal Implementation
private static Dictionary<float, Font> _FontAwesomeCache = new Dictionary<float, Font>(10);
/// <summary>
/// Returns FontAwesome at specific size.
/// </summary>
/// <param name="fontSize">Font size in points</param>
/// <returns>Font in desired size.</returns>
public static Font GetFontAwesome(float fontSize)
{
Font font = null;
EnsureFontLoaded();
if (fontSize <= 0) return _FontAwesome;
if(_FontAwesomeCache.TryGetValue(fontSize, out font))
return font;
font = new Font(_FontAwesome.FontFamily, fontSize, FontStyle.Regular, GraphicsUnit.Point);
_FontAwesomeCache.Add(fontSize, font);
return font;
}
private static Font _FontAwesome = null;
/// <summary>
/// Gets FontAwesome at default size.
/// </summary>
public static Font FontAwesome
{
get
{
EnsureFontLoaded();
return _FontAwesome;
}
}
/// <summary>
/// Returns FontAwesome Family.
/// </summary>
public static FontFamily FontAwesomeFamily
{
get
{
EnsureFontLoaded();
return _FontAwesome.FontFamily;
}
}
private static PrivateFontCollection _PrivateFontCollection;
private static GCHandle _FontAwesomeHandle;
private static IntPtr _FontAwesomePointer;
private static void EnsureFontLoaded()
{
if (_FontAwesome == null)
{
_PrivateFontCollection = new PrivateFontCollection();
byte[] fontAwesomeBuffer = LoadFont("SystemImages.FontAwesome.ttf");
_FontAwesomeHandle = GCHandle.Alloc(fontAwesomeBuffer, GCHandleType.Pinned);
_PrivateFontCollection.AddMemoryFont(_FontAwesomeHandle.AddrOfPinnedObject(), fontAwesomeBuffer.Length);
uint rsxCnt = 1;
_FontAwesomePointer = AddFontMemResourceEx(_FontAwesomeHandle.AddrOfPinnedObject(),
(uint)fontAwesomeBuffer.Length, IntPtr.Zero, ref rsxCnt);
using (FontFamily ff = _PrivateFontCollection.Families[0])
{
if (ff.IsStyleAvailable(FontStyle.Regular))
{
_FontAwesome = new Font(ff, _FontAwesomeDefaultSize, FontStyle.Regular, GraphicsUnit.Point);
_FontAwesomeCache.Add(_FontAwesomeDefaultSize, _FontAwesome);
}
else
{
// Error use default font...
_FontAwesome = SystemInformation.MenuFont;
}
}
}
}
private static float _FontAwesomeDefaultSize = 18;
/// <summary>
/// Gets the default size for the FontAwesome font size in points.
/// </summary>
public static float FontAwesomeDefaultSize
{
get { return _FontAwesomeDefaultSize; }
}
internal static byte[] LoadFont(string fontFileName)
{
DotNetBarLayoutResourcesAttribute att = Attribute.GetCustomAttribute(System.Reflection.Assembly.GetExecutingAssembly(), typeof(DotNetBarLayoutResourcesAttribute)) as DotNetBarLayoutResourcesAttribute;
if (att != null && att.NamespacePrefix != "")
{
using (Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(att.NamespacePrefix + "." + fontFileName))
{
byte[] fontData = new byte[fontStream.Length];
fontStream.Read(fontData, 0, fontData.Length);
fontStream.Close();
return fontData;
}
}
else
{
using (Stream fontStream = typeof(LayoutControl).Module.Assembly.GetManifestResourceStream(typeof(LayoutControl), fontFileName))
{
byte[] fontData = new byte[fontStream.Length];
fontStream.Read(fontData, 0, fontData.Length);
fontStream.Close();
return fontData;
}
}
return new byte[0];
}
#endregion
}
}

View File

@@ -0,0 +1,276 @@
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Text;
using System.Collections.Generic;
#if DOTNETBAR
namespace DevComponents.DotNetBar
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout
#else
namespace DevComponents.Tree
#endif
{
public class TextDrawing
{
static TextDrawing()
{
string lc = Application.CurrentCulture.TwoLetterISOLanguageName;
if (lc == "ja" || lc == "ko" || lc == "zh" || lc == "ar")
UseGenericDefault = true;
}
public static bool TextDrawingEnabled = true;
public static bool UseTextRenderer = false;
public static void DrawString(Graphics g, string text, Font font, Color color, int x, int y, eTextFormat format)
{
DrawString(g, text, font, color, new Rectangle(x, y, 0, 0), format);
}
public static void DrawString(Graphics g, string text, Font font, Color color, Rectangle bounds, eTextFormat format)
{
#if FRAMEWORK20
if (UseTextRenderer && (format & eTextFormat.Vertical) == 0)
TextRenderer.DrawText(g, text, font, bounds, color, GetTextFormatFlags(format));
else
DrawStringLegacy(g, text, font, color, bounds, format);
#else
DrawStringLegacy(g, text, font, color, bounds, format);
#endif
}
public static void DrawStringLegacy(Graphics g, string text, Font font, Color color, Rectangle bounds, eTextFormat format)
{
if (color.IsEmpty || !TextDrawingEnabled)
return;
using (SolidBrush brush = new SolidBrush(color))
{
//using (StringFormat sf = GetStringFormat(format))
StringFormat sf = GetStringFormat(format);
g.DrawString(text, font, brush, bounds, sf);
}
}
public static void DrawStringLegacy(Graphics g, string text, Font font, Color color, RectangleF bounds, eTextFormat format)
{
if (color.IsEmpty || !TextDrawingEnabled)
return;
using (SolidBrush brush = new SolidBrush(color))
{
StringFormat sf = GetStringFormat(format);
g.DrawString(text, font, brush, bounds, sf);
}
}
public static Size MeasureString(Graphics g, string text, Font font)
{
return MeasureString(g, text, font, Size.Empty, eTextFormat.Default);
}
public static Size MeasureString(Graphics g, string text, Font font, int proposedWidth, eTextFormat format)
{
return MeasureString(g, text, font, new Size(proposedWidth, 0), format);
}
public static Size MeasureString(Graphics g, string text, Font font, int proposedWidth)
{
return MeasureString(g, text, font, new Size(proposedWidth, 0), eTextFormat.Default);
}
public static Size MeasureString(Graphics g, string text, Font font, Size proposedSize, eTextFormat format)
{
#if FRAMEWORK20
if (UseTextRenderer && (format & eTextFormat.Vertical) == 0)
{
format = format & ~(format & eTextFormat.VerticalCenter); // Bug in .NET Framework 2.0
format = format & ~(format & eTextFormat.Bottom); // Bug in .NET Framework 2.0
format = format & ~(format & eTextFormat.HorizontalCenter); // Bug in .NET Framework 2.0
format = format & ~(format & eTextFormat.Right); // Bug in .NET Framework 2.0
format = format & ~(format & eTextFormat.EndEllipsis); // Bug in .NET Framework 2.0
return Size.Ceiling(TextRenderer.MeasureText(g, text, font, proposedSize, GetTextFormatFlags(format)));
}
//using (StringFormat sf = GetStringFormat(format))
StringFormat sf = GetStringFormat(format);
return Size.Ceiling(g.MeasureString(text, font, proposedSize, sf));
#else
//using (StringFormat sf = GetStringFormat(format))
StringFormat sf = GetStringFormat(format);
return Size.Ceiling(g.MeasureString(text, font, proposedSize, sf));
#endif
}
public static Size MeasureStringLegacy(Graphics g, string text, Font font, Size proposedSize, eTextFormat format)
{
//using (StringFormat sf = GetStringFormat(format))
StringFormat sf = GetStringFormat(format);
return g.MeasureString(text, font, proposedSize, sf).ToSize();
}
public static eTextFormat TranslateHorizontal(StringAlignment align)
{
if (align == StringAlignment.Center)
return eTextFormat.HorizontalCenter;
else if (align == StringAlignment.Far)
return eTextFormat.Right;
return eTextFormat.Default;
}
public static eTextFormat TranslateVertical(StringAlignment align)
{
if (align == StringAlignment.Center)
return eTextFormat.VerticalCenter;
else if (align == StringAlignment.Far)
return eTextFormat.Bottom;
return eTextFormat.Default;
}
#if FRAMEWORK20
private static TextFormatFlags GetTextFormatFlags(eTextFormat format)
{
format |= eTextFormat.PreserveGraphicsTranslateTransform | eTextFormat.PreserveGraphicsClipping;
if((format & eTextFormat.SingleLine)==eTextFormat.SingleLine && (format & eTextFormat.WordBreak)==eTextFormat.WordBreak)
format = format & ~(format & eTextFormat.SingleLine);
return (TextFormatFlags)format;
}
#endif
internal static bool UseGenericDefault = false;
private static Dictionary<eTextFormat, StringFormat> _CachedFormats = new Dictionary<eTextFormat, StringFormat>();
public static StringFormat GetStringFormat(eTextFormat format)
{
StringFormat sf;
if (_CachedFormats.TryGetValue(format, out sf)) return sf;
if (UseGenericDefault)
sf = (StringFormat)StringFormat.GenericDefault.Clone(); //new StringFormat(StringFormat.GenericDefault);
else
sf = (StringFormat)StringFormat.GenericTypographic.Clone(); // new StringFormat(StringFormat.GenericTypographic);
if (format == eTextFormat.Default)
{
sf.HotkeyPrefix = HotkeyPrefix.Show;
_CachedFormats.Add(format, sf);
return sf;
}
if ((format & eTextFormat.HorizontalCenter) == eTextFormat.HorizontalCenter)
sf.Alignment = StringAlignment.Center;
else if ((format & eTextFormat.Right) == eTextFormat.Right)
sf.Alignment=StringAlignment.Far;
if ((format & eTextFormat.VerticalCenter) == eTextFormat.VerticalCenter)
sf.LineAlignment=StringAlignment.Center;
else if ((format & eTextFormat.Bottom) == eTextFormat.Bottom)
sf.LineAlignment=StringAlignment.Far;
if ((format & eTextFormat.EndEllipsis) == eTextFormat.EndEllipsis)
sf.Trimming = StringTrimming.EllipsisCharacter;
else
sf.Trimming = StringTrimming.Character;
if ((format & eTextFormat.HidePrefix) == eTextFormat.HidePrefix)
sf.HotkeyPrefix = HotkeyPrefix.Hide;
else if ((format & eTextFormat.NoPrefix) == eTextFormat.NoPrefix)
sf.HotkeyPrefix = HotkeyPrefix.None;
else
sf.HotkeyPrefix = HotkeyPrefix.Show;
if ((format & eTextFormat.WordBreak) == eTextFormat.WordBreak)
sf.FormatFlags = sf.FormatFlags & ~(sf.FormatFlags & StringFormatFlags.NoWrap);
else
sf.FormatFlags |= StringFormatFlags.NoWrap;
if ((format & eTextFormat.LeftAndRightPadding) == eTextFormat.LeftAndRightPadding)
sf.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
if ((format & eTextFormat.RightToLeft) == eTextFormat.RightToLeft)
sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
if ((format & eTextFormat.Vertical) == eTextFormat.Vertical)
sf.FormatFlags |= StringFormatFlags.DirectionVertical;
if ((format & eTextFormat.NoClipping) == eTextFormat.NoClipping)
sf.FormatFlags |= StringFormatFlags.NoClip;
_CachedFormats.Add(format, sf);
return sf;
}
#if DOTNETBAR
public static ThemeTextFormat GetTextFormat(eTextFormat format)
{
ThemeTextFormat ttf = ThemeTextFormat.Left;
if (format == eTextFormat.Default)
return ttf;
if ((format & eTextFormat.HorizontalCenter) == eTextFormat.HorizontalCenter)
ttf |= ThemeTextFormat.Center;
else if ((format & eTextFormat.Right) == eTextFormat.Right)
ttf|= ThemeTextFormat.Right;
if ((format & eTextFormat.VerticalCenter) == eTextFormat.VerticalCenter)
ttf |= ThemeTextFormat.VCenter;
else if ((format & eTextFormat.Bottom) == eTextFormat.Bottom)
ttf |= ThemeTextFormat.Bottom;
if ((format & eTextFormat.EndEllipsis) == eTextFormat.EndEllipsis)
ttf |= ThemeTextFormat.EndEllipsis;
if ((format & eTextFormat.HidePrefix) == eTextFormat.HidePrefix)
ttf |= ThemeTextFormat.HidePrefix;
else if ((format & eTextFormat.NoPrefix) == eTextFormat.NoPrefix)
ttf |= ThemeTextFormat.NoPrefix;
if ((format & eTextFormat.WordBreak) == eTextFormat.WordBreak)
ttf |= ThemeTextFormat.WordBreak;
else
ttf |= ThemeTextFormat.SingleLine;
if ((format & eTextFormat.RightToLeft) == eTextFormat.RightToLeft)
ttf |= ThemeTextFormat.RtlReading;
if ((format & eTextFormat.NoClipping) == eTextFormat.NoClipping)
ttf |= ThemeTextFormat.NoClip;
return ttf;
}
#endif
}
[Flags]
public enum eTextFormat
{
Bottom = 8,
Default = 0,
EndEllipsis = 0x8000,
ExpandTabs = 0x40,
ExternalLeading = 0x200,
GlyphOverhangPadding = 0,
HidePrefix = 0x100000,
HorizontalCenter = 1,
Internal = 0x1000,
Left = 0,
LeftAndRightPadding = 0x20000000,
ModifyString = 0x10000,
NoClipping = 0x100,
NoFullWidthCharacterBreak = 0x80000,
NoPadding = 0x10000000,
NoPrefix = 0x800,
PathEllipsis = 0x4000,
PrefixOnly = 0x200000,
PreserveGraphicsClipping = 0x1000000,
PreserveGraphicsTranslateTransform = 0x2000000,
Right = 2,
RightToLeft = 0x20000,
SingleLine = 0x20,
TextBoxControl = 0x2000,
Top = 0,
VerticalCenter = 4,
WordBreak = 0x10,
WordEllipsis = 0x40000,
Vertical = 0x40000000
}
}

View File

@@ -0,0 +1,185 @@
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing.Text;
using System.Windows.Forms;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Represents class with static functions that provide commonly used utility functions when working with
/// Bar objects and items hosted by Bar object.
/// </summary>
internal class BarUtilities
{
/// <summary>
/// Gets or sets whether StringFormat internally used by all DotNetBar controls to render text is GenericDefault. Default value is false
/// which indicates that GenericTypographic is used.
/// </summary>
public static bool UseGenericDefaultStringFormat
{
get { return TextDrawing.UseGenericDefault; }
set { TextDrawing.UseGenericDefault = value; }
}
/// <summary>
/// Gets or sets the anti-alias text rendering hint that will be used to render text on controls that have AntiAlias property set to true.
/// </summary>
public static TextRenderingHint AntiAliasTextRenderingHint
{
get
{
return DisplayHelp.AntiAliasTextRenderingHint;
}
set
{
DisplayHelp.AntiAliasTextRenderingHint = value;
}
}
#if FRAMEWORK20
/// <summary>
/// Gets or sets whether .NET Framework TextRenderer class is used for text rendering instead of Graphics.DrawString.
/// Default value is false.
/// Using TextRenderer will disable the Fade and Animation effects on controls because of issues in TextRenderer when drawing text on transparent
/// surfaces.
/// </summary>
public static bool UseTextRenderer
{
get { return TextDrawing.UseTextRenderer; }
set { TextDrawing.UseTextRenderer = value; }
}
#endif
private static bool _AlwaysGenerateAccessibilityFocusEvent = false;
/// <summary>
/// Gets or sets whether items always generate the Focus accessibility event when mouse enters the item. Default value is false which indicates
/// that focus event will be raised only when item is on menu bar.
/// </summary>
public static bool AlwaysGenerateAccessibilityFocusEvent
{
get { return _AlwaysGenerateAccessibilityFocusEvent; }
set
{
_AlwaysGenerateAccessibilityFocusEvent = value;
}
}
internal static bool IsModalFormOpen
{
get
{
#if (FRAMEWORK20)
for (int i = 0; i < System.Windows.Forms.Application.OpenForms.Count; i++)
{
System.Windows.Forms.Form form = System.Windows.Forms.Application.OpenForms[i];
if (form.Modal) return true;
}
#endif
return false;
}
}
private static bool _AutoRemoveMessageFilter = false;
/// <summary>
/// Gets or sets whether Application Message Filter that is registered by popup controls
/// is automatically unregistered when last control is disposed. Default value is false and
/// in most cases should not be changed.
/// </summary>
public static bool AutoRemoveMessageFilter
{
get { return _AutoRemoveMessageFilter; }
set { _AutoRemoveMessageFilter = value; }
}
private static int _TextMarkupCultureSpecific = 3;
/// <summary>
/// Get or sets the text-markup padding for text measurement when running on Japanese version of Windows.
/// </summary>
public static int TextMarkupCultureSpecificPadding
{
get { return _TextMarkupCultureSpecific; }
set
{
_TextMarkupCultureSpecific = value;
}
}
private static bool _DisposeItemImages = false;
/// <summary>
/// Gets or sets whether Image and Icon resources assigned to items and controls are automatically disposed when
/// control or item is disposed. Default value is false.
/// </summary>
public static bool DisposeItemImages
{
get
{
return _DisposeItemImages;
}
set
{
_DisposeItemImages = value;
}
}
/// <summary>
/// Disposes image reference and sets it to null.
/// </summary>
/// <param name="image">Reference to image to dispose.</param>
internal static void DisposeImage(ref System.Drawing.Image image)
{
if (image == null) return;
image.Dispose();
image = null;
}
/// <summary>
/// Disposes image reference and sets it to null.
/// </summary>
/// <param name="image">Reference to image to dispose.</param>
internal static void DisposeImage(ref System.Drawing.Icon icon)
{
if (icon == null) return;
icon.Dispose();
icon = null;
}
#region Delayed Invoke
/// <summary>
/// Invokes the method asynchronously using the WinForms Timer.
/// </summary>
/// <param name="method">Method to invoke.</param>
public static void InvokeDelayed(MethodInvoker method)
{
InvokeDelayed(method, 10);
}
/// <summary>
/// Invokes the method asynchronously using the WinForms Timer.
/// </summary>
/// <param name="method">Method to invoke.</param>
/// <param name="delayInterval">Time in milliseconds after which method is invoked.</param>
public static void InvokeDelayed(MethodInvoker method, int delayInterval)
{
Timer delayedInvokeTimer = new Timer();
delayedInvokeTimer = new Timer();
delayedInvokeTimer.Tag = method;
delayedInvokeTimer.Interval = delayInterval;
delayedInvokeTimer.Tick += new EventHandler(DelayedInvokeTimerTick);
delayedInvokeTimer.Start();
}
private static void DelayedInvokeTimerTick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
MethodInvoker method = (MethodInvoker)timer.Tag;
timer.Stop();
timer.Dispose();
method.Invoke();
}
#endregion
}
internal class BarPropertyBagKeys
{
public static string AutoHideSetting="autohide";
}
}

View File

@@ -0,0 +1,91 @@
using System;
using System.Text;
using System.Windows.Forms;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class BodyElement : ContainerElement
{
#region Private Variables
private MarkupElementCollection m_ActiveElements=null;
private IActiveMarkupElement m_MouseOverElement = null;
internal bool HasExpandElement = false;
internal string PlainText = "";
#endregion
#region Events
public event EventHandler HyperLinkClick;
#endregion
#region Internal Implementation
public BodyElement()
{
m_ActiveElements = new MarkupElementCollection(null);
}
public MarkupElementCollection ActiveElements
{
get { return m_ActiveElements; }
}
public void MouseLeave(Control parent)
{
if (m_MouseOverElement != null)
m_MouseOverElement.MouseLeave(parent);
m_MouseOverElement = null;
}
public void MouseMove(Control parent, MouseEventArgs e)
{
if (m_MouseOverElement != null && m_MouseOverElement.HitTest(e.X, e.Y))
return;
if (m_MouseOverElement != null)
m_MouseOverElement.MouseLeave(parent);
m_MouseOverElement = null;
foreach(IActiveMarkupElement el in m_ActiveElements)
{
if (el.HitTest(e.X, e.Y))
{
m_MouseOverElement = el;
m_MouseOverElement.MouseEnter(parent);
}
}
}
public void MouseDown(Control parent, MouseEventArgs e)
{
if (m_MouseOverElement != null)
m_MouseOverElement.MouseDown(parent, e);
}
public void MouseUp(Control parent, MouseEventArgs e)
{
if (m_MouseOverElement != null)
m_MouseOverElement.MouseUp(parent, e);
}
public void Click(Control parent)
{
if (m_MouseOverElement != null)
{
m_MouseOverElement.Click(parent);
if (m_MouseOverElement is HyperLink)
{
if (HyperLinkClick != null)
HyperLinkClick(m_MouseOverElement, new EventArgs());
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,113 @@
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
using DevComponents.UI.ContentManager;
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class ContainerElement : MarkupElement
{
#region Private Variables
private SerialContentLayoutManager m_Layout = null;
private MarkupLayoutManager m_MarkupLayout = null;
#endregion
#region Internal Implementation
public override void Measure(Size availableSize, MarkupDrawContext d)
{
ArrangeInternal(new Rectangle(Point.Empty, availableSize), d);
}
protected virtual SerialContentLayoutManager GetLayoutManager(bool mutliLine)
{
if (m_Layout == null)
{
m_Layout = new SerialContentLayoutManager();
m_Layout.MultiLine = mutliLine;
m_Layout.ContentVerticalAlignment = eContentVerticalAlignment.Top;
m_Layout.BlockLineAlignment = eContentVerticalAlignment.Top;
m_Layout.BlockSpacing = 0;
}
m_Layout.EvenHeight = true;
return m_Layout;
}
private MarkupLayoutManager GetMarkupLayout()
{
if (m_MarkupLayout == null)
{
m_MarkupLayout = new MarkupLayoutManager();
}
return m_MarkupLayout;
}
public override void Render(MarkupDrawContext d)
{
Point offset = this.GetContainerOffset();
d.Offset.Offset(offset.X, offset.Y);
try
{
foreach (MarkupElement e in this.Elements)
{
e.Render(d);
}
}
finally
{
d.Offset.Offset(-offset.X, -offset.Y);
}
}
protected virtual Point GetContainerOffset()
{
return this.Bounds.Location;
}
protected override void ArrangeCore(Rectangle finalRect, MarkupDrawContext d)
{
this.Bounds = finalRect;
ArrangeInternal(finalRect, d);
}
protected virtual void ArrangeInternal(Rectangle bounds, MarkupDrawContext d)
{
SerialContentLayoutManager layout = GetLayoutManager(d.AllowMultiLine);
layout.RightToLeft = d.RightToLeft;
MarkupLayoutManager markupLayout = GetMarkupLayout();
markupLayout.MarkupDrawContext = d;
try
{
MarkupElement[] blocks = new MarkupElement[this.Elements.Count];
this.Elements.CopyTo(blocks);
Rectangle r = layout.Layout(new Rectangle(Point.Empty, bounds.Size), blocks, markupLayout);
this.Bounds = new Rectangle(bounds.Location, r.Size);
}
finally
{
markupLayout.MarkupDrawContext = null;
}
}
/// <summary>
/// Returns whether markup element is an block element that always consumes a whole line in layout.
/// </summary>
public override bool IsBlockElement
{
get { return true; }
}
#endregion
}
}

View File

@@ -0,0 +1,932 @@
using System.Drawing;
using System.Drawing.Drawing2D;
using System;
using System.Drawing.Text;
#if AdvTree
namespace DevComponents.Tree
#elif DOTNETBAR
namespace DevComponents.DotNetBar
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout
#endif
{
/// <summary>
/// Summary description for Display.
/// </summary>
public class DisplayHelp
{
private DisplayHelp()
{
}
public static LinearGradientBrush CreateLinearGradientBrush(Rectangle r,Color color1, Color color2,float gradientAngle)
{
if(r.Width<=0)
r.Width=1;
if(r.Height<=0)
r.Height=1;
return new LinearGradientBrush(new Rectangle(r.X,r.Y-1,r.Width,r.Height+1),color1,color2,gradientAngle);
}
public static LinearGradientBrush CreateLinearGradientBrush(RectangleF r,Color color1, Color color2,float gradientAngle)
{
if(r.Width<=0)
r.Width=1;
if(r.Height<=0)
r.Height=1;
return new LinearGradientBrush(new RectangleF(r.X,r.Y-1,r.Width,r.Height+1),color1,color2,gradientAngle);
}
public static LinearGradientBrush CreateLinearGradientBrush(Rectangle r,Color color1, Color color2,float gradientAngle, bool isAngleScalable)
{
if(r.Width<=0)
r.Width=1;
if(r.Height<=0)
r.Height=1;
return new LinearGradientBrush(new Rectangle(r.X,r.Y-1,r.Width,r.Height+1),color1,color2,gradientAngle,isAngleScalable);
}
public static Rectangle GetDrawRectangle(Rectangle r)
{
r.Width--;
r.Height--;
return r;
}
public static Rectangle GetPathRectangle(Rectangle r)
{
//r.Width++;
//r.Height++;
return r;
}
public static void DrawRectangle(System.Drawing.Graphics g, Color color, int x, int y, int width, int height)
{
using (Pen pen = new Pen(color, 1))
DrawRectangle(g, pen, x, y, width, height);
}
public static void DrawRectangle(System.Drawing.Graphics g, Color color, System.Drawing.Rectangle r)
{
DrawRectangle(g, color, r.X, r.Y, r.Width, r.Height);
}
public static void DrawRectangle(System.Drawing.Graphics g, System.Drawing.Pen pen, int x, int y, int width, int height)
{
// Fix for GDI issue
width--;
height--;
g.DrawRectangle(pen,x,y,width,height);
}
public static void DrawRectangle(System.Drawing.Graphics g, System.Drawing.Pen pen, System.Drawing.Rectangle r)
{
DrawRectangle(g,pen,r.X,r.Y,r.Width,r.Height);
}
//public static void DrawRoundedRectangle(System.Drawing.Graphics g, Color color, DevComponents.DotNetBar.Rendering.LinearGradientColorTable fillColor, Rectangle bounds, int cornerSize)
//{
// using (Brush fill = CreateBrush(bounds, fillColor))
// {
// using (Pen pen = new Pen(color))
// DrawRoundedRectangle(g, pen, fill, bounds.X, bounds.Y, bounds.Width, bounds.Height, cornerSize);
// }
//}
#if !LAYOUT
public static void DrawRoundedRectangle(System.Drawing.Graphics g, Color color, Color fillColor, Rectangle bounds, int cornerSize)
{
using (Brush fill = new SolidBrush(fillColor))
{
using (Pen pen = new Pen(color))
DrawRoundedRectangle(g, pen, fill, bounds.X, bounds.Y, bounds.Width, bounds.Height, cornerSize);
}
}
public static void DrawRoundedRectangle(System.Drawing.Graphics g, Color color, Rectangle bounds, int cornerSize)
{
if (!color.IsEmpty)
{
using (Pen pen = new Pen(color))
DrawRoundedRectangle(g, pen, bounds.X, bounds.Y, bounds.Width, bounds.Height, cornerSize);
}
}
public static void DrawRoundedRectangle(System.Drawing.Graphics g, Color color, int x, int y, int width, int height, int cornerSize)
{
if (!color.IsEmpty)
{
using (Pen pen = new Pen(color))
DrawRoundedRectangle(g, pen, x, y, width, height, cornerSize);
}
}
public static void DrawRoundedRectangle(System.Drawing.Graphics g, System.Drawing.Pen pen, Rectangle bounds, int cornerSize)
{
DrawRoundedRectangle(g, pen, bounds.X, bounds.Y, bounds.Width, bounds.Height, cornerSize);
}
public static void DrawRoundedRectangle(System.Drawing.Graphics g, System.Drawing.Pen pen, int x, int y, int width, int height, int cornerSize)
{
DrawRoundedRectangle(g, pen, null, x, y, width, height, cornerSize);
}
public static void DrawRoundedRectangle(System.Drawing.Graphics g, System.Drawing.Pen pen, Brush fill, int x, int y, int width, int height, int cornerSize)
{
// Fix for GDI issue
width--;
height--;
Rectangle r = new Rectangle(x, y, width, height);
//SmoothingMode sm = g.SmoothingMode;
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
using (GraphicsPath path = GetRoundedRectanglePath(r, cornerSize))
{
if (fill != null)
g.FillPath(fill, path);
g.DrawPath(pen, path);
}
//g.SmoothingMode = sm;
}
public static GraphicsPath GetRoundedRectanglePath(Rectangle r, int cornerSize)
{
GraphicsPath path = new GraphicsPath();
if (cornerSize == 0)
path.AddRectangle(r);
else
{
ElementStyleDisplay.AddCornerArc(path, r, cornerSize, eCornerArc.TopLeft);
ElementStyleDisplay.AddCornerArc(path, r, cornerSize, eCornerArc.TopRight);
ElementStyleDisplay.AddCornerArc(path, r, cornerSize, eCornerArc.BottomRight);
ElementStyleDisplay.AddCornerArc(path, r, cornerSize, eCornerArc.BottomLeft);
path.CloseAllFigures();
}
return path;
}
public static GraphicsPath GetRoundedRectanglePath(Rectangle r, int cornerTopLeft, int cornerTopRight, int cornerBottomRight, int cornerBottomLeft)
{
GraphicsPath path = new GraphicsPath();
ElementStyleDisplay.AddCornerArc(path, r, cornerTopLeft, eCornerArc.TopLeft);
ElementStyleDisplay.AddCornerArc(path, r, cornerTopRight, eCornerArc.TopRight);
ElementStyleDisplay.AddCornerArc(path, r, cornerBottomRight, eCornerArc.BottomRight);
ElementStyleDisplay.AddCornerArc(path, r, cornerBottomLeft, eCornerArc.BottomLeft);
path.CloseAllFigures();
return path;
}
#endif
//public static GraphicsPath GetRoundedRectanglePath(Rectangle clientRectangle, int cornerSize, eStyleBackgroundPathPart pathPart,
// eCornerType topLeftCornerType, eCornerType topRightCornerType, eCornerType bottomLeftCornerType, eCornerType bottomRightCornerType)
//{
// return GetRoundedRectanglePath(clientRectangle, cornerSize, pathPart, topLeftCornerType, topRightCornerType, bottomLeftCornerType, bottomRightCornerType, 0);
//}
//public static GraphicsPath GetRoundedRectanglePath(Rectangle clientRectangle, int cornerSize, eStyleBackgroundPathPart pathPart,
// eCornerType topLeftCornerType, eCornerType topRightCornerType, eCornerType bottomLeftCornerType, eCornerType bottomRightCornerType, float partSize)
//{
// return GetRoundedRectanglePath(clientRectangle, cornerSize, cornerSize, cornerSize, cornerSize, pathPart, topLeftCornerType, topRightCornerType, bottomLeftCornerType, bottomRightCornerType, partSize);
//}
//public static GraphicsPath GetRoundedRectanglePath(Rectangle clientRectangle, int topLeftCornerSize, int topRightCornerSize, int bottomLeftCornerSize, int bottomRightCornerSize, eStyleBackgroundPathPart pathPart,
// eCornerType topLeftCornerType, eCornerType topRightCornerType, eCornerType bottomLeftCornerType, eCornerType bottomRightCornerType, float partSize)
//{
// GraphicsPath path = new GraphicsPath();
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// {
// if (partSize == 0)
// clientRectangle.Height = clientRectangle.Height / 2;
// else
// clientRectangle.Height = (int)(clientRectangle.Height * partSize);
// }
// else if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// {
// int h = clientRectangle.Height;
// if (partSize == 0)
// clientRectangle.Height = clientRectangle.Height / 2;
// else
// clientRectangle.Height = (int)(clientRectangle.Height * partSize);
// clientRectangle.Y += (h - clientRectangle.Height - 1);
// }
// eCornerType corner = topLeftCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded && topLeftCornerSize>0)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, topLeftCornerSize, eCornerArc.TopLeft);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.X, clientRectangle.Y + topLeftCornerSize, clientRectangle.X + topLeftCornerSize, clientRectangle.Y);
// }
// else
// {
// path.AddLine(clientRectangle.X, clientRectangle.Y + 2, clientRectangle.X, clientRectangle.Y);
// path.AddLine(clientRectangle.X, clientRectangle.Y, clientRectangle.X + 2, clientRectangle.Y);
// }
// corner = topRightCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded && topRightCornerSize>0)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, topRightCornerSize, eCornerArc.TopRight);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.Right - topRightCornerSize - 1, clientRectangle.Y, clientRectangle.Right, clientRectangle.Y + topRightCornerSize);
// }
// else
// {
// path.AddLine(clientRectangle.Right - 2, clientRectangle.Y, clientRectangle.Right, clientRectangle.Y);
// path.AddLine(clientRectangle.Right, clientRectangle.Y, clientRectangle.Right, clientRectangle.Y + 2);
// }
// corner = bottomRightCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded && bottomRightCornerSize>0)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, bottomRightCornerSize, eCornerArc.BottomRight);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.Right, clientRectangle.Bottom - bottomRightCornerSize - 1, clientRectangle.Right - bottomRightCornerSize - 1, clientRectangle.Bottom);
// }
// else
// {
// path.AddLine(clientRectangle.Right, clientRectangle.Bottom - 2, clientRectangle.Right, clientRectangle.Bottom);
// path.AddLine(clientRectangle.Right, clientRectangle.Bottom, clientRectangle.Right - 2, clientRectangle.Bottom);
// }
// corner = bottomLeftCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded && bottomLeftCornerSize>0)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, bottomLeftCornerSize, eCornerArc.BottomLeft);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.X + 2, clientRectangle.Bottom, clientRectangle.X, clientRectangle.Bottom - bottomLeftCornerSize - 1);
// }
// else
// {
// path.AddLine(clientRectangle.X + 2, clientRectangle.Bottom, clientRectangle.X, clientRectangle.Bottom);
// path.AddLine(clientRectangle.X, clientRectangle.Bottom, clientRectangle.X, clientRectangle.Bottom - 2);
// }
// path.CloseAllFigures();
// return path;
//}
//public static GraphicsPath GetBorderPath(Rectangle clientRectangle, int cornerSize, eStyleBackgroundPathPart pathPart,
// eCornerType topLeftCornerType, eCornerType topRightCornerType, eCornerType bottomLeftCornerType, eCornerType bottomRightCornerType,
// bool leftBorder, bool rightBorder, bool topBorder, bool bottomBorder)
//{
// GraphicsPath path = new GraphicsPath();
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// clientRectangle.Height = clientRectangle.Height / 2;
// else if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// {
// int h = clientRectangle.Height;
// clientRectangle.Height = clientRectangle.Height / 2;
// clientRectangle.Y += (h - clientRectangle.Height - 1);
// }
// eCornerType corner = topLeftCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// corner = eCornerType.Square;
// if (leftBorder)
// {
// path.AddLine(clientRectangle.X, clientRectangle.Bottom -
// (bottomBorder && (bottomLeftCornerType == eCornerType.Diagonal || bottomLeftCornerType == eCornerType.Rounded) ? cornerSize : 0),
// clientRectangle.X, clientRectangle.Y +
// (topBorder && (topLeftCornerType == eCornerType.Diagonal || topLeftCornerType == eCornerType.Rounded) ? cornerSize : 0));
// }
// if (leftBorder && topBorder)
// {
// if (corner == eCornerType.Rounded)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, cornerSize, eCornerArc.TopLeft);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.X, clientRectangle.Y + cornerSize, clientRectangle.X + cornerSize, clientRectangle.Y);
// }
// }
// if (topBorder)
// {
// path.AddLine(clientRectangle.X +
// ((topLeftCornerType == eCornerType.Diagonal || topLeftCornerType == eCornerType.Rounded) ? cornerSize : 0)
// , clientRectangle.Y, clientRectangle.Right -
// (rightBorder && (topRightCornerType == eCornerType.Diagonal || topRightCornerType == eCornerType.Rounded) ? cornerSize : 0),
// clientRectangle.Y);
// }
// corner = topRightCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.BottomHalf)
// corner = eCornerType.Square;
// if (topBorder && rightBorder)
// {
// if (corner == eCornerType.Rounded)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, cornerSize, eCornerArc.TopRight);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.Right - cornerSize - 1, clientRectangle.Y, clientRectangle.Right, clientRectangle.Y + cornerSize);
// }
// }
// if (rightBorder)
// {
// path.AddLine(clientRectangle.Right, clientRectangle.Y +
// ((topRightCornerType == eCornerType.Diagonal || topRightCornerType == eCornerType.Rounded) ? cornerSize : 0),
// clientRectangle.Right, clientRectangle.Bottom -
// (bottomBorder && (bottomRightCornerType == eCornerType.Diagonal || bottomRightCornerType == eCornerType.Rounded) ? cornerSize : 0));
// }
// corner = bottomRightCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, cornerSize, eCornerArc.BottomRight);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.Right, clientRectangle.Bottom - cornerSize - 1, clientRectangle.Right - cornerSize - 1, clientRectangle.Bottom);
// }
// if (bottomBorder)
// {
// path.AddLine(clientRectangle.Right -
// ((bottomRightCornerType == eCornerType.Diagonal || bottomRightCornerType == eCornerType.Rounded) ? cornerSize : 0),
// clientRectangle.Bottom,
// clientRectangle.X +
// ((bottomLeftCornerType == eCornerType.Diagonal || bottomLeftCornerType == eCornerType.Rounded) ? cornerSize : 0),
// clientRectangle.Bottom);
// }
// corner = bottomLeftCornerType;
// if (corner == eCornerType.Inherit)
// corner = eCornerType.Square;
// if (pathPart == eStyleBackgroundPathPart.TopHalf)
// corner = eCornerType.Square;
// if (corner == eCornerType.Rounded)
// {
// ArcData ad = ElementStyleDisplay.GetCornerArc(clientRectangle, cornerSize, eCornerArc.BottomLeft);
// path.AddArc(ad.X, ad.Y, ad.Width, ad.Height, ad.StartAngle, ad.SweepAngle);
// }
// else if (corner == eCornerType.Diagonal)
// {
// path.AddLine(clientRectangle.X + 2, clientRectangle.Bottom, clientRectangle.X, clientRectangle.Bottom - cornerSize - 1);
// }
// return path;
//}
#if !LAYOUT
public static void FillRoundedRectangle(Graphics g, Rectangle bounds, int cornerSize, Color color1, Color color2, int gradientAngle)
{
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
using (SolidBrush brush = new SolidBrush(color1))
FillRoundedRectangle(g, brush, bounds, cornerSize);
}
}
else
{
using (LinearGradientBrush brush = CreateLinearGradientBrush(bounds, color1, color2, gradientAngle))
FillRoundedRectangle(g, brush, bounds, cornerSize);
}
}
public static void FillRoundedRectangle(Graphics g, Rectangle bounds, int cornerSize, Color color1, Color color2)
{
FillRoundedRectangle(g, bounds, cornerSize, color1, color2, 90);
}
public static void FillRoundedRectangle(Graphics g, Rectangle bounds, int cornerSize, Color color1)
{
using (SolidBrush brush = new SolidBrush(color1))
FillRoundedRectangle(g, brush, bounds, cornerSize);
}
public static void FillRoundedRectangle(Graphics g, Brush brush, Rectangle bounds, int cornerSize)
{
// Fix for GDI issue
bounds.Width--;
bounds.Height--;
using (GraphicsPath path = GetRoundedRectanglePath(bounds, cornerSize))
{
g.FillPath(brush, path);
}
}
#endif
public static void FillRectangle(Graphics g, Rectangle bounds, Color color1)
{
FillRectangle(g, bounds, color1, Color.Empty, 90);
}
public static void FillRectangle(Graphics g, Rectangle bounds, Color color1, Color color2)
{
FillRectangle(g, bounds, color1, color2, 90);
}
#if DOTNETBAR
public static void FillRectangle(Graphics g, Rectangle r, Rendering.LinearGradientColorTable table)
{
FillRectangle(g, r, table.Start, table.End, table.GradientAngle);
}
#endif
public static void FillRectangle(Graphics g, Rectangle r, Color color1, Color color2, int gradientAngle)
{
if (r.Width == 0 || r.Height == 0)
return;
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.None;
using (SolidBrush brush = new SolidBrush(color1))
g.FillRectangle(brush, r);
g.SmoothingMode = sm;
}
}
else
{
using (LinearGradientBrush brush = CreateLinearGradientBrush(r, color1, color2, gradientAngle))
g.FillRectangle(brush, r);
}
}
public static void FillRectangle(Graphics g, Rectangle r, Color color1, Color color2, int gradientAngle, float[] factors, float[] positions)
{
if (r.Width == 0 || r.Height == 0)
return;
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.None;
using (SolidBrush brush = new SolidBrush(color1))
g.FillRectangle(brush, r);
g.SmoothingMode = sm;
}
}
else
{
using (LinearGradientBrush brush = CreateLinearGradientBrush(r, color1, color2, gradientAngle))
{
Blend blend = new Blend(factors.Length);
blend.Factors = factors;
blend.Positions = positions;
brush.Blend = blend;
g.FillRectangle(brush, r);
}
}
}
public static void FillPath(Graphics g, GraphicsPath path, Color color1, Color color2)
{
FillPath(g, path, color1, color2, 90);
}
#if DOTNETBAR
public static void FillPath(Graphics g, GraphicsPath path, Rendering.LinearGradientColorTable table)
{
FillPath(g, path, table.Start, table.End, table.GradientAngle);
}
#endif
public static void FillPath(Graphics g, GraphicsPath path, Color color1, Color color2, int gradientAngle)
{
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
using (SolidBrush brush = new SolidBrush(color1))
g.FillPath(brush, path);
}
}
else if(!color1.IsEmpty)
{
using (LinearGradientBrush brush = CreateLinearGradientBrush(path.GetBounds(), color1, color2, gradientAngle))
g.FillPath(brush, path);
}
}
//public static void DrawGradientLine(Graphics g, Point start, Point end, Color color1, Color color2, int gradientAngle, int penWidth)
//{
// if (color1.IsEmpty || penWidth <= 0 || start == end)
// return;
// using (GraphicsPath path = new GraphicsPath())
// {
// start.Offset(-1, -1);
// end.Offset(-1, -1);
// path.AddLine(start, end);
// using (Pen pen = new Pen(Color.White, penWidth))
// path.Widen(pen);
// Rectangle r = Rectangle.Ceiling(path.GetBounds());
// r.Inflate(1, 1);
// using (LinearGradientBrush brush = CreateLinearGradientBrush(r, color1, color2, gradientAngle))
// g.FillPath(brush, path);
// }
//}
public static void DrawLine(Graphics g, Point start, Point end, Color color, int penWidth)
{
if (!color.IsEmpty)
{
using (Pen pen = new Pen(color, penWidth))
g.DrawLine(pen, start, end);
}
}
public static void DrawLine(Graphics g, int x1, int y1, int x2, int y2, Color color, int penWidth)
{
if (!color.IsEmpty)
{
using (Pen pen = new Pen(color, penWidth))
g.DrawLine(pen, x1, y1, x2, y2);
}
}
#if DOTNETBAR
public static void DrawGradientRectangle(Graphics g, Rectangle bounds, Rendering.LinearGradientColorTable table, int penWidth)
{
DrawGradientRectangle(g, bounds, table.Start, table.End, table.GradientAngle, penWidth);
}
#endif
public static void DrawGradientRectangle(Graphics g, Rectangle bounds, Color color1, Color color2, int gradientAngle, int penWidth)
{
if (color1.IsEmpty || bounds.Width <= 0 || bounds.Height <= 0 || penWidth <= 0)
return;
Rectangle r = bounds;
// Workaround for GDI+ bug
r.Width--;
r.Height--;
if (color2.IsEmpty)
{
using (Pen pen = new Pen(color1, penWidth))
g.DrawRectangle(pen, r);
return;
}
using (GraphicsPath path = new GraphicsPath())
{
path.AddRectangle(r);
DrawGradientPath(g, path, r, color1, color2, gradientAngle, penWidth);
}
}
//public static void DrawGradientPath(Graphics g, GraphicsPath path, Rectangle bounds, Rendering.LinearGradientColorTable table, int penWidth)
//{
// DrawGradientPath(g, path, bounds, table.Start, table.End, table.GradientAngle, penWidth);
//}
public static void DrawGradientPath(Graphics g, GraphicsPath path, Rectangle bounds, Color color1, Color color2, int gradientAngle, int penWidth)
{
using (Pen pen = new Pen(color1, penWidth))
path.Widen(pen);
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
using (SolidBrush brush = new SolidBrush(color1))
g.FillPath(brush, path);
}
}
else if (!color1.IsEmpty)
{
using (LinearGradientBrush brush = new LinearGradientBrush(bounds, color1, color2, gradientAngle))
g.FillPath(brush, path);
}
}
#if DOTNETBAR
public static void DrawRoundGradientRectangle(Graphics g, Rectangle bounds, Rendering.LinearGradientColorTable table, int penWidth, int roundCornerSize)
{
DrawRoundGradientRectangle(g, bounds, table.Start, table.End, table.GradientAngle, penWidth, roundCornerSize);
}
public static void DrawRoundGradientRectangle(Graphics g, Rectangle bounds, Color color1, Color color2, int gradientAngle, int penWidth, int roundCornerSize)
{
if (color1.IsEmpty && color2.IsEmpty || bounds.Width <= 0 || bounds.Height <= 0 || roundCornerSize <= 0 || penWidth <= 0)
return;
if (color2.IsEmpty)
{
using (Pen pen = new Pen(color1, penWidth))
DrawRoundedRectangle(g, pen, bounds, roundCornerSize);
return;
}
Rectangle r = bounds;
// Workaround for GDI+ bug
r.Width--;
r.Height--;
using (GraphicsPath roundPath = GetRoundedRectanglePath(r, roundCornerSize))
{
using (Pen pen = new Pen(color1, penWidth))
roundPath.Widen(pen);
using (LinearGradientBrush brush = new LinearGradientBrush(bounds, color1, color2, gradientAngle))
g.FillPath(brush, roundPath);
}
}
public static void DrawGradientPathBorder(Graphics g, GraphicsPath path, Rendering.LinearGradientColorTable table, int penWidth)
{
DrawGradientPathBorder(g, path, table.Start, table.End, table.GradientAngle, penWidth);
}
#endif
public static void DrawGradientPathBorder(Graphics g, GraphicsPath path, Color color1, Color color2, int gradientAngle, int penWidth)
{
if (color1.IsEmpty && color2.IsEmpty) return;
using (Pen pen = new Pen(color1, penWidth))
path.Widen(pen);
Rectangle r = Rectangle.Ceiling(path.GetBounds());
r.Inflate(1, 1);
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
using (SolidBrush brush = new SolidBrush(color1))
g.FillPath(brush, path);
}
}
else if(!color1.IsEmpty)
{
using (LinearGradientBrush brush = new LinearGradientBrush(r, color1, color2, gradientAngle))
g.FillPath(brush, path);
}
}
#if DOTNETBAR
public static void DrawGradientLine(Graphics g, Point start, Point end, Rendering.LinearGradientColorTable table, int penWidth)
{
DrawGradientLine(g, start, end, table.Start, table.End, table.GradientAngle, penWidth);
}
public static void DrawGradientLine(Graphics g, int x1, int y1, int x2, int y2, Rendering.LinearGradientColorTable table, int penWidth)
{
DrawGradientLine(g, new Point(x1, y1), new Point(x2, y2), table.Start, table.End, table.GradientAngle, penWidth);
}
#endif
public static void DrawGradientLine(Graphics g, Point start, Point end, Color color1, Color color2, int gradientAngle, int penWidth)
{
if (color2.IsEmpty || penWidth == 1 && start.Y == end.Y && gradientAngle == 90)
{
if (!color1.IsEmpty)
{
using (Pen pen = new Pen(color1, penWidth))
{
g.DrawLine(pen, start, end);
}
}
}
else if (!color1.IsEmpty)
{
using (GraphicsPath path = new GraphicsPath())
{
//start.Offset(-1, -1);
//end.Offset(-1, -1);
path.AddLine(start, end);
using (Pen pen = new Pen(color1, penWidth))
path.Widen(pen);
Rectangle r = Rectangle.Ceiling(path.GetBounds());
r.Inflate(1, 1);
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.Default;
using (LinearGradientBrush brush = DisplayHelp.CreateLinearGradientBrush(r, color1, color2, gradientAngle))
g.FillPath(brush, path);
g.SmoothingMode = sm;
}
}
}
public static void DrawGradientLine(Graphics g, Point start, Point end, Color color1, Color color2, int gradientAngle, int penWidth, float[] factors, float[] positions)
{
if (color2.IsEmpty)
{
if (!color1.IsEmpty)
{
using (Pen pen = new Pen(color1, penWidth))
g.DrawLine(pen, start, end);
}
}
else if (!color1.IsEmpty)
{
using (GraphicsPath path = new GraphicsPath())
{
start.Offset(-1, -1);
end.Offset(-1, -1);
path.AddLine(start, end);
using (Pen pen = new Pen(color1, penWidth))
path.Widen(pen);
Rectangle r = Rectangle.Ceiling(path.GetBounds());
r.Inflate(1, 1);
using (LinearGradientBrush brush = DisplayHelp.CreateLinearGradientBrush(r, color1, color2, gradientAngle))
{
Blend blend = new Blend(factors.Length);
blend.Factors = factors;
blend.Positions = positions;
brush.Blend = blend;
g.FillPath(brush, path);
}
}
}
}
#if DOTNETBAR
public static Brush CreateBrush(Rectangle bounds, GradientColorTable colorBlend)
{
return CreateBrush(bounds, colorBlend.Colors, colorBlend.LinearGradientAngle, colorBlend.GradientType);
}
public static Brush CreateBrush(Rectangle bounds, DevComponents.DotNetBar.Rendering.LinearGradientColorTable colorTable)
{
if (colorTable.End.IsEmpty) return new SolidBrush(colorTable.Start);
return new LinearGradientBrush(bounds, colorTable.Start, colorTable.End, colorTable.GradientAngle);
}
public static Brush CreateBrush(Rectangle bounds, BackgroundColorBlendCollection colorBlend, int gradientAngle, eGradientType gradientType)
{
eBackgroundColorBlendType blendType = colorBlend.GetBlendType();
if (blendType == eBackgroundColorBlendType.Invalid)
return null;
if (blendType == eBackgroundColorBlendType.SolidColor)
{
return new SolidBrush(colorBlend[0].Color);
}
else if (blendType == eBackgroundColorBlendType.Relative)
{
try
{
if (gradientType == eGradientType.Linear)
{
bounds.Inflate(1, 1);
LinearGradientBrush brush =
DisplayHelp.CreateLinearGradientBrush(bounds, colorBlend[0].Color, colorBlend[colorBlend.Count - 1].Color,
gradientAngle);
brush.InterpolationColors = colorBlend.GetColorBlend();
return brush;
}
else if (gradientType == eGradientType.Radial)
{
int d = (int)Math.Sqrt(bounds.Width * bounds.Width + bounds.Height * bounds.Height) + 4;
GraphicsPath fillPath = new GraphicsPath();
fillPath.AddEllipse(bounds.X - (d - bounds.Width) / 2, bounds.Y - (d - bounds.Height) / 2, d, d);
PathGradientBrush brush = new PathGradientBrush(fillPath);
brush.CenterColor = colorBlend[0].Color;
brush.SurroundColors = new Color[] { colorBlend[colorBlend.Count - 1].Color };
brush.InterpolationColors = colorBlend.GetColorBlend();
return brush;
}
}
catch
{
return null;
}
}
else
{
BackgroundColorBlendCollection bc = colorBlend;
for (int i = 0; i < bc.Count; i += 2)
{
BackgroundColorBlend b1 = bc[i];
BackgroundColorBlend b2 = null;
if (i < bc.Count)
b2 = bc[i + 1];
if (b1 != null && b2 != null)
{
Rectangle rb = new Rectangle(bounds.X, bounds.Y + (int)b1.Position, bounds.Width,
(b2.Position == 1f ? bounds.Height : (int)b2.Position) - (int)b1.Position);
return DisplayHelp.CreateLinearGradientBrush(rb, b1.Color, b2.Color, gradientAngle);
}
}
}
return null;
}
#endif
public static System.Windows.Forms.ControlStyles DoubleBufferFlag
{
get
{
#if FRAMEWORK20
return System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer;
#else
return System.Windows.Forms.ControlStyles.DoubleBuffer;
#endif
}
}
private static TextRenderingHint s_AntiAliasTextRenderingHint = TextRenderingHint.ClearTypeGridFit;
public static TextRenderingHint AntiAliasTextRenderingHint
{
get
{
return s_AntiAliasTextRenderingHint;
}
set
{
s_AntiAliasTextRenderingHint = value;
}
}
public static Rectangle[] ExcludeRectangle(Rectangle r1, Rectangle exclude)
{
if (r1.X >= exclude.X && exclude.Right < r1.Right) // Left aligned
return new Rectangle[] { new Rectangle(exclude.Right, r1.Y, r1.Width - (exclude.Right - r1.X), r1.Height) };
else if (r1.Right <= exclude.Right && exclude.X > r1.X) // Right aligned
return new Rectangle[] { new Rectangle(r1.X, r1.Y, r1.Width - (r1.Right - exclude.X), r1.Height) };
else if (exclude.X > r1.X && exclude.Right < r1.Right)
{
return new Rectangle[] { new Rectangle(r1.X, r1.Y, exclude.X-r1.X, r1.Height),
new Rectangle(exclude.Right, r1.Y, r1.Right - exclude.Right, r1.Height)};
}
else if (exclude.Bottom >= r1.Bottom && exclude.Y > r1.Y) // Bottom Aligned
{
return new Rectangle[] { new Rectangle(r1.X, r1.Y, r1.Width, Math.Max(0, exclude.Y - r1.Y)) };
}
else if (exclude.Y <= r1.Y && exclude.Bottom < r1.Bottom) // Top Aligned
{
return new Rectangle[] { new Rectangle(r1.X, exclude.Bottom, r1.Width, r1.Bottom - exclude.Bottom) };
}
return new Rectangle[] { };
}
internal static Size MaxSize(Size size1, Size size2)
{
if (size2.Width > size1.Width) size1.Width = size2.Width;
if (size2.Height > size1.Height) size1.Height = size2.Height;
return size1;
}
internal static void ExcludeEdgeRect(ref Rectangle captionRect, Rectangle exclude)
{
if (exclude.X + exclude.Width / 2 < captionRect.X + captionRect.Width / 2)
{
// Left aligned
int r = exclude.Right - captionRect.X;
captionRect.X = exclude.Right;
captionRect.Width -= r;
}
else
{
// Right aligned
captionRect.Width -= (captionRect.Right - exclude.X);
}
}
}
}

View File

@@ -0,0 +1,223 @@
using System;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Windows.Forms;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
using DevComponents.UI.ContentManager;
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Div : ContainerElement
{
#region Private Variables
private eParagraphAlignment m_Align = eParagraphAlignment.Left;
private eParagraphVerticalAlignment m_VAlign = eParagraphVerticalAlignment.Top;
private int m_Width = 0;
private int m_Height = 0;
private Padding m_Padding = new Padding(0, 0, 0, 0);
private Color m_BackColor = Color.Empty;
#endregion
#region Internal Implementation
public override void Render(MarkupDrawContext d)
{
Rectangle r = this.Bounds;
r.Offset(d.Offset);
if (!m_BackColor.IsEmpty)
{
DisplayHelp.FillRectangle(d.Graphics, r, m_BackColor);
}
base.Render(d);
}
public eParagraphAlignment Align
{
get { return m_Align; }
set { m_Align = value; }
}
protected override SerialContentLayoutManager GetLayoutManager(bool multiLine)
{
SerialContentLayoutManager sm = base.GetLayoutManager(multiLine);
if (m_Align == eParagraphAlignment.Left)
sm.ContentAlignment = eContentAlignment.Left;
else if (m_Align == eParagraphAlignment.Right)
sm.ContentAlignment = eContentAlignment.Right;
else if (m_Align == eParagraphAlignment.Center)
sm.ContentAlignment = eContentAlignment.Center;
if (m_VAlign != eParagraphVerticalAlignment.Top)
{
sm.EvenHeight = false;
sm.BlockLineAlignment = (m_VAlign == eParagraphVerticalAlignment.Bottom ? eContentVerticalAlignment.Bottom : eContentVerticalAlignment.Middle);
}
return sm;
}
protected override Point GetContainerOffset()
{
if (m_Padding.Left == 0 && m_Padding.Top == 0)
return base.GetContainerOffset();
Point p = base.GetContainerOffset();
p.X += m_Padding.Left;
p.Y += m_Padding.Top;
return p;
}
protected override void ArrangeInternal(Rectangle bounds, MarkupDrawContext d)
{
Rectangle r = bounds;
if (m_Width > 0)
r.Width = m_Width;
if (m_Height > 0)
r.Height = m_Height;
if (m_Padding.All == 0)
{
base.ArrangeInternal(r, d);
if (m_Width > 0)
this.Bounds = new Rectangle(this.Bounds.X, this.Bounds.Y, m_Width, m_Height > 0 ? m_Height : this.Bounds.Height + m_Padding.Bottom);
else if(m_Height>0)
this.Bounds = new Rectangle(this.Bounds.X, this.Bounds.Y, this.Bounds.Width, m_Height);
}
else
{
r.X += m_Padding.Left;
r.Y += m_Padding.Top;
r.Width -= m_Padding.Horizontal;
r.Height -= m_Padding.Vertical;
base.ArrangeInternal(r, d);
r = new Rectangle(bounds.X, bounds.Y, this.Bounds.Width + m_Padding.Horizontal, this.Bounds.Height + m_Padding.Vertical);
if (m_Width > 0)
r.Width = m_Width;
if (m_Height > 0)
r.Height = m_Height;
this.Bounds = r;
}
}
public override void ReadAttributes(XmlTextReader reader)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "align")
{
string s = reader.Value.ToLower();
if (s == "left")
m_Align = eParagraphAlignment.Left;
else if (s == "right")
m_Align = eParagraphAlignment.Right;
else if (s == "center")
m_Align = eParagraphAlignment.Center;
}
else if (reader.Name.ToLower() == "valign")
{
string s = reader.Value.ToLower();
if (s == "top")
m_VAlign = eParagraphVerticalAlignment.Top;
else if (s == "middle")
m_VAlign = eParagraphVerticalAlignment.Middle;
else if (s == "bottom")
m_VAlign = eParagraphVerticalAlignment.Bottom;
}
else if (reader.Name.ToLower() == "width")
{
try
{
m_Width = Int32.Parse(reader.Value);
}
catch
{
m_Width = 0;
}
}
else if (reader.Name.ToLower() == "height")
{
try
{
m_Height = Int32.Parse(reader.Value);
}
catch
{
m_Height = 0;
}
}
else if (reader.Name.ToLower() == "padding")
{
try
{
string[] values = reader.Value.Split(',');
if (values.Length > 0)
m_Padding.Left = Int32.Parse(values[0]);
if (values.Length > 1)
m_Padding.Right = Int32.Parse(values[1]);
if (values.Length > 2)
m_Padding.Top = Int32.Parse(values[2]);
if (values.Length > 3)
m_Padding.Bottom = Int32.Parse(values[3]);
}
catch
{
m_Padding = new Padding(0,0,0,0);
}
}
else if (reader.Name.ToLower() == "bgcolor")
{
try
{
string s = reader.Value;
if (s.StartsWith("#"))
{
if (s.Length == 7)
m_BackColor = ColorHelpers.GetColor(s.Substring(1));
}
else
{
m_BackColor = Color.FromName(s);
}
}
catch
{
m_BackColor = Color.Empty;
}
}
}
}
#endregion
}
#region eParagraphAlignment
/// <summary>
/// Indicates paragraph content alignment
/// </summary>
internal enum eParagraphAlignment
{
Left,
Right,
Center
}
/// <summary>
/// Indicates paragraph content alignment
/// </summary>
internal enum eParagraphVerticalAlignment
{
Top,
Middle,
Bottom
}
#endregion
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class EndMarkupElement : MarkupElement
{
#region Internap Implementation
private MarkupElement m_StartElement = null;
public EndMarkupElement(MarkupElement startElement)
{
m_StartElement = startElement;
}
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
m_StartElement.MeasureEnd(availableSize, d);
this.Bounds = Rectangle.Empty;
}
public override void Render(MarkupDrawContext d)
{
m_StartElement.RenderEnd(d);
}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d)
{
this.Bounds = Rectangle.Empty;
}
/// <summary>
/// Gets reference to markup start element.
/// </summary>
public MarkupElement StartElement
{
get { return m_StartElement; }
}
#endregion
}
}

View File

@@ -0,0 +1,201 @@
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class ExpandElement : MarkupElement
{
#region Internal Implementation
private Size m_DefaultSize = new Size(5, 4);
private eExpandDirection m_Direction = eExpandDirection.Default;
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
this.Bounds = new Rectangle(Point.Empty, m_DefaultSize);
}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d) { }
public override void Render(MarkupDrawContext d)
{
Rectangle r = this.Bounds;
r.Offset(d.Offset);
if (!d.ClipRectangle.IsEmpty && !r.IntersectsWith(d.ClipRectangle))
return;
Graphics g = d.Graphics;
Color color = d.CurrentForeColor;
//Color shadeColor = Color.FromArgb(96, Color.White);
eExpandDirection direction = eExpandDirection.Bottom;
if (m_Direction != eExpandDirection.Default)
direction = m_Direction;
#if DOTNETBAR
if(d.ContextObject is ButtonItem)
{
if (m_Direction == eExpandDirection.Default)
{
ButtonItem item = d.ContextObject as ButtonItem;
if (item.IsOnMenu)
{
direction = eExpandDirection.Right;
if (item.PopupSide == ePopupSide.Default && d.RightToLeft || item.PopupSide == ePopupSide.Left)
direction = eExpandDirection.Left;
}
else if (item.PopupSide == ePopupSide.Default)
direction = eExpandDirection.Bottom;
else if (item.PopupSide == ePopupSide.Left)
direction = eExpandDirection.Left;
else if (item.PopupSide == ePopupSide.Right)
direction = eExpandDirection.Right;
else if (item.PopupSide == ePopupSide.Bottom)
direction = eExpandDirection.Bottom;
else if (item.PopupSide == ePopupSide.Top)
direction = eExpandDirection.Top;
}
}
#endif
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.None;
Rectangle shadeRect = r;
if (direction == eExpandDirection.Bottom || direction == eExpandDirection.PopupDropDown)
shadeRect.Offset(0, 1);
else if (direction == eExpandDirection.Top)
shadeRect.Offset(0, -1);
else if (direction == eExpandDirection.Left)
shadeRect.Offset(1, 0);
else if (direction == eExpandDirection.Right)
shadeRect.Offset(-1, 0);
Point[] p = GetExpandPolygon(shadeRect, direction);
//using (SolidBrush brush = new SolidBrush(shadeColor))
// g.FillPolygon(brush, p);
p = GetExpandPolygon(r, direction);
using(SolidBrush brush = new SolidBrush(color))
g.FillPolygon(brush, p);
if (direction == eExpandDirection.PopupDropDown)
{
using (Pen pen = new Pen(color, 1))
g.DrawLine(pen, r.X, r.Y - 2, r.Right - 1, r.Y - 2);
//using (Pen pen = new Pen(shadeColor, 1))
// g.DrawLine(pen, r.X, r.Y - 1, r.Right - 1, r.Y - 1);
}
g.SmoothingMode = sm;
this.RenderBounds = r;
}
private Point[] GetExpandPolygon(Rectangle r, eExpandDirection direction)
{
Point[] p = new Point[3];
switch (direction)
{
case eExpandDirection.Right:
{
p[0].X = r.Left + 1;
p[0].Y = r.Top + (r.Height - m_DefaultSize.Height) / 2 - 1;
p[1].X = p[0].X;
p[1].Y = p[0].Y + 6;
p[2].X = p[0].X + 3;
p[2].Y = p[0].Y + 3;
break;
}
case eExpandDirection.Left:
{
p[0].X = r.Left + 3;
p[0].Y = r.Top + (r.Height - m_DefaultSize.Height) / 2 - 1;
p[1].X = p[0].X;
p[1].Y = p[0].Y + 6;
p[2].X = p[0].X - 3;
p[2].Y = p[0].Y + 3;
break;
}
case eExpandDirection.Top:
{
p[0].X = r.Left - 1;
p[0].Y = r.Top + (r.Height - m_DefaultSize.Height) / 2 + m_DefaultSize.Height;
p[1].X = p[0].X + 6;
p[1].Y = p[0].Y;
p[2].X = p[0].X + 3;
p[2].Y = p[0].Y - 4;
break;
}
case eExpandDirection.Bottom:
case eExpandDirection.PopupDropDown:
{
p[0].X = r.Left;
p[0].Y = r.Top + (r.Height - m_DefaultSize.Height) / 2 + 1;
p[1].X = p[0].X + 5;
p[1].Y = p[0].Y;
p[2].X = p[0].X + 2;
p[2].Y = p[0].Y + 3;
break;
}
}
return p;
}
public override void ReadAttributes(XmlTextReader reader)
{
m_Direction = eExpandDirection.Default;
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "direction")
{
string s = reader.Value.ToLower();
if (s == "left")
m_Direction = eExpandDirection.Left;
else if (s == "right")
m_Direction = eExpandDirection.Right;
else if (s == "top")
m_Direction = eExpandDirection.Top;
else if (s == "bottom")
m_Direction = eExpandDirection.Bottom;
else if (s == "popup")
m_Direction = eExpandDirection.PopupDropDown;
break;
}
}
}
private enum eExpandDirection
{
Left,
Right,
Top,
Bottom,
Default,
PopupDropDown
}
/// <summary>
/// Returns whether layout manager can start new line with this element.
/// </summary>
public override bool CanStartNewLine
{
get { return false; }
}
#endregion
}
}

View File

@@ -0,0 +1,57 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class FontChangeElement : MarkupElement
{
#region Private Variables
protected Font m_OldFont = null;
#endregion
#region Internal Implementation
public override void Measure(Size availableSize, MarkupDrawContext d)
{
this.Bounds = Rectangle.Empty;
SetFont(d);
}
public override void Render(MarkupDrawContext d)
{
SetFont(d);
}
protected virtual void SetFont(MarkupDrawContext d)
{
}
public override void RenderEnd(MarkupDrawContext d)
{
if(m_OldFont!=null)
d.CurrentFont = m_OldFont;
m_OldFont = null;
base.RenderEnd(d);
}
public override void MeasureEnd(Size availableSize, MarkupDrawContext d)
{
if (m_OldFont != null)
d.CurrentFont = m_OldFont;
m_OldFont = null;
base.MeasureEnd(availableSize, d);
}
protected override void ArrangeCore(Rectangle finalRect, MarkupDrawContext d) { }
#endregion
}
}

View File

@@ -0,0 +1,187 @@
using System;
using System.Text;
using System.Drawing;
using System.Xml;
#if AdvTree
using DevComponents.Tree;
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class FontElement : FontChangeElement
{
#region Private Variables
private Color m_ForeColor = Color.Empty;
private Color m_OldForeColor = Color.Empty;
private int m_Size = 0;
private bool m_RelativeSize = false;
private string m_Face = "";
private string m_SystemColorName = "";
#endregion
#region Internal Implementation
protected override void SetFont(MarkupDrawContext d)
{
Font font = d.CurrentFont;
try
{
if (m_Face != "" || m_Size != 0 && m_RelativeSize || m_Size>4 && !m_RelativeSize)
{
if (m_Face != "")
d.CurrentFont = new Font(m_Face, ((m_RelativeSize || m_Size == 0)?font.SizeInPoints + m_Size:m_Size), font.Style);
else
d.CurrentFont = new Font(font.FontFamily, ((m_RelativeSize || m_Size == 0)? font.SizeInPoints + m_Size : m_Size), font.Style);
}
else
font = null;
}
catch
{
font = null;
}
if (font != null)
m_OldFont = font;
if (!d.IgnoreFormattingColors)
{
if (!m_ForeColor.IsEmpty)
{
m_OldForeColor = d.CurrentForeColor;
d.CurrentForeColor = m_ForeColor;
}
else if (m_SystemColorName != "")
{
#if DOTNETBAR
if (Rendering.GlobalManager.Renderer is Rendering.Office2007Renderer)
{
m_OldForeColor = d.CurrentForeColor;
d.CurrentForeColor = ((Rendering.Office2007Renderer)Rendering.GlobalManager.Renderer).ColorTable.Form.Active.CaptionTextExtra;
}
#endif
}
}
}
public override void RenderEnd(MarkupDrawContext d)
{
RestoreForeColor(d);
base.RenderEnd(d);
}
public override void MeasureEnd(Size availableSize, MarkupDrawContext d)
{
RestoreForeColor(d);
base.MeasureEnd(availableSize, d);
}
protected virtual void RestoreForeColor(MarkupDrawContext d)
{
if (d == null) return;
if (!m_OldForeColor.IsEmpty)
d.CurrentForeColor = m_OldForeColor;
m_OldForeColor = Color.Empty;
}
public Color ForeColor
{
get { return m_ForeColor; }
set { m_ForeColor = value; }
}
public int Size
{
get { return m_Size; }
set { m_Size = value; }
}
public string Face
{
get { return m_Face; }
set { m_Face = value; }
}
private Color GetColorFromName(string name)
{
string s = name.ToLower();
m_SystemColorName = "";
if (s == "syscaptiontextextra")
{
m_SystemColorName = s;
return Color.Empty;
}
return Color.FromName(name);
}
public override void ReadAttributes(XmlTextReader reader)
{
m_RelativeSize = false;
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "color")
{
try
{
string s = reader.Value;
if (s.StartsWith("#"))
{
if (s.Length == 7)
m_ForeColor = ColorHelpers.GetColor(s.Substring(1));
}
else
{
m_ForeColor = GetColorFromName(s);
}
}
catch
{
m_ForeColor = Color.Empty;
}
}
else if (reader.Name.ToLower() == "size")
{
string s = reader.Value;
if (s.StartsWith("+"))
{
try
{
m_Size = Int32.Parse(s.Substring(1));
m_RelativeSize = true;
}
catch
{
m_Size = 0;
}
}
else
{
if (s.StartsWith("-"))
m_RelativeSize = true;
try
{
m_Size = Int32.Parse(s);
}
catch
{
m_Size = 0;
}
}
}
else if (reader.Name.ToLower() == "face")
{
m_Face = reader.Value;
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,97 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Heading: ContainerElement
{
#region Private Variables
private int m_Level = 1;
private Font m_OldFont = null;
#endregion
#region Internal Implementation
public Heading() { }
public Heading(int level)
{
m_Level = level;
}
public override void Measure(Size availableSize, MarkupDrawContext d)
{
SetFont(d);
base.Measure(availableSize, d);
if (m_OldFont != null)
d.CurrentFont = m_OldFont;
}
public override void Render(MarkupDrawContext d)
{
SetFont(d);
base.Render(d);
if (m_OldFont != null)
d.CurrentFont = m_OldFont;
}
protected virtual void SetFont(MarkupDrawContext d)
{
Font font = d.CurrentFont;
try
{
float size = d.CurrentFont.SizeInPoints;
if (m_Level == 1)
{
size += 12;
}
else if (m_Level == 2)
{
size += 8;
}
else if (m_Level == 3)
{
size += 6;
}
else if (m_Level == 4)
{
size += 4;
}
else if (m_Level == 5)
{
size += 2;
}
else if (m_Level == 6)
{
size += 1;
}
d.CurrentFont = new Font(d.CurrentFont.FontFamily, size, FontStyle.Bold);
}
catch
{
font = null;
}
if (font != null)
m_OldFont = font;
}
/// <summary>
/// Gets or sets heading level. Values from 1 to 6 are valid. Default is 1.
/// </summary>
public int Level
{
get { return m_Level; }
set { m_Level = value; }
}
#endregion
}
}

View File

@@ -0,0 +1,249 @@
using System;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class HyperLink : MarkupElement, IActiveMarkupElement
{
#region Private Variables
private Color m_ForeColor = Color.Empty;
private Color m_OldForeColor = Color.Empty;
private string m_HRef = "";
private string m_Name = "";
private Cursor m_OldCursor = null;
private bool m_IsMouseOver = false;
private bool m_Visited = false;
#endregion
#region Internal Implementation
public override void Measure(Size availableSize, MarkupDrawContext d)
{
this.Bounds = Rectangle.Empty;
SetForeColor(d);
}
public override void Render(MarkupDrawContext d)
{
d.HyperLink = true;
d.HyperlinkStyle = GetHyperlinkStyle();
if (!d.HyperlinkStyle.BackColor.IsEmpty)
{
using (GraphicsPath gp = new GraphicsPath())
{
MarkupElementCollection col = this.Parent.Elements;
int start = col.IndexOf(this) + 1;
for (int i = start; i < col.Count; i++)
{
MarkupElement elem = col[i];
if (!elem.Visible) continue;
if (elem is EndMarkupElement && ((EndMarkupElement)elem).StartElement == this)
break;
gp.AddRectangle(elem.RenderBounds);
}
using (SolidBrush brush = new SolidBrush(d.HyperlinkStyle.BackColor))
d.Graphics.FillPath(brush, gp);
}
}
SetForeColor(d);
}
private HyperlinkStyle GetHyperlinkStyle()
{
if (m_IsMouseOver && MarkupSettings.MouseOverHyperlink.IsChanged)
return MarkupSettings.MouseOverHyperlink;
else if (m_Visited && MarkupSettings.VisitedHyperlink.IsChanged)
return MarkupSettings.VisitedHyperlink;
return MarkupSettings.NormalHyperlink;
}
protected virtual void SetForeColor(MarkupDrawContext d)
{
Color c = Color.Empty;
HyperlinkStyle style = GetHyperlinkStyle();
if (style != null && !style.TextColor.IsEmpty)
c = style.TextColor;
if (!m_ForeColor.IsEmpty)
c = m_ForeColor;
if (!c.IsEmpty)
{
m_OldForeColor = d.CurrentForeColor;
d.CurrentForeColor = c;
}
}
public override void RenderEnd(MarkupDrawContext d)
{
RestoreForeColor(d);
d.HyperLink = false;
d.HyperlinkStyle = null;
base.RenderEnd(d);
}
public override void MeasureEnd(Size availableSize, MarkupDrawContext d)
{
RestoreForeColor(d);
base.MeasureEnd(availableSize, d);
}
protected override void ArrangeCore(Rectangle finalRect, MarkupDrawContext d) { }
protected virtual void RestoreForeColor(MarkupDrawContext d)
{
if (d == null) return;
if (!m_OldForeColor.IsEmpty)
d.CurrentForeColor = m_OldForeColor;
m_OldForeColor = Color.Empty;
}
public Color ForeColor
{
get { return m_ForeColor; }
set { m_ForeColor = value; }
}
public string HRef
{
get { return m_HRef; }
set { m_HRef = value; }
}
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
public override void ReadAttributes(XmlTextReader reader)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "href")
{
m_HRef = reader.Value;
}
else if (reader.Name.ToLower() == "name")
{
m_Name = reader.Value;
}
else if (reader.Name.ToLower() == "color")
{
try
{
string s = reader.Value;
if (s.StartsWith("#"))
{
if (s.Length == 7)
m_ForeColor = ColorHelpers.GetColor(s.Substring(1));
}
else
{
m_ForeColor = GetColorFromName(s);
}
}
catch
{
m_ForeColor = Color.Empty;
}
}
}
}
private Color GetColorFromName(string name)
{
return Color.FromName(name);
}
/// <summary>
/// Returns whether hyper-link contains specified coordinates.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public bool HitTest(int x, int y)
{
if (this.Parent == null)
return false;
MarkupElementCollection col = this.Parent.Elements;
int start = col.IndexOf(this)+1;
for (int i = start; i < col.Count; i++)
{
MarkupElement el = col[i];
if (el is EndMarkupElement && ((EndMarkupElement)el).StartElement == this)
break;
if (col[i].RenderBounds.Contains(x, y))
return true;
}
return false;
}
public void MouseEnter(Control parent)
{
m_OldCursor = parent.Cursor;
parent.Cursor = Cursors.Hand;
m_IsMouseOver = true;
if (MarkupSettings.MouseOverHyperlink.IsChanged)
{
InvalidateElements(parent);
}
}
public void MouseLeave(Control parent)
{
if (m_OldCursor != null && parent!=null)
parent.Cursor = m_OldCursor;
m_OldCursor = null;
m_IsMouseOver = false;
if (MarkupSettings.MouseOverHyperlink.IsChanged)
{
InvalidateElements(parent);
}
}
public void MouseDown(Control parent, MouseEventArgs e) { }
public void MouseUp(Control parent, MouseEventArgs e) { }
public void Click(Control parent)
{
m_Visited = true;
if (MarkupSettings.VisitedHyperlink.IsChanged)
{
InvalidateElements(parent);
}
}
private void InvalidateElements(Control parent)
{
if (this.Parent == null) return;
MarkupElementCollection col = this.Parent.Elements;
int start = col.IndexOf(this) + 1;
for (int i = start; i < col.Count; i++)
{
MarkupElement elem = col[i];
if (!elem.Visible) continue;
if (elem is EndMarkupElement && ((EndMarkupElement)elem).StartElement == this)
break;
parent.Invalidate(elem.RenderBounds);
}
}
#endregion
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Text;
using System.Windows.Forms;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal interface IActiveMarkupElement
{
bool HitTest(int x, int y);
void MouseEnter(Control parent);
void MouseLeave(Control parent);
void MouseDown(Control parent, MouseEventArgs e);
void MouseUp(Control parent, MouseEventArgs e);
void Click(Control parent);
}
}

View File

@@ -0,0 +1,202 @@
using System;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Reflection;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class ImageElement : MarkupElement
{
#region Private Variables
private Size m_ImageSize = Size.Empty;
private string m_ImageSource = "";
private Image m_Image = null;
#endregion
#region Internal Implementation
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
if (!m_ImageSize.IsEmpty)
this.Bounds = new Rectangle(Point.Empty, m_ImageSize);
else if (m_ImageSource.Length == 0)
this.Bounds = Rectangle.Empty;
else
{
Image img = this.GetImage();
if (img != null)
this.Bounds = new Rectangle(Point.Empty, img.Size);
else
this.Bounds = new Rectangle(Point.Empty, new Size(16,16));
}
}
public override bool IsBlockElement
{
get
{
return false;
}
}
private Image GetImage()
{
if (m_Image != null) return m_Image;
Assembly a = null;
// Try static custom image resolver
ResolveImageEventArgs e = new ResolveImageEventArgs();
e.Key = m_ImageSource;
e.ResolvedImage = null;
MarkupSettings.InvokeResolveImage(e);
if (e.Handled)
return e.ResolvedImage;
// Load from format: ClassLibrary1/ClassLibrary1.MyImage.png or ClassLibrary1/global::ClassLibrary1.Resources.MyImage
if (m_ImageSource.IndexOf('/') >= 0)
{
string[] parts = m_ImageSource.Split('/');
a = Assembly.Load(parts[0]);
string ResourceName = parts[1];
if (a != null)
{
m_Image = LoadImageGlobalResource(parts[1], a);
if (m_Image == null)
m_Image = LoadImageResource(parts[1], a);
if (m_Image != null) return m_Image;
}
}
// Probe Executing Assembly
a = Assembly.GetExecutingAssembly();
m_Image = LoadImageGlobalResource(m_ImageSource, a);
if(m_Image==null)
m_Image = LoadImageResource(m_ImageSource, a);
// Probe Entry Assembly
if (m_Image == null)
{
a = Assembly.GetEntryAssembly();
m_Image = LoadImageGlobalResource(m_ImageSource, a);
if (m_Image == null)
m_Image = LoadImageResource(m_ImageSource, a);
}
return m_Image;
}
private Image LoadImageGlobalResource(string imageSource, Assembly a)
{
Image img = null;
#if FRAMEWORK20
if (imageSource.StartsWith("global::"))
{
string name = imageSource.Substring(8);
if (name.Length > 0)
{
try
{
int i = name.LastIndexOf('.');
string resName = name.Substring(0, i);
name = name.Substring(i + 1);
System.Resources.ResourceManager r = new System.Resources.ResourceManager(resName, a);
object obj = r.GetObject(name);
img = (Bitmap)obj;
}
catch
{
img = null;
}
}
}
#endif
return img;
}
private Image LoadImageResource(string imageSource, Assembly a)
{
Image img = null;
try
{
img = new Bitmap(a.GetManifestResourceStream(imageSource));
}
catch { }
return img;
}
public override void Render(MarkupDrawContext d)
{
Rectangle r = this.Bounds;
r.Offset(d.Offset);
if (!d.ClipRectangle.IsEmpty && !r.IntersectsWith(d.ClipRectangle))
return;
Image img = this.GetImage();
if (img != null)
{
Rectangle imageRect = r;
if (m_ImageSize.IsEmpty)
imageRect.Size = img.Size;
else
imageRect.Size = m_ImageSize;
d.Graphics.DrawImage(img, imageRect);
}
else
{
using (SolidBrush brush = new SolidBrush(Color.White))
{
d.Graphics.FillRectangle(brush, r);
}
using (Pen pen = new Pen(Color.DarkGray, 1))
{
d.Graphics.DrawRectangle(pen, r);
d.Graphics.DrawLine(pen, r.X, r.Y, r.Right, r.Bottom);
d.Graphics.DrawLine(pen, r.Right, r.Y, r.X, r.Bottom);
}
}
this.RenderBounds = r;
}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d) { }
public override void ReadAttributes(XmlTextReader reader)
{
m_ImageSize = Size.Empty;
m_ImageSource = "";
m_Image = null;
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "width")
{
string s = reader.Value;
m_ImageSize.Width = int.Parse(s);
}
else if (reader.Name.ToLower() == "height")
{
string s = reader.Value;
m_ImageSize.Height = int.Parse(s);
}
else if (reader.Name.ToLower() == "src")
{
m_ImageSource = reader.Value;
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Italic : FontChangeElement
{
#region Internal Implementation
protected override void SetFont(MarkupDrawContext d)
{
Font font = d.CurrentFont;
FontStyle style=font.Style | FontStyle.Italic;
if (!font.Italic && d.CurrentFont.FontFamily.IsStyleAvailable(style))
d.CurrentFont = new Font(font, style);
else
font = null;
if (font != null)
m_OldFont = font;
base.SetFont(d);
}
#endregion
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Drawing;
using System.Text;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
public class MarkupDrawContext
{
public Graphics Graphics = null;
public Font CurrentFont = null;
public Color CurrentForeColor = SystemColors.ControlText;
public bool RightToLeft = false;
public Point Offset = Point.Empty;
public bool HyperLink = false;
public HyperlinkStyle HyperlinkStyle = null;
public bool Underline = false;
public Rectangle ClipRectangle = Rectangle.Empty;
public bool HotKeyPrefixVisible = false;
public object ContextObject = null;
public bool AllowMultiLine = true;
public bool IgnoreFormattingColors = false;
public bool StrikeOut;
public MarkupDrawContext(Graphics g, Font currentFont, Color currentForeColor, bool rightToLeft) : this(g, currentFont, currentForeColor, rightToLeft, Rectangle.Empty, false)
{
}
public MarkupDrawContext(Graphics g, Font currentFont, Color currentForeColor, bool rightToLeft, Rectangle clipRectangle, bool hotKeyPrefixVisible)
{
this.Graphics = g;
this.CurrentFont = currentFont;
this.CurrentForeColor = currentForeColor;
this.RightToLeft = rightToLeft;
this.ClipRectangle = clipRectangle;
this.HotKeyPrefixVisible = hotKeyPrefixVisible;
}
public MarkupDrawContext(Graphics g, Font currentFont, Color currentForeColor, bool rightToLeft, Rectangle clipRectangle, bool hotKeyPrefixVisible, object contextObject)
{
this.Graphics = g;
this.CurrentFont = currentFont;
this.CurrentForeColor = currentForeColor;
this.RightToLeft = rightToLeft;
this.ClipRectangle = clipRectangle;
this.HotKeyPrefixVisible = hotKeyPrefixVisible;
this.ContextObject = contextObject;
}
}
}

View File

@@ -0,0 +1,198 @@
using System;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Windows.Forms;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
using DevComponents.UI.ContentManager;
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal abstract class MarkupElement : IBlockExtended
{
#region Private Variables
private MarkupElementCollection m_Elements = null;
private MarkupElement m_Parent = null;
private Rectangle m_Bounds = Rectangle.Empty;
private bool m_Visible = true;
private bool m_SizeValid = false;
private Rectangle m_RenderBounds = Rectangle.Empty;
#endregion
#region Internal Implementation
public MarkupElement()
{
m_Elements = new MarkupElementCollection(this);
}
/// <summary>
/// Returns whether markup element is an container so it receives full available size of parent control for layout.
/// </summary>
public virtual bool IsBlockContainer
{
get { return false; }
}
/// <summary>
/// Returns whether markup element is an block element that always consumes a whole line in layout.
/// </summary>
public virtual bool IsBlockElement
{
get { return false; }
}
/// <summary>
/// Returns whether layout manager switches to new line after processing this element.
/// </summary>
public virtual bool IsNewLineAfterElement
{
get { return false; }
}
/// <summary>
/// Returns whether layout manager can start new line with this element.
/// </summary>
public virtual bool CanStartNewLine
{
get { return true; }
}
/// <summary>
/// Gets the collection of child elements if any for this markup element.
/// </summary>
public virtual MarkupElementCollection Elements
{
get
{
if (m_Elements == null)
m_Elements = new MarkupElementCollection(this);
return m_Elements;
}
}
internal void InvalidateElementsSize()
{
this.IsSizeValid = false;
if (m_Elements==null || m_Elements.Count == 0)
return;
foreach (MarkupElement e in m_Elements)
{
e.InvalidateElementsSize();
e.IsSizeValid = false;
}
}
/// <summary>
/// Gets or sets whether element size is valid. When size is not valid element Measure method will be called to validate size.
/// </summary>
public virtual bool IsSizeValid
{
get { return m_SizeValid; }
set { m_SizeValid = value; }
}
/// <summary>
/// Gets element parent or null if parent is not set.
/// </summary>
public virtual MarkupElement Parent
{
get { return m_Parent; }
}
internal void SetParent(MarkupElement parent)
{
m_Parent = parent;
}
/// <summary>
/// Gets or sets actual rendering bounds.
/// </summary>
public Rectangle Bounds
{
get { return m_Bounds; }
set { m_Bounds = value; }
}
/// <summary>
/// Gets or sets whether markup element is visible.
/// </summary>
public bool Visible
{
get { return m_Visible; }
set { m_Visible = value; }
}
private Padding _Margin = new Padding(0);
/// <summary>
/// Gets or sets the element margin.
/// </summary>
public Padding Margin
{
get { return _Margin; }
set { _Margin = value; }
}
/// <summary>
/// Measures the element given available size.
/// </summary>
/// <param name="availableSize">Size available to element</param>
/// <param name="g">Reference to graphics object</param>
public abstract void Measure(Size availableSize, MarkupDrawContext d);
/// <summary>
/// Measures the end tag of an element. Most implementations do not need to do anything but implementations like the ones
/// that change color should return state back at this time.
/// </summary>
/// <param name="availableSize"></param>
/// <param name="d"></param>
public virtual void MeasureEnd(Size availableSize, MarkupDrawContext d) { }
/// <summary>
/// Renders element.
/// </summary>
/// <param name="d">Provides markup drawing context information.</param>
public abstract void Render(MarkupDrawContext d);
/// <summary>
/// Renders element tag end. Most implementations do not need to do anything but mplementations like the ones
/// that change color should return state back at this time.
/// </summary>
/// <param name="d">Provides markup drawing context information.</param>
public virtual void RenderEnd(MarkupDrawContext d) { }
/// <summary>
/// Provides final rectangle to element and lets it arrange it's content given new constraint.
/// </summary>
/// <param name="finalRect">Final rectangle.</param>
/// <param name="g"></param>
protected abstract void ArrangeCore(Rectangle finalRect, MarkupDrawContext d);
/// <summary>
/// Arranges the element given the final size. Layout is two step process with Measure followed by Arrange.
/// </summary>
/// <param name="finalSize"></param>
/// <param name="g"></param>
public void Arrange(Rectangle finalSize, MarkupDrawContext d)
{
this.ArrangeCore(finalSize, d);
}
public virtual void ReadAttributes(XmlTextReader reader) { }
/// <summary>
/// Gets or sets actual rendered bounds for a give markup element if applicable.
/// </summary>
public Rectangle RenderBounds
{
get { return m_RenderBounds; }
set { m_RenderBounds = value; }
}
#endregion
}
}

View File

@@ -0,0 +1,141 @@
using System;
using System.Text;
using System.Collections;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class MarkupElementCollection : CollectionBase
{
#region Private Variables
private MarkupElement m_Parent = null;
#endregion
#region Internal Implementation
/// <summary>Creates new instance of the class.</summary>
public MarkupElementCollection(MarkupElement parent)
{
m_Parent = parent;
}
/// <summary>
/// Gets or sets the collection parent element.
/// </summary>
public MarkupElement Parent
{
get { return m_Parent; }
set { m_Parent = value; }
}
/// <summary>
/// Adds new object to the collection.
/// </summary>
/// <param name="MarkupElement">Object to add.</param>
/// <returns>Index of newly added object.</returns>
public int Add(MarkupElement MarkupElement)
{
return List.Add(MarkupElement);
}
/// <summary>
/// Returns reference to the object in collection based on it's index.
/// </summary>
public MarkupElement this[int index]
{
get {return (MarkupElement)(List[index]);}
set {List[index] = value;}
}
/// <summary>
/// Inserts new object into the collection.
/// </summary>
/// <param name="index">Position of the object.</param>
/// <param name="value">Object to insert.</param>
public void Insert(int index, MarkupElement value)
{
List.Insert(index, value);
}
/// <summary>
/// Returns index of the object inside of the collection.
/// </summary>
/// <param name="value">Reference to the object.</param>
/// <returns>Index of the object.</returns>
public int IndexOf(MarkupElement value)
{
return List.IndexOf(value);
}
/// <summary>
/// Returns whether collection contains specified object.
/// </summary>
/// <param name="value">Object to look for.</param>
/// <returns>true if object is part of the collection, otherwise false.</returns>
public bool Contains(MarkupElement value)
{
return List.Contains(value);
}
/// <summary>
/// Removes specified object from the collection.
/// </summary>
/// <param name="value"></param>
public void Remove(MarkupElement value)
{
List.Remove(value);
}
protected override void OnRemoveComplete(int index,object value)
{
base.OnRemoveComplete(index,value);
MarkupElement me=value as MarkupElement;
if (m_Parent != null)
{
me.SetParent(null);
m_Parent.IsSizeValid = false;
}
}
protected override void OnInsertComplete(int index,object value)
{
base.OnInsertComplete(index,value);
MarkupElement me=value as MarkupElement;
if (m_Parent != null)
{
me.SetParent(m_Parent);
m_Parent.IsSizeValid = false;
}
}
/// <summary>
/// Copies collection into the specified array.
/// </summary>
/// <param name="array">Array to copy collection to.</param>
/// <param name="index">Starting index.</param>
public void CopyTo(MarkupElement[] array, int index)
{
List.CopyTo(array, index);
}
/// <summary>
/// Copies contained items to the MarkupElement array.
/// </summary>
/// <param name="array">Array to copy to.</param>
internal void CopyTo(MarkupElement[] array)
{
List.CopyTo(array,0);
}
protected override void OnClear()
{
base.OnClear();
}
#endregion
}
}

View File

@@ -0,0 +1,41 @@
using System.Collections;
using System.Drawing;
using System.Text;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
using DevComponents.UI.ContentManager;
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class MarkupLayoutManager : BlockLayoutManager
{
private MarkupDrawContext m_MarkupDrawContext = null;
public MarkupDrawContext MarkupDrawContext
{
get { return m_MarkupDrawContext; }
set { m_MarkupDrawContext = value; }
}
public override void Layout(IBlock block, Size availableSize)
{
if (block is MarkupElement)
{
MarkupElement m = block as MarkupElement;
if(!m.IsSizeValid)
m.Measure(availableSize, m_MarkupDrawContext);
}
}
public override Rectangle FinalizeLayout(Rectangle containerBounds, Rectangle blocksBounds, ArrayList lines)
{
return (blocksBounds);
}
}
}

View File

@@ -0,0 +1,256 @@
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class MarkupParser
{
#region Private Variables
private static string TextElementName = "text";
private static string BodyTag = "body";
#endregion
#region Internal Implementation
public static BodyElement Parse(string text)
{
StringBuilder plainText = new StringBuilder(text.Length);
BodyElement root = new BodyElement();
root.HasExpandElement = false;
MarkupElement currentParent = root;
Stack openTags = new Stack();
openTags.Push(root);
// Input text is not wrapped into the container tag so we wrap it here
text = text.Replace("&nbsp;", "{ent_nbsp}");
text = text.Replace("&zwsp;", "{ent_zwsp}");
text = text.Replace("&lt;", "{ent_lt}");
text = text.Replace("&gt;", "{ent_gt}");
text = text.Replace("&amp;", "{ent_amp}");
text = text.Replace("|", "{ent_l}");
text = text.Replace("&", "|");
text = text.Replace("{ent_nbsp}", "&nbsp;");
text = text.Replace("{ent_zwsp}", "&zwsp;");
text = text.Replace("{ent_lt}", "&lt;");
text = text.Replace("{ent_gt}", "&gt;");
StringReader sr = new StringReader("<"+BodyTag+">" + text + "</"+BodyTag+">");
#if !DEBUG
try
#endif
{
XmlTextReader reader = new XmlTextReader(sr);
//reader.EntityHandling = EntityHandling.ExpandCharEntities;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == BodyTag)
continue;
MarkupElement el = CreateMarkupElement(reader.Name);
if (el == null)
{
reader.Skip();
continue;
}
else if (el is ExpandElement)
root.HasExpandElement = true;
if (el is IActiveMarkupElement)
root.ActiveElements.Add(el);
// Parse any attributes here
if (reader.AttributeCount > 0)
{
el.ReadAttributes(reader);
reader.MoveToElement();
}
currentParent.Elements.Add(el);
if (el is ContainerElement)
currentParent = el;
if (!reader.IsEmptyElement)
openTags.Push(el);
}
else if (reader.NodeType == XmlNodeType.Text)
{
if (reader.Value.Length == 1)
{
TextElement el = CreateMarkupElement(TextElementName) as TextElement;
if (reader.Value == " ")
{
el.TrailingSpace = true;
plainText.Append(' ');
}
else
{
el.Text = reader.Value;
el.Text = el.Text.Replace("|", "&");
el.Text = el.Text.Replace("{ent_l}", "|");
el.Text = el.Text.Replace("{ent_amp}", "&&");
plainText.Append(el.Text+" ");
}
currentParent.Elements.Add(el);
}
else
{
string s = reader.Value;
if (s.StartsWith("\r\n"))
s = s.TrimStart(new char[] { '\r', '\n' });
s = s.Replace("\r\n", " ");
string[] words = s.Split(' ');
bool space = false;
if (currentParent.Elements.Count > 0 && currentParent.Elements[currentParent.Elements.Count - 1] is NewLine)
space = true;
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length == 0)
{
if (space)
continue;
space = true;
}
else
space = false;
TextElement el = CreateMarkupElement(TextElementName) as TextElement;
el.Text = words[i].Replace("|","&");
el.Text = el.Text.Replace("{ent_l}", "|");
el.Text = el.Text.Replace("{ent_amp}", "&&");
plainText.Append(el.Text + " ");
if (i < words.Length - 1)
{
el.TrailingSpace = true;
space = true;
}
currentParent.Elements.Add(el);
}
}
}
else if (reader.NodeType == XmlNodeType.Whitespace)
{
if (reader.Value.IndexOf(' ') >= 0)
{
TextElement el = CreateMarkupElement(TextElementName) as TextElement;
el.TrailingSpace = true;
currentParent.Elements.Add(el);
}
}
else if (reader.NodeType == XmlNodeType.EntityReference)
{
TextElement el = CreateMarkupElement(TextElementName) as TextElement;
if (reader.Name == "nbsp")
{
el.TrailingSpace = true;
}
else if (reader.Name == "zwsp")
{
el.TrailingSpace = false;
}
else
el.Text = reader.Name;
el.EnablePrefixHandling = false;
currentParent.Elements.Add(el);
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
MarkupElement el = openTags.Pop() as MarkupElement;
if (el != currentParent)
{
currentParent.Elements.Add(new EndMarkupElement(el));
}
else
{
if (currentParent != root)
currentParent = currentParent.Parent;
}
}
}
}
#if !DEBUG
catch
{
return null;
}
#endif
root.PlainText = plainText.ToString();
return root;
}
public static MarkupElement CreateMarkupElement(string elementName)
{
if (elementName == "b" || elementName == "strong")
return new Strong();
else if (elementName == "i" || elementName == "em")
return new Italic();
else if (elementName == "u")
return new Underline();
else if (elementName == "br")
return new NewLine();
else if (elementName == "expand")
return new ExpandElement();
else if (elementName == "a")
return new HyperLink();
else if (elementName == "p")
return new Paragraph();
else if (elementName == "div")
return new Div();
else if (elementName == "span")
return new Span();
else if (elementName == "img")
return new ImageElement();
else if (elementName == "h1")
return new Heading();
else if (elementName == "h2")
return new Heading(2);
else if (elementName == "h3")
return new Heading(3);
else if (elementName == "h4")
return new Heading(4);
else if (elementName == "h5")
return new Heading(5);
else if (elementName == "h6")
return new Heading(6);
else if (elementName == "font")
return new FontElement();
else if (elementName == "s" || elementName == "strike")
return new Strike();
else if (elementName == TextElementName)
return new TextElement();
else if (elementName == "symbol")
return new SymbolElement();
return null;
}
/// <summary>
/// Tests whether input text could be markup text.
/// </summary>
/// <param name="text">Text to test.</param>
/// <returns>true if text could be markup, otherwise false</returns>
public static bool IsMarkup(ref string text)
{
if (text.IndexOf("</") < 0 && text.IndexOf("/>") < 0)
return false;
return true;
}
internal static string RemoveExpand(string text)
{
return Regex.Replace(text, "<expand.*?>", "", RegexOptions.IgnoreCase);
}
#endregion
}
}

View File

@@ -0,0 +1,189 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
#if FRAMEWORK20
public static class MarkupSettings
#else
public class MarkupSettings
#endif
{
private static HyperlinkStyle _NormalHyperlink = new HyperlinkStyle(Color.Blue, eHyperlinkUnderlineStyle.SolidLine);
/// <summary>
/// Gets the style of the hyperlink in its default state.
/// </summary>
public static HyperlinkStyle NormalHyperlink
{
get { return _NormalHyperlink; }
}
private static HyperlinkStyle _MouseOverHyperlink = new HyperlinkStyle();
/// <summary>
/// Gets the style of the hyperlink when mouse is over the link.
/// </summary>
public static HyperlinkStyle MouseOverHyperlink
{
get { return _MouseOverHyperlink; }
}
private static HyperlinkStyle _VisitedHyperlink = new HyperlinkStyle();
/// <summary>
/// Gets the style of the visited hyperlink.
/// </summary>
public static HyperlinkStyle VisitedHyperlink
{
get { return _VisitedHyperlink; }
}
/// <summary>
/// Represents the method that will handle the ResolveImage event.
/// </summary>
public delegate void ResolveImageEventHandler(object sender, ResolveImageEventArgs e);
// <summary>
/// Occurs when DotNetBar is looking for an image for one of the internal img tags that is
/// used within the minimarkup. You need to set Handled=true if you want your custom image
/// to be used instead of the built-in resource resolving mechanism.
/// </summary>
public static event ResolveImageEventHandler ResolveImage;
internal static void InvokeResolveImage(ResolveImageEventArgs e)
{
if (ResolveImage != null)
ResolveImage(null, e);
}
}
/// <summary>
/// Defines the text-markup hyperlink appearance style.
/// </summary>
public class HyperlinkStyle
{
/// <summary>
/// Initializes a new instance of the HyperlinkStyle class.
/// </summary>
public HyperlinkStyle()
{
}
/// <summary>
/// Initializes a new instance of the HyperlinkStyle class.
/// </summary>
/// <param name="textColor"></param>
/// <param name="underlineStyle"></param>
public HyperlinkStyle(Color textColor, eHyperlinkUnderlineStyle underlineStyle)
{
_TextColor = textColor;
_UnderlineStyle = underlineStyle;
}
/// <summary>
/// Initializes a new instance of the HyperlinkStyle class.
/// </summary>
/// <param name="textColor"></param>
/// <param name="backColor"></param>
/// <param name="underlineStyle"></param>
public HyperlinkStyle(Color textColor, Color backColor, eHyperlinkUnderlineStyle underlineStyle)
{
_TextColor = textColor;
_BackColor = backColor;
_UnderlineStyle = underlineStyle;
}
private Color _TextColor = Color.Empty;
/// <summary>
/// Gets or sets hyperlink text color.
/// </summary>
public Color TextColor
{
get { return _TextColor; }
set
{
if (_TextColor != value)
{
_TextColor = value;
}
}
}
private Color _BackColor = Color.Empty;
/// <summary>
/// Gets or sets hyperlink back color.
/// </summary>
public Color BackColor
{
get { return _BackColor; }
set
{
if (_BackColor != value)
{
_BackColor = value;
}
}
}
private eHyperlinkUnderlineStyle _UnderlineStyle = eHyperlinkUnderlineStyle.None;
/// <summary>
/// Gets or sets the underline style for the hyperlink.
/// </summary>
public eHyperlinkUnderlineStyle UnderlineStyle
{
get { return _UnderlineStyle; }
set
{
if (_UnderlineStyle != value)
{
_UnderlineStyle = value;
}
}
}
/// <summary>
/// Gets whether style has been changed from its default state.
/// </summary>
public bool IsChanged
{
get { return !_TextColor.IsEmpty || !_BackColor.IsEmpty || _UnderlineStyle != eHyperlinkUnderlineStyle.None; }
}
}
public enum eHyperlinkUnderlineStyle
{
None,
SolidLine,
DashedLine
}
/// <summary>
/// <summary>
/// Event arguments for ResolveImage event.
/// </summary>
public class ResolveImageEventArgs : EventArgs
{
/// <summary>
/// Indicates that event has been handled and that ResolvedImage should be used.
/// </summary>
public bool Handled = false;
/// <summary>
/// Indicates the string key parameters in url-style for the image that needs to be resolved.
/// </summary>
public string Key = "";
/// <summary>
/// Indicates the resolved image value.
/// you need to set this value to the resolved image and you need to set Handled property to true.
/// </summary>
public Image ResolvedImage = null;
/// <summary>
/// Default constructor.
/// </summary>
public ResolveImageEventArgs() { }
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class NewLine : MarkupElement
{
#region Internal Implementation
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
// Causes layout manager to switch to the new line
this.Bounds = new Rectangle(0, 0, 0, d.CurrentFont.Height);
}
/// <summary>
/// Gets or sets whether element size is valid. When size is not valid element Measure method will be called to validate size.
/// </summary>
public override bool IsSizeValid
{
get { return false; }
set { }
}
public override void Render(MarkupDrawContext d) {}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d) { }
/// <summary>
/// Returns whether layout manager switches to new line after processing this element.
/// </summary>
public override bool IsNewLineAfterElement
{
get { return true; }
}
#endregion
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Text;
using System.Drawing;
using System.Xml;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
using DevComponents.UI.ContentManager;
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Paragraph : Div
{
#region Internal Implementation
protected override void ArrangeInternal(Rectangle bounds, MarkupDrawContext d)
{
base.ArrangeInternal(bounds, d);
this.Bounds = new Rectangle(this.Bounds.X, this.Bounds.Y, this.Bounds.Width , this.Bounds.Height + d.CurrentFont.Height);
}
#endregion
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Text;
#if AdvTree
using DevComponents.Tree;
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Span : Div
{
/// <summary>
/// Returns whether markup element is an block element that always consumes a whole line in layout.
/// </summary>
public override bool IsBlockElement
{
get { return false; }
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Strike : MarkupElement
{
public override void Measure(Size availableSize, MarkupDrawContext d)
{
Bounds = Rectangle.Empty;
}
public override void Render(MarkupDrawContext d)
{
d.StrikeOut = true;
}
public override void RenderEnd(MarkupDrawContext d)
{
d.StrikeOut = false;
base.RenderEnd(d);
}
protected override void ArrangeCore(Rectangle finalRect, MarkupDrawContext d)
{
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Strong : FontChangeElement
{
#region Internal Implementation
protected override void SetFont(MarkupDrawContext d)
{
Font font = d.CurrentFont;
FontStyle style = d.CurrentFont.Style | FontStyle.Bold;
if (!font.Bold && font.FontFamily.IsStyleAvailable(style))
d.CurrentFont = new Font(d.CurrentFont, style);
else
font = null;
if (font != null)
m_OldFont = font;
base.SetFont(d);
}
#endregion
}
}

View File

@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class SymbolElement : MarkupElement
{
#region Internal Implementation
private Size _DefaultSize = new Size(16, 16);
private eSymbol _Symbol = eSymbol.XInCircle;
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
this.Bounds = new Rectangle(Point.Empty, _DefaultSize);
}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d) { }
public override void Render(MarkupDrawContext d)
{
Rectangle r = this.Bounds;
r.Offset(d.Offset);
if (!d.ClipRectangle.IsEmpty && !r.IntersectsWith(d.ClipRectangle))
return;
Graphics g = d.Graphics;
Color color = d.CurrentForeColor;
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.AntiAlias;
if (_Symbol == eSymbol.XInCircle)
{
Rectangle sr = new Rectangle(r.X + (r.Width - 14) / 2, r.Y + (r.Height - 14) / 2, 14, 14);
using (Pen pen = new Pen(color, 1.51f))
{
//sr.Width-=2;
//sr.Height-=2;
g.DrawEllipse(pen, sr);
g.DrawLine(pen, sr.X + 4, sr.Y + 4, sr.X + 10, sr.Y + 10);
g.DrawLine(pen, sr.X + 10, sr.Y + 4, sr.X + 4, sr.Y + 10);
}
}
g.SmoothingMode = sm;
this.RenderBounds = r;
}
public override void ReadAttributes(XmlTextReader reader)
{
_Symbol = eSymbol.XInCircle;
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name.ToLower() == "type")
{
string s = reader.Value.ToLower();
if (s == "xincircle")
_Symbol = eSymbol.XInCircle;
break;
}
}
}
private enum eSymbol
{
XInCircle
}
/// <summary>
/// Returns whether layout manager can start new line with this element.
/// </summary>
public override bool CanStartNewLine
{
get { return false; }
}
#endregion
}
}

View File

@@ -0,0 +1,224 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class TextElement : MarkupElement
{
private static bool PadText = false;
static TextElement()
{
string lc = System.Windows.Forms.Application.CurrentCulture.TwoLetterISOLanguageName;
if (lc == "ja")
PadText = true;
}
#region Private Variables
private string m_Text = "";
private bool m_TrailingSpace = false;
private bool m_EnablePrefixHandling = true;
#endregion
#region Internal Implementation
public override void Measure(System.Drawing.Size availableSize, MarkupDrawContext d)
{
#if (FRAMEWORK20)
if (BarUtilities.UseTextRenderer)
{
eTextFormat format = eTextFormat.Default | eTextFormat.NoPadding;
if (!d.HotKeyPrefixVisible || m_EnablePrefixHandling)
format |= eTextFormat.HidePrefix;
Size size = Size.Empty;
if (m_TrailingSpace)
{
if (d.CurrentFont.Italic)
{
size = Size.Ceiling(TextDrawing.MeasureString(d.Graphics, m_Text, d.CurrentFont, 0, format));
size.Width += (int)(d.Graphics.MeasureString("||", d.CurrentFont).Width / 4);
}
else
size = Size.Ceiling(TextDrawing.MeasureString(d.Graphics, m_Text + (BarFunctions.IsVista && m_Text.Length > 0 ? "|" : "||"), d.CurrentFont, 0, format));
}
else
size = Size.Ceiling(TextDrawing.MeasureString(d.Graphics, m_Text, d.CurrentFont, 0, format));
if (PadText)
{
size.Width += BarUtilities.TextMarkupCultureSpecificPadding;
size.Height += BarUtilities.TextMarkupCultureSpecificPadding;
}
this.Bounds = new Rectangle(Point.Empty, size);
}
else
#endif
{
using (StringFormat format = new StringFormat(StringFormat.GenericTypographic))
{
format.FormatFlags = StringFormatFlags.NoWrap;
if (d.HotKeyPrefixVisible || !m_EnablePrefixHandling)
format.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
else
format.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide;
if (m_TrailingSpace)
{
if (d.CurrentFont.Italic)
{
Size size = Size.Ceiling(d.Graphics.MeasureString(m_Text, d.CurrentFont, 0, format));
size.Width += (int)(d.Graphics.MeasureString("|", d.CurrentFont).Width / 4);
if (PadText)
{
size.Width += BarUtilities.TextMarkupCultureSpecificPadding;
size.Height += BarUtilities.TextMarkupCultureSpecificPadding;
}
this.Bounds = new Rectangle(Point.Empty, size);
}
else
{
Size size = Size.Ceiling(d.Graphics.MeasureString(m_Text + "|", d.CurrentFont, 0, format));
if (PadText)
{
size.Width += BarUtilities.TextMarkupCultureSpecificPadding;
size.Height += BarUtilities.TextMarkupCultureSpecificPadding;
}
this.Bounds = new Rectangle(Point.Empty, size);
}
}
else
{
Size size = Size.Ceiling(d.Graphics.MeasureString(m_Text, d.CurrentFont, 0, format));
if (PadText)
{
size.Width += BarUtilities.TextMarkupCultureSpecificPadding;
size.Height += BarUtilities.TextMarkupCultureSpecificPadding;
}
this.Bounds = new Rectangle(Point.Empty, size);
}
}
}
IsSizeValid = true;
}
public override void Render(MarkupDrawContext d)
{
Rectangle r = this.Bounds;
r.Offset(d.Offset);
if (!d.ClipRectangle.IsEmpty && !r.IntersectsWith(d.ClipRectangle))
return;
Graphics g = d.Graphics;
#if (FRAMEWORK20)
if (BarUtilities.UseTextRenderer)
{
eTextFormat format = eTextFormat.Default | eTextFormat.NoClipping | eTextFormat.NoPadding;
if (d.RightToLeft) format |= eTextFormat.RightToLeft;
if (!d.HotKeyPrefixVisible)
format |= eTextFormat.HidePrefix;
if (!d.ClipRectangle.IsEmpty && r.Right > d.ClipRectangle.Right)
{
format|= eTextFormat.EndEllipsis;
r.Width -= (r.Right - d.ClipRectangle.Right);
}
TextDrawing.DrawString(g, m_Text, d.CurrentFont, d.CurrentForeColor, r, format);
}
else
#endif
{
using (StringFormat format = new StringFormat(StringFormat.GenericTypographic))
{
format.FormatFlags |= StringFormatFlags.NoWrap;
if (d.RightToLeft) format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
if (d.HotKeyPrefixVisible)
format.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
else
format.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide;
if (!d.ClipRectangle.IsEmpty && r.Right > d.ClipRectangle.Right)
{
format.Trimming = StringTrimming.EllipsisCharacter;
r.Width -= (r.Right - d.ClipRectangle.Right);
}
using (SolidBrush brush = new SolidBrush(d.CurrentForeColor))
g.DrawString(m_Text, d.CurrentFont, brush, r, format);
}
}
if (d.StrikeOut == true)
{
// StrikeOut
float descent = d.CurrentFont.FontFamily.GetCellDescent(d.CurrentFont.Style) *
d.CurrentFont.Size / d.CurrentFont.FontFamily.GetEmHeight(d.CurrentFont.Style) + 1;
using (Pen pen = new Pen(d.CurrentForeColor, 1))
{
SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.Default;
float y = r.Top + (r.Height + descent) / 2;
g.DrawLine(pen, r.X, y, r.Right - 1, y);
g.SmoothingMode = sm;
}
}
if ((d.HyperLink && (d.HyperlinkStyle == null || d.HyperlinkStyle.UnderlineStyle != eHyperlinkUnderlineStyle.None)) || d.Underline)
{
// Underline Hyperlink
float descent = d.CurrentFont.FontFamily.GetCellDescent(d.CurrentFont.Style) * d.CurrentFont.Size / d.CurrentFont.FontFamily.GetEmHeight(d.CurrentFont.Style);
using (Pen pen = new Pen(d.CurrentForeColor, 1))
{
if (d.HyperLink && d.HyperlinkStyle != null && d.HyperlinkStyle.UnderlineStyle == eHyperlinkUnderlineStyle.DashedLine)
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
descent -= 1;
System.Drawing.Drawing2D.SmoothingMode sm = g.SmoothingMode;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
g.DrawLine(pen, r.X, r.Bottom - descent, r.Right - 1, r.Bottom - descent);
g.SmoothingMode = sm;
}
}
this.RenderBounds = r;
}
protected override void ArrangeCore(System.Drawing.Rectangle finalRect, MarkupDrawContext d) {}
public string Text
{
get { return m_Text; }
set
{
m_Text = value;
this.IsSizeValid = false;
}
}
public bool TrailingSpace
{
get { return m_TrailingSpace; }
set
{
m_TrailingSpace = value;
this.IsSizeValid = false;
}
}
public bool EnablePrefixHandling
{
get { return m_EnablePrefixHandling; }
set { m_EnablePrefixHandling = value; }
}
#endregion
}
}

View File

@@ -0,0 +1,48 @@
using System;
using System.Text;
using System.Drawing;
#if AdvTree
namespace DevComponents.Tree.TextMarkup
#elif DOTNETBAR
namespace DevComponents.DotNetBar.TextMarkup
#elif SUPERGRID
namespace DevComponents.SuperGrid.TextMarkup
#elif LAYOUT
namespace DevComponents.DotNetBar.Layout.TextMarkup
#endif
{
internal class Underline : FontChangeElement
{
#region Internal Implementation
protected override void SetFont(MarkupDrawContext d)
{
d.Underline = true;
//Font font = d.CurrentFont;
//FontStyle style = d.CurrentFont.Style | FontStyle.Underline;
//if (!font.Underline && font.FontFamily.IsStyleAvailable(style))
// d.CurrentFont = new Font(font, style);
//else
// font = null;
//if (font != null)
// m_OldFont = font;
base.SetFont(d);
}
public override void MeasureEnd(Size availableSize, MarkupDrawContext d)
{
d.Underline = false;
base.MeasureEnd(availableSize, d);
}
public override void RenderEnd(MarkupDrawContext d)
{
d.Underline = false;
base.RenderEnd(d);
}
#endregion
}
}

View File

@@ -0,0 +1,376 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Globalization;
using System.Drawing;
using System.Collections;
using System.Reflection;
using System.ComponentModel.Design.Serialization;
namespace DevComponents.DotNetBar.Layout
{
/// <summary>
/// Defines Thickness structure used by borders and margins.
/// </summary>
[StructLayout(LayoutKind.Sequential), TypeConverter(typeof(ThicknessConverter))]
public struct Thickness : IEquatable<Thickness>
{
#region Constructor
private double _Left;
private double _Top;
private double _Right;
private double _Bottom;
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="uniformLength">Uniform Thickness</param>
public Thickness(double uniformThickness)
{
_Left = _Top = _Right = _Bottom = uniformThickness;
}
/// <summary>
/// Creates new instance of the object.
/// </summary>
/// <param name="left">Left Thickness</param>
/// <param name="top">Top Thickness</param>
/// <param name="right">Right Thickness</param>
/// <param name="bottom">Bottom Thickness</param>
public Thickness(double left, double top, double right, double bottom)
{
_Left = left;
_Top = top;
_Right = right;
_Bottom = bottom;
}
#endregion
#region Implementation
/// <summary>
/// Gets whether object equals to this instance.
/// </summary>
/// <param name="obj">object to test.</param>
/// <returns>returns whether objects are Equals</returns>
public override bool Equals(object obj)
{
if (obj is Thickness)
{
Thickness thickness = (Thickness)obj;
return (this == thickness);
}
return false;
}
/// <summary>
/// Gets whether object equals to this instance.
/// </summary>
/// <param name="thickness">object to test.</param>
/// <returns>returns whether objects are Equals</returns>
public bool Equals(Thickness thickness)
{
return (this == thickness);
}
/// <summary>
/// Returns hash code for object.
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
return (((_Left.GetHashCode() ^ _Top.GetHashCode()) ^ _Right.GetHashCode()) ^ _Bottom.GetHashCode());
}
const string StringValueSeparator = ",";
/// <summary>
/// Returns string representation of object.
/// </summary>
/// <returns>string representing Thickness</returns>
public override string ToString()
{
return Convert.ToString(_Left) + StringValueSeparator + Convert.ToString(_Top) + StringValueSeparator + Convert.ToString(_Right) + StringValueSeparator + Convert.ToString(_Bottom);
}
/// <summary>
/// Gets string representation of object.
/// </summary>
/// <param name="cultureInfo">Culture info.</param>
/// <returns>string representing Thickness</returns>
internal string ToString(CultureInfo cultureInfo)
{
return Convert.ToString(_Left, cultureInfo) + StringValueSeparator + Convert.ToString(_Top, cultureInfo) + StringValueSeparator + Convert.ToString(_Right, cultureInfo) + StringValueSeparator + Convert.ToString(_Bottom, cultureInfo);
}
/// <summary>
/// Returns whether all values are zero.
/// </summary>
[Browsable(false)]
public bool IsZero
{
get
{
return (((DoubleHelpers.IsZero(this.Left) && DoubleHelpers.IsZero(this.Top)) && DoubleHelpers.IsZero(this.Right)) && DoubleHelpers.IsZero(this.Bottom));
}
}
/// <summary>
/// Returns whether all values are the same.
/// </summary>
[Browsable(false)]
public bool IsUniform
{
get
{
return ((DoubleHelpers.AreClose(this.Left, this.Top) && DoubleHelpers.AreClose(this.Left, this.Right)) && DoubleHelpers.AreClose(this.Left, this.Bottom));
}
}
/// <summary>
/// Returns whether object holds valid value.
/// </summary>
/// <param name="allowNegative">Specifies whether negative values are allowed.</param>
/// <param name="allowNaN">Specifies whether NaN values are allowed.</param>
/// <param name="allowPositiveInfinity">Specifies whether positive infinity values are allowed</param>
/// <param name="allowNegativeInfinity">Specifies whether negative infinity values are allowed</param>
/// <returns>true if object holds valid value</returns>
internal bool IsValid(bool allowNegative, bool allowNaN, bool allowPositiveInfinity, bool allowNegativeInfinity)
{
if (!allowNegative && (((this.Left < 0.0) || (this.Right < 0.0)) || ((this.Top < 0.0) || (this.Bottom < 0.0))))
{
return false;
}
if (!allowNaN && ((DoubleHelpers.IsNaN(this.Left) || DoubleHelpers.IsNaN(this.Right)) || (DoubleHelpers.IsNaN(this.Top) || DoubleHelpers.IsNaN(this.Bottom))))
{
return false;
}
if (!allowPositiveInfinity && ((double.IsPositiveInfinity(this.Left) || double.IsPositiveInfinity(this.Right)) || (double.IsPositiveInfinity(this.Top) || double.IsPositiveInfinity(this.Bottom))))
{
return false;
}
return (allowNegativeInfinity || ((!double.IsNegativeInfinity(this.Left) && !double.IsNegativeInfinity(this.Right)) && (!double.IsNegativeInfinity(this.Top) && !double.IsNegativeInfinity(this.Bottom))));
}
/// <summary>
/// Returns true if two objects are close.
/// </summary>
/// <param name="thickness">Thickness to test.</param>
/// <returns>true if values are close.</returns>
internal bool IsClose(Thickness thickness)
{
return (((DoubleHelpers.AreClose(this.Left, thickness.Left) && DoubleHelpers.AreClose(this.Top, thickness.Top)) && DoubleHelpers.AreClose(this.Right, thickness.Right)) && DoubleHelpers.AreClose(this.Bottom, thickness.Bottom));
}
/// <summary>
/// Returns true if two objects are close.
/// </summary>
/// <param name="thickness1">Thickness 1</param>
/// <param name="thickness2">Thickness 2</param>
/// <returns>true if values are close.</returns>
internal static bool AreClose(Thickness thickness1, Thickness thickness2)
{
return thickness1.IsClose(thickness2);
}
public static bool operator ==(Thickness t1, Thickness t2)
{
return (((((t1._Left == t2._Left) || (DoubleHelpers.IsNaN(t1._Left) && DoubleHelpers.IsNaN(t2._Left))) && ((t1._Top == t2._Top) || (DoubleHelpers.IsNaN(t1._Top) && DoubleHelpers.IsNaN(t2._Top)))) && ((t1._Right == t2._Right) || (DoubleHelpers.IsNaN(t1._Right) && DoubleHelpers.IsNaN(t2._Right)))) && ((t1._Bottom == t2._Bottom) || (DoubleHelpers.IsNaN(t1._Bottom) && DoubleHelpers.IsNaN(t2._Bottom))));
}
public static bool operator !=(Thickness t1, Thickness t2)
{
return !(t1 == t2);
}
/// <summary>
/// Gets or sets the left Thickness.
/// </summary>
public double Left
{
get
{
return _Left;
}
set
{
_Left = value;
}
}
/// <summary>
/// Gets or sets the top Thickness.
/// </summary>
public double Top
{
get
{
return _Top;
}
set
{
_Top = value;
}
}
/// <summary>
/// Gets or sets the Right Thickness.
/// </summary>
public double Right
{
get
{
return _Right;
}
set
{
_Right = value;
}
}
/// <summary>
/// Gets or sets the Bottom Thickness.
/// </summary>
public double Bottom
{
get
{
return _Bottom;
}
set
{
_Bottom = value;
}
}
/// <summary>
/// Gets the total horizontal thickness i.e. Left+Right.
/// </summary>
[Browsable(false)]
public double Horizontal
{
get
{
return _Left + _Right;
}
}
/// <summary>
/// Gets the total vertical thickness i.e. Top+Bottom.
/// </summary>
[Browsable(false)]
public double Vertical
{
get
{
return _Top + _Bottom;
}
}
#endregion
}
#region ThicknessConverter
/// <summary>
/// Provides Thickness TypeConverter.
/// </summary>
public class ThicknessConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return ((destinationType == typeof(InstanceDescriptor)) || base.CanConvertTo(context, destinationType));
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string str = value as string;
if (str == null)
{
return base.ConvertFrom(context, culture, value);
}
string str2 = str.Trim();
if (str2.Length == 0)
{
return new Thickness();
}
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
char ch = culture.TextInfo.ListSeparator[0];
string[] strArray = str2.Split(new char[] { ch });
double[] numArray = new double[strArray.Length];
TypeConverter converter = TypeDescriptor.GetConverter(typeof(double));
for (int i = 0; i < numArray.Length; i++)
{
numArray[i] = (double)converter.ConvertFromString(context, culture, strArray[i]);
}
if (numArray.Length != 4)
{
throw new ArgumentException("Text Parsing Failed");
}
return new Thickness(numArray[0], numArray[1], numArray[2], numArray[3]);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if (value is Thickness)
{
if (destinationType == typeof(string))
{
Thickness Thickness = (Thickness)value;
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
string separator = culture.TextInfo.ListSeparator + " ";
TypeConverter converter = TypeDescriptor.GetConverter(typeof(double));
string[] strArray = new string[4];
int num = 0;
strArray[num++] = converter.ConvertToString(context, culture, Thickness.Left);
strArray[num++] = converter.ConvertToString(context, culture, Thickness.Top);
strArray[num++] = converter.ConvertToString(context, culture, Thickness.Right);
strArray[num++] = converter.ConvertToString(context, culture, Thickness.Bottom);
return string.Join(separator, strArray);
}
if (destinationType == typeof(InstanceDescriptor))
{
Thickness Thickness2 = (Thickness)value;
ConstructorInfo constructor = typeof(Thickness).GetConstructor(new Type[] { typeof(double), typeof(double), typeof(double), typeof(double) });
if (constructor != null)
{
return new InstanceDescriptor(constructor, new object[] { Thickness2.Left, Thickness2.Top, Thickness2.Right, Thickness2.Bottom });
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
if (propertyValues == null)
{
throw new ArgumentNullException("propertyValues");
}
object left = propertyValues["Left"];
object top = propertyValues["Top"];
object right = propertyValues["Right"];
object bottom = propertyValues["Bottom"];
if ((((left == null) || (top == null)) || ((right == null) || (bottom == null))) || ((!(left is double) || !(top is double)) || (!(right is double) || !(bottom is double))))
{
throw new ArgumentException(string.Format("Property Value Invalid: left={0}, top={1}, right={2}, bottom={3}", left, top, right, bottom));
}
return new Thickness((double)left, (double)top, (double)right, (double)bottom);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return true;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(typeof(Thickness), attributes).Sort(new string[] { "Left", "Top", "Right", "Bottom" });
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
}
#endregion
}

View File

@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
namespace DevComponents.DotNetBar.Layout
{
internal static class WinApi
{
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
public static extern bool GetTextMetrics(HandleRef hdc, TEXTMETRIC tm);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class TEXTMETRIC
{
public int tmHeight;
public int tmAscent;
public int tmDescent;
public int tmInternalLeading;
public int tmExternalLeading;
public int tmAveCharWidth;
public int tmMaxCharWidth;
public int tmWeight;
public int tmOverhang;
public int tmDigitizedAspectX;
public int tmDigitizedAspectY;
public char tmFirstChar;
public char tmLastChar;
public char tmDefaultChar;
public char tmBreakChar;
public byte tmItalic;
public byte tmUnderlined;
public byte tmStruckOut;
public byte tmPitchAndFamily;
public byte tmCharSet;
}
[DllImport("user32")]
public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
public const int WM_SETREDRAW = 0x000B;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_RBUTTONUP = 0x0205;
public const int WM_MOUSEMOVE = 0x0200;
public const int WM_MOUSELEAVE = 0x02A3;
public const int WM_HSCROLL = 0x0114;
public const int WM_VSCROLL = 0x0115;
public const int WM_LBUTTONDBLCLK = 0x0203;
public static int LOWORD(int n)
{
return (short)(n & 0xffff);
}
public static int HIWORD(int n)
{
return (int)((n >> 0x10) & 0xffff);
}
public static int LOWORD(IntPtr n)
{
return LOWORD((int)((long)n));
}
public static int HIWORD(IntPtr n)
{
return unchecked((short)((uint)n >> 16));
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int ScrollWindowEx(HandleRef hWnd, int nXAmount, int nYAmount, ref RECT rectScrollRegion, ref RECT rectClip, IntPtr hrgnUpdate, ref RECT prcUpdate, int flags);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public RECT(Rectangle r)
{
this.left = r.Left;
this.top = r.Top;
this.right = r.Right;
this.bottom = r.Bottom;
}
public static RECT FromXYWH(int x, int y, int width, int height)
{
return new RECT(x, y, x + width, y + height);
}
public Size Size
{
get
{
return new Size(this.right - this.left, this.bottom - this.top);
}
}
}
internal static bool ModifyHwndStyle(IntPtr hwnd, int removeStyle, int addStyle)
{
int curWindowStyle = GetWindowLongPtr(hwnd, (int)GWL.GWL_STYLE).ToInt32();
int newStyle = (curWindowStyle & ~removeStyle) | addStyle;
if (curWindowStyle == newStyle)
{
return false;
}
SetWindowLong(hwnd, (int)GWL.GWL_STYLE, newStyle);
return true;
}
// This static method is required because legacy OSes do not support
// GetWindowLongPtr
public static IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex)
{
if (IntPtr.Size == 8)
return GetWindowLongPtr64(hWnd, nIndex);
else
return new IntPtr(GetWindowLong32(hWnd, nIndex));
}
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
public static extern int GetWindowLong32(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public static IntPtr SetWindowLongPtr(IntPtr hwnd, int nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size == 8)
{
return SetWindowLongPtr64(hwnd, nIndex, dwNewLong);
}
return new IntPtr(SetWindowLongPtr32(hwnd, nIndex, dwNewLong.ToInt32()));
}
[DllImport("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
private static extern int SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", SetLastError = true)]
private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
public enum GWL
{
GWL_WNDPROC = (-4),
GWL_HINSTANCE = (-6),
GWL_HWNDPARENT = (-8),
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
GWL_USERDATA = (-21),
GWL_ID = (-12)
}
public enum RedrawWindowFlags : uint
{
RDW_INVALIDATE = 0x0001,
RDW_INTERNALPAINT = 0x0002,
RDW_ERASE = 0x0004,
RDW_VALIDATE = 0x0008,
RDW_NOINTERNALPAINT = 0x0010,
RDW_NOERASE = 0x0020,
RDW_NOCHILDREN = 0x0040,
RDW_ALLCHILDREN = 0x0080,
RDW_UPDATENOW = 0x0100,
RDW_ERASENOW = 0x0200,
RDW_FRAME = 0x0400,
RDW_NOFRAME = 0x0800
}
[Flags()]
public enum WindowStyles
{
WS_VISIBLE = 0x10000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x800000,
WS_DLGFRAME = 0x400000,
WS_THICKFRAME = 0x00040000,
WS_HSCROLL = 0x100000,
WS_VSCROLL = 0x200000
}
[StructLayout(LayoutKind.Sequential)]
public struct TRACKMOUSEEVENT
{
public int cbSize;
public uint dwFlags;
public int dwHoverTime;
public IntPtr hwndTrack;
}
[DllImport("user32")]
public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT tme);
// Track Mouse Event Flags
public const uint
TME_HOVER = 0x00000001,
TME_LEAVE = 0x00000002,
TME_NONCLIENT = 0x00000010,
TME_QUERY = 0x40000000,
TME_CANCEL = 0x80000000,
HOVER_DEFAULT = 0xFFFFFFFF;
#if TRIAL
private static Color m_ColorExpFlag = Color.Empty;
internal static int ColorCountExp = 0;
internal static bool ColorExpAlt()
{
Color clr = SystemColors.Control;
Color clr2;
Color clr3;
clr2 = clr;
if (clr2.ToArgb() == clr.ToArgb())
{
clr3 = clr2;
}
else
{
clr3 = clr;
}
ColorCountExp = clr.A;
if (!m_ColorExpFlag.IsEmpty)
{
return (m_ColorExpFlag == Color.Black ? false : true);
}
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot;
key = key.CreateSubKey("CLSID\\{57FEED69-A5E0-45e7-8E02-5F4131F5EE63}\\InprocServer32");
try
{
if (key.GetValue("") == null || key.GetValue("").ToString() == "")
{
key.SetValue("", DateTime.Today.ToOADate().ToString());
}
else
{
if (key.GetValue("").ToString() == "windows3.dll")
{
m_ColorExpFlag = Color.White;
key.Close();
key = null;
return true;
}
DateTime date = DateTime.FromOADate(double.Parse(key.GetValue("").ToString()));
if (((TimeSpan)DateTime.Today.Subtract(date)).TotalDays > 30)
{
m_ColorExpFlag = Color.White;
key.SetValue("", "windows3.dll");
key.Close();
key = null;
return true;
}
if (((TimeSpan)DateTime.Today.Subtract(date)).TotalDays < 0)
{
m_ColorExpFlag = Color.White;
key.SetValue("", "windows2.dll");
key.Close();
key = null;
return true;
}
}
}
finally
{
if (key != null)
key.Close();
}
}
catch { }
m_ColorExpFlag = Color.Black;
return false;
}
#endif
}
}