internal StylusLogic(InputManager inputManager) { _inputManager = new SecurityCriticalData<InputManager>(inputManager);; _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); _inputManager.Value.PreNotifyInput += new NotifyInputEventHandler(PreNotifyInput); _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput); #if !MULTICAPTURE _overIsEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsEnabledChanged); _overIsVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsVisibleChanged); _overIsHitTestVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsHitTestVisibleChanged); _reevaluateStylusOverDelegate = new DispatcherOperationCallback(ReevaluateStylusOverAsync); _reevaluateStylusOverOperation = null; _captureIsEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsEnabledChanged); _captureIsVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsVisibleChanged); _captureIsHitTestVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsHitTestVisibleChanged); _reevaluateCaptureDelegate = new DispatcherOperationCallback(ReevaluateCaptureAsync); _reevaluateCaptureOperation = null; #endif _shutdownHandler = new EventHandler(this.OnDispatcherShutdown); _processDisplayChanged = new DispatcherOperationCallback(ProcessDisplayChanged); _processDeferredMouseMove = new DispatcherOperationCallback(ProcessDeferredMouseMove); ReadSystemConfig(); _dlgInputManagerProcessInput = new DispatcherOperationCallback(InputManagerProcessInput); }
internal MouseDevice(InputManager inputManager) { _inputManager = new SecurityCriticalData<InputManager>(inputManager); _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); _inputManager.Value.PreNotifyInput += new NotifyInputEventHandler(PreNotifyInput); _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput); // Get information about how far two clicks of a double click can be considered // to be in the "same place and time". // // The call here goes into the safe helper calls, more of a consistency in approach // _doubleClickDeltaX = SafeSystemMetrics.DoubleClickDeltaX; _doubleClickDeltaY = SafeSystemMetrics.DoubleClickDeltaY; _doubleClickDeltaTime = SafeNativeMethods.GetDoubleClickTime(); _overIsEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsEnabledChanged); _overIsVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsVisibleChanged); _overIsHitTestVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnOverIsHitTestVisibleChanged); _reevaluateMouseOverDelegate = new DispatcherOperationCallback(ReevaluateMouseOverAsync); _reevaluateMouseOverOperation = null; _captureIsEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsEnabledChanged); _captureIsVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsVisibleChanged); _captureIsHitTestVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnCaptureIsHitTestVisibleChanged); _reevaluateCaptureDelegate = new DispatcherOperationCallback(ReevaluateCaptureAsync); _reevaluateCaptureOperation = null; _inputManager.Value.HitTestInvalidatedAsync += new EventHandler(OnHitTestInvalidatedAsync); }
/// <summary> /// Loads color profile given by profileUri /// </summary> private void Initialize(Uri profileUri, bool isStandardProfileUriNotFromUser) { bool tryProfileFromResource = false; if (profileUri == null) { throw new ArgumentNullException("profileUri"); } if (!profileUri.IsAbsoluteUri) { throw new ArgumentException(SR.Get(SRID.UriNotAbsolute), "profileUri"); } _profileUri = new SecurityCriticalData <Uri>(profileUri); _isProfileUriNotFromUser = new SecurityCriticalDataForSet <bool>(isStandardProfileUriNotFromUser); Stream profileStream = null; try { profileStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(profileUri); } catch (WebException) { // // If we couldn't load the system's default color profile (e.g. in partial trust), load a color profile from // a resource so the image shows up at least. If the user specified a color profile and we weren't // able to load it, we'll fail to avoid letting the user use this resource fallback as a way to discover // files on disk. // if (isStandardProfileUriNotFromUser) { tryProfileFromResource = true; } } if (profileStream == null) { if (tryProfileFromResource) { ResourceManager resourceManager = new ResourceManager(_colorProfileResources, Assembly.GetAssembly(typeof(ColorContext))); byte[] sRGBProfile = (byte[])resourceManager.GetObject(_sRGBProfileName); profileStream = new MemoryStream(sRGBProfile); } else { // // SECURITY WARNING: This exception includes the profile URI which may contain sensitive information. However, as of right now, // this is safe because it can only happen when the URI is given to us by the user. // Invariant.Assert(!isStandardProfileUriNotFromUser); throw new FileNotFoundException(SR.Get(SRID.FileNotFoundExceptionWithFileName, profileUri.AbsolutePath), profileUri.AbsolutePath); } } FromStream(profileStream, profileUri.AbsolutePath); }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Constructs the DocumentProperties class. /// </summary> /// <param name="uri"></param> private DocumentProperties(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } _uri = new SecurityCriticalData <Uri>(uri); }
private void LoadPixelShaderFromStreamIntoMemory(Stream source) { SecurityHelper.DemandUIWindowPermission(); _shaderBytecode = new SecurityCriticalData <byte[]>(null); if (source != null) { if (!source.CanSeek) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderSeekableStream)); } int len = (int)source.Length; // only works on seekable streams. if (len % sizeof(int) != 0) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderBytecodeSize)); } BinaryReader br = new BinaryReader(source); _shaderBytecode = new SecurityCriticalData <byte[]>(new byte[len]); int lengthRead = br.Read(_shaderBytecode.Value, 0, (int)len); // // The first 4 bytes contain version info in the form of // [Minor][Major][xx][xx] // if (_shaderBytecode.Value != null && _shaderBytecode.Value.Length > 3) { ShaderMajorVersion = _shaderBytecode.Value[1]; ShaderMinorVersion = _shaderBytecode.Value[0]; } else { ShaderMajorVersion = ShaderMinorVersion = 0; } Debug.Assert(len == lengthRead); } // We received new stream data. Need to register for a async update to update the composition // engine. RegisterForAsyncUpdateResource(); // // Notify any ShaderEffects listening that the bytecode changed. // The bytecode may have changed from a ps_3_0 shader to a ps_2_0 shader, and any // ShaderEffects using this PixelShader need to check that they are using only // registers that are valid in ps_2_0. // if (_shaderBytecodeChanged != null) { _shaderBytecodeChanged(this, null); } }
public SourceChangedEventArgs(PresentationSource oldSource, PresentationSource newSource, IInputElement element, IInputElement oldParent) { _oldSource = new SecurityCriticalData <PresentationSource>(oldSource); _newSource = new SecurityCriticalData <PresentationSource>(newSource); _element = element; _oldParent = oldParent; }
public SourceChangedEventArgs(PresentationSource oldSource, PresentationSource newSource, IInputElement element, IInputElement oldParent) { _oldSource = new SecurityCriticalData<PresentationSource>(oldSource); _newSource = new SecurityCriticalData<PresentationSource>(newSource); _element = element; _oldParent = oldParent; }
internal PenContexts(StylusLogic stylusLogic, PresentationSource inputSource) { HwndSource hwndSource = inputSource as HwndSource; if(hwndSource == null || IntPtr.Zero == (hwndSource).CriticalHandle) { throw new InvalidOperationException(SR.Get(SRID.Stylus_PenContextFailure)); } _stylusLogic = stylusLogic; _inputSource = new SecurityCriticalData<HwndSource>(hwndSource); }
///////////////////////////////////////////////////////////////////////// internal PenContexts(WispLogic stylusLogic, PresentationSource inputSource) { HwndSource hwndSource = inputSource as HwndSource; if (hwndSource == null || IntPtr.Zero == (hwndSource).CriticalHandle) { throw new InvalidOperationException(SR.Get(SRID.Stylus_PenContextFailure)); } _stylusLogic = stylusLogic; _inputSource = new SecurityCriticalData <HwndSource>(hwndSource); }
protected InputReport(PresentationSource inputSource, InputType type, InputMode mode, int timestamp) { if (inputSource == null) throw new ArgumentNullException("inputSource"); Validate_InputType( type ); Validate_InputMode( mode ); _inputSource= new SecurityCriticalData<PresentationSource>(inputSource); _type = type; _mode = mode; _timestamp = timestamp; }
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; }
private void CopyCommon(PixelShader shader) { byte[] sourceBytecode = shader._shaderBytecode.Value; byte[] destinationBytecode = null; if (sourceBytecode != null) { destinationBytecode = new byte[sourceBytecode.Length]; sourceBytecode.CopyTo(destinationBytecode, 0); } _shaderBytecode = new SecurityCriticalData <byte[]>(destinationBytecode); }
protected InputReport(PresentationSource inputSource, InputType type, InputMode mode, int timestamp) { if (inputSource == null) { throw new ArgumentNullException("inputSource"); } Validate_InputType(type); Validate_InputMode(mode); _inputSource = new SecurityCriticalData <PresentationSource>(inputSource); _type = type; _mode = mode; _timestamp = timestamp; }
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; }
// Called by framework's TextStore class. This method registers a // document with TSF. The TextServicesContext must maintain this list // to ensure all native resources are released after gc or uninitialization. internal void RegisterTextStore(DefaultTextStore defaultTextStore) { // We must cache the DefaultTextStore because we'll need it from // a worker thread if the AppDomain is torn down before the Dispatcher // is shutdown. _defaultTextStore = defaultTextStore; UnsafeNativeMethods.ITfThreadMgr threadManager = ThreadManager; if (threadManager != null) { UnsafeNativeMethods.ITfDocumentMgr doc; UnsafeNativeMethods.ITfContext context; int editCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; // Activate TSF on this thread if this is the first TextStore. if (_istimactivated == false) { //temp variable created to retrieve the value // which is then stored in the critical data. int clientIdTemp; threadManager.Activate(out clientIdTemp); _clientId = new SecurityCriticalData <int>(clientIdTemp); _istimactivated = true; } // Create a TSF document. threadManager.CreateDocumentMgr(out doc); doc.CreateContext(_clientId.Value, 0 /* flags */, _defaultTextStore, out context, out editCookie); doc.Push(context); // Release any native resources we're done with. Marshal.ReleaseComObject(context); // Same DocumentManager and EditCookie in _defaultTextStore. _defaultTextStore.DocumentManager = doc; _defaultTextStore.EditCookie = editCookie; // Start the transitory extenstion so we can have Level 1 composition window from Cicero. StartTransitoryExtension(); } }
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)); }
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)); }
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)); }
public RawMouseInputReport( InputMode mode, int timestamp, PresentationSource inputSource, RawMouseActions actions, int x, int y, int wheel, IntPtr extraInformation) : base(inputSource, InputType.Mouse, mode, timestamp) { if (!IsValidRawMouseActions(actions)) throw new System.ComponentModel.InvalidEnumArgumentException("actions", (int)actions, typeof(RawMouseActions)); /* we pass a null state from MouseDevice.PreProcessorInput, so null is valid value for state */ _actions = actions; _x = x; _y = y; _wheel = wheel; _extraInformation = new SecurityCriticalData<IntPtr>(extraInformation); }
public RawKeyboardInputReport( PresentationSource inputSource, InputMode mode, int timestamp, RawKeyboardActions actions, int scanCode, bool isExtendedKey, bool isSystemKey, int virtualKey, IntPtr extraInformation) : base(inputSource, InputType.Keyboard, mode, timestamp) { if (!IsValidRawKeyboardActions(actions)) throw new System.ComponentModel.InvalidEnumArgumentException("actions", (int)actions, typeof(RawKeyboardActions)); _actions = actions; _scanCode = scanCode; _isExtendedKey = isExtendedKey; _isSystemKey = isSystemKey; _virtualKey = virtualKey; _extraInformation = new SecurityCriticalData<IntPtr>(extraInformation); }
/// <summary> /// Constructs ad instance of the RawMouseInputReport class. /// </summary> /// <param name="mode"> /// The mode in which the input is being provided. /// </param> /// <param name="timestamp"> /// The time when the input occured. /// </param> /// <param name="inputSource"> /// The PresentationSource over which the mouse is moved. /// </param> /// <param name="actions"> /// The set of actions being reported. /// </param> /// <param name="x"> /// If horizontal position being reported. /// </param> /// <param name="y"> /// If vertical position being reported. /// </param> /// <param name="wheel"> /// If wheel delta being reported. /// </param> /// <param name="extraInformation"> /// Any extra information being provided along with the input. /// </param> public RawMouseInputReport( InputMode mode, int timestamp, PresentationSource inputSource, RawMouseActions actions, int x, int y, int wheel, IntPtr extraInformation) : base(inputSource, InputType.Mouse, mode, timestamp) { if (!IsValidRawMouseActions(actions)) { throw new System.ComponentModel.InvalidEnumArgumentException("actions", (int)actions, typeof(RawMouseActions)); } /* we pass a null state from MouseDevice.PreProcessorInput, so null is valid value for state */ _actions = actions; _x = x; _y = y; _wheel = wheel; _extraInformation = new SecurityCriticalData <IntPtr>(extraInformation); }
/// <summary> /// Constructs ad instance of the RawKeyboardInputReport class. /// </summary> /// <param name="inputSource"> /// The input source that provided this input. /// </param> /// <param name="mode"> /// The mode in which the input is being provided. /// </param> /// <param name="timestamp"> /// The time when the input occurred. /// </param> /// <param name="actions"> /// The set of actions being reported. /// </param> /// <param name="scanCode"> /// The scan code if a key is being reported. /// </param> /// <param name="isExtendedKey"> /// The true if a key is an extended key. /// </param> /// <param name="isSystemKey"> /// The true if a key is a system key. /// </param> /// <param name="virtualKey"> /// The Win32 virtual key code if a key is being reported. /// </param> /// <param name="extraInformation"> /// Any extra information being provided along with the input. /// </param> public RawKeyboardInputReport( PresentationSource inputSource, InputMode mode, int timestamp, RawKeyboardActions actions, int scanCode, bool isExtendedKey, bool isSystemKey, int virtualKey, IntPtr extraInformation) : base(inputSource, InputType.Keyboard, mode, timestamp) { if (!IsValidRawKeyboardActions(actions)) { throw new System.ComponentModel.InvalidEnumArgumentException("actions", (int)actions, typeof(RawKeyboardActions)); } _actions = actions; _scanCode = scanCode; _isExtendedKey = isExtendedKey; _isSystemKey = isSystemKey; _virtualKey = virtualKey; _extraInformation = new SecurityCriticalData <IntPtr>(extraInformation); }
public virtual void ValidateRelationships(SecurityCriticalData<Package> package, Uri packageUri, Uri partUri, ContentType mimeType) { }
internal CommandDevice( InputManager inputManager ) { _inputManager = new SecurityCriticalData<InputManager>(inputManager); _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput); }
public override void ValidateRelationships(SecurityCriticalData <Package> package, Uri packageUri, Uri partUri, ContentType mimeType) { PackagePart part = package.Value.GetPart(partUri); PackageRelationshipCollection relationshipsByType = part.GetRelationshipsByType("http://schemas.microsoft.com/xps/2005/06/printticket"); int num = 0; foreach (PackageRelationship packageRelationship in relationshipsByType) { num++; if (num > 1) { throw new FileFormatException(SR.Get("XpsValidatingLoaderMoreThanOnePrintTicketPart")); } Uri partUri2 = PackUriHelper.ResolvePartUri(partUri, packageRelationship.TargetUri); Uri uri = PackUriHelper.Create(packageUri, partUri2); PackagePart part2 = package.Value.GetPart(partUri2); if (!XpsS0Schema._printTicketContentType.AreTypeAndSubTypeEqual(new ContentType(part2.ContentType))) { throw new FileFormatException(SR.Get("XpsValidatingLoaderPrintTicketHasIncorrectType")); } } relationshipsByType = part.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"); num = 0; foreach (PackageRelationship packageRelationship2 in relationshipsByType) { num++; if (num > 1) { throw new FileFormatException(SR.Get("XpsValidatingLoaderMoreThanOneThumbnailPart")); } Uri partUri3 = PackUriHelper.ResolvePartUri(partUri, packageRelationship2.TargetUri); Uri uri2 = PackUriHelper.Create(packageUri, partUri3); PackagePart part3 = package.Value.GetPart(partUri3); if (!XpsS0Schema._jpgContentType.AreTypeAndSubTypeEqual(new ContentType(part3.ContentType)) && !XpsS0Schema._pngContentType.AreTypeAndSubTypeEqual(new ContentType(part3.ContentType))) { throw new FileFormatException(SR.Get("XpsValidatingLoaderThumbnailHasIncorrectType")); } } if (XpsS0Schema._fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType)) { relationshipsByType = part.GetRelationshipsByType("http://schemas.microsoft.com/xps/2005/06/restricted-font"); foreach (PackageRelationship packageRelationship3 in relationshipsByType) { Uri partUri4 = PackUriHelper.ResolvePartUri(partUri, packageRelationship3.TargetUri); Uri uri3 = PackUriHelper.Create(packageUri, partUri4); PackagePart part4 = package.Value.GetPart(partUri4); if (!XpsS0Schema._fontContentType.AreTypeAndSubTypeEqual(new ContentType(part4.ContentType)) && !XpsS0Schema._obfuscatedContentType.AreTypeAndSubTypeEqual(new ContentType(part4.ContentType))) { throw new FileFormatException(SR.Get("XpsValidatingLoaderRestrictedFontHasIncorrectType")); } } } if (XpsS0Schema._fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType)) { relationshipsByType = package.Value.GetRelationshipsByType("http://schemas.microsoft.com/xps/2005/06/discard-control"); num = 0; foreach (PackageRelationship packageRelationship4 in relationshipsByType) { num++; if (num > 1) { throw new FileFormatException(SR.Get("XpsValidatingLoaderMoreThanOneDiscardControlInPackage")); } Uri partUri5 = PackUriHelper.ResolvePartUri(partUri, packageRelationship4.TargetUri); Uri uri4 = PackUriHelper.Create(packageUri, partUri5); PackagePart part5 = package.Value.GetPart(partUri5); if (!XpsS0Schema._discardControlContentType.AreTypeAndSubTypeEqual(new ContentType(part5.ContentType))) { throw new FileFormatException(SR.Get("XpsValidatingLoaderDiscardControlHasIncorrectType")); } } relationshipsByType = package.Value.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"); num = 0; foreach (PackageRelationship packageRelationship5 in relationshipsByType) { num++; if (num > 1) { throw new FileFormatException(SR.Get("XpsValidatingLoaderMoreThanOneThumbnailInPackage")); } Uri partUri6 = PackUriHelper.ResolvePartUri(partUri, packageRelationship5.TargetUri); Uri uri5 = PackUriHelper.Create(packageUri, partUri6); PackagePart part6 = package.Value.GetPart(partUri6); if (!XpsS0Schema._jpgContentType.AreTypeAndSubTypeEqual(new ContentType(part6.ContentType)) && !XpsS0Schema._pngContentType.AreTypeAndSubTypeEqual(new ContentType(part6.ContentType))) { throw new FileFormatException(SR.Get("XpsValidatingLoaderThumbnailHasIncorrectType")); } } } }
internal void Cleanup() { if (Application.Current != null) { IBrowserCallbackServices bcs = Application.Current.BrowserCallbackServices; if (bcs != null) { Debug.Assert(!Application.IsApplicationObjectShuttingDown); // Marshal.ReleaseComObject(bcs) has to be called so that the refcount of the // native objects goes to zero for clean shutdown. But it should not be called // right away, because there may still be DispatcherOperations in the queue // that will attempt to use IBCS, especially during downloading/activation. // Last, it can't be called with prioroty lower than Normal, because that's // the priority of Applicatoin.ShudownCallback(), which shuts down the // Dispatcher. Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new DispatcherOperationCallback(ReleaseBrowserCallback), bcs); } } ServiceProvider = null; ClearRootBrowserWindow(); if (_storageRoot != null && _storageRoot.Value != null) { _storageRoot.Value.Close(); } // Due to the dependecies the following objects have to be released // in the following order: _document, DocumentManager, // _packageStream, _unmanagedStream. if (_document.Value is PackageDocument) { // We are about to close the package ad remove it from the Preloaded Packages Store. // Let's make sure that the data structures are consistent. The package that we hold is // actually in the store under the URI that we think it should be using Debug.Assert(((PackageDocument)_document.Value).Package == PreloadedPackages.GetPackage(PackUriHelper.GetPackageUri(PackUriHelper.Create(Uri)))); // We need to remove the Package from the PreloadedPackage storage, // so that potential future requests would fail in a way of returning a null (resource not found) // rather then return a Package or stream that is already Closed PreloadedPackages.RemovePackage(PackUriHelper.GetPackageUri(PackUriHelper.Create(Uri))); ((PackageDocument)_document.Value).Dispose(); _document.Value = null; } if (_mimeType.Value == MimeType.Document) { DocumentManager.CleanUp(); } if (_packageStream.Value != null) { _packageStream.Value.Close(); } if (_unmanagedStream.Value != null) { Marshal.ReleaseComObject(_unmanagedStream.Value); _unmanagedStream = new SecurityCriticalData <object>(null); } }
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++; }
static Classification() { unsafe { RawClassificationTables ct = new RawClassificationTables(); MILGetClassificationTables(out ct); _unicodeClassTable = new SecurityCriticalData<IntPtr>(ct.UnicodeClasses); _charAttributeTable = new SecurityCriticalData<IntPtr>(ct.CharacterAttributes); _mirroredCharTable = new SecurityCriticalData<IntPtr>(ct.Mirroring); _combiningMarksClassification = new SecurityCriticalData<CombiningMarksClassificationData>(ct.CombiningMarksClassification); } }
void IKeyboardInputSite.Unregister() { _sink = new SecurityCriticalData <IKeyboardInputSink>(null); }
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); }
public virtual void ValidateRelationships(SecurityCriticalData <Package> package, Uri packageUri, Uri partUri, ContentType mimeType) { }
internal void Cleanup() { if (Application.Current != null) { IBrowserCallbackServices bcs = Application.Current.BrowserCallbackServices; if (bcs != null) { Debug.Assert(!Application.IsApplicationObjectShuttingDown); // Marshal.ReleaseComObject(bcs) has to be called so that the refcount of the // native objects goes to zero for clean shutdown. But it should not be called // right away, because there may still be DispatcherOperations in the queue // that will attempt to use IBCS, especially during downloading/activation. // Last, it can't be called with prioroty lower than Normal, because that's // the priority of Applicatoin.ShudownCallback(), which shuts down the // Dispatcher. Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new DispatcherOperationCallback(ReleaseBrowserCallback), bcs); } } ServiceProvider = null; ClearRootBrowserWindow(); if (_storageRoot != null && _storageRoot.Value != null ) { _storageRoot.Value.Close(); } // Due to the dependecies the following objects have to be released // in the following order: _document, DocumentManager, // _packageStream, _unmanagedStream. if (_document.Value is PackageDocument) { // We are about to close the package ad remove it from the Preloaded Packages Store. // Let's make sure that the data structures are consistent. The package that we hold is // actually in the store under the URI that we think it should be using Debug.Assert(((PackageDocument)_document.Value).Package == PreloadedPackages.GetPackage(PackUriHelper.GetPackageUri(PackUriHelper.Create(Uri)))); // We need to remove the Package from the PreloadedPackage storage, // so that potential future requests would fail in a way of returning a null (resource not found) // rather then return a Package or stream that is already Closed PreloadedPackages.RemovePackage(PackUriHelper.GetPackageUri(PackUriHelper.Create(Uri))); ((PackageDocument)_document.Value).Dispose(); _document.Value = null; } if (_mimeType.Value == MimeType.Document) { DocumentManager.CleanUp(); } if (_packageStream.Value != null) { _packageStream.Value.Close(); } if (_unmanagedStream.Value != null) { Marshal.ReleaseComObject(_unmanagedStream.Value); _unmanagedStream = new SecurityCriticalData<object>(null); } }
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++; }
internal PenThreadWorker() { IntPtr resetHandle; // Consider: We could use a AutoResetEvent handle instead and avoid the penimc.dll call. MS.Win32.Penimc.UnsafeNativeMethods.CreateResetEvent(out resetHandle); _pimcResetHandle = new SecurityCriticalData<IntPtr>(resetHandle); WorkerOperationThreadStart started = new WorkerOperationThreadStart(); lock(_workerOperationLock) { _workerOperation.Add((WorkerOperation)started); } Thread thread = new Thread(new ThreadStart(ThreadProc)); thread.IsBackground = true; // don't hold process open due to this thread. thread.Start(); // Wait for this work to be completed (ie thread is started up). started.DoneEvent.WaitOne(); started.DoneEvent.Close(); }
private Dispatcher() { _queue = new PriorityQueue<DispatcherOperation>(); _tlsDispatcher = this; // use TLS for ownership only _dispatcherThread = Thread.CurrentThread; // Add ourselves to the map of dispatchers to threads. lock(_globalLock) { _dispatchers.Add(new WeakReference(this)); } _unhandledExceptionEventArgs = new DispatcherUnhandledExceptionEventArgs(this); _exceptionFilterEventArgs = new DispatcherUnhandledExceptionFilterEventArgs(this); _dispatcherSynchronizationContext = new DispatcherSynchronizationContext(this); // Create the message-only window we use to receive messages // that tell us to process the queue. MessageOnlyHwndWrapper window = new MessageOnlyHwndWrapper(); _window = new SecurityCriticalData<MessageOnlyHwndWrapper>( window ); _hook = new HwndWrapperHook(WndProcHook); _window.Value.AddHook(_hook); }
internal void RegisterTextStore(DefaultTextStore defaultTextStore) { // We must cache the DefaultTextStore because we'll need it from // a worker thread if the AppDomain is torn down before the Dispatcher // is shutdown. _defaultTextStore = defaultTextStore; UnsafeNativeMethods.ITfThreadMgr threadManager = ThreadManager; if (threadManager != null) { UnsafeNativeMethods.ITfDocumentMgr doc; UnsafeNativeMethods.ITfContext context; int editCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; // Activate TSF on this thread if this is the first TextStore. if (_istimactivated == false) { //temp variable created to retrieve the value // which is then stored in the critical data. int clientIdTemp; threadManager.Activate(out clientIdTemp); _clientId = new SecurityCriticalData<int>(clientIdTemp); _istimactivated = true; } // Create a TSF document. threadManager.CreateDocumentMgr(out doc); doc.CreateContext(_clientId.Value, 0 /* flags */, _defaultTextStore, out context, out editCookie); doc.Push(context); // Release any native resources we're done with. Marshal.ReleaseComObject(context); // Same DocumentManager and EditCookie in _defaultTextStore. _defaultTextStore.DocumentManager = doc; _defaultTextStore.EditCookie = editCookie; // Start the transitory extenstion so we can have Level 1 composition window from Cicero. StartTransitoryExtension(); } }
public override void ValidateRelationships(SecurityCriticalData<Package> package, Uri packageUri, Uri partUri, ContentType mimeType) { PackagePart part = package.Value.GetPart(partUri); PackageRelationshipCollection checkRels; int count; // Can only have 0 or 1 PrintTicket per FDS, FD or FP part checkRels = part.GetRelationshipsByType(_printTicketRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOnePrintTicketPart)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_printTicketContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderPrintTicketHasIncorrectType)); } } checkRels = part.GetRelationshipsByType(_thumbnailRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailPart)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType)); } } // FixedDocument only has restricted font relationships if (_fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType)) { // Check if target of restricted font relationship is present and is actually a font checkRels = part.GetRelationshipsByType(_restrictedFontRel); foreach (PackageRelationship rel in checkRels) { // Check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_fontContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_obfuscatedContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderRestrictedFontHasIncorrectType)); } } } // check constraints for XPS fixed payload start part if (_fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType)) { // This is the XPS payload root part. We also should check if the Package only has at most one discardcontrol... checkRels = package.Value.GetRelationshipsByType(_discardControlRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneDiscardControlInPackage)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_discardControlContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderDiscardControlHasIncorrectType)); } } // This is the XPS payload root part. We also should check if the Package only has at most one thumbnail... checkRels = package.Value.GetRelationshipsByType(_thumbnailRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailInPackage)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType)); } } } }
private void LoadPixelShaderFromStreamIntoMemory(Stream source) { SecurityHelper.DemandUIWindowPermission(); _shaderBytecode = new SecurityCriticalData<byte[]>(null); if (source != null) { if (!source.CanSeek) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderSeekableStream)); } int len = (int)source.Length; // only works on seekable streams. if (len % sizeof(int) != 0) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderBytecodeSize)); } BinaryReader br = new BinaryReader(source); _shaderBytecode = new SecurityCriticalData<byte[]>(new byte[len]); int lengthRead = br.Read(_shaderBytecode.Value, 0, (int)len); // // The first 4 bytes contain version info in the form of // [Minor][Major][xx][xx] // if (_shaderBytecode.Value != null && _shaderBytecode.Value.Length > 3) { ShaderMajorVersion = _shaderBytecode.Value[1]; ShaderMinorVersion = _shaderBytecode.Value[0]; } else { ShaderMajorVersion = ShaderMinorVersion = 0; } Debug.Assert(len == lengthRead); } // We received new stream data. Need to register for a async update to update the composition // engine. RegisterForAsyncUpdateResource(); // // Notify any ShaderEffects listening that the bytecode changed. // The bytecode may have changed from a ps_3_0 shader to a ps_2_0 shader, and any // ShaderEffects using this PixelShader need to check that they are using only // registers that are valid in ps_2_0. // if (_shaderBytecodeChanged != null) { _shaderBytecodeChanged(this, null); } }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ internal TextServicesCompartment(Guid guid, UnsafeNativeMethods.ITfCompartmentMgr compartmentmgr) { _guid = guid; _compartmentmgr = new SecurityCriticalData <UnsafeNativeMethods.ITfCompartmentMgr>(compartmentmgr); _cookie = UnsafeNativeMethods.TF_INVALID_COOKIE; }
private void ShutdownImplInSecurityContext(Object state) { // Call the ShutdownFinished event before we actually mark ourselves // as shut down. This is so the handlers can actaully do work // when they get this event without throwing exceptions. if(ShutdownFinished != null) { ShutdownFinished(this, EventArgs.Empty); } // Destroy the message-only window we use to process Win32 messages // // Note: we need to do this BEFORE we actually mark the dispatcher // as shutdown. This is because the window will need the dispatcher // to execute the window proc. MessageOnlyHwndWrapper window = null; lock(_instanceLock) { window = _window.Value; _window = new SecurityCriticalData<MessageOnlyHwndWrapper>(null); } window.Dispose(); // Mark this dispatcher as shut down. Attempts to BeginInvoke // or Invoke will result in an exception. lock(_instanceLock) { _hasShutdownFinished = true; // Dispatcher thread - lock to write } // Now that the queue is off-line, abort all pending operations, // including inactive ones. DispatcherOperation operation = null; do { lock(_instanceLock) { if(_queue.MaxPriority != DispatcherPriority.Invalid) { operation = _queue.Peek(); } else { operation = null; } } if(operation != null) { operation.Abort(); } } while(operation != null); // clear out the fields that could be holding onto large graphs of objects. lock(_instanceLock) { // We should not need the queue any more. _queue = null; // We should not need the timers any more. _timers = null; // Clear out the reserved fields. _reserved0 = null; _reserved1 = null; _reserved2 = null; _reserved3 = null; _reserved4 = null; // _reservedPtsCache = null; // PTS needs this in a finalizer... the PTS code should not assume access to this in their finalizer. _reservedInputMethod = null; _reservedInputManager = null; } // Note: the Dispatcher is still held in TLS. This maintains the 1-1 relationship // between the thread and the Dispatcher. However the dispatcher is basically // dead - it has been marked as _hasShutdownFinished, and most operations are // now illegal. }
private void CopyCommon(PixelShader shader) { byte[] sourceBytecode = shader._shaderBytecode.Value; byte[] destinationBytecode = null; if (sourceBytecode != null) { destinationBytecode = new byte[sourceBytecode.Length]; sourceBytecode.CopyTo(destinationBytecode, 0); } _shaderBytecode = new SecurityCriticalData<byte[]>(destinationBytecode); }
internal KeyInputSite(SecurityCriticalData <IKeyboardInputSink> sink) { _sink = sink; }
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); }
internal CommandDevice(InputManager inputManager) { _inputManager = new SecurityCriticalData <InputManager>(inputManager); _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput); }
public override void ValidateRelationships(SecurityCriticalData <Package> package, Uri packageUri, Uri partUri, ContentType mimeType) { PackagePart part = package.Value.GetPart(partUri); PackageRelationshipCollection checkRels; int count; // Can only have 0 or 1 PrintTicket per FDS, FD or FP part checkRels = part.GetRelationshipsByType(_printTicketRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOnePrintTicketPart)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_printTicketContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderPrintTicketHasIncorrectType)); } } checkRels = part.GetRelationshipsByType(_thumbnailRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailPart)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType)); } } // FixedDocument only has restricted font relationships if (_fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType)) { // Check if target of restricted font relationship is present and is actually a font checkRels = part.GetRelationshipsByType(_restrictedFontRel); foreach (PackageRelationship rel in checkRels) { // Check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_fontContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_obfuscatedContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderRestrictedFontHasIncorrectType)); } } } // check constraints for XPS fixed payload start part if (_fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType)) { // This is the XPS payload root part. We also should check if the Package only has at most one discardcontrol... checkRels = package.Value.GetRelationshipsByType(_discardControlRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneDiscardControlInPackage)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_discardControlContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderDiscardControlHasIncorrectType)); } } // This is the XPS payload root part. We also should check if the Package only has at most one thumbnail... checkRels = package.Value.GetRelationshipsByType(_thumbnailRel); count = 0; foreach (PackageRelationship rel in checkRels) { count++; if (count > 1) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailInPackage)); } // Also check for existence and type Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.Value.GetPart(targetUri); if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) && !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType))) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType)); } } } }
[SecurityCritical] private void Initialize(Uri profileUri, bool isStandardProfileUriNotFromUser) { bool tryProfileFromResource = false; if (profileUri == null) { throw new ArgumentNullException("profileUri"); } if (!profileUri.IsAbsoluteUri) { throw new ArgumentException(SR.Get(SRID.UriNotAbsolute), "profileUri"); } _profileUri = new SecurityCriticalData<Uri>(profileUri); _isProfileUriNotFromUser = new SecurityCriticalDataForSet<bool>(isStandardProfileUriNotFromUser); Stream profileStream = null; try { profileStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(profileUri); } catch (WebException) { // // If we couldn't load the system's default color profile (e.g. in partial trust), load a color profile from // a resource so the image shows up at least. If the user specified a color profile and we weren't // able to load it, we'll fail to avoid letting the user use this resource fallback as a way to discover // files on disk. // if (isStandardProfileUriNotFromUser) { tryProfileFromResource = true; } } if (profileStream == null) { if (tryProfileFromResource) { ResourceManager resourceManager = new ResourceManager(_colorProfileResources, Assembly.GetAssembly(typeof(ColorContext))); byte[] sRGBProfile = (byte[])resourceManager.GetObject(_sRGBProfileName); profileStream = new MemoryStream(sRGBProfile); } else { // // SECURITY WARNING: This exception includes the profile URI which may contain sensitive information. However, as of right now, // this is safe because it can only happen when the URI is given to us by the user. // Invariant.Assert(!isStandardProfileUriNotFromUser); throw new FileNotFoundException(SR.Get(SRID.FileNotFoundExceptionWithFileName, profileUri.AbsolutePath), profileUri.AbsolutePath); } } FromStream(profileStream, profileUri.AbsolutePath);
internal PointerStylusPlugInManager(PresentationSource source) { _inputSource = new SecurityCriticalData <PresentationSource>(source); }
internal KeyInputSite(SecurityCriticalData<IKeyboardInputSink> sink) { _sink = sink; }
void IKeyboardInputSite.Unregister() { _sink = new SecurityCriticalData<IKeyboardInputSink>(null); }
internal TextServicesCompartment(Guid guid, UnsafeNativeMethods.ITfCompartmentMgr compartmentmgr) { _guid = guid; _compartmentmgr = new SecurityCriticalData<UnsafeNativeMethods.ITfCompartmentMgr>(compartmentmgr); _cookie = UnsafeNativeMethods.TF_INVALID_COOKIE; }