Example #1
0
        internal HwndStylusInputProvider(HwndSource source)
        {
            InputManager inputManager = InputManager.Current;
            StylusLogic stylusLogic = inputManager.StylusLogic;

            IntPtr sourceHandle;

            (new UIPermission(PermissionState.Unrestricted)).Assert();
            try //Blessed Assert this is for RegisterInputManager and RegisterHwndforinput
            {
                // Register ourselves as an input provider with the input manager.
                _site = new SecurityCriticalDataClass<InputProviderSite>(inputManager.RegisterInputProvider(this));

                sourceHandle = source.Handle;
            }
            finally
            {
                UIPermission.RevertAssert();
            }

            stylusLogic.RegisterHwndForInput(inputManager, source);
            _source = new SecurityCriticalDataClass<HwndSource>(source);
            _stylusLogic = new SecurityCriticalDataClass<StylusLogic>(stylusLogic);

            // Enables multi-touch input
            UnsafeNativeMethods.SetProp(new HandleRef(this, sourceHandle), "MicrosoftTabletPenServiceProperty", new HandleRef(null, new IntPtr(MultiTouchEnabledFlag)));
        }
        internal MediaContextNotificationWindow(MediaContext ownerMediaContext)
        {
            // Remember the pointer to the owner MediaContext that we'll forward the broadcasts to.
            _ownerMediaContext = ownerMediaContext; 

            // Create a top-level, invisible window so we can get the WM_DWMCOMPOSITIONCHANGED 
            // and other DWM notifications that are broadcasted to top-level windows only. 
            HwndWrapper hwndNotification;
            hwndNotification = new HwndWrapper(0, NativeMethods.WS_POPUP, 0, 0, 0, 0, 0, "MediaContextNotificationWindow", IntPtr.Zero, null); 

            _hwndNotificationHook = new HwndWrapperHook(MessageFilter);

            _hwndNotification = new SecurityCriticalDataClass<HwndWrapper>(hwndNotification); 
            _hwndNotification.Value.AddHook(_hwndNotificationHook);
 
            _isDisposed = false; 

            // 
            // On Vista, we need to know when the Magnifier goes on and off
            // in order to switch to and from software rendering because the
            // Vista Magnifier cannot magnify D3D content. To receive the
            // window message informing us of this, we must tell the DWM 
            // we are MIL content.
            // 
            // The Win7 Magnifier can magnify D3D content so it's not an 
            // issue there. In fact, Win7 doesn't even send the WM.
            // 
            // If the DWM is not running, this call will result in NoOp.
            //

            ChangeWindowMessageFilter(s_dwmRedirectionEnvironmentChanged, 1 /* MSGFLT_ADD */); 
            MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle));
        } 
Example #3
0
        internal HwndStylusInputProvider(HwndSource source)
        {
            InputManager inputManager = InputManager.Current;
            StylusLogic  stylusLogic  = inputManager.StylusLogic;

            IntPtr sourceHandle;

            (new UIPermission(PermissionState.Unrestricted)).Assert();
            try //Blessed Assert this is for RegisterInputManager and RegisterHwndforinput
            {
                // Register ourselves as an input provider with the input manager.
                _site = new SecurityCriticalDataClass <InputProviderSite>(inputManager.RegisterInputProvider(this));

                sourceHandle = source.Handle;
            }
            finally
            {
                UIPermission.RevertAssert();
            }

            stylusLogic.RegisterHwndForInput(inputManager, source);
            _source      = new SecurityCriticalDataClass <HwndSource>(source);
            _stylusLogic = new SecurityCriticalDataClass <StylusLogic>(stylusLogic);

            // Enables multi-touch input
            UnsafeNativeMethods.SetProp(new HandleRef(this, sourceHandle), "MicrosoftTabletPenServiceProperty", new HandleRef(null, new IntPtr(MultiTouchEnabledFlag)));
        }
Example #4
0
        internal RawStylusInputReport(
            InputMode mode,
            int timestamp,
            PresentationSource inputSource,
            PenContext penContext,
            RawStylusActions actions,
            int tabletDeviceId,
            int stylusDeviceId,
            int[] data)
            : base(inputSource, InputType.Stylus, mode, timestamp)
        {
            // Validate parameters
            if (!RawStylusActionsHelper.IsValid(actions))
            {
                throw new InvalidEnumArgumentException(SR.Get(SRID.Enum_Invalid, "actions"));
            }
            if (data == null && actions != RawStylusActions.InRange)
            {
                throw new ArgumentNullException("data");
            }

            _penContext     = new SecurityCriticalDataClass <PenContext>(penContext);
            _actions        = actions;
            _tabletDeviceId = tabletDeviceId;
            _stylusDeviceId = stylusDeviceId;
            _data           = data;
            _isSynchronize  = false;
        }
Example #5
0
        internal RawStylusInputReport(
            InputMode mode,
            int timestamp,
            PresentationSource inputSource,
            PenContext penContext,
            RawStylusActions actions,
            int tabletDeviceId,
            int stylusDeviceId,
            int[] data)
            : base(inputSource, InputType.Stylus, mode, timestamp)
        {
            // Validate parameters
            if (!RawStylusActionsHelper.IsValid(actions))
            {
                throw new InvalidEnumArgumentException(SR.Get(SRID.Enum_Invalid, "actions"));
            }
            if (data == null && actions != RawStylusActions.InRange)
            {
                throw new ArgumentNullException("data");
            }

            _penContext     = new SecurityCriticalDataClass<PenContext>(penContext);
            _actions        = actions;
            _tabletDeviceId = tabletDeviceId;
            _stylusDeviceId = stylusDeviceId;
            _data           = data;
            _isSynchronize  = false;
        }
Example #6
0
        internal void Update(HwndPointerInputProvider provider, PresentationSource inputSource,
                             PointerData pointerData, RawStylusInputReport rsir)
        {
            _lastEventTimeTicks = Environment.TickCount;

            _inputSource = new SecurityCriticalDataClass <PresentationSource>(inputSource);

            _pointerData = pointerData;

            // First get the initial stylus points.  Raw data from pointer input comes in screen coordinates, keep that here since that is what we expect.
            _currentStylusPoints = new StylusPointCollection(rsir.StylusPointDescription, rsir.GetRawPacketData(), GetTabletToElementTransform(null), Matrix.Identity);

            // If a plugin has modified these points, we need to fixup the points with the new input
            if (rsir?.RawStylusInput?.StylusPointsModified ?? false)
            {
                // Note that RawStylusInput.Target (of type StylusPluginCollection)
                // guarantees that ViewToElement is invertible.
                GeneralTransform transformToElement = rsir.RawStylusInput.Target.ViewToElement.Inverse;

                Debug.Assert(transformToElement != null);

                _currentStylusPoints = rsir.RawStylusInput.GetStylusPoints(transformToElement);
            }

            // Store the current hwnd provider so we know for what hwnd we are processing this message
            CurrentPointerProvider = provider;

            if (PointerTabletDevice.Type == TabletDeviceType.Touch)
            {
                // If we are a touch device, sync the ActiveSource
                TouchDevice.ChangeActiveSource(_inputSource.Value);
            }
        }
Example #7
0
        //+---------------------------------------------------------------------
        //
        //  Internal Methods
        //
        //----------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        /// Sets the owner MediaContext and creates the notification window.
        /// </summary>
        internal MediaContextNotificationWindow(MediaContext ownerMediaContext)
        {
            // Remember the pointer to the owner MediaContext that we'll forward the broadcasts to.
            _ownerMediaContext = ownerMediaContext;

            // Create a top-level, invisible window so we can get the WM_DWMCOMPOSITIONCHANGED
            // and other DWM notifications that are broadcasted to top-level windows only.
            HwndWrapper hwndNotification;

            hwndNotification = new HwndWrapper(0, NativeMethods.WS_POPUP, 0, 0, 0, 0, 0, "MediaContextNotificationWindow", IntPtr.Zero, null);

            _hwndNotificationHook = new HwndWrapperHook(MessageFilter);

            _hwndNotification = new SecurityCriticalDataClass <HwndWrapper>(hwndNotification);
            _hwndNotification.Value.AddHook(_hwndNotificationHook);

            _isDisposed = false;

            //
            // On Vista, we need to know when the Magnifier goes on and off
            // in order to switch to and from software rendering because the
            // Vista Magnifier cannot magnify D3D content. To receive the
            // window message informing us of this, we must tell the DWM
            // we are MIL content.
            //
            // The Win7 Magnifier can magnify D3D content so it's not an
            // issue there. In fact, Win7 doesn't even send the WM.
            //
            // If the DWM is not running, this call will result in NoOp.
            //

            ChangeWindowMessageFilter(s_dwmRedirectionEnvironmentChanged, 1 /* MSGFLT_ADD */);
            MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle));
        }
Example #8
0
        internal RawStylusInputReport(
            InputMode mode,
            int timestamp,
            PresentationSource inputSource,
            RawStylusActions actions,
            StylusPointDescription mousePointDescription,
            int[] mouseData)
            : base(inputSource, InputType.Stylus, mode, timestamp)
        {
            // Validate parameters
            if (!RawStylusActionsHelper.IsValid(actions))
            {
                throw new InvalidEnumArgumentException(SR.Get(SRID.Enum_Invalid, "actions"));
            }
            if (mouseData == null)
            {
                throw new ArgumentNullException("mouseData");
            }

            _penContext            = new SecurityCriticalDataClass <PenContext>(null);
            _actions               = actions;
            _tabletDeviceId        = 0;
            _stylusDeviceId        = 0;
            _data                  = mouseData;
            _isSynchronize         = false;
            _mousePointDescription = mousePointDescription;
            _isMouseInput          = true;
        }
Example #9
0
 internal void AddHookLast(HwndWrapperHook hook)
 {
     if (_hooks == null)
     {
         _hooks = new SecurityCriticalDataClass <WeakReferenceList>(new WeakReferenceList());
     }
     _hooks.Value.Add(hook);
 }
Example #10
0
            private bool AddReconversionItems(TextEditor textEditor)
            {
                MenuItem  menuItem;
                TextStore textStore = textEditor.TextStore;

                if (textStore == null)
                {
                    GC.SuppressFinalize(this);
                    return(false);
                }

                ReleaseCandidateList(null);
                _candidateList = new  SecurityCriticalDataClass <UnsafeNativeMethods.ITfCandidateList>(textStore.GetReconversionCandidateList());
                if (CandidateList == null)
                {
                    GC.SuppressFinalize(this);
                    return(false);
                }

                int count = 0;

                CandidateList.GetCandidateNum(out count);

                if (count > 0)
                {
                    // Like Winword, we show the first 5 candidates in the context menu.
                    int i;
                    for (i = 0; i < 5 && i < count; i++)
                    {
                        string suggestion;
                        UnsafeNativeMethods.ITfCandidateString candString;

                        CandidateList.GetCandidate(i, out candString);
                        candString.GetString(out suggestion);

                        menuItem                  = new ReconversionMenuItem(this, i);
                        menuItem.Header           = suggestion;
                        menuItem.InputGestureText = GetMenuItemDescription(suggestion);
                        this.Items.Add(menuItem);

                        Marshal.ReleaseComObject(candString);
                    }
                }

                // Like Winword, we show "More" menu to open TIP's candidate list if there are more
                // than 5 candidates.
                if (count > 5)
                {
                    menuItem         = new EditorMenuItem();
                    menuItem.Header  = SR.Get(SRID.TextBox_ContextMenu_More);
                    menuItem.Command = ApplicationCommands.CorrectionList;
                    this.Items.Add(menuItem);
                    menuItem.CommandTarget = textEditor.UiScope;
                }

                return((count > 0) ? true : false);
            }
