# HG changeset patch # User stevenhollidge # Date 1336302998 -3600 # Node ID 4cfdecdb1d12247c4a1f8fdaef604ab51b25b577 # Parent 8cb4f36717e91f6fa0884229b1b6603dcd13578d Silverlight Glimpse now lives on codeplex, StockDisplay lives on Google code diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/Libs/FluentValidation.dll Binary file SilverlightGlimpse/Libs/FluentValidation.dll has changed diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/Libs/System.Windows.Controls.Data.Input.dll Binary file SilverlightGlimpse/Libs/System.Windows.Controls.Data.Input.dll has changed diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/Libs/System.Windows.Controls.dll Binary file SilverlightGlimpse/Libs/System.Windows.Controls.dll has changed diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse.sln --- a/SilverlightGlimpse/SilverlightGlimpse.sln Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SilverlightGlimpse", "SilverlightGlimpse\SilverlightGlimpse.csproj", "{BB51026B-2864-4389-AACA-0BBDF1926E46}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SilverlightValidation", "SilverlightValidation\SilverlightValidation.csproj", "{0C1CC1FC-915A-4428-8952-CDC79EABC3F4}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {BB51026B-2864-4389-AACA-0BBDF1926E46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BB51026B-2864-4389-AACA-0BBDF1926E46}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BB51026B-2864-4389-AACA-0BBDF1926E46}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BB51026B-2864-4389-AACA-0BBDF1926E46}.Release|Any CPU.Build.0 = Release|Any CPU - {0C1CC1FC-915A-4428-8952-CDC79EABC3F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0C1CC1FC-915A-4428-8952-CDC79EABC3F4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0C1CC1FC-915A-4428-8952-CDC79EABC3F4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0C1CC1FC-915A-4428-8952-CDC79EABC3F4}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse.suo Binary file SilverlightGlimpse/SilverlightGlimpse.suo has changed diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Controls/FloatableWindow/FloatableWindow.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Controls/FloatableWindow/FloatableWindow.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1593 +0,0 @@ -// Original code: http://floatablewindow.codeplex.com/ -// Author: Tim Heuer http://timheuer.com/blog/ - -// This source is subject to the Microsoft Public License (Ms-PL). -// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. -// All other rights reserved. - -using System.Collections; -using System.ComponentModel; -using System.Diagnostics; -using System.Windows.Automation; -using System.Windows.Automation.Peers; -using System.Windows.Controls.Primitives; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Animation; - -namespace System.Windows.Controls -{ - /// - /// Provides a window that can be displayed over a parent window and blocks - /// interaction with the parent window. - /// - /// Preview - [TemplatePart(Name = PART_Chrome, Type = typeof(FrameworkElement))] - [TemplatePart(Name = PART_CloseButton, Type = typeof(ButtonBase))] - [TemplatePart(Name = PART_ContentPresenter, Type = typeof(FrameworkElement))] - [TemplatePart(Name = PART_ContentRoot, Type = typeof(FrameworkElement))] - [TemplatePart(Name = PART_Overlay, Type = typeof(Panel))] - [TemplatePart(Name = PART_Root, Type = typeof(FrameworkElement))] - [TemplateVisualState(Name = VSMSTATE_StateClosed, GroupName = VSMGROUP_Window)] - [TemplateVisualState(Name = VSMSTATE_StateOpen, GroupName = VSMGROUP_Window)] - public class FloatableWindow : ContentControl - { - #region Static Fields and Constants - - /// - /// The name of the Chrome template part. - /// - private const string PART_Chrome = "Chrome"; - - /// - /// The name of the CloseButton template part. - /// - private const string PART_CloseButton = "CloseButton"; - - /// - /// The name of the ContentPresenter template part. - /// - private const string PART_ContentPresenter = "ContentPresenter"; - - /// - /// The name of the ContentRoot template part. - /// - private const string PART_ContentRoot = "ContentRoot"; - - /// - /// The name of the Overlay template part. - /// - private const string PART_Overlay = "Overlay"; - - /// - /// The name of the Root template part. - /// - private const string PART_Root = "Root"; - - /// - /// The name of the WindowStates VSM group. - /// - private const string VSMGROUP_Window = "WindowStates"; - - /// - /// The name of the Closing VSM state. - /// - private const string VSMSTATE_StateClosed = "Closed"; - - /// - /// The name of the Opening VSM state. - /// - private const string VSMSTATE_StateOpen = "Open"; - - #region public bool HasCloseButton - - /// - /// Gets or sets a value indicating whether the - /// has a close - /// button. - /// - /// - /// True if the child window has a close button; otherwise, false. The - /// default is true. - /// - public bool HasCloseButton - { - get { return (bool)GetValue(HasCloseButtonProperty); } - set { SetValue(HasCloseButtonProperty, value); } - } - - /// - /// Identifies the - /// - /// dependency property. - /// - /// - /// The identifier for the - /// - /// dependency property. - /// - public static readonly DependencyProperty HasCloseButtonProperty = - DependencyProperty.Register( - "HasCloseButton", - typeof(bool), - typeof(FloatableWindow), - new PropertyMetadata(true, OnHasCloseButtonPropertyChanged)); - - /// - /// HasCloseButtonProperty PropertyChangedCallback call back static function. - /// - /// FloatableWindow object whose HasCloseButton property is changed. - /// DependencyPropertyChangedEventArgs which contains the old and new values. - private static void OnHasCloseButtonPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - FloatableWindow cw = (FloatableWindow)d; - - if (cw.CloseButton != null) - { - if ((bool)e.NewValue) - { - cw.CloseButton.Visibility = Visibility.Visible; - } - else - { - cw.CloseButton.Visibility = Visibility.Collapsed; - } - } - } - - #endregion public bool HasCloseButton - - #region public Brush OverlayBrush - - /// - /// Gets or sets the visual brush that is used to cover the parent - /// window when the child window is open. - /// - /// - /// The visual brush that is used to cover the parent window when the - /// is open. The - /// default is null. - /// - public Brush OverlayBrush - { - get { return (Brush)GetValue(OverlayBrushProperty); } - set { SetValue(OverlayBrushProperty, value); } - } - - /// - /// Identifies the - /// - /// dependency property. - /// - /// - /// The identifier for the - /// - /// dependency property. - /// - public static readonly DependencyProperty OverlayBrushProperty = - DependencyProperty.Register( - "OverlayBrush", - typeof(Brush), - typeof(FloatableWindow), - new PropertyMetadata(OnOverlayBrushPropertyChanged)); - - /// - /// OverlayBrushProperty PropertyChangedCallback call back static function. - /// - /// FloatableWindow object whose OverlayBrush property is changed. - /// DependencyPropertyChangedEventArgs which contains the old and new values. - private static void OnOverlayBrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - FloatableWindow cw = (FloatableWindow)d; - - if (cw.Overlay != null) - { - cw.Overlay.Background = (Brush)e.NewValue; - } - } - - #endregion public Brush OverlayBrush - - #region public double OverlayOpacity - - /// - /// Gets or sets the opacity of the overlay brush that is used to cover - /// the parent window when the child window is open. - /// - /// - /// The opacity of the overlay brush that is used to cover the parent - /// window when the - /// is open. The default is 1.0. - /// - public double OverlayOpacity - { - get { return (double)GetValue(OverlayOpacityProperty); } - set { SetValue(OverlayOpacityProperty, value); } - } - - /// - /// Identifies the - /// - /// dependency property. - /// - /// - /// The identifier for the - /// - /// dependency property. - /// - public static readonly DependencyProperty OverlayOpacityProperty = - DependencyProperty.Register( - "OverlayOpacity", - typeof(double), - typeof(FloatableWindow), - new PropertyMetadata(OnOverlayOpacityPropertyChanged)); - - /// - /// OverlayOpacityProperty PropertyChangedCallback call back static function. - /// - /// FloatableWindow object whose OverlayOpacity property is changed. - /// DependencyPropertyChangedEventArgs which contains the old and new values. - private static void OnOverlayOpacityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - FloatableWindow cw = (FloatableWindow)d; - - if (cw.Overlay != null) - { - cw.Overlay.Opacity = (double)e.NewValue; - } - } - - #endregion public double OverlayOpacity - - #region private static Control RootVisual - - /// - /// Gets the root visual element. - /// - private static Control RootVisual - { - get - { - return Application.Current == null ? null : (Application.Current.RootVisual as Control); - } - } - - #endregion private static Control RootVisual - - #region public object Title - - /// - /// Gets or sets the title that is displayed in the frame of the - /// . - /// - /// - /// The title displayed at the top of the window. The default is null. - /// - public object Title - { - get { return GetValue(TitleProperty); } - set { SetValue(TitleProperty, value); } - } - - /// - /// Identifies the - /// - /// dependency property. - /// - /// - /// The identifier for the - /// - /// dependency property. - /// - public static readonly DependencyProperty TitleProperty = - DependencyProperty.Register( - "Title", - typeof(object), - typeof(FloatableWindow), - null); - - #endregion public object Title - - #endregion Static Fields and Constants - - #region Member Fields - /// - /// Set in the overloaded Show method. Offsets the Popup vertically from the top left corner of the browser window by this amount. - /// - private double _verticalOffset; - - /// - /// Set in the overloaded Show method. Offsets the Popup horizontally from the top left corner of the browser window by this amount. - /// - private double _horizontalOffset; - - /// - /// Private accessor for the IsModal - /// - [DefaultValue(false)] - private bool _modal; - - /// - /// Private accessor for the Chrome. - /// - private FrameworkElement _chrome; - - /// - /// Private accessor for the click point on the chrome. - /// - private Point _clickPoint; - - /// - /// Private accessor for the Closing storyboard. - /// - private Storyboard _closed; - - /// - /// Private accessor for the ContentPresenter. - /// - private FrameworkElement _contentPresenter; - - /// - /// Private accessor for the translate transform that needs to be applied on to the ContentRoot. - /// - private TranslateTransform _contentRootTransform; - - /// - /// Content area desired width. - /// - private double _desiredContentWidth; - - /// - /// Content area desired height. - /// - private double _desiredContentHeight; - - /// - /// Desired margin for the window. - /// - private Thickness _desiredMargin; - - /// - /// Private accessor for the Dialog Result property. - /// - private bool? _dialogresult; - - /// - /// Private accessor for the FloatableWindow InteractionState. - /// - private WindowInteractionState _interactionState; - - /// - /// Boolean value that specifies whether the application is exit or not. - /// - private bool _isAppExit; - - /// - /// Boolean value that specifies whether the window is in closing state or not. - /// - private bool _isClosing; - - /// - /// Boolean value that specifies whether the window is opened. - /// - private bool _isOpen; - - /// - /// Private accessor for the Opening storyboard. - /// - private Storyboard _opened; - - /// - /// Boolean value that specifies whether the mouse is captured or not. - /// - private bool _isMouseCaptured; - - /// - /// Private accessor for the Root of the window. - /// - private FrameworkElement _root; - - /// - /// Private accessor for the position of the window with respect to RootVisual. - /// - private Point _windowPosition; - - private static int z; - - #endregion Member Fields - - #region Constructors - - /// - /// Initializes a new instance of the - /// class. - /// - public FloatableWindow() - { - this.DefaultStyleKey = typeof(FloatableWindow); - this.InteractionState = WindowInteractionState.NotResponding; - } - - #endregion Constructors - - #region Events - - /// - /// Occurs when the - /// is closed. - /// - public event EventHandler Closed; - - /// - /// Occurs when the - /// is closing. - /// - public event EventHandler Closing; - - #endregion Events - - #region Properties - - private Panel _parentLayoutRoot; - public Panel ParentLayoutRoot - { - get { return _parentLayoutRoot; } - set - { - _parentLayoutRoot = value; - var grid = _parentLayoutRoot as Grid; - if (grid == null) return; - if (grid.RowDefinitions.Count > 0) Grid.SetRowSpan(this, grid.RowDefinitions.Count); - if (grid.ColumnDefinitions.Count > 0) Grid.SetColumnSpan(this, grid.ColumnDefinitions.Count); - } - } - - /// - /// Gets the internal accessor for the ContentRoot of the window. - /// - internal FrameworkElement ContentRoot - { - get; - private set; - } - - /// - /// Setting for the horizontal positioning offset for start position - /// - public double HorizontalOffset - { - get { return _horizontalOffset; } - set { _horizontalOffset = value; } - } - - /// - /// Setting for the vertical positioning offset for start position - /// - public double VerticalOffset - { - get { return _verticalOffset; } - set { _verticalOffset = value; } - } - - /// - /// Gets the internal accessor for the modal of the window. - /// - public bool IsModal - { - get - { - return _modal; - } - } - - /// - /// Gets or sets a value indicating whether the - /// was accepted or - /// canceled. - /// - /// - /// True if the child window was accepted; false if the child window was - /// canceled. The default is null. - /// - [TypeConverter(typeof(NullableBoolConverter))] - public bool? DialogResult - { - get - { - return this._dialogresult; - } - - set - { - if (this._dialogresult != value) - { - this._dialogresult = value; - this.Close(); - } - } - } - - /// - /// Gets the internal accessor for the PopUp of the window. - /// - internal Popup ChildWindowPopup - { - get; - private set; - } - - /// - /// Gets the internal accessor for the close button of the window. - /// - internal ButtonBase CloseButton - { - get; - private set; - } - - /// - /// Gets the InteractionState for the FloatableWindow. - /// - internal WindowInteractionState InteractionState - { - get - { - return this._interactionState; - } - private set - { - if (this._interactionState != value) - { - WindowInteractionState oldValue = this._interactionState; - this._interactionState = value; - FloatableWindowAutomationPeer peer = FloatableWindowAutomationPeer.FromElement(this) as FloatableWindowAutomationPeer; - - if (peer != null) - { - peer.RaiseInteractionStatePropertyChangedEvent(oldValue, this._interactionState); - } - } - } - } - - /// - /// Gets a value indicating whether the PopUp is open or not. - /// - private bool IsOpen - { - get - { - return (this.ChildWindowPopup != null && this.ChildWindowPopup.IsOpen) || - ((ParentLayoutRoot != null) && (ParentLayoutRoot.Children.Contains(this))); - } - } - - /// - /// Gets the internal accessor for the overlay of the window. - /// - internal Panel Overlay - { - get; - private set; - } - - #endregion Properties - - #region Static Methods - - /// - /// Inverts the input matrix. - /// - /// The matrix values that is to be inverted. - /// Returns a value indicating whether the inversion was successful or not. - private static bool InvertMatrix(ref Matrix matrix) - { - double determinant = (matrix.M11 * matrix.M22) - (matrix.M12 * matrix.M21); - - if (determinant == 0.0) - { - return false; - } - - Matrix matCopy = matrix; - matrix.M11 = matCopy.M22 / determinant; - matrix.M12 = -1 * matCopy.M12 / determinant; - matrix.M21 = -1 * matCopy.M21 / determinant; - matrix.M22 = matCopy.M11 / determinant; - matrix.OffsetX = ((matCopy.OffsetY * matCopy.M21) - (matCopy.OffsetX * matCopy.M22)) / determinant; - matrix.OffsetY = ((matCopy.OffsetX * matCopy.M12) - (matCopy.OffsetY * matCopy.M11)) / determinant; - - return true; - } - - #endregion Static Methods - - #region Methods - - /// - /// Executed when the application is exited. - /// - /// The sender. - /// Event args. - internal void Application_Exit(object sender, EventArgs e) - { - if (this.IsOpen) - { - this._isAppExit = true; - try - { - this.Close(); - } - finally - { - this._isAppExit = false; - } - } - } - - /// - /// Executed when focus is given to the window via a click. Attempts to bring current - /// window to the front in the event there are more windows. - /// - internal void BringToFront() - { - z++; - Canvas.SetZIndex(this, z); -#if DEBUG - //this.Title = z.ToString(); -#endif - } - - /// - /// Changes the visual state of the FloatableWindow. - /// - private void ChangeVisualState() - { - if (this._isClosing) - { - VisualStateManager.GoToState(this, VSMSTATE_StateClosed, true); - } - else - { - VisualStateManager.GoToState(this, VSMSTATE_StateOpen, true); - BringToFront(); - } - } - - /// - /// Executed when FloatableWindow size is changed. - /// - /// Sender object. - /// Size changed event args. - private void ChildWindow_SizeChanged(object sender, SizeChangedEventArgs e) - { - if (_modal) - { - if (this.Overlay != null) - { - if (e.NewSize.Height != this.Overlay.Height) - { - this._desiredContentHeight = e.NewSize.Height; - } - - if (e.NewSize.Width != this.Overlay.Width) - { - this._desiredContentWidth = e.NewSize.Width; - } - } - - if (this.IsOpen) - { - this.UpdateOverlaySize(); - } - } - } - - /// - /// Closes a . - /// - public void Close() - { - // AutomationPeer returns "Closing" when Close() is called - // but the window is not closed completely: - this.InteractionState = WindowInteractionState.Closing; - CancelEventArgs e = new CancelEventArgs(); - this.OnClosing(e); - - // On ApplicationExit, close() cannot be cancelled - if (!e.Cancel || this._isAppExit) - { - if (RootVisual != null) - { - RootVisual.IsEnabled = true; - } - - // Close Popup - if (this.IsOpen) - { - if (this._closed != null) - { - // Popup will be closed when the storyboard ends - this._isClosing = true; - try - { - var sb = GetVisualStateStoryboard("WindowStates", "Closed"); - sb.Completed += (s, args) => - { - this.ParentLayoutRoot.Children.Remove(this); - this.OnClosed(EventArgs.Empty); - this.UnSubscribeFromEvents(); - this.UnsubscribeFromTemplatePartEvents(); - - if (Application.Current.RootVisual != null) - { - Application.Current.RootVisual.GotFocus -= new RoutedEventHandler(this.RootVisual_GotFocus); - } - }; - this.ChangeVisualState(); - } - finally - { - this._isClosing = false; - } - } - else - { - // If no closing storyboard is defined, close the Popup - this.ChildWindowPopup.IsOpen = false; - } - - if (!this._dialogresult.HasValue) - { - // If close action is not happening because of DialogResult property change action, - // Dialogresult is always false: - this._dialogresult = false; - } - - //this.OnClosed(EventArgs.Empty); - //this.UnSubscribeFromEvents(); - //this.UnsubscribeFromTemplatePartEvents(); - - //if (Application.Current.RootVisual != null) - //{ - // Application.Current.RootVisual.GotFocus -= new RoutedEventHandler(this.RootVisual_GotFocus); - //} - } - } - else - { - // If the Close is cancelled, DialogResult should always be NULL: - this._dialogresult = null; - this.InteractionState = WindowInteractionState.Running; - } - } - - /// - /// Brings the window to the front of others - /// - /// - /// - internal void ContentRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) - { - BringToFront(); - } - - /// - /// Executed when the CloseButton is clicked. - /// - /// Sender object. - /// Routed event args. - internal void CloseButton_Click(object sender, RoutedEventArgs e) - { - this.Close(); - } - - /// - /// Executed when the Closing storyboard ends. - /// - /// Sender object. - /// Event args. - private void Closing_Completed(object sender, EventArgs e) - { - if (this.ChildWindowPopup != null) - { - this.ChildWindowPopup.IsOpen = false; - } - - // AutomationPeer returns "NotResponding" when the FloatableWindow is closed: - this.InteractionState = WindowInteractionState.NotResponding; - - if (this._closed != null) - { - this._closed.Completed -= new EventHandler(this.Closing_Completed); - } - } - - /// - /// Executed when the a key is presses when the window is open. - /// - /// Sender object. - /// Key event args. - private void ChildWindow_KeyDown(object sender, KeyEventArgs e) - { - FloatableWindow ew = sender as FloatableWindow; - Debug.Assert(ew != null, "FloatableWindow instance is null."); - - // Ctrl+Shift+F4 closes the FloatableWindow - if (e != null && !e.Handled && e.Key == Key.F4 && - ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) && - ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)) - { - ew.Close(); - e.Handled = true; - } - } - - /// - /// Executed when the window loses focus. - /// - /// Sender object. - /// Routed event args. - private void ChildWindow_LostFocus(object sender, RoutedEventArgs e) - { - // If the FloatableWindow loses focus but the popup is still open, - // it means another popup is opened. To get the focus back when the - // popup is closed, we handle GotFocus on the RootVisual - // TODO: Something else could get focus and handle the GotFocus event right. - // Try listening to routed events that were Handled (new SL 3 feature) - // Blocked by Jolt bug #29419 - if (this.IsOpen && Application.Current != null && Application.Current.RootVisual != null) - { - this.InteractionState = WindowInteractionState.BlockedByModalWindow; - Application.Current.RootVisual.GotFocus += new RoutedEventHandler(this.RootVisual_GotFocus); - } - } - - /// - /// Executed when mouse left button is down on the chrome. - /// - /// Sender object. - /// Mouse button event args. - private void Chrome_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) - { - if (this._chrome != null) - { - e.Handled = true; - - if (this.CloseButton != null && !this.CloseButton.IsTabStop) - { - this.CloseButton.IsTabStop = true; - try - { - this.Focus(); - } - finally - { - this.CloseButton.IsTabStop = false; - } - } - else - { - this.Focus(); - } - this._chrome.CaptureMouse(); - this._isMouseCaptured = true; - this._clickPoint = e.GetPosition(sender as UIElement); -#if DEBUG - //this.Title = string.Format("X:{0},Y:{1}", this._clickPoint.X.ToString(), this._clickPoint.Y.ToString()); -#endif - } - } - - /// - /// Executed when mouse left button is up on the chrome. - /// - /// Sender object. - /// Mouse button event args. - private void Chrome_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) - { - if (this._chrome != null) - { - //e.Handled = true; - this._chrome.ReleaseMouseCapture(); - this._isMouseCaptured = false; - } - } - - /// - /// Executed when mouse moves on the chrome. - /// - /// Sender object. - /// Mouse event args. - private void Chrome_MouseMove(object sender, MouseEventArgs e) - { - #region New ChildWindow Code not working - //if (this._isMouseCaptured && this.ContentRoot != null && Application.Current != null && Application.Current.RootVisual != null) - //{ - // Point position = e.GetPosition(Application.Current.RootVisual); - - // GeneralTransform gt = this.ContentRoot.TransformToVisual(Application.Current.RootVisual); - - // if (gt != null) - // { - // Point p = gt.Transform(this._clickPoint); - // this._windowPosition = gt.Transform(new Point(0, 0)); - - // if (position.X < 0) - // { - // double Y = FindPositionY(p, position, 0); - // position = new Point(0, Y); - // } - - // if (position.X > this.Width) - // { - // double Y = FindPositionY(p, position, this.Width); - // position = new Point(this.Width, Y); - // } - - // if (position.Y < 0) - // { - // double X = FindPositionX(p, position, 0); - // position = new Point(X, 0); - // } - - // if (position.Y > this.Height) - // { - // double X = FindPositionX(p, position, this.Height); - // position = new Point(X, this.Height); - // } - - // double x = position.X - p.X; - // double y = position.Y - p.Y; - // UpdateContentRootTransform(x, y); - // } - //} - #endregion - if (this._isMouseCaptured && this.ContentRoot != null) - { - // If the child window is dragged out of the page, return - if (Application.Current != null && Application.Current.RootVisual != null && - (e.GetPosition(Application.Current.RootVisual).X < 0 || e.GetPosition(Application.Current.RootVisual).Y < 0)) - { - return; - } - - TransformGroup transformGroup = this.ContentRoot.RenderTransform as TransformGroup; - - if (transformGroup == null) - { - transformGroup = new TransformGroup(); - transformGroup.Children.Add(this.ContentRoot.RenderTransform); - } - - TranslateTransform t = new TranslateTransform(); - t.X = e.GetPosition(this.ContentRoot).X - this._clickPoint.X; - t.Y = e.GetPosition(this.ContentRoot).Y - this._clickPoint.Y; - if (transformGroup != null) - { - transformGroup.Children.Add(t); - this.ContentRoot.RenderTransform = transformGroup; - } - } - } - - /// - /// Finds the X coordinate of a point that is defined by a line. - /// - /// Starting point of the line. - /// Ending point of the line. - /// Y coordinate of the point. - /// X coordinate of the point. - private static double FindPositionX(Point p1, Point p2, double y) - { - if (y == p1.Y || p1.X == p2.X) - { - return p2.X; - } - - Debug.Assert(p1.Y != p2.Y, "Unexpected equal Y coordinates"); - - return (((y - p1.Y) * (p1.X - p2.X)) / (p1.Y - p2.Y)) + p1.X; - } - - /// - /// Finds the Y coordinate of a point that is defined by a line. - /// - /// Starting point of the line. - /// Ending point of the line. - /// X coordinate of the point. - /// Y coordinate of the point. - private static double FindPositionY(Point p1, Point p2, double x) - { - if (p1.Y == p2.Y || x == p1.X) - { - return p2.Y; - } - - Debug.Assert(p1.X != p2.X, "Unexpected equal X coordinates"); - - return (((p1.Y - p2.Y) * (x - p1.X)) / (p1.X - p2.X)) + p1.Y; - } - - /// - /// Builds the visual tree for the - /// control when a - /// new template is applied. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "No need to split the code into two parts.")] - public override void OnApplyTemplate() - { - this.UnsubscribeFromTemplatePartEvents(); - - base.OnApplyTemplate(); - - this.CloseButton = GetTemplateChild(PART_CloseButton) as ButtonBase; - - if (this.CloseButton != null) - { - if (this.HasCloseButton) - { - this.CloseButton.Visibility = Visibility.Visible; - } - else - { - this.CloseButton.Visibility = Visibility.Collapsed; - } - } - - if (this._closed != null) - { - this._closed.Completed -= new EventHandler(this.Closing_Completed); - } - - if (this._opened != null) - { - this._opened.Completed -= new EventHandler(this.Opening_Completed); - } - - this._root = GetTemplateChild(PART_Root) as FrameworkElement; - - if (this._root != null) - { - IList groups = VisualStateManager.GetVisualStateGroups(this._root); - - if (groups != null) - { - IList states = null; - - foreach (VisualStateGroup vsg in groups) - { - if (vsg.Name == FloatableWindow.VSMGROUP_Window) - { - states = vsg.States; - break; - } - } - - if (states != null) - { - foreach (VisualState state in states) - { - if (state.Name == FloatableWindow.VSMSTATE_StateClosed) - { - this._closed = state.Storyboard; - } - - if (state.Name == FloatableWindow.VSMSTATE_StateOpen) - { - this._opened = state.Storyboard; - } - } - } - } - //TODO: Figure out why I can't wire up the event below in SubscribeToTemplatePartEvents - this._root.MouseLeftButtonDown += new MouseButtonEventHandler(this.ContentRoot_MouseLeftButtonDown); - } - - this.ContentRoot = GetTemplateChild(PART_ContentRoot) as FrameworkElement; - - this._chrome = GetTemplateChild(PART_Chrome) as FrameworkElement; - - this.Overlay = GetTemplateChild(PART_Overlay) as Panel; - - this._contentPresenter = GetTemplateChild(PART_ContentPresenter) as FrameworkElement; - - this.SubscribeToTemplatePartEvents(); - this.SubscribeToStoryBoardEvents(); - this._desiredMargin = this.Margin; - this.Margin = new Thickness(0); - - // Update overlay size - if (this.IsOpen && (this.ChildWindowPopup != null)) - { - this._desiredContentHeight = this.Height; - this._desiredContentWidth = this.Width; - this.UpdateOverlaySize(); - this.UpdateRenderTransform(); - this.ChangeVisualState(); - } - } - - - /// - /// Raises the - /// event. - /// - /// The event data. - protected virtual void OnClosed(EventArgs e) - { - EventHandler handler = this.Closed; - - if (null != handler) - { - handler(this, e); - } - - this._isOpen = false; - if (!_modal) - { - this.ParentLayoutRoot.Children.Remove(this); - } - } - - /// - /// Raises the - /// event. - /// - /// The event data. - protected virtual void OnClosing(CancelEventArgs e) - { - EventHandler handler = this.Closing; - - if (null != handler) - { - handler(this, e); - } - } - - /// - /// Returns a - /// - /// for use by the Silverlight automation infrastructure. - /// - /// - /// - /// for the object. - /// - protected override AutomationPeer OnCreateAutomationPeer() - { - return new FloatableWindowAutomationPeer(this); - } - - /// - /// This method is called every time a - /// is displayed. - /// - protected virtual void OnOpened() - { - this.UpdatePosition(); - this._isOpen = true; - - if (this.Overlay != null) - { - this.Overlay.Opacity = this.OverlayOpacity; - this.Overlay.Background = this.OverlayBrush; - } - - if (!this.Focus()) - { - // If the Focus() fails it means there is no focusable element in the - // FloatableWindow. In this case we set IsTabStop to true to have the keyboard functionality - this.IsTabStop = true; - this.Focus(); - } - } - - /// - /// Executed when the opening storyboard finishes. - /// - /// Sender object. - /// Event args. - private void Opening_Completed(object sender, EventArgs e) - { - if (this._opened != null) - { - this._opened.Completed -= new EventHandler(this.Opening_Completed); - } - // AutomationPeer returns "ReadyForUserInteraction" when the FloatableWindow - // is open and all animations have been completed. - this.InteractionState = WindowInteractionState.ReadyForUserInteraction; - this.OnOpened(); - } - - /// - /// Executed when the page resizes. - /// - /// Sender object. - /// Event args. - private void Page_Resized(object sender, EventArgs e) - { - if (this.ChildWindowPopup != null) - { - this.UpdateOverlaySize(); - } - } - - /// - /// Executed when the root visual gets focus. - /// - /// Sender object. - /// Routed event args. - private void RootVisual_GotFocus(object sender, RoutedEventArgs e) - { - this.Focus(); - this.InteractionState = WindowInteractionState.ReadyForUserInteraction; - } - - public void Show() - { - ShowWindow(false); - } - - public void ShowDialog() - { - _verticalOffset = 0; - _horizontalOffset = 0; - ShowWindow(true); - } - - public void Show(double horizontalOffset, double verticalOffset) - { - _horizontalOffset = horizontalOffset; - _verticalOffset = verticalOffset; - ShowWindow(false); - } - - /// - /// Opens a and - /// returns without waiting for the - /// to close. - /// - /// - /// The child window is already in the visual tree. - /// - internal void ShowWindow(bool isModal) - { - _modal = isModal; - - // AutomationPeer returns "Running" when Show() is called - // but the FloatableWindow is not ready for user interaction: - this.InteractionState = WindowInteractionState.Running; - - this.SubscribeToEvents(); - this.SubscribeToTemplatePartEvents(); - this.SubscribeToStoryBoardEvents(); - - - // MaxHeight and MinHeight properties should not be overwritten: - this.MaxHeight = double.PositiveInfinity; - this.MaxWidth = double.PositiveInfinity; - - if (_modal) - { - if (this.ChildWindowPopup == null) - { - this.ChildWindowPopup = new Popup(); - - try - { - this.ChildWindowPopup.Child = this; - } - catch (ArgumentException) - { - // If the FloatableWindow is already in the visualtree, we cannot set it to be the child of the popup - // we are throwing a friendlier exception for this case: - this.InteractionState = WindowInteractionState.NotResponding; - throw new InvalidOperationException("Cannot call Show() on a ChildWindow that is in the visual tree. ChildWindow should be the top-most element in the .xaml file."); - } - } - - if (this.ChildWindowPopup != null && Application.Current.RootVisual != null) - { - this.ChildWindowPopup.IsOpen = true; - - this.ChildWindowPopup.HorizontalOffset = _horizontalOffset; - this.ChildWindowPopup.VerticalOffset = _verticalOffset; - - // while the FloatableWindow is open, the DialogResult is always NULL: - this._dialogresult = null; - } - } - else - { - if (ParentLayoutRoot != null) - { - var canvas = ParentLayoutRoot as Canvas; - if (canvas != null) - { - this.SetValue(Canvas.TopProperty, _verticalOffset); - this.SetValue(Canvas.LeftProperty, _horizontalOffset); - } - else - { - this.HorizontalAlignment = HorizontalAlignment.Left; - this.VerticalAlignment = VerticalAlignment.Top; - } - - this.ParentLayoutRoot.Children.Add(this); - this.BringToFront(); - } - else - { - throw new ArgumentNullException("ParentLayoutRoot", "You need to specify a root Panel element to add the window elements to."); - } - } - - // disable the underlying UI - if (RootVisual != null && _modal) - { - RootVisual.IsEnabled = false; - } - - // if the template is already loaded, display loading visuals animation - if (this.ContentRoot == null) - { - this.Loaded += (s, args) => - { - if (this.ContentRoot != null) - { - this.ChangeVisualState(); - } - }; - } - else - { - this.ChangeVisualState(); - } - } - - /// - /// Subscribes to events when the FloatableWindow is opened. - /// - private void SubscribeToEvents() - { - if (Application.Current != null && Application.Current.Host != null && Application.Current.Host.Content != null) - { - Application.Current.Exit += new EventHandler(this.Application_Exit); - Application.Current.Host.Content.Resized += new EventHandler(this.Page_Resized); - } - - this.KeyDown += new KeyEventHandler(this.ChildWindow_KeyDown); - if (_modal) - { - this.LostFocus += new RoutedEventHandler(this.ChildWindow_LostFocus); - } - this.SizeChanged += new SizeChangedEventHandler(this.ChildWindow_SizeChanged); - } - - /// - /// Subscribes to events that are on the storyboards. - /// Unsubscribing from these events happen in the event handlers individually. - /// - private void SubscribeToStoryBoardEvents() - { - if (this._closed != null) - { - this._closed.Completed += new EventHandler(this.Closing_Completed); - } - - if (this._opened != null) - { - this._opened.Completed += new EventHandler(this.Opening_Completed); - } - } - - /// - /// Subscribes to events on the template parts. - /// - private void SubscribeToTemplatePartEvents() - { - if (this.CloseButton != null) - { - this.CloseButton.Click += new RoutedEventHandler(this.CloseButton_Click); - } - - if (this._chrome != null) - { - this._chrome.MouseLeftButtonDown += new MouseButtonEventHandler(this.Chrome_MouseLeftButtonDown); - this._chrome.MouseLeftButtonUp += new MouseButtonEventHandler(this.Chrome_MouseLeftButtonUp); - this._chrome.MouseMove += new MouseEventHandler(this.Chrome_MouseMove); - } - - } - - /// - /// Unsubscribe from events when the FloatableWindow is closed. - /// - private void UnSubscribeFromEvents() - { - if (Application.Current != null && Application.Current.Host != null && Application.Current.Host.Content != null) - { - Application.Current.Exit -= new EventHandler(this.Application_Exit); - Application.Current.Host.Content.Resized -= new EventHandler(this.Page_Resized); - } - - this.KeyDown -= new KeyEventHandler(this.ChildWindow_KeyDown); - if (_modal) - { - this.LostFocus -= new RoutedEventHandler(this.ChildWindow_LostFocus); - } - this.SizeChanged -= new SizeChangedEventHandler(this.ChildWindow_SizeChanged); - } - - /// - /// Unsubscribe from the events that are subscribed on the template part elements. - /// - private void UnsubscribeFromTemplatePartEvents() - { - if (this.CloseButton != null) - { - this.CloseButton.Click -= new RoutedEventHandler(this.CloseButton_Click); - } - - if (this._chrome != null) - { - this._chrome.MouseLeftButtonDown -= new MouseButtonEventHandler(this.Chrome_MouseLeftButtonDown); - this._chrome.MouseLeftButtonUp -= new MouseButtonEventHandler(this.Chrome_MouseLeftButtonUp); - this._chrome.MouseMove -= new MouseEventHandler(this.Chrome_MouseMove); - } - } - - /// - /// Updates the size of the overlay of the window. - /// - private void UpdateOverlaySize() - { - if (_modal) - { - if (this.Overlay != null && Application.Current != null && Application.Current.Host != null && Application.Current.Host.Content != null) - { - this.Height = Application.Current.Host.Content.ActualHeight; - this.Width = Application.Current.Host.Content.ActualWidth; - this.Overlay.Height = this.Height; - this.Overlay.Width = this.Width; - - if (this.ContentRoot != null) - { - this.ContentRoot.Width = this._desiredContentWidth; - this.ContentRoot.Height = this._desiredContentHeight; - this.ContentRoot.Margin = this._desiredMargin; - } - } - } - else - { - if (this.Overlay != null) - { - this.Overlay.Visibility = Visibility.Collapsed; - } - } - } - - /// - /// Updates the position of the window in case the size of the content changes. - /// This allows FloatableWindow only scale from right and bottom. - /// - private void UpdatePosition() - { - if (this.ContentRoot != null && Application.Current != null && Application.Current.RootVisual != null) - { - GeneralTransform gt = this.ContentRoot.TransformToVisual(Application.Current.RootVisual); - - if (gt != null) - { - this._windowPosition = gt.Transform(new Point(0, 0)); - } - } - } - - /// - /// Updates the render transform applied on the overlay. - /// - private void UpdateRenderTransform() - { - if (this._root != null && this.ContentRoot != null) - { - // The Overlay part should not be affected by the render transform applied on the - // FloatableWindow. In order to achieve this, we adjust an identity matrix to represent - // the _root's transformation, invert it, apply the inverted matrix on the _root, so that - // nothing is affected by the rendertransform, and apply the original transform only on the Content - GeneralTransform gt = this._root.TransformToVisual(null); - if (gt != null) - { - Point p10 = new Point(1, 0); - Point p01 = new Point(0, 1); - Point transform10 = gt.Transform(p10); - Point transform01 = gt.Transform(p01); - - Matrix transformToRootMatrix = Matrix.Identity; - transformToRootMatrix.M11 = transform10.X; - transformToRootMatrix.M12 = transform10.Y; - transformToRootMatrix.M21 = transform01.X; - transformToRootMatrix.M22 = transform01.Y; - - MatrixTransform original = new MatrixTransform(); - original.Matrix = transformToRootMatrix; - - InvertMatrix(ref transformToRootMatrix); - MatrixTransform mt = new MatrixTransform(); - mt.Matrix = transformToRootMatrix; - - TransformGroup tg = this._root.RenderTransform as TransformGroup; - - if (tg != null) - { - tg.Children.Add(mt); - } - else - { - this._root.RenderTransform = mt; - } - - tg = this.ContentRoot.RenderTransform as TransformGroup; - - if (tg != null) - { - tg.Children.Add(original); - } - else - { - this.ContentRoot.RenderTransform = original; - } - } - } - } - - /// - /// Updates the ContentRootTranslateTransform. - /// - /// X coordinate of the transform. - /// Y coordinate of the transform. - private void UpdateContentRootTransform(double X, double Y) - { - if (this._contentRootTransform == null) - { - this._contentRootTransform = new TranslateTransform(); - this._contentRootTransform.X = X; - this._contentRootTransform.Y = Y; - - TransformGroup transformGroup = this.ContentRoot.RenderTransform as TransformGroup; - - if (transformGroup == null) - { - transformGroup = new TransformGroup(); - transformGroup.Children.Add(this.ContentRoot.RenderTransform); - } - transformGroup.Children.Add(this._contentRootTransform); - this.ContentRoot.RenderTransform = transformGroup; - } - else - { - this._contentRootTransform.X += X; - this._contentRootTransform.Y += Y; - } - } - - - private Storyboard GetVisualStateStoryboard(string visualStateGroupName, string visualStateName) - { - foreach (VisualStateGroup g in VisualStateManager.GetVisualStateGroups((FrameworkElement)this.ContentRoot.Parent)) - { - if (g.Name != visualStateGroupName) continue; - foreach (VisualState s in g.States) - { - if (s.Name != visualStateName) continue; - return s.Storyboard; - } - } - return null; - } - - #endregion Methods - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Controls/FloatableWindow/FloatableWindowAutomationPeer.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Controls/FloatableWindow/FloatableWindowAutomationPeer.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,414 +0,0 @@ -// (c) Copyright Microsoft Corporation. -// This source is subject to the Microsoft Public License (Ms-PL). -// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. -// All other rights reserved. - -using System.Windows.Automation.Provider; -using System.Windows.Controls; -using System.Windows.Media; - -namespace System.Windows.Automation.Peers -{ - public class FloatableWindowAutomationPeer : FrameworkElementAutomationPeer, IWindowProvider, ITransformProvider - { - #region Data - - /// - /// Specifies whether the FloatableWindow is the top most element. - /// - private bool _isTopMost; - - #endregion Data - - #region Properties - - /// - /// Gets or sets a value indicating whether the FloatableWindow is the top most element. - /// - private bool IsTopMostPrivate - { - get - { - return this._isTopMost; - } - set - { - if (this._isTopMost != value) - { - this._isTopMost = value; - this.RaisePropertyChangedEvent(WindowPatternIdentifiers.IsTopmostProperty, !this._isTopMost, this._isTopMost); - } - } - } - - /// - /// Gets the owning FloatableWindow. - /// - private FloatableWindow OwningFloatableWindow - { - get - { - return (FloatableWindow)Owner; - } - } - - #endregion Properties - - public FloatableWindowAutomationPeer(FloatableWindow owner) - : base(owner) - { - if (owner == null) - { - throw new ArgumentNullException("owner"); - } - this.RefreshIsTopMostProperty(); - } - - #region AutomationPeer overrides - - /// - /// Gets the control pattern for this - /// . - /// - /// - /// One of the enumeration values. - /// - /// - /// The object that implements the pattern interface, or null if the - /// specified pattern interface is not implemented by this peer. - /// - public override object GetPattern(PatternInterface patternInterface) - { - if (patternInterface == PatternInterface.Transform || patternInterface == PatternInterface.Window) - { - return this; - } - - return base.GetPattern(patternInterface); - } - - /// - /// Gets the - /// - /// for the element associated with this - /// . - /// Called by - /// . - /// - /// A value of the enumeration. - protected override AutomationControlType GetAutomationControlTypeCore() - { - return AutomationControlType.Window; - } - - /// - /// Gets the name of the class for the object associated with this - /// . - /// Called by - /// . - /// - /// - /// A string value that represents the type of the child window. - /// - protected override string GetClassNameCore() - { - return this.Owner.GetType().Name; - } - - /// - /// Gets the text label of the - /// that is - /// associated with this - /// . - /// Called by - /// . - /// - /// - /// The text label of the element that is associated with this - /// automation peer. - /// - protected override string GetNameCore() - { - string name = base.GetNameCore(); - if (string.IsNullOrEmpty(name)) - { - AutomationPeer labeledBy = GetLabeledByCore(); - if (labeledBy != null) - { - name = labeledBy.GetName(); - } - - if (string.IsNullOrEmpty(name) && this.OwningFloatableWindow.Title != null) - { - name = this.OwningFloatableWindow.Title.ToString(); - } - } - return name; - } - - #endregion AutomationPeer overrides - - #region IWindowProvider - - /// - /// Gets the interaction state of the window. - /// - /// - /// The interaction state of the control, as a value of the enumeration. - /// - WindowInteractionState IWindowProvider.InteractionState - { - get - { - return this.OwningFloatableWindow.InteractionState; - } - } - - /// - /// Gets a value indicating whether the window is modal. - /// - /// - /// True in all cases. - /// - bool IWindowProvider.IsModal - { - get { return true; } - } - - /// - /// Gets a value indicating whether the window is the topmost - /// element in the z-order of layout. - /// - /// - /// True if the window is topmost; otherwise, false. - /// - bool IWindowProvider.IsTopmost - { - get - { - return this.IsTopMostPrivate; - } - } - - /// - /// Gets a value indicating whether the window can be maximized. - /// - /// False in all cases. - bool IWindowProvider.Maximizable - { - get { return false; } - } - - /// - /// Gets a value indicating whether the window can be minimized. - /// - /// False in all cases. - bool IWindowProvider.Minimizable - { - get { return false; } - } - - /// - /// Gets the visual state of the window. - /// - /// - /// - /// in all cases. - /// - WindowVisualState IWindowProvider.VisualState - { - get - { - return WindowVisualState.Normal; - } - } - - /// - /// Closes the window. - /// - void IWindowProvider.Close() - { - this.OwningFloatableWindow.Close(); - } - - /// - /// Changes the visual state of the window (such as minimizing or - /// maximizing it). - /// - /// - /// The visual state of the window to change to, as a value of the - /// enumeration. - /// - void IWindowProvider.SetVisualState(WindowVisualState state) - { - } - - /// - /// Blocks the calling code for the specified time or until the - /// associated process enters an idle state, whichever completes first. - /// - /// - /// The amount of time, in milliseconds, to wait for the associated - /// process to become idle. - /// - /// - /// True if the window has entered the idle state; false if the timeout - /// occurred. - /// - bool IWindowProvider.WaitForInputIdle(int milliseconds) - { - return false; - } - - #endregion IWindowProvider - - #region ITransformProvider - - /// - /// Moves the control. - /// - /// - /// The absolute screen coordinates of the left side of the control. - /// - /// - /// The absolute screen coordinates of the top of the control. - /// - void ITransformProvider.Move(double x, double y) - { - if (x < 0) - { - x = 0; - } - - if (y < 0) - { - y = 0; - } - - if (x > this.OwningFloatableWindow.Width) - { - x = this.OwningFloatableWindow.Width; - } - - if (y > this.OwningFloatableWindow.Height) - { - y = this.OwningFloatableWindow.Height; - } - - FrameworkElement contentRoot = this.OwningFloatableWindow.ContentRoot; - - if (contentRoot != null) - { - GeneralTransform gt = contentRoot.TransformToVisual(null); - - if (gt != null) - { - Point p = gt.Transform(new Point(0, 0)); - - TransformGroup transformGroup = contentRoot.RenderTransform as TransformGroup; - - if (transformGroup == null) - { - transformGroup = new TransformGroup(); - transformGroup.Children.Add(contentRoot.RenderTransform); - } - - TranslateTransform t = new TranslateTransform(); - t.X = x - p.X; - t.Y = y - p.Y; - - if (transformGroup != null) - { - transformGroup.Children.Add(t); - contentRoot.RenderTransform = transformGroup; - } - } - } - } - - /// - /// Resizes the control. - /// - /// The new width of the window, in pixels. - /// - /// The new height of the window, in pixels. - /// - void ITransformProvider.Resize(double width, double height) - { - } - - /// - /// Rotates the control. - /// - /// - /// The number of degrees to rotate the control. A positive number - /// rotates the control clockwise. A negative number rotates the - /// control counterclockwise. - /// - void ITransformProvider.Rotate(double degrees) - { - } - - /// - /// Gets a value indicating whether the element can be moved. - /// - /// True in all cases. - bool ITransformProvider.CanMove - { - get { return true; } - } - - /// - /// Gets a value indicating whether the element can be resized. - /// - /// False in all cases. - bool ITransformProvider.CanResize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the element can be rotated. - /// - /// False in all cases. - bool ITransformProvider.CanRotate - { - get { return false; } - } - - #endregion ITransformProvider - - #region Methods - - /// - /// Returns if the FloatableWindow is the top most element. - /// - /// Bool value. - private bool GetIsTopMostCore() - { - return !(this.OwningFloatableWindow.InteractionState == WindowInteractionState.BlockedByModalWindow); - } - - /// - /// Raises PropertyChangedEvent for WindowInteractionStateProperty. - /// - /// Old WindowInteractionStateProperty. - /// New WindowInteractionStateProperty. - internal void RaiseInteractionStatePropertyChangedEvent(WindowInteractionState oldValue, WindowInteractionState newValue) - { - this.RaisePropertyChangedEvent(WindowPatternIdentifiers.WindowInteractionStateProperty, oldValue, newValue); - this.RefreshIsTopMostProperty(); - } - - /// - /// Updates the IsTopMostPrivate property. - /// - private void RefreshIsTopMostProperty() - { - this.IsTopMostPrivate = this.GetIsTopMostCore(); - } - - #endregion Methods - } -} - diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Converters/BoolToValueConverter.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Converters/BoolToValueConverter.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,31 +0,0 @@ -// original code: http://geekswithblogs.net/codingbloke/archive/2010/05/28/a-generic-boolean-value-converter.aspx - -using System; -using System.Globalization; -using System.Windows.Data; -using System.Windows.Markup; - -namespace SilverlightGlimpse.Converters -{ - public class BoolToValueConverter : MarkupExtension, IValueConverter - { - public T FalseValue { get; set; } - public T TrueValue { get; set; } - - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value == null) return FalseValue; - return (bool)value ? TrueValue : FalseValue; - } - - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null && value.Equals(TrueValue); - } - - public override object ProvideValue(IServiceProvider serviceProvider) - { - return this; - } - } -} diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Converters/BoolToVisibilityConverter.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Converters/BoolToVisibilityConverter.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6 +0,0 @@ -using System.Windows; - -namespace SilverlightGlimpse.Converters -{ - public class BoolToVisibilityConverter : BoolToValueConverter { } -} diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Diagnostics/PropertyPathHelper.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Diagnostics/PropertyPathHelper.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,30 +0,0 @@ -using System.Windows; -using System.Windows.Data; - -namespace SilverlightGlimpse.Diagnostics -{ - public static class PropertyPathHelper - { - private static readonly Dummy _dummy = new Dummy(); - - public static object GetValue(object source, string propertyPath) - { - var binding = new Binding(propertyPath) - { - Mode = BindingMode.OneTime, - Source = source - }; - BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding); - return _dummy.GetValue(Dummy.ValueProperty); - } - - private class Dummy : DependencyObject - { - public static readonly DependencyProperty ValueProperty = - DependencyProperty.Register("Value", - typeof (object), - typeof (Dummy), - new PropertyMetadata(null)); - } - } -} diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Diagnostics/Stopwatch.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Diagnostics/Stopwatch.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,29 +0,0 @@ -using System; - -namespace SilverlightGlimpse.Diagnostics -{ - public class Stopwatch - { - private long _start; - private long _end; - - public void Start() - { - _start = DateTime.Now.Ticks; - } - - public void Stop() - { - _end = DateTime.Now.Ticks; - } - - public TimeSpan ElapsedTime { get { return new TimeSpan(_end - _start); }} - - public static Stopwatch StartNew() - { - var stopwatch = new Stopwatch(); - stopwatch.Start(); - return stopwatch; - } - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Interfaces/IBrokenBindingsService.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Interfaces/IBrokenBindingsService.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using System.Windows; -using SilverlightGlimpse.Models; - -namespace SilverlightGlimpse.Interfaces -{ - public interface IBrokenBindingsService - { - void LoadBrokenBindings(UIElement uiElement, IList bindingErrors); - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Interfaces/ILogWriter.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Interfaces/ILogWriter.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,9 +0,0 @@ -using System.Collections; - -namespace SilverlightGlimpse.Interfaces -{ - public interface ILogWriter - { - void Write(IList log, int maxLogItems, string text, params object[] args); - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Models/BindingError.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Models/BindingError.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,47 +0,0 @@ -namespace SilverlightGlimpse.Models -{ - public class BindingError - { - #region Fields - - private readonly string _controlName = string.Empty; - - #endregion - - #region Constructor - - public BindingError(string controlName, string controlTypeName, string propertyName, string path) - { - _controlName = controlName; - ControlType = controlTypeName; - PropertyName = propertyName; - Path = path; - } - - #endregion - - #region Properties - - public string ControlName { get { return string.IsNullOrEmpty(_controlName) ? "(none)" : _controlName; } } - public string ControlType { get; private set; } - public string Path { get; private set; } - public string PropertyName { get; private set; } - public string ToStringProperty { get { return ToString(); } } - - #endregion - - #region Methods - - public override string ToString() - { - return string.Format( - "Control Name: {0}, Type: {1}, Property: {2}, Path: {3}", - ControlName, - ControlType, - PropertyName, - Path); - } - - #endregion - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Models/ValidationWrapper.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Models/ValidationWrapper.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ -using System.Windows.Controls; - -namespace SilverlightGlimpse.Models -{ - public class ValidationWrapper - { - #region Constructor - - public ValidationWrapper( - ValidationErrorEventAction enumAction, - string controlName, - string controlType, - string errorContent) - { - Action = enumAction; - ControlName = controlName; - ControlType = controlType; - ErrorContent = errorContent; - } - - #endregion - - #region Properties - - public ValidationErrorEventAction Action { get; private set; } - public string ControlName { get; private set; } - public string ControlType { get; private set; } - public string ErrorContent { get; private set; } - public string ToStringProperty { get { return ToString(); } } - - #endregion - - #region Methods - - public override string ToString() - { - return string.Format( - "Validation Action: {0}, Name: {1} Type: {2}, ErrorContent: {3}", - Action, - ControlName, - ControlType, - ErrorContent); - } - - - #endregion - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Properties/AppManifest.xml --- a/SilverlightGlimpse/SilverlightGlimpse/Properties/AppManifest.xml Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6 +0,0 @@ - - - - diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Properties/AssemblyInfo.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Properties/AssemblyInfo.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SilverlightGlimpse")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SilverlightGlimpse")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("52ef33ca-e923-41ef-a7c8-98ec475bc956")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Services/BrokenBindingsService.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Services/BrokenBindingsService.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Reflection; -using System.Windows; -using System.Windows.Media; -using SilverlightGlimpse.Diagnostics; -using SilverlightGlimpse.Interfaces; -using SilverlightGlimpse.Models; - -namespace SilverlightGlimpse.Services -{ - public class BrokenBindingsService : IBrokenBindingsService - { - public void LoadBrokenBindings(UIElement uiElement, IList bindingErrors) - { - var fe = uiElement as FrameworkElement; - if (fe == null) return; - - foreach (var fi in fe.GetType().GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static)) - { - if (!ReferenceEquals(fi.FieldType, typeof(DependencyProperty))) continue; - - var be = fe.GetBindingExpression((DependencyProperty)fi.GetValue(null)); - - if (be == null || be.ParentBinding.Source != null || - be.ParentBinding.RelativeSource != null) continue; - - var isInherited = false; - - if (fe.DataContext != null && !string.IsNullOrEmpty(be.ParentBinding.Path.Path)) - { - foreach (var propertyInfo in fe.DataContext.GetType().GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Instance)) - { - if (String.Compare(propertyInfo.Name, be.ParentBinding.Path.Path) != 0) continue; - isInherited = true; - break; - } - } - - if (isInherited) break; - - //this code handles empty bindings on the Button controls - // unsure as to why the Button has an empty or unresolved binding of textblock type... - if ((fe.Name == "") - && (fe.GetType().Name == "TextBlock") - && (fi.Name == "TextProperty") - && (be.ParentBinding.Path.Path == "")) - { - continue; - } - - var value = PropertyPathHelper.GetValue(fe, "Text"); - if ((value!=null) && value.ToString() != string.Empty) - continue; - - var brokenBinding = new BindingError( - fe.Name, - fe.GetType().Name, - fi.Name, - be.ParentBinding.Path.Path); - - bindingErrors.Add(brokenBinding); - Debug.WriteLine("Broken Binding: {0}", brokenBinding); - } - - int children = VisualTreeHelper.GetChildrenCount(fe); - - for (int j = 0; j <= children - 1; j++) - { - var child = VisualTreeHelper.GetChild(fe, j) as FrameworkElement; - - if (child != null) - { - LoadBrokenBindings(child, bindingErrors); - } - } - } - } -} diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Services/DebugMonitor.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Services/DebugMonitor.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,404 +0,0 @@ -//Original code: http://www.codeproject.com/Articles/13345/DbMon-NET-A-simple-NET-OutputDebugString-capturer -//Author: Christian Birkl http://stackoverflow.com/users/144377/christian-birkl - -using System; -using System.Threading; -using System.Runtime.InteropServices; - -namespace SilverlightGlimpse.Services -{ - /// - /// Delegate used when firing DebugMonitor.OnOutputDebug event - /// - public delegate void OnOutputDebugStringHandler(int pid, string text); - - /// - /// This class captures all strings passed to OutputDebugString when - /// the application is not debugged. - /// - /// - /// This class is a port of Microsofts Visual Studio's C++ example "dbmon", which - /// can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcsample98/html/vcsmpdbmon.asp. - /// - /// - /// - /// public static void Main(string[] args) { - /// DebugMonitor.Start(); - /// DebugMonitor.OnOutputDebugString += new OnOutputDebugStringHandler(OnOutputDebugString); - /// Console.WriteLine("Press 'Enter' to exit."); - /// Console.ReadLine(); - /// DebugMonitor.Stop(); - /// } - /// - /// private static void OnOutputDebugString(int pid, string text) { - /// Console.WriteLine(DateTime.Now + ": " + text); - /// } - /// - /// - public sealed class DebugMonitor - { - - /// - /// Private constructor so no one can create a instance - /// of this static class - /// - private DebugMonitor() - { - } - - #region Win32 API Imports - - [StructLayout(LayoutKind.Sequential)] - private struct SECURITY_DESCRIPTOR - { - public byte revision; - public byte size; - public short control; - public IntPtr owner; - public IntPtr group; - public IntPtr sacl; - public IntPtr dacl; - } - - [StructLayout(LayoutKind.Sequential)] - private struct SECURITY_ATTRIBUTES - { - public int nLength; - public IntPtr lpSecurityDescriptor; - public int bInheritHandle; - } - - [Flags] - private enum PageProtection : uint - { - NoAccess = 0x01, - Readonly = 0x02, - ReadWrite = 0x04, - WriteCopy = 0x08, - Execute = 0x10, - ExecuteRead = 0x20, - ExecuteReadWrite = 0x40, - ExecuteWriteCopy = 0x80, - Guard = 0x100, - NoCache = 0x200, - WriteCombine = 0x400, - } - - - private const int WAIT_OBJECT_0 = 0; - private const uint INFINITE = 0xFFFFFFFF; - private const int ERROR_ALREADY_EXISTS = 183; - - private const uint SECURITY_DESCRIPTOR_REVISION = 1; - - private const uint SECTION_MAP_READ = 0x0004; - - [DllImport("kernel32.dll", SetLastError = true)] - private static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint - dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, - uint dwNumberOfBytesToMap); - - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern bool InitializeSecurityDescriptor(ref SECURITY_DESCRIPTOR sd, uint dwRevision); - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern bool SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR sd, bool daclPresent, IntPtr dacl, bool daclDefaulted); - - [DllImport("kernel32.dll")] - private static extern IntPtr CreateEvent(ref SECURITY_ATTRIBUTES sa, bool bManualReset, bool bInitialState, string lpName); - - [DllImport("kernel32.dll")] - private static extern bool PulseEvent(IntPtr hEvent); - - [DllImport("kernel32.dll")] - private static extern bool SetEvent(IntPtr hEvent); - - [DllImport("kernel32.dll", SetLastError = true)] - private static extern IntPtr CreateFileMapping(IntPtr hFile, - ref SECURITY_ATTRIBUTES lpFileMappingAttributes, PageProtection flProtect, uint dwMaximumSizeHigh, - uint dwMaximumSizeLow, string lpName); - - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool CloseHandle(IntPtr hHandle); - - [DllImport("kernel32", SetLastError = true, ExactSpelling = true)] - private static extern Int32 WaitForSingleObject(IntPtr handle, uint milliseconds); - #endregion - - /// - /// Fired if an application calls OutputDebugString - /// - public static event OnOutputDebugStringHandler OnOutputDebugString; - - /// - /// Event handle for slot 'DBWIN_BUFFER_READY' - /// - private static IntPtr m_AckEvent = IntPtr.Zero; - - /// - /// Event handle for slot 'DBWIN_DATA_READY' - /// - private static IntPtr m_ReadyEvent = IntPtr.Zero; - - /// - /// Handle for our shared file - /// - private static IntPtr m_SharedFile = IntPtr.Zero; - - /// - /// Handle for our shared memory - /// - private static IntPtr m_SharedMem = IntPtr.Zero; - - /// - /// Our capturing thread - /// - private static Thread m_Capturer = null; - - /// - /// Our synchronization root - /// - private static object m_SyncRoot = new object(); - - /// - /// Mutex for singleton check - /// - /// TODO: Work out a mutex equivalent for Silverlight - //private static Mutex m_Mutex = null; - - /// - /// Starts this debug monitor - /// - public static void Start() - { - lock (m_SyncRoot) - { - if (m_Capturer != null) - throw new Exception("This DebugMonitor is already started."); - - // Check for supported operating system. Mono (at least with *nix) won't support - // our P/Invoke calls. - if (Environment.OSVersion.ToString().IndexOf("Microsoft") == -1) - throw new NotSupportedException("This DebugMonitor is only supported on Microsoft operating systems."); - - // Check for multiple instances. As the README.TXT of the msdn - // example notes it is possible to have multiple debug monitors - // listen on OutputDebugString, but the message will be randomly - // distributed among all running instances so this won't be - // such a good idea. - // TODO: Work out a mutex equivalent for Silverlight - //bool createdNew = false; - //m_Mutex = new Mutex(false, typeof(DebugMonitor).Namespace, out createdNew); - //if (!createdNew) - // throw new Exception("There is already an instance of 'DbMon.NET' running."); - - SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR(); - - // Initialize the security descriptor. - if (!InitializeSecurityDescriptor(ref sd, SECURITY_DESCRIPTOR_REVISION)) - { - throw CreateApplicationException("Failed to initializes the security descriptor."); - } - - // Set information in a discretionary access control list - if (!SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false)) - { - throw CreateApplicationException("Failed to initializes the security descriptor"); - } - - SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); - - // Create the event for slot 'DBWIN_BUFFER_READY' - m_AckEvent = CreateEvent(ref sa, false, false, "DBWIN_BUFFER_READY"); - if (m_AckEvent == IntPtr.Zero) - { - throw CreateApplicationException("Failed to create event 'DBWIN_BUFFER_READY'"); - } - - // Create the event for slot 'DBWIN_DATA_READY' - m_ReadyEvent = CreateEvent(ref sa, false, false, "DBWIN_DATA_READY"); - if (m_ReadyEvent == IntPtr.Zero) - { - throw CreateApplicationException("Failed to create event 'DBWIN_DATA_READY'"); - } - - // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'. - m_SharedFile = CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "DBWIN_BUFFER"); - if (m_SharedFile == IntPtr.Zero) - { - throw CreateApplicationException("Failed to create a file mapping to slot 'DBWIN_BUFFER'"); - } - - // Create a view for this file mapping so we can access it - m_SharedMem = MapViewOfFile(m_SharedFile, SECTION_MAP_READ, 0, 0, 512); - if (m_SharedMem == IntPtr.Zero) - { - throw CreateApplicationException("Failed to create a mapping view for slot 'DBWIN_BUFFER'"); - } - - // Start a new thread where we can capture the output - // of OutputDebugString calls so we don't block here. - m_Capturer = new Thread(new ThreadStart(Capture)); - m_Capturer.Start(); - } - } - - /// - /// Captures - /// - private static void Capture() - { - try - { - // Everything after the first DWORD is our debugging text - IntPtr pString = new IntPtr( - m_SharedMem.ToInt32() + Marshal.SizeOf(typeof(int)) - ); - - while (true) - { - SetEvent(m_AckEvent); - - int ret = WaitForSingleObject(m_ReadyEvent, INFINITE); - - // if we have no capture set it means that someone - // called 'Stop()' and is now waiting for us to exit - // this endless loop. - if (m_Capturer == null) - break; - - if (ret == WAIT_OBJECT_0) - { - // The first DWORD of the shared memory buffer contains - // the process ID of the client that sent the debug string. - FireOnOutputDebugString( - Marshal.ReadInt32(m_SharedMem), - Marshal.PtrToStringAnsi(pString)); - } - } - - } - catch - { - throw; - - // Cleanup - } - finally - { - Dispose(); - } - } - - private static void FireOnOutputDebugString(int pid, string text) - { - // Raise event if we have any listeners - if (OnOutputDebugString == null) - return; - -#if !DEBUG - try - { -#endif - OnOutputDebugString(pid, text); -#if !DEBUG - } - catch (Exception ex) - { - Console.WriteLine("An 'OnOutputDebugString' handler failed to execute: " + ex.ToString()); - } -#endif - } - - /// - /// Dispose all resources - /// - private static void Dispose() - { - // Close AckEvent - if (m_AckEvent != IntPtr.Zero) - { - if (!CloseHandle(m_AckEvent)) - { - throw CreateApplicationException("Failed to close handle for 'AckEvent'"); - } - m_AckEvent = IntPtr.Zero; - } - - // Close ReadyEvent - if (m_ReadyEvent != IntPtr.Zero) - { - if (!CloseHandle(m_ReadyEvent)) - { - throw CreateApplicationException("Failed to close handle for 'ReadyEvent'"); - } - m_ReadyEvent = IntPtr.Zero; - } - - // Close SharedFile - if (m_SharedFile != IntPtr.Zero) - { - if (!CloseHandle(m_SharedFile)) - { - throw CreateApplicationException("Failed to close handle for 'SharedFile'"); - } - m_SharedFile = IntPtr.Zero; - } - - - // Unmap SharedMem - if (m_SharedMem != IntPtr.Zero) - { - if (!UnmapViewOfFile(m_SharedMem)) - { - throw CreateApplicationException("Failed to unmap view for slot 'DBWIN_BUFFER'"); - } - m_SharedMem = IntPtr.Zero; - } - - //TODO: Work out replacement for Mutex in Silverlight - // Close our mutex - //if (m_Mutex != null) - //{ - // m_Mutex.Close(); - // m_Mutex = null; - //} - } - - /// - /// Stops this debug monitor. This call we block the executing thread - /// until this debug monitor is stopped. - /// - public static void Stop() - { - lock (m_SyncRoot) - { - if (m_Capturer == null) - throw new ObjectDisposedException("DebugMonitor", "This DebugMonitor is not running."); - m_Capturer = null; - PulseEvent(m_ReadyEvent); - while (m_AckEvent != IntPtr.Zero) - ; - } - } - - /// - /// Helper to create a new exception, which has automaticly the - /// last win 32 error code appended. - /// - /// text - private static Exception CreateApplicationException(string text) - { - if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text", "'text' may not be empty or null."); - - return new Exception( - string.Format("{0}. Last Win32 Error was {1}", - text, - Marshal.GetLastWin32Error())); - } - - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Services/Glimpse.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Services/Glimpse.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,193 +0,0 @@ -using System; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Threading; -using SilverlightGlimpse.Diagnostics; -using SilverlightGlimpse.Interfaces; -using SilverlightGlimpse.Views; -using SilverlightGlimpse.Models; -using System.Windows.Media; - -namespace SilverlightGlimpse.Services -{ - public class Glimpse - { - #region Fields - - private static Glimpse _instance; - private DispatcherTimer _refreshBindingCountTimer; - private static readonly TimeSpan FiveSeconds = new TimeSpan(0, 0, 0, 5); - private const int MAX_LOG_ITEMS = 9; - private const string SILVERLIGHT_GLIMPSE = "Silverlight Glimpse"; - private readonly ILogWriter _logWriter; - private readonly IBrokenBindingsService _brokenBindingsService; - - #endregion - - #region Private constructor - - private Glimpse(ILogWriter logWriter, IBrokenBindingsService brokenBindingsService) - { - BindingErrors = new ObservableCollection(); - ValidationErrors = new ObservableCollection(); - Exceptions = new ObservableCollection(); - Log = new ObservableCollection(); - _logWriter = logWriter; - _brokenBindingsService = brokenBindingsService; - } - - #endregion - - #region Properties - - public static Glimpse Service { get { return _instance ?? (_instance = new Glimpse(new LogWriter(), new BrokenBindingsService())); } } - internal Application App { get; private set; } - internal FloatableWindow GlimpseWindow { get; set;} - internal string Title { get; set; } - public ObservableCollection BindingErrors { get; private set; } - public ObservableCollection ValidationErrors { get; private set; } - public ObservableCollection Exceptions { get; private set; } - internal FrameworkElement RootVisual { get; private set; } - internal TimeSpan BindingsRefreshRate { get; private set; } - public ObservableCollection Log { get; private set; } - public bool IsInDebugMode - { - get { -#if DEBUG - return true; -#endif -#pragma warning disable 162 - return false; -#pragma warning restore 162 - } - } - - #endregion - - #region Methods - - // Used when application fails to load a rootpage due to an exception. - // Silverlight Glimpse becomes the new rootpage. - public void DisplayLoadFailure(Application app, Exception ex) - { - var source = ex.StackTrace.Substring(0, ex.StackTrace.IndexOf(Environment.NewLine, StringComparison.Ordinal)); - - App = app; - App.RootVisual = new LoadExceptionViewer(ex, source); - Title = SILVERLIGHT_GLIMPSE; - Debug.WriteLine("{0} had exception. {1}", Title, ex); - } - - - // Normal loading of Silverlight Glimpse. - public void Load(Application app, TimeSpan bindingsRefreshRate = default(TimeSpan)) - { - App = app; - RootVisual = App.RootVisual as FrameworkElement; - if (RootVisual == null) throw new NullReferenceException("The Application provided did not have a valid RootVisual object"); - Title = SILVERLIGHT_GLIMPSE; - BindingsRefreshRate = (bindingsRefreshRate == default(TimeSpan)) ? FiveSeconds : bindingsRefreshRate; - - RootVisual.BindingValidationError += HostRootVisual_BindingValidationError; - App.UnhandledException += Application_UnhandledException; - - GlimpseWindow = new FloatableWindow - { - Title = Title, - Content = new GlimpseViewer(), - ParentLayoutRoot = (Panel) VisualTreeHelper.GetChild(RootVisual, 0) - }; - - if (Double.IsNaN(RootVisual.Width)) - { - //if the host control is autosized (consumes the browser window) then locate Glimpse in the top, left - GlimpseWindow.Show(); - } - else - { - //if the host is fixed size then attempt to locate the popup control in the upper right corner - var dblLeft = RootVisual.Width - 200; - - if (dblLeft < 0) - dblLeft = 0; - - GlimpseWindow.Show(dblLeft, 10); - } - - _brokenBindingsService.LoadBrokenBindings(RootVisual, BindingErrors); - - _refreshBindingCountTimer = new DispatcherTimer(); - _refreshBindingCountTimer.Tick += RefreshBindingCountTimer_Tick; - _refreshBindingCountTimer.Interval = BindingsRefreshRate; - _refreshBindingCountTimer.Start(); - } - - public void Clear() - { - BindingErrors.Clear(); - Log.Clear(); - ValidationErrors.Clear(); - Exceptions.Clear(); - } - - #endregion - - #region Events handlers - - // Bindings - private void RefreshBindingCountTimer_Tick(object sender, EventArgs e) - { - var stopwatch = Stopwatch.StartNew(); - - _refreshBindingCountTimer.Stop(); - - BindingErrors.Clear(); - _brokenBindingsService.LoadBrokenBindings(RootVisual, BindingErrors); - - stopwatch.Stop(); - _logWriter.Write(Log, MAX_LOG_ITEMS, "Refreshing the binding errors took {0} {1}", stopwatch.ElapsedTime.Milliseconds, "ms"); - - _refreshBindingCountTimer.Start(); - } - - // Validation - private void HostRootVisual_BindingValidationError(object sender, ValidationErrorEventArgs e) - { - var controlName = "(none)"; - var control = e.OriginalSource as Control; - - if (control != null && !string.IsNullOrEmpty(control.Name)) - { - controlName = control.Name; - } - - ValidationErrors.Add( - new ValidationWrapper( - e.Action, - controlName, - e.OriginalSource.GetType().Name, - e.Error.ErrorContent.ToString())); - } - - // Exceptions - private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) - { - Debug.WriteLine("{0} had exception. {1}", Title, e.ExceptionObject); - - Exception ex = e.ExceptionObject; - - while (ex != null) - { - // TODO: Decide whether inner exceptions should be viewable separately - this.Exceptions.Add(ex); - ex = ex.InnerException; - } - - e.Handled = true; - } - - #endregion - } -} \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Services/LogWriter.cs --- a/SilverlightGlimpse/SilverlightGlimpse/Services/LogWriter.cs Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,16 +0,0 @@ -using System; -using System.Collections; -using SilverlightGlimpse.Interfaces; - -namespace SilverlightGlimpse.Services -{ - public class LogWriter : ILogWriter - { - public void Write(IList log, int maxLogItems, string text, params object[] args) - { - var date = DateTime.Now.ToString("HH:mm:ss.ffff"); - log.Add(string.Concat(date, "\t", string.Format(text, args))); - if (log.Count > maxLogItems) log.RemoveAt(0); - } - } -} diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/SilverlightGlimpse.csproj --- a/SilverlightGlimpse/SilverlightGlimpse/SilverlightGlimpse.csproj Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,157 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {BB51026B-2864-4389-AACA-0BBDF1926E46} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - SilverlightGlimpse - SilverlightGlimpse - Silverlight - v5.0 - $(TargetFrameworkVersion) - true - - - true - true - SilverlightGlimpse.xap - Properties\AppManifest.xml - SilverlightGlimpse.App - SilverlightGlimpseTestPage.html - true - true - false - Properties\OutOfBrowserSettings.xml - false - true - - - - - - v3.5 - - - true - full - false - Bin\Debug - DEBUG;TRACE;SILVERLIGHT - true - true - prompt - 4 - - - pdbonly - true - Bin\Release - TRACE;SILVERLIGHT - true - true - prompt - 4 - - - - - - - - ..\Libs\System.Windows.Controls.dll - - - - - - - - - - - BindingsViewer.xaml - - - ValidationsViewer.xaml - - - GlimpseViewer.xaml - - - LoadExceptionViewer.xaml - - - ExceptionsViewer.xaml - - - - - LogViewer.xaml - - - - - - - - - - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - - - - - - - - - - - - - - - - \ No newline at end of file diff -r 8cb4f36717e9 -r 4cfdecdb1d12 SilverlightGlimpse/SilverlightGlimpse/Themes/generic.xaml --- a/SilverlightGlimpse/SilverlightGlimpse/Themes/generic.xaml Sun May 06 12:14:53 2012 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,352 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -