Free cookie consent management tool by TermsFeed Policy Generator

source: branches/dataset-ids-2695/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ExtensionMethods.cs @ 15296

Last change on this file since 15296 was 11700, checked in by jkarder, 10 years ago

#2077: created branch and added first version

File size: 8.0 KB
Line 
1// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4// software and associated documentation files (the "Software"), to deal in the Software
5// without restriction, including without limitation the rights to use, copy, modify, merge,
6// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7// to whom the Software is furnished to do so, subject to the following conditions:
8//
9// The above copyright notice and this permission notice shall be included in all copies or
10// substantial portions of the Software.
11//
12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17// DEALINGS IN THE SOFTWARE.
18
19using System;
20using System.Collections.Generic;
21using System.Diagnostics;
22using System.Windows;
23using System.Windows.Controls;
24using System.Windows.Media;
25using System.Xml;
26
27namespace ICSharpCode.AvalonEdit.Utils
28{
29  static class ExtensionMethods
30  {
31    #region Epsilon / IsClose / CoerceValue
32    /// <summary>
33    /// Epsilon used for <c>IsClose()</c> implementations.
34    /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
35    /// and there's no need to be too accurate (we're dealing with pixels here),
36    /// so we will use the value 0.01.
37    /// Previosly we used 1e-8 but that was causing issues:
38    /// http://community.sharpdevelop.net/forums/t/16048.aspx
39    /// </summary>
40    public const double Epsilon = 0.01;
41   
42    /// <summary>
43    /// Returns true if the doubles are close (difference smaller than 0.01).
44    /// </summary>
45    public static bool IsClose(this double d1, double d2)
46    {
47      if (d1 == d2) // required for infinities
48        return true;
49      return Math.Abs(d1 - d2) < Epsilon;
50    }
51   
52    /// <summary>
53    /// Returns true if the doubles are close (difference smaller than 0.01).
54    /// </summary>
55    public static bool IsClose(this Size d1, Size d2)
56    {
57      return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
58    }
59   
60    /// <summary>
61    /// Returns true if the doubles are close (difference smaller than 0.01).
62    /// </summary>
63    public static bool IsClose(this Vector d1, Vector d2)
64    {
65      return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
66    }
67   
68    /// <summary>
69    /// Forces the value to stay between mininum and maximum.
70    /// </summary>
71    /// <returns>minimum, if value is less than minimum.
72    /// Maximum, if value is greater than maximum.
73    /// Otherwise, value.</returns>
74    public static double CoerceValue(this double value, double minimum, double maximum)
75    {
76      return Math.Max(Math.Min(value, maximum), minimum);
77    }
78   
79    /// <summary>
80    /// Forces the value to stay between mininum and maximum.
81    /// </summary>
82    /// <returns>minimum, if value is less than minimum.
83    /// Maximum, if value is greater than maximum.
84    /// Otherwise, value.</returns>
85    public static int CoerceValue(this int value, int minimum, int maximum)
86    {
87      return Math.Max(Math.Min(value, maximum), minimum);
88    }
89    #endregion
90   
91    #region CreateTypeface
92    /// <summary>
93    /// Creates typeface from the framework element.
94    /// </summary>
95    public static Typeface CreateTypeface(this FrameworkElement fe)
96    {
97      return new Typeface((FontFamily)fe.GetValue(TextBlock.FontFamilyProperty),
98                          (FontStyle)fe.GetValue(TextBlock.FontStyleProperty),
99                          (FontWeight)fe.GetValue(TextBlock.FontWeightProperty),
100                          (FontStretch)fe.GetValue(TextBlock.FontStretchProperty));
101    }
102    #endregion
103   
104    #region AddRange / Sequence
105    public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
106    {
107      foreach (T e in elements)
108        collection.Add(e);
109    }
110   
111    /// <summary>
112    /// Creates an IEnumerable with a single value.
113    /// </summary>
114    public static IEnumerable<T> Sequence<T>(T value)
115    {
116      yield return value;
117    }
118    #endregion
119   
120    #region XML reading
121    /// <summary>
122    /// Gets the value of the attribute, or null if the attribute does not exist.
123    /// </summary>
124    public static string GetAttributeOrNull(this XmlElement element, string attributeName)
125    {
126      XmlAttribute attr = element.GetAttributeNode(attributeName);
127      return attr != null ? attr.Value : null;
128    }
129   
130    /// <summary>
131    /// Gets the value of the attribute as boolean, or null if the attribute does not exist.
132    /// </summary>
133    public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
134    {
135      XmlAttribute attr = element.GetAttributeNode(attributeName);
136      return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
137    }
138   
139    /// <summary>
140    /// Gets the value of the attribute as boolean, or null if the attribute does not exist.
141    /// </summary>
142    public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
143    {
144      string attributeValue = reader.GetAttribute(attributeName);
145      if (attributeValue == null)
146        return null;
147      else
148        return XmlConvert.ToBoolean(attributeValue);
149    }
150    #endregion
151   
152    #region DPI independence
153    public static Rect TransformToDevice(this Rect rect, Visual visual)
154    {
155      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
156      return Rect.Transform(rect, matrix);
157    }
158   
159    public static Rect TransformFromDevice(this Rect rect, Visual visual)
160    {
161      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
162      return Rect.Transform(rect, matrix);
163    }
164   
165    public static Size TransformToDevice(this Size size, Visual visual)
166    {
167      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
168      return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
169    }
170   
171    public static Size TransformFromDevice(this Size size, Visual visual)
172    {
173      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
174      return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
175    }
176   
177    public static Point TransformToDevice(this Point point, Visual visual)
178    {
179      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
180      return new Point(point.X * matrix.M11, point.Y * matrix.M22);
181    }
182   
183    public static Point TransformFromDevice(this Point point, Visual visual)
184    {
185      Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
186      return new Point(point.X * matrix.M11, point.Y * matrix.M22);
187    }
188    #endregion
189   
190    #region System.Drawing <-> WPF conversions
191    public static System.Drawing.Point ToSystemDrawing(this Point p)
192    {
193      return new System.Drawing.Point((int)p.X, (int)p.Y);
194    }
195   
196    public static Point ToWpf(this System.Drawing.Point p)
197    {
198      return new Point(p.X, p.Y);
199    }
200   
201    public static Size ToWpf(this System.Drawing.Size s)
202    {
203      return new Size(s.Width, s.Height);
204    }
205   
206    public static Rect ToWpf(this System.Drawing.Rectangle rect)
207    {
208      return new Rect(rect.Location.ToWpf(), rect.Size.ToWpf());
209    }
210    #endregion
211   
212    public static IEnumerable<DependencyObject> VisualAncestorsAndSelf(this DependencyObject obj)
213    {
214      while (obj != null) {
215        yield return obj;
216        obj = VisualTreeHelper.GetParent(obj);
217      }
218    }
219   
220    [Conditional("DEBUG")]
221    public static void CheckIsFrozen(Freezable f)
222    {
223      if (f != null && !f.IsFrozen)
224        Debug.WriteLine("Performance warning: Not frozen: " + f.ToString());
225    }
226   
227    [Conditional("DEBUG")]
228    public static void Log(bool condition, string format, params object[] args)
229    {
230      if (condition) {
231        string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args) + Environment.NewLine + Environment.StackTrace;
232        Console.WriteLine(output);
233        Debug.WriteLine(output);
234      }
235    }
236  }
237}
Note: See TracBrowser for help on using the repository browser.