Example #11
0
        public void AddHook(HwndWrapperHook hook)
        {
            //VerifyAccess();
            if (_hooks == null)
            {
                _hooks = new SecurityCriticalDataClass <WeakReferenceList>(new WeakReferenceList());
            }

            _hooks.Value.Insert(0, hook);
        }
 internal HwndKeyboardInputProvider(HwndSource source)
 {
     (new UIPermission(PermissionState.Unrestricted)).Assert();
     try //Blessed assert for InputManager.Current.RegisterInputProvider
     {
         _site = new SecurityCriticalDataClass <InputProviderSite>(InputManager.Current.RegisterInputProvider(this));
     }
     finally
     {
         UIPermission.RevertAssert();
     }
     _source = new SecurityCriticalDataClass <HwndSource>(source);
 }
 internal HwndAppCommandInputProvider( HwndSource source )
 {
     (new UIPermission(PermissionState.Unrestricted)).Assert();
     try
     {
          _site = new SecurityCriticalDataClass<InputProviderSite>(InputManager.Current.RegisterInputProvider(this));
     }
     finally
     {
         UIPermission.RevertAssert();
     }
     _source = new SecurityCriticalDataClass<HwndSource>(source);
 }
Example #14
0
 internal PenContext(IPimcContext pimcContext, IntPtr hwnd, 
                         PenContexts contexts, bool supportInRange, bool isIntegrated,
                         int id, IntPtr commHandle, int tabletDeviceId) 
 { 
     _contexts = contexts;
     _pimcContext = new SecurityCriticalDataClass<IPimcContext>(pimcContext); 
     _id = id;
     _tabletDeviceId = tabletDeviceId;
     _commHandle = new SecurityCriticalData<IntPtr>(commHandle);
     _hwnd = new SecurityCriticalData<IntPtr>(hwnd); 
     _supportInRange = supportInRange;
     _isIntegrated = isIntegrated; 
 } 
Example #15
0
 internal PenContext(IPimcContext2 pimcContext, IntPtr hwnd,
                     PenContexts contexts, bool supportInRange, bool isIntegrated,
                     int id, IntPtr commHandle, int tabletDeviceId)
 {
     _contexts       = contexts;
     _pimcContext    = new SecurityCriticalDataClass <IPimcContext2>(pimcContext);
     _id             = id;
     _tabletDeviceId = tabletDeviceId;
     _commHandle     = new SecurityCriticalData <IntPtr>(commHandle);
     _hwnd           = new SecurityCriticalData <IntPtr>(hwnd);
     _supportInRange = supportInRange;
     _isIntegrated   = isIntegrated;
     UpdateScreenMeasurementsPending = false;
 }
Example #16
0
        /// <summary>
        /// Destroys the window with the given handle and class atom and unregisters its window class
        /// </summary>
        /// <param name="args">A DestrowWindowParams instance</param>
        internal static object DestroyWindow(object args)
        {
            SecurityCriticalDataClass <IntPtr> handle = ((DestroyWindowArgs)args).Handle;
            ushort classAtom = ((DestroyWindowArgs)args).ClassAtom;

            Invariant.Assert(handle != null && handle.Value != IntPtr.Zero,
                             "Attempting to destroy an invalid hwnd");

            UnsafeNativeMethods.DestroyWindow(new HandleRef(null, handle.Value));

            UnregisterClass((object)classAtom);

            return(null);
        }
        /// <summary>
        /// Creates a new input provider for a particular source that handles WM_POINTER messages
        /// </summary>
        /// <param name="source">The source to handle messages for</param>
        internal HwndPointerInputProvider(HwndSource source)
        {
            _site = new SecurityCriticalDataClass <InputProviderSite>(InputManager.Current.RegisterInputProvider(this));

            _source       = new SecurityCriticalDataClass <HwndSource>(source);
            _pointerLogic = new SecurityCriticalDataClass <PointerLogic>(StylusLogic.GetCurrentStylusLogicAs <PointerLogic>());

            // Register the stylus plugin manager
            _pointerLogic.Value.PlugInManagers[_source.Value] = new PointerStylusPlugInManager(_source.Value);

            // Store if this window is enabled or disabled
            int style = MS.Win32.UnsafeNativeMethods.GetWindowLong(new HandleRef(this, source.CriticalHandle), MS.Win32.NativeMethods.GWL_STYLE);

            IsWindowEnabled = (style & MS.Win32.NativeMethods.WS_DISABLED) == 0;
        }
Example #18
0
 /// <summary>
 /// Initializes a new StylusLogic based on the AppContext switches.
 /// </summary>
 /// <returns></returns>
 private static void Initialize()
 {
     // Initialize a new StylusLogic based on AppContext switches
     // or do nothing if touch is turned off.
     if (IsStylusAndTouchSupportEnabled)
     {
         // Choose between WISP and Pointer stacks
         if (IsPointerStackEnabled)
         {
             _currentStylusLogic = new SecurityCriticalDataClass <StylusLogic>(new PointerLogic(InputManager.UnsecureCurrent));
         }
         else
         {
             _currentStylusLogic = new SecurityCriticalDataClass <StylusLogic>(new WispLogic(InputManager.UnsecureCurrent));
         }
     }
 }
        /// <summary>
        /// Clean up any held resources
        /// </summary>
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_site != null)
                    {
                        _site.Value.Dispose();
                        _site = null;
                    }

                    _pointerLogic.Value.PlugInManagers.Remove(_source.Value);
                }
            }

            _disposed = true;
        }
Example #20
0
        /////////////////////////////////////////////////////////////////////
        internal HwndStylusInputProvider(HwndSource source)
        {
            InputManager inputManager = InputManager.Current;

            _stylusLogic = new SecurityCriticalDataClass <WispLogic>(StylusLogic.GetCurrentStylusLogicAs <WispLogic>());

            IntPtr sourceHandle;

            // Register ourselves as an input provider with the input manager.
            _site = new SecurityCriticalDataClass <InputProviderSite>(inputManager.RegisterInputProvider(this));

            sourceHandle = source.Handle;

            _stylusLogic.Value.RegisterHwndForInput(inputManager, source);
            _source = new SecurityCriticalDataClass <HwndSource>(source);

            // Enables multi-touch input
            UnsafeNativeMethods.SetProp(new HandleRef(this, sourceHandle), "MicrosoftTabletPenServiceProperty", new HandleRef(null, new IntPtr(MultiTouchEnabledFlag)));
        }
Example #21
0
        protected KeyboardDevice(InputManager inputManager)
        { 
            _inputManager = new SecurityCriticalDataClass<InputManager>(inputManager);
            _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); 
            _inputManager.Value.PreNotifyInput += new NotifyInputEventHandler(PreNotifyInput); 
            _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput);
 
            _isEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsEnabledChanged);
            _isVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsVisibleChanged);
            _focusableChangedEventHandler = new DependencyPropertyChangedEventHandler(OnFocusableChanged);
 
            _reevaluateFocusCallback = new DispatcherOperationCallback(ReevaluateFocusCallback);
            _reevaluateFocusOperation = null; 
 
            //
 

            _TsfManager = new SecurityCriticalDataClass<TextServicesManager>(new TextServicesManager(inputManager));
            _textcompositionManager = new SecurityCriticalData<TextCompositionManager>(new TextCompositionManager(inputManager));
        } 
Example #22
0
        internal HwndMouseInputProvider(HwndSource source)
        {
            (new UIPermission(PermissionState.Unrestricted)).Assert();
            try //Blessed Assert for InputManager.Current.RegisterInputProvider
            {

                 _site = new SecurityCriticalDataClass<InputProviderSite>(InputManager.Current.RegisterInputProvider(this));
            }
            finally
            {
                 UIPermission.RevertAssert();
            }

            _source = new SecurityCriticalDataClass<HwndSource>(source);

            // MITIGATION_SETCURSOR
            _setCursorState = SetCursorState.SetCursorNotReceived;
            _haveCapture = false;
            _queryCursorOperation = null;
        }
Example #23
0
        protected KeyboardDevice(InputManager inputManager)
        {
            _inputManager = new SecurityCriticalDataClass <InputManager>(inputManager);
            _inputManager.Value.PreProcessInput  += new PreProcessInputEventHandler(PreProcessInput);
            _inputManager.Value.PreNotifyInput   += new NotifyInputEventHandler(PreNotifyInput);
            _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput);

            _isEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsEnabledChanged);
            _isVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsVisibleChanged);
            _focusableChangedEventHandler = new DependencyPropertyChangedEventHandler(OnFocusableChanged);

            _reevaluateFocusCallback  = new DispatcherOperationCallback(ReevaluateFocusCallback);
            _reevaluateFocusOperation = null;

            // Consider moving this elsewhere
            // The TextServicesManager must be created before the TextCompositionManager
            // so that TIP/IME listeners get precedence.
            _TsfManager             = new SecurityCriticalDataClass <TextServicesManager>(new TextServicesManager(inputManager));
            _textcompositionManager = new SecurityCriticalData <TextCompositionManager>(new TextCompositionManager(inputManager));
        }
Example #24
0
        protected KeyboardDevice(InputManager inputManager)
        {
            _inputManager = new SecurityCriticalDataClass <InputManager>(inputManager);
            _inputManager.Value.PreProcessInput  += new PreProcessInputEventHandler(PreProcessInput);
            _inputManager.Value.PreNotifyInput   += new NotifyInputEventHandler(PreNotifyInput);
            _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput);

            _isEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsEnabledChanged);
            _isVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsVisibleChanged);
            _focusableChangedEventHandler = new DependencyPropertyChangedEventHandler(OnFocusableChanged);

            _reevaluateFocusCallback  = new DispatcherOperationCallback(ReevaluateFocusCallback);
            _reevaluateFocusOperation = null;

            //


            _TsfManager             = new SecurityCriticalDataClass <TextServicesManager>(new TextServicesManager(inputManager));
            _textcompositionManager = new SecurityCriticalData <TextCompositionManager>(new TextCompositionManager(inputManager));
        }
Example #25
0
        private void PreNotifyInput(object sender, NotifyInputEventArgs e)
        {
            RawKeyboardInputReport keyboardInput = ExtractRawKeyboardInputReport(e, InputManager.PreviewInputReportEvent);

            if (keyboardInput != null)
            {
                CheckForDisconnectedFocus();

                // Activation
                //
                // MITIGATION: KEYBOARD_STATE_OUT_OF_SYNC
                //
                // It is very important that we allow multiple activate events.
                // This is how we deal with the fact that Win32 sometimes sends
                // us a WM_SETFOCUS message BEFORE it has updated it's internal
                // internal keyboard state information.  When we get the
                // WM_SETFOCUS message, we activate the keyboard with the
                // keyboard state (even though it could be wrong).  Then when
                // we get the first "real" keyboard input event, we activate
                // the keyboard again, since Win32 will have updated the
                // keyboard state correctly by then.
                //
                if ((keyboardInput.Actions & RawKeyboardActions.Activate) == RawKeyboardActions.Activate)
                {
                    //if active source is null, no need to do special-case handling
                    if (_activeSource == null)
                    {
                        // we are now active.
                        _activeSource = new SecurityCriticalDataClass <PresentationSource>(keyboardInput.InputSource);
                    }
                    else if (_activeSource.Value != keyboardInput.InputSource)
                    {
                        IKeyboardInputProvider toDeactivate = _activeSource.Value.GetInputProvider(typeof(KeyboardDevice)) as IKeyboardInputProvider;

                        // we are now active.
                        _activeSource = new SecurityCriticalDataClass <PresentationSource>(keyboardInput.InputSource);

                        if (toDeactivate != null)
                        {
                            toDeactivate.NotifyDeactivate();
                        }
                    }
                }

                // Generally, we need to check against redundant actions.
                // We never prevet the raw event from going through, but we
                // will only generate the high-level events for non-redundant
                // actions.  We store the set of non-redundant actions in
                // the dictionary of this event.

                // If the input is reporting a key down, the action is never
                // considered redundant.
                if ((keyboardInput.Actions & RawKeyboardActions.KeyDown) == RawKeyboardActions.KeyDown)
                {
                    RawKeyboardActions actions = GetNonRedundantActions(e);
                    actions |= RawKeyboardActions.KeyDown;
                    e.StagingItem.SetData(_tagNonRedundantActions, actions);

                    // Pass along the key that was pressed, and update our state.
                    Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey);
                    e.StagingItem.SetData(_tagKey, key);
                    e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey));

                    // Tell the InputManager that the MostRecentDevice is us.
                    if (_inputManager != null)
                    {
                        _inputManager.Value.MostRecentInputDevice = this;
                    }
                }

                // We are missing detection for redundant ups
                if ((keyboardInput.Actions & RawKeyboardActions.KeyUp) == RawKeyboardActions.KeyUp)
                {
                    RawKeyboardActions actions = GetNonRedundantActions(e);
                    actions |= RawKeyboardActions.KeyUp;
                    e.StagingItem.SetData(_tagNonRedundantActions, actions);

                    // Pass along the key that was pressed, and update our state.
                    Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey);
                    e.StagingItem.SetData(_tagKey, key);
                    e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey));

                    // Tell the InputManager that the MostRecentDevice is us.
                    if (_inputManager != null)
                    {
                        _inputManager.Value.MostRecentInputDevice = this;
                    }
                }
            }

            // On KeyDown, we might need to set the Repeat flag

            if (e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyDownEvent)
            {
                CheckForDisconnectedFocus();

                KeyEventArgs args = (KeyEventArgs)e.StagingItem.Input;

                // Is this the same as the previous key?  (Look at the real key, e.g. TextManager
                // might have changed args.Key it to Key.TextInput.)

                if (_previousKey == args.RealKey)
                {
                    // Yes, this is a repeat (we got the keydown for it twice, with no KeyUp in between)
                    args.SetRepeat(true);
                }

                // Otherwise, keep this key to check against next time.
                else
                {
                    _previousKey = args.RealKey;
                    args.SetRepeat(false);
                }
            }

            // On KeyUp, we clear Repeat flag
            else if (e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyUpEvent)
            {
                CheckForDisconnectedFocus();

                KeyEventArgs args = (KeyEventArgs)e.StagingItem.Input;
                args.SetRepeat(false);

                // Clear _previousKey, so that down/up/down/up doesn't look like a repeat
                _previousKey = Key.None;
            }
        }
Example #26
0
        private void PreNotifyInput(object sender, NotifyInputEventArgs e)
        {
            if ( e.StagingItem.Input.RoutedEvent == InputManager.PreviewInputReportEvent )
            {
                InputReportEventArgs inputReportEventArgs = e.StagingItem.Input as InputReportEventArgs;

                if (!inputReportEventArgs.Handled && inputReportEventArgs.Report.Type == InputType.Mouse)
                {
                    RawMouseInputReport rawMouseInputReport = (RawMouseInputReport) inputReportEventArgs.Report;

                    // Generally, we need to check against redundant actions.
                    // We never prevent the raw event from going through, but we
                    // will only generate the high-level events for non-redundant
                    // actions.  We store the set of non-redundant actions in
                    // the dictionary of this event.

                    // Get the current Non-Redundant Actions for this event and
                    // make a copy.  We will compare the original value against the copy
                    // at the end of this function and write it back in if changed.

                    RawMouseActions actions = GetNonRedundantActions(e);
                    RawMouseActions originalActions = actions;

                    _stylusDevice = GetStylusDevice(e.StagingItem);

                    // Normally we only process mouse input that is from our
                    // active presentation source.  The only exception to this is
                    // the activate report, which is how we change the visual
                    // manager that is active.
                    if ((rawMouseInputReport.Actions & RawMouseActions.Activate) == RawMouseActions.Activate)
                    {
                        // System.Console.WriteLine("Initializing the mouse state.");

                        actions |= RawMouseActions.Activate;

                        _positionRelativeToOver.X = 0;
                        _positionRelativeToOver.Y = 0;

                        _lastPosition.X = rawMouseInputReport.X;
                        _lastPosition.Y = rawMouseInputReport.Y;
                        _forceUpdateLastPosition = true;

                        _stylusDevice = inputReportEventArgs.Device as StylusDevice;

                        // if the existing source is null, no need to do any special-case handling
                        if (_inputSource == null)
                        {
                            _inputSource = new SecurityCriticalDataClass<PresentationSource>(rawMouseInputReport.InputSource);
                        }
                        // if the new source is the same as the old source, don't bother doing anything
                        else if (_inputSource.Value != rawMouseInputReport.InputSource)
                        {
                            IMouseInputProvider toDeactivate = _inputSource.Value.GetInputProvider(typeof(MouseDevice)) as IMouseInputProvider;

                            // All mouse information is now restricted to this presentation source.
                            _inputSource = new SecurityCriticalDataClass<PresentationSource>(rawMouseInputReport.InputSource);

                            if (toDeactivate != null)
                            {
                                toDeactivate.NotifyDeactivate();
                            }
                        }
                    }

                    // Only process mouse input that is from our active presentation source.
                    if ((_inputSource != null) && (rawMouseInputReport.InputSource == _inputSource.Value))
                    {
                        // If the input is reporting mouse deactivation, we need
                        // to break any capture we may have.  Note that we only do
                        // this if the presentation source associated with this event
                        // is the same presentation source we are already over.
                        if ((rawMouseInputReport.Actions & RawMouseActions.Deactivate) == RawMouseActions.Deactivate)
                        {
                            // Console.WriteLine("RawMouseActions.Deactivate");
                            Debug.Assert(_mouseOver == null, "_mouseOver should be null because we have called ChangeMouseOver(null) already.");
                            _inputSource = null;

                            ChangeMouseCapture(null, null, CaptureMode.None, e.StagingItem.Input.Timestamp);
                        }

                        if ((rawMouseInputReport.Actions & RawMouseActions.CancelCapture) == RawMouseActions.CancelCapture)
                        {
                            // Console.WriteLine("RawMouseActions.CancelCapture");
                            ChangeMouseCapture(null, null, CaptureMode.None, e.StagingItem.Input.Timestamp);
                        }

                        // If the input is reporting mouse movement, only update the
                        // set of non-redundant actions if the position changed.
                        if ((rawMouseInputReport.Actions & RawMouseActions.AbsoluteMove) == RawMouseActions.AbsoluteMove) // 
                        {
                            //Console.WriteLine("RawMouseActions.AbsoluteMove: X=" + rawMouseInputReport.X + " Y=" + rawMouseInputReport.Y );

                            // Translate the mouse coordinates to both root relative and "mouseOver" relate.
                            // - Note: "mouseOver" in this case is the element the mouse "was" over before this move.
                            bool mouseOverAvailable = false;
                            Point ptClient = new Point(rawMouseInputReport.X, rawMouseInputReport.Y);
                            Point ptRoot = (Point) e.StagingItem.GetData(_tagRootPoint);
                            Point ptRelativeToOver = InputElement.TranslatePoint(ptRoot, rawMouseInputReport.InputSource.RootVisual, (DependencyObject)_mouseOver, out mouseOverAvailable);

                            IInputElement mouseOver = _mouseOver; // assume mouse is still over whatever it was before
                            IInputElement rawMouseOver = (_rawMouseOver != null) ? (IInputElement)_rawMouseOver.Target : null;
                            bool isPhysicallyOver = _isPhysicallyOver;
                            bool isGlobalChange = ArePointsClose(ptClient, _lastPosition) == false;  // determine if the mouse actually physically moved

                            // Invoke Hit Test logic to determine what element the mouse will be over AFTER the move is processed.
                            // - Only do this if:
                            //      - The mouse physcially moved (isGlobalChange)
                            //      - We are simulating a mouse move (_isSynchronize)
                            //      - mouseOver isn't availabe (!mouseOverAvailable)  Could be caused by a degenerate transform.
                            // - This is to mitigate the redundant AbsoluteMove notifications associated with QueryCursor
                            if (isGlobalChange || rawMouseInputReport._isSynchronize || !mouseOverAvailable)
                            {
                                isPhysicallyOver = true;  // assume mouse is physical over element, we'll set it false if it's due to capture

                                switch (_captureMode)
                                {
                                    // In this case there is no capture, so a simple hit test will determine which element becomes "mouseOver"
                                    case CaptureMode.None:
                                        {
                                            if (rawMouseInputReport._isSynchronize)
                                            {
                                                GlobalHitTest(true, ptClient, _inputSource.Value, out mouseOver, out rawMouseOver);
                                            }
                                            else
                                            {
                                                LocalHitTest(true, ptClient, _inputSource.Value, out mouseOver, out rawMouseOver);
                                            }

                                            if (mouseOver == rawMouseOver)
                                            {
                                                // Since they are the same, there is no reason to process rawMouseOver
                                                rawMouseOver = null;
                                            }

                                            // We understand UIElements and ContentElements.
                                            // If we are over something else (like a raw visual)
                                            // find the containing element.
                                            if (!InputElement.IsValid(mouseOver))
                                                mouseOver = InputElement.GetContainingInputElement(mouseOver as DependencyObject);
                                            if ((rawMouseOver != null) && !InputElement.IsValid(rawMouseOver))
                                                rawMouseOver = InputElement.GetContainingInputElement(rawMouseOver as DependencyObject);
                                        }
                                        break;

                                    // In this case, capture is to a specific element, so it will ALWAYS become "mouseOver"
                                    // - however, we do a hit test to see if the mouse is actually physically over the element,
                                    // - if it is not, we toggle isPhysicallyOver
                                    case CaptureMode.Element:
                                        if (rawMouseInputReport._isSynchronize)
                                        {
                                            mouseOver = GlobalHitTest(true, ptClient, _inputSource.Value);
                                        }
                                        else
                                        {
                                            mouseOver = LocalHitTest(true, ptClient, _inputSource.Value);
                                        }

                                        // There is no reason to process rawMouseOver when
                                        // the element should always be the one with mouse capture.
                                        rawMouseOver = null;

                                        if (mouseOver != _mouseCapture)
                                        {
                                            // Always consider the mouse over the capture point.
                                            mouseOver = _mouseCapture;
                                            isPhysicallyOver = false;
                                        }
                                        break;

                                    // In this case, capture is set to an entire subtree.  We use simple hit testing to determine
                                    // which, if any element in the subtree it is over, and set "mouseOver to that element
                                    // If it is not over any specific subtree element, "mouseOver" is set to the root of the subtree.
                                    // - Note: a subtree can span multiple HWNDs
                                    case CaptureMode.SubTree:
                                        {
                                            IInputElement mouseCapture = InputElement.GetContainingInputElement(_mouseCapture as DependencyObject);
                                            if (mouseCapture != null)
                                            {
                                                // We need to re-hit-test to get the "real" UIElement we are over.
                                                // This allows us to have our capture-to-subtree span multiple windows.

                                                // GlobalHitTest always returns an IInputElement, so we are sure to have one.
                                                GlobalHitTest(true, ptClient, _inputSource.Value, out mouseOver, out rawMouseOver);
                                            }

                                            if (mouseOver != null && !InputElement.IsValid(mouseOver) )
                                                mouseOver = InputElement.GetContainingInputElement(mouseOver as DependencyObject);

                                            // Make sure that the element we hit is acutally underneath
                                            // our captured element.  Because we did a global hit test, we
                                            // could have hit an element in a completely different window.
                                            //
                                            // Note that we support the child being in a completely different window.
                                            // So we use the GetUIParent method instead of just looking at
                                            // visual/content parents.
                                            if (mouseOver != null)
                                            {
                                                IInputElement ieTest = mouseOver;
                                                UIElement eTest = null;
                                                ContentElement ceTest = null;
                                                UIElement3D e3DTest = null;

                                                while (ieTest != null && ieTest != mouseCapture)
                                                {
                                                    eTest = ieTest as UIElement;

                                                    if (eTest != null)
                                                    {
                                                        ieTest = InputElement.GetContainingInputElement(eTest.GetUIParent(true));
                                                    }
                                                    else
                                                    {
                                                        ceTest = ieTest as ContentElement; 

                                                        if (ceTest != null)
                                                        {
                                                            ieTest = InputElement.GetContainingInputElement(ceTest.GetUIParent(true));
                                                        }
                                                        else
                                                        {
                                                            e3DTest = ieTest as UIElement3D; // Should never fail.

                                                            ieTest = InputElement.GetContainingInputElement(e3DTest.GetUIParent(true));
                                                        }                                                        
                                                    }
                                                }

                                                // If we missed the capture point, we didn't hit anything.
                                                if (ieTest != mouseCapture)
                                                {
                                                    mouseOver = _mouseCapture;
                                                    isPhysicallyOver = false;

                                                    // Since they are the same, there is no reason to process rawMouseOver
                                                    rawMouseOver = null;
                                                }
                                            }
                                            else
                                            {
                                                // We didn't hit anything.  Consider the mouse over the capture point.
                                                mouseOver = _mouseCapture;
                                                isPhysicallyOver = false;

                                                // Since they are the same, there is no reason to process rawMouseOver
                                                rawMouseOver = null;
                                            }

                                            if (rawMouseOver != null)
                                            {
                                                if (mouseOver == rawMouseOver)
                                                {
                                                    // Since they are the same, there is no reason to process rawMouseOver
                                                    rawMouseOver = null;
                                                }
                                                else if (!InputElement.IsValid(rawMouseOver))
                                                {
                                                    rawMouseOver = InputElement.GetContainingInputElement(rawMouseOver as DependencyObject);
                                                }
                                            }
                                        }
                                        break;
                                }
                            }

                            _isPhysicallyOver = mouseOver == null ? false : isPhysicallyOver;

                            // Now that we've determine what element the mouse is over now (mouseOver)
                            // - we need to check if it's changed

                            bool isMouseOverChange = mouseOver != _mouseOver;

                            // If mouseOver changed, we need to recalculate the ptRelativeToOver, because "Over" changed!

                            if (isMouseOverChange)
                            {
                                ptRelativeToOver = InputElement.TranslatePoint(ptRoot, rawMouseInputReport.InputSource.RootVisual, (DependencyObject)mouseOver);
                            }

                            //Console.WriteLine("RawMouseActions.AbsoluteMove: mouse moved over " + (isMouseOverChange ? "same" : "different") + " element.  old=" + _mouseOver + " new=" + mouseOver);
                            //Console.WriteLine("RawMouseActions.AbsoluteMove: capture=" + _mouseCapture);

                            // Check to see if the local mouse position changed.  This can be
                            // caused by a change to the geometry of the
                            // element we are over or a change in which element
                            // we are over.
                            //
                            bool isLocalChange = isMouseOverChange || ArePointsClose(ptRelativeToOver, _positionRelativeToOver) == false;

                            // Console.WriteLine("RawMouseActions.AbsoluteMove: isGlobalChange=" + isGlobalChange + " isLocalChange=" + isLocalChange);

                            // We only update our cached position (_lastPosition & _positionRelativeToOver )
                            // if we have moved "far enough" allowing small incrementaly moves to accumulate

                            if (isGlobalChange || isLocalChange || _forceUpdateLastPosition)
                            {
                                _forceUpdateLastPosition = false;

                                _lastPosition = ptClient;
                                _positionRelativeToOver = ptRelativeToOver;

                                if (isMouseOverChange)
                                {
                                    ChangeMouseOver(mouseOver, e.StagingItem.Input.Timestamp);
                                }

                                if ((_rawMouseOver == null) && (rawMouseOver != null))
                                {
                                    _rawMouseOver = new WeakReference(rawMouseOver);
                                }
                                else if (_rawMouseOver != null)
                                {
                                    _rawMouseOver.Target = rawMouseOver;
                                }

                                // Console.WriteLine("RawMouseActions.AbsoluteMove: ptRoot=" + ptRoot);

                                actions |= RawMouseActions.AbsoluteMove; // 

                                // In most cases the sequence of messages received from the system are HitTest, SetCursor & MouseMove.
                                // The SetCursor message in this case will be traslated into an Avalon MouseMove & QueryCursor.
                                // The MouseMove message to follow is redundant and is thrown away.
                                // But imagine a case where Capture is taken. Here the system produces only two messages HitTest & MouseMove.
                                // Hence we translate the MouseMove into an Avalon MouseMove & QueryCursor.
                                // Logically MouseMove and QueryCursor go as a pair.
                                actions |= RawMouseActions.QueryCursor;
                            }
                        }

                        // Mouse wheel rotate events are never considered redundant.
                        if ((rawMouseInputReport.Actions & RawMouseActions.VerticalWheelRotate) == RawMouseActions.VerticalWheelRotate)
                        {
                            // Console.WriteLine("RawMouseActions.VerticalWheelRotate");

                            actions |= RawMouseActions.VerticalWheelRotate;

                            // Tell the InputManager that the MostRecentDevice is us.
                            _inputManager.Value.MostRecentInputDevice = this;
                        }

                        // Mouse query cursor events are never considered redundant.
                        if ((rawMouseInputReport.Actions & RawMouseActions.QueryCursor) == RawMouseActions.QueryCursor)
                        {
                            // Console.WriteLine("RawMouseActions.QueryCursor");

                            actions |= RawMouseActions.QueryCursor;
                        }

                        RawMouseActions[] ButtonPressActions =
                        {
                            RawMouseActions.Button1Press,
                            RawMouseActions.Button2Press,
                            RawMouseActions.Button3Press,
                            RawMouseActions.Button4Press,
                            RawMouseActions.Button5Press
                        };

                        RawMouseActions[] ButtonReleaseActions =
                        {
                            RawMouseActions.Button1Release,
                            RawMouseActions.Button2Release,
                            RawMouseActions.Button3Release,
                            RawMouseActions.Button4Release,
                            RawMouseActions.Button5Release
                        };

                        for (int iButton = 0; iButton < 5; iButton++)
                        {
                            if ((rawMouseInputReport.Actions & ButtonPressActions[iButton]) == ButtonPressActions[iButton])
                            {
                                actions |= ButtonPressActions[iButton];

                                // Tell the InputManager that the MostRecentDevice is us.
                                _inputManager.Value.MostRecentInputDevice = this;
                            }

                            if ((rawMouseInputReport.Actions & ButtonReleaseActions[iButton]) == ButtonReleaseActions[iButton])
                            {
                                actions |= ButtonReleaseActions[iButton];

                                // Tell the InputManager that the MostRecentDevice is us.
                                _inputManager.Value.MostRecentInputDevice = this;
                            }
                        }
                    }

                    if (actions != originalActions)
                    {
                        e.StagingItem.SetData(_tagNonRedundantActions, actions);
                    }
                }
            }
            else
            {
                // All mouse event processing should only happen if we still have an active input source.

                if (_inputSource != null)
                {
                    // During the PreviewMouseDown event, we update the click count, if there are
                    // multiple "quick" clicks in approximately the "same" location (as defined
                    // by the hosting environment, aka the registry).
                    if (e.StagingItem.Input.RoutedEvent == Mouse.PreviewMouseDownEvent)
                    {
                        MouseButtonEventArgs mouseButtonArgs = e.StagingItem.Input as MouseButtonEventArgs;
                        StylusDevice stylusDevice = GetStylusDevice(e.StagingItem);
                        Point ptClient = GetClientPosition();

                        _clickCount = CalculateClickCount(mouseButtonArgs.ChangedButton, mouseButtonArgs.Timestamp, stylusDevice, ptClient);
                        if (_clickCount == 1)
                        {
                            // we need to reset out data, since this is the start of the click count process...
                            _lastClick = ptClient;
                            _lastButton = mouseButtonArgs.ChangedButton;
                            _lastClickTime = mouseButtonArgs.Timestamp;
                        }
                        // Put the updated count into the args.
                        mouseButtonArgs.ClickCount = _clickCount;
                    }
                }
            }
        }
Example #27
0
        public HwndWrapper(
            int classStyle,
            int style,
            int exStyle,
            int x,
            int y,
            int width,
            int height,
            string name,
            IntPtr parent,
            HwndWrapperHook[] hooks)
        {

            _ownerThreadID = new SecurityCriticalDataForSet<int>(Thread.CurrentThread.ManagedThreadId);


            // First, add the set of hooks.  This allows the hooks to receive the
            // messages sent to the window very early in the process.
            if(hooks != null)
            {
                for(int i = 0, iEnd = hooks.Length; i < iEnd; i++)
                {
                    if(null != hooks[i])
                        AddHook(hooks[i]);
                }
            }


            _wndProc = new SecurityCriticalData<HwndWrapperHook>(new HwndWrapperHook(WndProc));

            // We create the HwndSubclass object so that we can use its
            // window proc directly.  We will not be "subclassing" the
            // window we create.
            HwndSubclass hwndSubclass = new HwndSubclass(_wndProc.Value);
            
            // Register a unique window class for this instance.
            NativeMethods.WNDCLASSEX_D wc_d = new NativeMethods.WNDCLASSEX_D();

            IntPtr hNullBrush = UnsafeNativeMethods.CriticalGetStockObject(NativeMethods.NULL_BRUSH);

            if (hNullBrush == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle( null );

            // We need to keep the Delegate object alive through the call to CreateWindowEx().
            // Subclass.WndProc will install a better delegate (to the same function) when it
            // processes the first message.
            // But this first delegate needs be held alive until then.
            NativeMethods.WndProc initialWndProc = new NativeMethods.WndProc(hwndSubclass.SubclassWndProc);

            // The class name is a concat of AppName, ThreadName, and RandomNumber.
            // Register will fail if the string gets over 255 in length.
            // So limit each part to a reasonable amount.
            string appName;
            if(null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length)
                appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128);
            else
                appName = AppDomain.CurrentDomain.FriendlyName;

            string threadName;
            if(null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length)
                threadName = Thread.CurrentThread.Name.Substring(0, 64);
            else
                threadName = Thread.CurrentThread.Name;

            // Create a suitable unique class name.
            _classAtom = 0;
            string randomName = Guid.NewGuid().ToString();
            string className = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, randomName);

            wc_d.cbSize        = Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX_D));
            wc_d.style         = classStyle;
            wc_d.lpfnWndProc   = initialWndProc;
            wc_d.cbClsExtra    = 0;
            wc_d.cbWndExtra    = 0;
            wc_d.hInstance     = hInstance;
            wc_d.hIcon         = IntPtr.Zero;
            wc_d.hCursor       = IntPtr.Zero;
            wc_d.hbrBackground = hNullBrush;
            wc_d.lpszMenuName  = "";
            wc_d.lpszClassName = className;
            wc_d.hIconSm       = IntPtr.Zero;

            // Register the unique class for this instance.
            // Note we use a GUID in the name so we are confident that
            // the class name should be unique.  And RegisterClassEx won't
            // fail (for that reason).
            _classAtom = UnsafeNativeMethods.RegisterClassEx(wc_d);

            // call CreateWindow
            _isInCreateWindow = true;
            try {
                _handle = new SecurityCriticalDataClass<IntPtr>(UnsafeNativeMethods.CreateWindowEx(exStyle,
                                                         className,
                                                         name,
                                                         style,
                                                         x,
                                                         y,
                                                         width,
                                                         height,
                                                         new HandleRef(null,parent),
                                                         new HandleRef(null,IntPtr.Zero),
                                                         new HandleRef(null,IntPtr.Zero),
                                                         null));
            }
            finally
            {
                _isInCreateWindow = false;
                if(_handle == null || _handle.Value == IntPtr.Zero)
                {
                    new UIPermission(UIPermissionWindow.AllWindows).Assert(); //BlessedAssert to call Dispose
                    try
                    {
                        // Because the HwndSubclass is pinned, but the HWND creation failed,
                        // we need to manually clean it up.
                        hwndSubclass.Dispose();
                    }
                    finally
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }
            }
            GC.KeepAlive(initialWndProc);
        }
Example #28
0
        public void AddHook(HwndWrapperHook hook)
        {
            //VerifyAccess();
            if(_hooks == null)
            {
                _hooks = new SecurityCriticalDataClass<WeakReferenceList>(new WeakReferenceList());
            }

            _hooks.Value.Insert(0, hook);
        }
Example #29
0
        internal RawStylusInputReport(
            InputMode mode,
            int timestamp,
            PresentationSource inputSource,
            RawStylusActions actions,
            StylusPointDescription mousePointDescription,
            int[] mouseData)
            : base(inputSource, InputType.Stylus, mode, timestamp)
        {
            // Validate parameters
            if (!RawStylusActionsHelper.IsValid(actions))
            {
                throw new InvalidEnumArgumentException(SR.Get(SRID.Enum_Invalid, "actions"));
            }
            if (mouseData == null)
            {
                throw new ArgumentNullException("mouseData");
            }

            _penContext     = new SecurityCriticalDataClass<PenContext>(null);
            _actions        = actions;
            _tabletDeviceId = 0;
            _stylusDeviceId = 0;
            _data           = mouseData;
            _isSynchronize  = false;
            _mousePointDescription = mousePointDescription;
            _isMouseInput = true;
        }
        internal void UpdateInRange(bool inRange, PenContext penContext)
        {
            _fInRange = inRange;

            // Make sure we clean the last _inputSource for down at this time.
            //_inputSourceForDown = null;
            if (inRange)
                _activePenContext = new SecurityCriticalDataClass<PenContext>(penContext);
            else
                _activePenContext = null;
        }
Example #31
0
 public DestroyWindowArgs(SecurityCriticalDataClass <IntPtr> handle, ushort classAtom)
 {
     _handle    = handle;
     _classAtom = classAtom;
 }
Example #32
0
        private void _RegisterTextStore(TextStore textstore)
        {
            UnsafeNativeMethods.ITfDocumentMgr doc;
            UnsafeNativeMethods.ITfContext     context;
            UnsafeNativeMethods.ITfSource      source;
            int  editCookie        = UnsafeNativeMethods.TF_INVALID_COOKIE;
            int  threadFocusCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
            int  editSinkCookie    = UnsafeNativeMethods.TF_INVALID_COOKIE;
            Guid guid;

            Debug.Assert(CheckAccess(), "RegisterTextStore called on bad thread!");

            // Get ITfThreadMgr
            if (_threadManager == null)
            {
                Debug.Assert(_isDispatcherShutdownFinished == false, "Was this dispather finished?");
                Debug.Assert(_registeredtextstorecount == 0, "TextStore was registered without ThreadMgr?");

                // TextServicesLoader.Load() might return null if no text services are installed or enabled.
                _threadManager = new SecurityCriticalDataClass <UnsafeNativeMethods.ITfThreadMgr>(TextServicesLoader.Load());

                if (_threadManager.Value == null)
                {
                    _threadManager = null;
                    return;
                }

                // Activate TSF on this thread if this is the first TextStore.
                int clientIdTemp;
                _threadManager.Value.Activate(out clientIdTemp);
                _clientId = new SecurityCriticalData <int>(clientIdTemp);

                // We want to get the notification when Dispatcher is finished.
                Dispatcher.ShutdownFinished += new EventHandler(OnDispatcherShutdownFinished);
            }

            // Create a TSF document.
            _threadManager.Value.CreateDocumentMgr(out doc);
            doc.CreateContext(_clientId.Value, 0 /* flags */, textstore, out context, out editCookie);
            doc.Push(context);

            // Attach a thread focus sink.
            if (textstore is UnsafeNativeMethods.ITfThreadFocusSink)
            {
                guid   = UnsafeNativeMethods.IID_ITfThreadFocusSink;
                source = _threadManager.Value as UnsafeNativeMethods.ITfSource;
                source.AdviseSink(ref guid, textstore, out threadFocusCookie);
            }

            // Attach an edit sink.
            if (textstore is UnsafeNativeMethods.ITfTextEditSink)
            {
                guid   = UnsafeNativeMethods.IID_ITfTextEditSink;
                source = context as UnsafeNativeMethods.ITfSource;
                source.AdviseSink(ref guid, textstore, out editSinkCookie);
            }

            // Release any native resources we're done with.
            Marshal.ReleaseComObject(context);

            textstore.DocumentManager   = doc;
            textstore.ThreadFocusCookie = threadFocusCookie;
            textstore.EditSinkCookie    = editSinkCookie;
            textstore.EditCookie        = editCookie;

            // If Scope of this textstore already has a focus, we need to call SetFocus()
            // in order to put this DIM on Cicero's focus. TextStore.OnGotFocus() calls
            // ITfThreadMgr::SetFocus();
            if (textstore.UiScope.IsKeyboardFocused)
            {
                textstore.OnGotFocus();
            }

            _registeredtextstorecount++;
        }
Example #33
0
        private void PreNotifyInput(object sender, NotifyInputEventArgs e) 
        {
            RawKeyboardInputReport keyboardInput = ExtractRawKeyboardInputReport(e, InputManager.PreviewInputReportEvent); 
            if(keyboardInput != null) 
            {
                CheckForDisconnectedFocus(); 

                // Activation
                //
                // MITIGATION: KEYBOARD_STATE_OUT_OF_[....] 
                //
                // It is very important that we allow multiple activate events. 
                // This is how we deal with the fact that Win32 sometimes sends 
                // us a WM_SETFOCUS message BEFORE it has updated it's internal
                // internal keyboard state information.  When we get the 
                // WM_SETFOCUS message, we activate the keyboard with the
                // keyboard state (even though it could be wrong).  Then when
                // we get the first "real" keyboard input event, we activate
                // the keyboard again, since Win32 will have updated the 
                // keyboard state correctly by then.
                // 
                if((keyboardInput.Actions & RawKeyboardActions.Activate) == RawKeyboardActions.Activate) 
                {
                    //if active source is null, no need to do special-case handling 
                    if(_activeSource == null)
                    {
                        // we are now active.
                        _activeSource = new SecurityCriticalDataClass<PresentationSource>(keyboardInput.InputSource); 
                    }
                    else if(_activeSource.Value != keyboardInput.InputSource) 
                    { 
                        IKeyboardInputProvider toDeactivate = _activeSource.Value.GetInputProvider(typeof(KeyboardDevice)) as IKeyboardInputProvider;
 
                        // we are now active.
                        _activeSource = new SecurityCriticalDataClass<PresentationSource>(keyboardInput.InputSource);

                        if(toDeactivate != null) 
                        {
                            toDeactivate.NotifyDeactivate(); 
                        } 
                    }
                } 

                // Generally, we need to check against redundant actions.
                // We never prevet the raw event from going through, but we
                // will only generate the high-level events for non-redundant 
                // actions.  We store the set of non-redundant actions in
                // the dictionary of this event. 
 
                // If the input is reporting a key down, the action is never
                // considered redundant. 
                if((keyboardInput.Actions & RawKeyboardActions.KeyDown) == RawKeyboardActions.KeyDown)
                {
                    RawKeyboardActions actions = GetNonRedundantActions(e);
                    actions |= RawKeyboardActions.KeyDown; 
                    e.StagingItem.SetData(_tagNonRedundantActions, actions);
 
                    // Pass along the key that was pressed, and update our state. 
                    Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey);
                    e.StagingItem.SetData(_tagKey, key); 
                    e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey));

                    // Tell the InputManager that the MostRecentDevice is us.
                    if(_inputManager!=null) 
                        _inputManager.Value.MostRecentInputDevice = this;
                } 
 
                //
                if((keyboardInput.Actions & RawKeyboardActions.KeyUp) == RawKeyboardActions.KeyUp) 
                {
                    RawKeyboardActions actions = GetNonRedundantActions(e);
                    actions |= RawKeyboardActions.KeyUp;
                    e.StagingItem.SetData(_tagNonRedundantActions, actions); 

                    // Pass along the key that was pressed, and update our state. 
                    Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey); 
                    e.StagingItem.SetData(_tagKey, key);
                    e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey)); 

                    // Tell the InputManager that the MostRecentDevice is us.
                    if(_inputManager!=null)
                        _inputManager.Value.MostRecentInputDevice = this; 
                }
            } 
 
            // On KeyDown, we might need to set the Repeat flag
 
            if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyDownEvent)
            {
                CheckForDisconnectedFocus();
 
                KeyEventArgs args = (KeyEventArgs) e.StagingItem.Input;
 
                // Is this the same as the previous key?  (Look at the real key, e.g. TextManager 
                // might have changed args.Key it to Key.TextInput.)
 
                if (_previousKey == args.RealKey)
                {
                    // Yes, this is a repeat (we got the keydown for it twice, with no KeyUp in between)
                    args.SetRepeat(true); 
                }
 
                // Otherwise, keep this key to check against next time. 
                else
                { 
                    _previousKey = args.RealKey;
                    args.SetRepeat(false);
                }
            } 

            // On KeyUp, we clear Repeat flag 
            else if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyUpEvent) 
            {
                CheckForDisconnectedFocus(); 

                KeyEventArgs args = (KeyEventArgs) e.StagingItem.Input;
                args.SetRepeat(false);
 
                // Clear _previousKey, so that down/up/down/up doesn't look like a repeat
                _previousKey = Key.None; 
            } 
        }
Example #34
0
        internal HwndKeyboardInputProvider(HwndSource source)
        {
            _site = new SecurityCriticalDataClass <InputProviderSite>(InputManager.Current.RegisterInputProvider(this));

            _source = new SecurityCriticalDataClass <HwndSource>(source);
        }
Example #35
0
            internal void BuildWindow(int x, int y, Visual placementTarget,
                bool transparent, HwndSourceHook hook, AutoResizedEventHandler handler)
            {
                Debug.Assert(!IsChildPopup || (IsChildPopup && !transparent), "Child popups cannot be transparent");
                transparent = transparent && !IsChildPopup;

                Visual mainTreeVisual = placementTarget;
                if (IsChildPopup)
                {
                    // If the popup is nested inside other popups, get out into the main tree
                    // before querying for the presentation source.
                    mainTreeVisual = FindMainTreeVisual(placementTarget);
                }

                // get visual's PresentationSource
                HwndSource hwndSource = PopupSecurityHelper.GetPresentationSource(mainTreeVisual) as HwndSource;

                // get parent handle
                IntPtr parent = IntPtr.Zero;
                if (hwndSource != null)
                {
                    parent = PopupSecurityHelper.GetHandle(hwndSource);
                }

                int classStyle = 0;
                int style = NativeMethods.WS_CLIPSIBLINGS;
                int styleEx = NativeMethods.WS_EX_TOOLWINDOW | NativeMethods.WS_EX_NOACTIVATE;

                if (IsChildPopup)
                {
                    // The popup was created in an environment where it should be a child window, not a popup window.
                    style |= NativeMethods.WS_CHILD;
                }
                else
                {
                    style |= NativeMethods.WS_POPUP;
                    styleEx |= NativeMethods.WS_EX_TOPMOST;
                }

                // set window parameters
                HwndSourceParameters param = new HwndSourceParameters(String.Empty);
                param.WindowClassStyle = classStyle;
                param.WindowStyle = style;
                param.ExtendedWindowStyle = styleEx;
                param.SetPosition(x, y);

                if (IsChildPopup)
                {
                    if ( parent != IntPtr.Zero )
                    {
                        param.ParentWindow = parent;
                    }
                    else
                    {
                        SecurityHelper.DemandUIWindowPermission();
                    }
                }
                else
                {
                    param.UsesPerPixelOpacity = transparent;
                    if ((parent != IntPtr.Zero) && ConnectedToForegroundWindow(parent))
                    {
                        param.ParentWindow = parent;
                    }
                }

                // create popup's window object
                HwndSource newWindow = new HwndSource(param);

                new UIPermission(UIPermissionWindow.AllWindows).Assert(); //BlessedAssert
                try
                {
                    // add hook to the popup's window
                    newWindow.AddHook(hook);
                }
                finally
                {
                    UIPermission.RevertAssert();
                }

                // initialize the private critical window object
                _window = new SecurityCriticalDataClass<HwndSource>(newWindow);

                // Set background color
                HwndTarget hwndTarget = (HwndTarget)newWindow.CompositionTarget;
                hwndTarget.BackgroundColor = transparent ? Colors.Transparent : Colors.Black;

                // add AddAutoResizedEventHandler event handler
                newWindow.AutoResized += handler;
            }
Example #36
0
 public DestroyWindowArgs(SecurityCriticalDataClass<IntPtr> handle, ushort classAtom)
 {
     _handle = handle;
     _classAtom = classAtom;
 }
        private void Initialize(HwndSourceParameters parameters)
        {
            _mouse = new SecurityCriticalDataClass<HwndMouseInputProvider>(new HwndMouseInputProvider(this));
            _keyboard = new SecurityCriticalDataClass<HwndKeyboardInputProvider>(new HwndKeyboardInputProvider(this));
            _layoutHook = new HwndWrapperHook(LayoutFilterMessage);
            _inputHook = new HwndWrapperHook(InputFilterMessage);
            _hwndTargetHook = new HwndWrapperHook(HwndTargetFilterMessage);

            _publicHook = new HwndWrapperHook(PublicHooksFilterMessage);

            // When processing WM_SIZE, LayoutFilterMessage must be invoked before
            // HwndTargetFilterMessage. This way layout will be updated before resizing
            // HwndTarget, resulting in single render per resize. This means that
            // layout hook should appear before HwndTarget hook in the wrapper hooks
            // list. If this is done the other way around, first HwndTarget resize will
            // force re-render, then layout will be updated according to the new size,
            // scheduling another render.
            HwndWrapperHook[] wrapperHooks = { _hwndTargetHook, _layoutHook, _inputHook, null };

            if (null != parameters.HwndSourceHook)
            {
                // In case there's more than one delegate, add these to the event storage backwards
                // so they'll get invoked in the expected order.
                Delegate[] handlers = parameters.HwndSourceHook.GetInvocationList();
                for (int i = handlers.Length -1; i >= 0; --i)
                {
                    _hooks += (HwndSourceHook)handlers[i];
                }
                wrapperHooks[3] = _publicHook;
            }

            _restoreFocusMode = parameters.RestoreFocusMode;
            _acquireHwndFocusInMenuMode = parameters.AcquireHwndFocusInMenuMode;

            // A window must be marked WS_EX_LAYERED if (and only if):
            // 1) it is not a child window
            //    -- AND --
            // 2) a color-key is specified
            // 3) or an opacity other than 1.0 is specified
            // 4) or per-pixel alpha is requested.
            if((parameters.WindowStyle & NativeMethods.WS_CHILD) == 0 &&
               ( //parameters.ColorKey != null ||
                 //!MS.Internal.DoubleUtil.AreClose(parameters.Opacity, 1.0) ||
                parameters.UsesPerPixelOpacity))
            {
                parameters.ExtendedWindowStyle |= NativeMethods.WS_EX_LAYERED;
            }
            else
            {
                parameters.ExtendedWindowStyle &= (~NativeMethods.WS_EX_LAYERED);
            }


            _constructionParameters = parameters;
            _hwndWrapper = new HwndWrapper(parameters.WindowClassStyle,
                                       parameters.WindowStyle,
                                       parameters.ExtendedWindowStyle,
                                       parameters.PositionX,
                                       parameters.PositionY,
                                       parameters.Width,
                                       parameters.Height,
                                       parameters.WindowName,
                                       parameters.ParentWindow,
                                       wrapperHooks);

            _hwndTarget = new HwndTarget(_hwndWrapper.Handle);
            //_hwndTarget.ColorKey = parameters.ColorKey;
            //_hwndTarget.Opacity = parameters.Opacity;
            _hwndTarget.UsesPerPixelOpacity = parameters.UsesPerPixelOpacity;
            if(_hwndTarget.UsesPerPixelOpacity)
            {
                _hwndTarget.BackgroundColor = Colors.Transparent;

                // Prevent this window from being themed.
                UnsafeNativeMethods.CriticalSetWindowTheme(new HandleRef(this, _hwndWrapper.Handle), "", "");
            }
            _constructionParameters = null;

            if (!parameters.HasAssignedSize)
                _sizeToContent = SizeToContent.WidthAndHeight;

            _adjustSizingForNonClientArea = parameters.AdjustSizingForNonClientArea;
            _treatAncestorsAsNonClientArea = parameters.TreatAncestorsAsNonClientArea;
            
            // Listen to the UIContext.Disposed event so we can clean up.
            // The HwndTarget cannot work without a MediaContext which
            // is disposed when the UIContext is disposed.  So we need to
            // dispose the HwndTarget and also never use it again (to
            // paint or process input).  The easiest way to do this is to just
            // dispose the HwndSource at the same time.
            _weakShutdownHandler = new WeakEventDispatcherShutdown(this, this.Dispatcher);

            // Listen to the HwndWrapper.Disposed event so we can clean up.
            // The HwndTarget cannot work without a live HWND, and since
            // the HwndSource represents an HWND, we make sure we dispose
            // ourselves if the HWND is destroyed out from underneath us.
            _hwndWrapper.Disposed += new EventHandler(OnHwndDisposed);

            _stylus = new SecurityCriticalDataClass<HwndStylusInputProvider>(new HwndStylusInputProvider(this));

            // WM_APPCOMMAND events are handled thru this.
            _appCommand = new SecurityCriticalDataClass<HwndAppCommandInputProvider>(new HwndAppCommandInputProvider(this));

            // Register the top level source with the ComponentDispatcher.
            if (parameters.TreatAsInputRoot)
            {
                _weakPreprocessMessageHandler = new WeakEventPreprocessMessage(this, false);
            }
            AddSource();

            // Register dropable window.
            // The checking CallerHasPermissionWithAppDomainOptimization will call RegisterDropTarget
            // safely without the security exception in case of no unmanaged code permission.
            // So RegisterDropTarget will be called safely in case of having the unmanged code permission.
            // Otherwise, the security exception cause System.Printing to be instatiated which will
            // load system.drawing module.
            if (_hwndWrapper.Handle != IntPtr.Zero &&
                SecurityHelper.CallerHasPermissionWithAppDomainOptimization(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)))
            {
                // This call is safe since DragDrop.RegisterDropTarget is checking the unmanged
                // code permission.
                DragDrop.RegisterDropTarget(_hwndWrapper.Handle);
                _registeredDropTargetCount++;
            }
        }
Example #38
0
        private void ChangeMouseCapture(IInputElement mouseCapture, IMouseInputProvider providerCapture, CaptureMode captureMode, int timestamp)
        {
            DependencyObject o = null;

            if(mouseCapture != _mouseCapture)
            {
                // Console.WriteLine("ChangeMouseCapture(" + mouseCapture + ")");

                // Update the critical pieces of data.
                IInputElement oldMouseCapture = _mouseCapture;
                _mouseCapture = mouseCapture;
                if (_mouseCapture != null)
                {
                    _providerCapture = new SecurityCriticalDataClass<IMouseInputProvider>(providerCapture);
                }
                else
                {
                    _providerCapture = null;
                }
                _captureMode = captureMode;

                using (Dispatcher.DisableProcessing()) // Disable reentrancy due to locks taken
                {
                    // Adjust the handlers we use to track everything.
                    if (oldMouseCapture != null)
                    {
                        o = oldMouseCapture as DependencyObject;
                        if (InputElement.IsUIElement(o))
                        {
                            ((UIElement)o).IsEnabledChanged -= _captureIsEnabledChangedEventHandler;
                            ((UIElement)o).IsVisibleChanged -= _captureIsVisibleChangedEventHandler;
                            ((UIElement)o).IsHitTestVisibleChanged -= _captureIsHitTestVisibleChangedEventHandler;
                        }                        
                        else if (InputElement.IsContentElement(o))
                        {
                            ((ContentElement)o).IsEnabledChanged -= _captureIsEnabledChangedEventHandler;

                            // NOTE: there are no IsVisible or IsHitTestVisible properties for ContentElements.
                            //
                            // ((ContentElement)o).IsVisibleChanged -= _captureIsVisibleChangedEventHandler;
                            // ((ContentElement)o).IsHitTestVisibleChanged -= _captureIsHitTestVisibleChangedEventHandler;
                        }
                        else if (InputElement.IsUIElement3D(o))
                        {
                            ((UIElement3D)o).IsEnabledChanged -= _captureIsEnabledChangedEventHandler;
                            ((UIElement3D)o).IsVisibleChanged -= _captureIsVisibleChangedEventHandler;
                            ((UIElement3D)o).IsHitTestVisibleChanged -= _captureIsHitTestVisibleChangedEventHandler;
                        }
                    }
                    if (_mouseCapture != null)
                    {
                        o = _mouseCapture as DependencyObject;
                        if (InputElement.IsUIElement(o))
                        {
                            ((UIElement)o).IsEnabledChanged += _captureIsEnabledChangedEventHandler;
                            ((UIElement)o).IsVisibleChanged += _captureIsVisibleChangedEventHandler;
                            ((UIElement)o).IsHitTestVisibleChanged += _captureIsHitTestVisibleChangedEventHandler;
                        }                        
                        else if (InputElement.IsContentElement(o))
                        {
                            ((ContentElement)o).IsEnabledChanged += _captureIsEnabledChangedEventHandler;

                            // NOTE: there are no IsVisible or IsHitTestVisible properties for ContentElements.
                            //
                            // ((ContentElement)o).IsVisibleChanged += _captureIsVisibleChangedEventHandler;
                            // ((ContentElement)o).IsHitTestVisibleChanged += _captureIsHitTestVisibleChangedEventHandler;
                        }
                        else if (InputElement.IsUIElement3D(o))
                        {
                            ((UIElement3D)o).IsEnabledChanged += _captureIsEnabledChangedEventHandler;
                            ((UIElement3D)o).IsVisibleChanged += _captureIsVisibleChangedEventHandler;
                            ((UIElement3D)o).IsHitTestVisibleChanged += _captureIsHitTestVisibleChangedEventHandler;
                        }
                    }
                }

                // Oddly enough, update the IsMouseCaptureWithin property first.  This is
                // so any callbacks will see the more-common IsMouseCaptureWithin property
                // set correctly.
                UIElement.MouseCaptureWithinProperty.OnOriginValueChanged(oldMouseCapture as DependencyObject, _mouseCapture as DependencyObject, ref _mouseCaptureWithinTreeState);

                // Invalidate the IsMouseCaptured properties.
                if (oldMouseCapture != null)
                {
                    o = oldMouseCapture as DependencyObject;
                    o.SetValue(UIElement.IsMouseCapturedPropertyKey, false); // Same property for ContentElements
                }
                if (_mouseCapture != null)
                {
                    o = _mouseCapture as DependencyObject;
                    o.SetValue(UIElement.IsMouseCapturedPropertyKey, true); // Same property for ContentElements
                }

                // Send the LostMouseCapture and GotMouseCapture events.
                if (oldMouseCapture != null)
                {
                    MouseEventArgs lostCapture = new MouseEventArgs(this, timestamp, _stylusDevice);
                    lostCapture.RoutedEvent=Mouse.LostMouseCaptureEvent;
                    lostCapture.Source= oldMouseCapture;
                    //ProcessInput has a linkdemand
                    _inputManager.Value.ProcessInput(lostCapture);
                }
                if (_mouseCapture != null)
                {
                    MouseEventArgs gotCapture = new MouseEventArgs(this, timestamp, _stylusDevice);
                    gotCapture.RoutedEvent=Mouse.GotMouseCaptureEvent;
                    gotCapture.Source= _mouseCapture;
                    //ProcessInput has a linkdemand
                    _inputManager.Value.ProcessInput(gotCapture);
                }

                // Force a mouse move so we can update the mouse over.
                Synchronize();
            }
        }
            private bool AddReconversionItems(TextEditor textEditor)
            {
                MenuItem menuItem;
                TextStore textStore = textEditor.TextStore;

                if (textStore == null)
                {
                    GC.SuppressFinalize(this);
                    return false;
                }

                ReleaseCandidateList(null);
                _candidateList = new  SecurityCriticalDataClass<UnsafeNativeMethods.ITfCandidateList>(textStore.GetReconversionCandidateList());
                if (CandidateList == null)
                {
                    GC.SuppressFinalize(this);
                    return false;
                }

                int count = 0;
                CandidateList.GetCandidateNum(out count);

                if (count > 0)
                {
                    // Like Winword, we show the first 5 candidates in the context menu.
                    int i;
                    for (i = 0; i < 5 && i < count; i++)
                    {
                        string suggestion;
                        UnsafeNativeMethods.ITfCandidateString candString;

                        CandidateList.GetCandidate(i, out candString);
                        candString.GetString(out suggestion);

                        menuItem = new ReconversionMenuItem(this, i);
                        menuItem.Header = suggestion;
                        menuItem.InputGestureText = GetMenuItemDescription(suggestion);
                        this.Items.Add(menuItem);

                        Marshal.ReleaseComObject(candString);
                    }
                }

                // Like Winword, we show "More" menu to open TIP's candidate list if there are more
                // than 5 candidates.
                if (count > 5)
                {
                    menuItem = new EditorMenuItem();
                    menuItem.Header = SR.Get(SRID.TextBox_ContextMenu_More);
                    menuItem.Command = ApplicationCommands.CorrectionList;
                    this.Items.Add(menuItem);
                    menuItem.CommandTarget = textEditor.UiScope;
                }

                return (count > 0) ? true : false;
            }
Example #40
0
 internal InputProviderSite(InputManager inputManager, IInputProvider inputProvider)
 { 
     _inputManager = new SecurityCriticalDataClass<InputManager>(inputManager); 
     _inputProvider = new SecurityCriticalDataClass<IInputProvider>(inputProvider);
 } 
        private void _RegisterTextStore(TextStore textstore)
        {
            UnsafeNativeMethods.ITfDocumentMgr doc;
            UnsafeNativeMethods.ITfContext context;
            UnsafeNativeMethods.ITfSource source;
            int editCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
            int threadFocusCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
            int editSinkCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
            Guid guid;

            Debug.Assert(CheckAccess(), "RegisterTextStore called on bad thread!");

            // Get ITfThreadMgr
            if (_threadManager == null)
            {
                Debug.Assert(_isDispatcherShutdownFinished == false, "Was this dispather finished?");
                Debug.Assert(_registeredtextstorecount == 0, "TextStore was registered without ThreadMgr?");

                // TextServicesLoader.Load() might return null if no text services are installed or enabled.
                _threadManager = new SecurityCriticalDataClass<UnsafeNativeMethods.ITfThreadMgr>(TextServicesLoader.Load());

                if (_threadManager.Value == null)
                {
                    _threadManager = null;
                    return;
                }

                // Activate TSF on this thread if this is the first TextStore.
                int clientIdTemp;
                _threadManager.Value.Activate(out clientIdTemp);
                _clientId = new SecurityCriticalData<int>(clientIdTemp);

                // We want to get the notification when Dispatcher is finished.
                Dispatcher.ShutdownFinished += new EventHandler(OnDispatcherShutdownFinished);
            }

            // Create a TSF document.
            _threadManager.Value.CreateDocumentMgr(out doc);
            doc.CreateContext(_clientId.Value, 0 /* flags */, textstore, out context, out editCookie);
            doc.Push(context);

            // Attach a thread focus sink.
            if (textstore is UnsafeNativeMethods.ITfThreadFocusSink)
            {
                guid = UnsafeNativeMethods.IID_ITfThreadFocusSink;
                source = _threadManager.Value as UnsafeNativeMethods.ITfSource;
                source.AdviseSink(ref guid, textstore, out threadFocusCookie);
            }

            // Attach an edit sink.
            if (textstore is UnsafeNativeMethods.ITfTextEditSink)
            {
                guid = UnsafeNativeMethods.IID_ITfTextEditSink;
                source = context as UnsafeNativeMethods.ITfSource;
                source.AdviseSink(ref guid, textstore, out editSinkCookie);
            }

            // Release any native resources we're done with.
            Marshal.ReleaseComObject(context);

            textstore.DocumentManager = doc;
            textstore.ThreadFocusCookie = threadFocusCookie;
            textstore.EditSinkCookie = editSinkCookie;
            textstore.EditCookie = editCookie;

            // If Scope of this textstore already has a focus, we need to call SetFocus()
            // in order to put this DIM on Cicero's focus. TextStore.OnGotFocus() calls
            // ITfThreadMgr::SetFocus();
            if (textstore.UiScope.IsKeyboardFocused)
            {
                textstore.OnGotFocus();
            }

            _registeredtextstorecount++;
        }
Example #42
0
        public HwndWrapper(
            int classStyle,
            int style,
            int exStyle,
            int x,
            int y,
            int width,
            int height,
            string name,
            IntPtr parent,
            HwndWrapperHook[] hooks)
        {
            _ownerThreadID = new SecurityCriticalDataForSet <int>(Thread.CurrentThread.ManagedThreadId);


            // First, add the set of hooks.  This allows the hooks to receive the
            // messages sent to the window very early in the process.
            if (hooks != null)
            {
                for (int i = 0, iEnd = hooks.Length; i < iEnd; i++)
                {
                    if (null != hooks[i])
                    {
                        AddHook(hooks[i]);
                    }
                }
            }


            _wndProc = new SecurityCriticalData <HwndWrapperHook>(new HwndWrapperHook(WndProc));

            // We create the HwndSubclass object so that we can use its
            // window proc directly.  We will not be "subclassing" the
            // window we create.
            HwndSubclass hwndSubclass = new HwndSubclass(_wndProc.Value);

            // Register a unique window class for this instance.
            NativeMethods.WNDCLASSEX_D wc_d = new NativeMethods.WNDCLASSEX_D();

            IntPtr hNullBrush = UnsafeNativeMethods.CriticalGetStockObject(NativeMethods.NULL_BRUSH);

            if (hNullBrush == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle(null);

            // We need to keep the Delegate object alive through the call to CreateWindowEx().
            // Subclass.WndProc will install a better delegate (to the same function) when it
            // processes the first message.
            // But this first delegate needs be held alive until then.
            NativeMethods.WndProc initialWndProc = new NativeMethods.WndProc(hwndSubclass.SubclassWndProc);

            // The class name is a concat of AppName, ThreadName, and RandomNumber.
            // Register will fail if the string gets over 255 in length.
            // So limit each part to a reasonable amount.
            string appName;

            if (null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length)
            {
                appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128);
            }
            else
            {
                appName = AppDomain.CurrentDomain.FriendlyName;
            }

            string threadName;

            if (null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length)
            {
                threadName = Thread.CurrentThread.Name.Substring(0, 64);
            }
            else
            {
                threadName = Thread.CurrentThread.Name;
            }

            // Create a suitable unique class name.
            _classAtom = 0;
            string randomName = Guid.NewGuid().ToString();
            string className  = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, randomName);

            wc_d.cbSize        = Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX_D));
            wc_d.style         = classStyle;
            wc_d.lpfnWndProc   = initialWndProc;
            wc_d.cbClsExtra    = 0;
            wc_d.cbWndExtra    = 0;
            wc_d.hInstance     = hInstance;
            wc_d.hIcon         = IntPtr.Zero;
            wc_d.hCursor       = IntPtr.Zero;
            wc_d.hbrBackground = hNullBrush;
            wc_d.lpszMenuName  = "";
            wc_d.lpszClassName = className;
            wc_d.hIconSm       = IntPtr.Zero;

            // Register the unique class for this instance.
            // Note we use a GUID in the name so we are confident that
            // the class name should be unique.  And RegisterClassEx won't
            // fail (for that reason).
            _classAtom = UnsafeNativeMethods.RegisterClassEx(wc_d);

            // call CreateWindow
            _isInCreateWindow = true;
            try {
                _handle = new SecurityCriticalDataClass <IntPtr>(UnsafeNativeMethods.CreateWindowEx(exStyle,
                                                                                                    className,
                                                                                                    name,
                                                                                                    style,
                                                                                                    x,
                                                                                                    y,
                                                                                                    width,
                                                                                                    height,
                                                                                                    new HandleRef(null, parent),
                                                                                                    new HandleRef(null, IntPtr.Zero),
                                                                                                    new HandleRef(null, IntPtr.Zero),
                                                                                                    null));
            }
            finally
            {
                _isInCreateWindow = false;
                if (_handle == null || _handle.Value == IntPtr.Zero)
                {
                    // Because the HwndSubclass is pinned, but the HWND creation failed,
                    // we need to manually clean it up.
                    hwndSubclass.Dispose();
                }
            }
            GC.KeepAlive(initialWndProc);
        }
Example #43
0
 internal void AddHookLast(HwndWrapperHook hook)
 {
     if(_hooks == null)
     {
         _hooks = new SecurityCriticalDataClass<WeakReferenceList>(new WeakReferenceList());
     }
     _hooks.Value.Add(hook);
 }
        internal void UpdateState(RawStylusInputReport report)
        {
            Debug.Assert(report.TabletDeviceId == _tabletDevice.Id);
            Debug.Assert((report.Actions & RawStylusActions.None) == 0);

            _eventStylusPoints =
                new StylusPointCollection(  report.StylusPointDescription,
                                            report.GetRawPacketData(),
                                            GetTabletToElementTransform(null),
                                            Matrix.Identity);

            PresentationSource inputSource = DetermineValidSource(report.InputSource, _eventStylusPoints, report.PenContext.Contexts);
            
            // See if we need to remap the stylus data X and Y values to different presentation source.
            if (inputSource != null && inputSource != report.InputSource)
            {
                Point newWindowLocation = PointUtil.ClientToScreen(new Point(0, 0), inputSource);
                newWindowLocation = _stylusLogic.MeasureUnitsFromDeviceUnits(newWindowLocation);
                Point oldWindowLocation = _stylusLogic.MeasureUnitsFromDeviceUnits(report.PenContext.Contexts.DestroyedLocation);
                
                // Create translate matrix transform to shift coords to map points to new window location.
                MatrixTransform additionalTransform = new MatrixTransform(new Matrix(1, 0, 0, 1,
                                                            oldWindowLocation.X - newWindowLocation.X,
                                                            oldWindowLocation.Y - newWindowLocation.Y));
                _eventStylusPoints = _eventStylusPoints.Reformat(report.StylusPointDescription, additionalTransform);
            }

            _rawPosition = _eventStylusPoints[_eventStylusPoints.Count - 1];

            _inputSource = new SecurityCriticalDataClass<PresentationSource>(inputSource);

            if (inputSource != null)
            {
                // Update our screen position from this move.
                Point pt = _stylusLogic.DeviceUnitsFromMeasureUnits((Point)_rawPosition);
                _lastScreenLocation = PointUtil.ClientToScreen(pt, inputSource);
            }
            
            // If we are not blocked from updating the location we want to use for the 
            // promoted mouse location then update it.  We set this flag in the post process phase
            // of Stylus events (after they have fired).
            if (!_fBlockMouseMoveChanges)
            {
                _lastMouseScreenLocation = _lastScreenLocation;
            }

            if ((report.Actions & RawStylusActions.Down) != 0 ||
                 (report.Actions & RawStylusActions.Move) != 0)
            {
                _fInAir = false;

                // Keep the stylus down location for turning system gestures into mouse event
                if ((report.Actions & RawStylusActions.Down) != 0)
                {
                    _needToSendMouseDown = true;
                    // reset the gesture flag.  This is used to determine if we will need to fabricate a systemgesture tap on the 
                    // corresponding up event.
                    _fGestureWasFired = false;
                    _fDetectedDrag = false;
                    _seenHoldEnterGesture = false;

                    // Make sure our drag and move deltas are up to date.
                    TabletDevice.UpdateSizeDeltas(report.StylusPointDescription, _stylusLogic);
                }
                // See if we need to do our own Drag detection (on Stylus Move event)
                else if (inputSource != null && _fBlockMouseMoveChanges && _seenDoubleTapGesture && !_fGestureWasFired && !_fDetectedDrag)
                {
                    Size delta = TabletDevice.CancelSize;

                    // We use the first point of the packet data for Drag detection to try and
                    // filter out cases where the stylus skips when going down.
                    Point dragPosition =(Point)_eventStylusPoints[0];
                    dragPosition = _stylusLogic.DeviceUnitsFromMeasureUnits(dragPosition);
                    dragPosition = PointUtil.ClientToScreen(dragPosition, inputSource);

                    // See if we need to detect a Drag gesture.  If so do the calculation.
                    if ((Math.Abs(_lastMouseScreenLocation.X - dragPosition.X) > delta.Width) ||
                        (Math.Abs(_lastMouseScreenLocation.Y - dragPosition.Y) > delta.Height))
                    {
                        _fDetectedDrag = true;
                    }
                }
            }

            UpdateEventStylusPoints(report, false);

            if ((report.Actions & RawStylusActions.Up)        != 0 ||
                (report.Actions & RawStylusActions.InAirMove) != 0)
            {
                _fInAir = true;
                
                if ((report.Actions & RawStylusActions.Up) != 0)
                {
                    _sawMouseButton1Down = false; // reset this on Stylus Up.
                }
            }
        }
Example #45
0
 internal MouseSink(UnsafeNativeMethods.ITfRangeACP range, UnsafeNativeMethods.ITfMouseSink sink, int cookie)
 {
     _range = new SecurityCriticalDataClass<UnsafeNativeMethods.ITfRangeACP>(range);
     _sink = new SecurityCriticalDataClass<UnsafeNativeMethods.ITfMouseSink>(sink);
     _cookie = cookie;
 }
        private void UpdateStateForSystemGesture(SystemGesture gesture, RawStylusSystemGestureInputReport report)
        {
            switch (gesture)
            {
                case SystemGesture.Tap:
                case SystemGesture.Drag:
                    // request the next mouse move to become LeftButtonDown
                    _fLeftButtonDownTrigger = true;
                    _fGestureWasFired = true;
                    break;
                case SystemGesture.RightTap:
                case SystemGesture.RightDrag:
                    // request the next mouse move to become RightButtonDown
                    _fLeftButtonDownTrigger = false;
                    _fGestureWasFired = true;
                    break;
                case SystemGesture.HoldEnter:
                    // press & hold animation started..
                    _seenHoldEnterGesture = true;
                    break;
                case SystemGesture.Flick:
                    // We don't do any mouse promotion for a flick!
                    _fGestureWasFired = true;

                    // Update the stylus location info just for flick gestures.  This is because
                    // we want to fire the flick event not from the last stylus location
                    // (end of flick gesture) but from the beginning of the flick gesture
                    // (stylus down point) since this is the element that we query whether they
                    // allow flicks and since scrolling is targetted we need to scroll the
                    // element you really flicked on.

                    // Only route the flick if we have data we can send.
                    if (report != null && report.InputSource != null && _eventStylusPoints != null && _eventStylusPoints.Count > 0)
                    {
                        StylusPoint stylusPoint = _eventStylusPoints[_eventStylusPoints.Count - 1];

                        stylusPoint.X = report.GestureX;
                        stylusPoint.Y = report.GestureY;

                        // Update the current point with this data.
                        _eventStylusPoints = new StylusPointCollection(stylusPoint.Description,
                                                                       stylusPoint.GetPacketData(),
                                                                       GetTabletToElementTransform(null),
                                                                       Matrix.Identity);

                        PresentationSource inputSource = DetermineValidSource(report.InputSource, _eventStylusPoints, report.PenContext.Contexts);

                        if (inputSource != null)
                        {
                            // See if we need to remap the stylus data X and Y values to different presentation source.
                            if (inputSource != report.InputSource)
                            {
                                Point newWindowLocation = PointUtil.ClientToScreen(new Point(0, 0), inputSource);
                                newWindowLocation = _stylusLogic.MeasureUnitsFromDeviceUnits(newWindowLocation);
                                Point oldWindowLocation = _stylusLogic.MeasureUnitsFromDeviceUnits(report.PenContext.Contexts.DestroyedLocation);

                                // Create translate matrix transform to shift coords to map points to new window location.
                                MatrixTransform additionalTransform = new MatrixTransform(new Matrix(1, 0, 0, 1,
                                                                            oldWindowLocation.X - newWindowLocation.X,
                                                                            oldWindowLocation.Y - newWindowLocation.Y));
                                _eventStylusPoints = _eventStylusPoints.Reformat(report.StylusPointDescription, additionalTransform);
                            }

                            _rawPosition = _eventStylusPoints[_eventStylusPoints.Count - 1];
                            _inputSource = new SecurityCriticalDataClass<PresentationSource>(inputSource);
                            Point pt = _stylusLogic.DeviceUnitsFromMeasureUnits((Point)_rawPosition);
                            _lastScreenLocation = PointUtil.ClientToScreen(pt, inputSource);
                        }
                    }

                    break;
            }
        }
Example #47
0
 private static void EnsureResourceChangeListener() 
 {
     // Create a new notify window if we haven't already created one for this thread.
     if (_hwndNotify == null)
     { 
         // Create a top-level, invisible window so we can get the WM_THEMECHANGE notification
         // and for HwndHost to park non-visible HwndHosts. 
         HwndWrapper hwndNotify; 
         hwndNotify = new HwndWrapper(0, NativeMethods.WS_POPUP|NativeMethods.WS_DISABLED, 0, 0, 0, 0, 0, "SystemResourceNotifyWindow", IntPtr.Zero, null);
         _hwndNotify = new SecurityCriticalDataClass<HwndWrapper>(hwndNotify); 
         _hwndNotify.Value.Dispatcher.ShutdownFinished += OnShutdownFinished;
         _hwndNotifyHook = new HwndWrapperHook(SystemThemeFilterMessage);
         _hwndNotify.Value.AddHook(_hwndNotifyHook);
     } 
 }
Example #48
0
 internal InputProviderSite(InputManager inputManager, IInputProvider inputProvider)
 {
     _inputManager  = new SecurityCriticalDataClass <InputManager>(inputManager);
     _inputProvider = new SecurityCriticalDataClass <IInputProvider>(inputProvider);
 }
Example #49
0
        private void StartShutdownImpl() 
        {
            if(!_startingShutdown)
            {
                // We only need this to prevent reentrancy if the ShutdownStarted event 
                // tries to shut down again.
                _startingShutdown = true; 
 
                // Call the ShutdownStarted event before we actually mark ourselves
                // as shutting down.  This is so the handlers can actaully do work 
                // when they get this event without throwing exceptions.
                if(ShutdownStarted != null)
                {
                    ShutdownStarted(this, EventArgs.Empty); 
                }
 
                _hasShutdownStarted = true; 

                // Because we may have to defer the actual shutting-down until 
                // later, we need to remember the execution context we started
                // the shutdown from.
                //
                // Note that we demanded permissions when BeginInvokeShutdown 
                // or InvokeShutdown were called.  So if there were not enough
                // permissions, we would have thrown then. 
                // 
                ExecutionContext shutdownExecutionContext = ExecutionContext.Capture();
                _shutdownExecutionContext = new SecurityCriticalDataClass<ExecutionContext>(shutdownExecutionContext); 

                // Tell Win32 to exit the message loop for this thread.
                // NOTE: I removed this code because of bug 1062099.
                // 
                // UnsafeNativeMethods.PostQuitMessage(0);
 
                if(_frameDepth > 0) 
                {
                    // If there are any frames running, we have to wait for them 
                    // to unwind before we can safely destroy the dispatcher.
                }
                else
                { 
                    // The current thread is not spinning inside of the Dispatcher,
                    // so we can go ahead and destroy it. 
                    ShutdownImpl(); 
                }
            } 
        }