internal void OnPageBreakRecordCreated(SecurityCriticalDataForSet <IntPtr> br)
 {
     Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");
     Invariant.Assert(!this.Disposed, "PtsContext is already disposed.");
     Invariant.Assert(!this._pageBreakRecords.Contains(br.Value), "Break record already exists.");
     this._pageBreakRecords.Add(br.Value);
 }
 internal void OnPageCreated(SecurityCriticalDataForSet <IntPtr> ptsPage)
 {
     Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");
     Invariant.Assert(!this.Disposed, "PtsContext is already disposed.");
     Invariant.Assert(!this._pages.Contains(ptsPage.Value), "Page already exists.");
     this._pages.Add(ptsPage.Value);
 }
 private void OnDestroyPage(SecurityCriticalDataForSet <IntPtr> ptsPage, bool enterContext)
 {
     Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");
     if (!this.Disposed)
     {
         Invariant.Assert(this._pages != null, "Collection of pages does not exist.");
         Invariant.Assert(this._pages.Contains(ptsPage.Value), "Page does not exist.");
         try
         {
             if (enterContext)
             {
                 this.Enter();
             }
             PTS.Validate(PTS.FsDestroyPage(this._ptsHost.Context, ptsPage.Value));
         }
         finally
         {
             if (enterContext)
             {
                 this.Leave();
             }
             this._pages.Remove(ptsPage.Value);
         }
     }
 }
        // Token: 0x06006927 RID: 26919 RVA: 0x001DC11C File Offset: 0x001DA31C
        private object OnDestroyPage(object args)
        {
            SecurityCriticalDataForSet <IntPtr> ptsPage = (SecurityCriticalDataForSet <IntPtr>)args;

            this.OnDestroyPage(ptsPage, true);
            return(null);
        }
Beispiel #5
0
 static BaseUriHelper()
 {
     _baseUri = new SecurityCriticalDataForSet <Uri>(_packAppBaseUri);
     // Add an instance of the ResourceContainer to PreloadedPackages so that PackWebRequestFactory can find it
     // and mark it as thread-safe so PackWebResponse won't protect returned streams with a synchronizing wrapper
     PreloadedPackages.AddPackage(PackUriHelper.GetPackageUri(SiteOfOriginBaseUri), new SiteOfOriginContainer(), true);
 }
Beispiel #6
0
        /// <summary>
        /// Destroys PTS page break record.
        /// </summary>
        /// <param name="args">Pointer to PTS Page BreakRecord object that should be destroyed.</param>
        private object OnDestroyBreakRecord(object args)
        {
            SecurityCriticalDataForSet <IntPtr> br = (SecurityCriticalDataForSet <IntPtr>)args;

            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");

            // Dispatcher may invoke this operation when PtsContext is already explicitly
            // disposed.
            if (!this.Disposed)
            {
                Invariant.Assert(_pageBreakRecords != null, "Collection of break records does not exist.");
                Invariant.Assert(_pageBreakRecords.Contains(br.Value), "Break record does not exist.");

                // Destroy given page break record.
                // It is necessary to enter PTS Context when executing any PTS methods.
                try
                {
                    Enter();
                    PTS.Validate(PTS.FsDestroyPageBreakRecord(_ptsHost.Context, br.Value));
                }
                finally
                {
                    Leave();
                    _pageBreakRecords.Remove(br.Value);
                }
            }
            return(null);
        }
Beispiel #7
0
        /// <summary>
        /// Destroys PTS page.
        /// </summary>
        /// <param name="ptsPage">Pointer to PTS Page object that should be destroyed.</param>
        /// <param name="enterContext">Whether needs to enter PTS Context.</param>
        private void OnDestroyPage(SecurityCriticalDataForSet <IntPtr> ptsPage, bool enterContext)
        {
            Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");

            // Dispatcher may invoke this operation when PtsContext is already explicitly
            // disposed.
            if (!this.Disposed)
            {
                Invariant.Assert(_pages != null, "Collection of pages does not exist.");
                Invariant.Assert(_pages.Contains(ptsPage.Value), "Page does not exist.");

                // Destroy given page.
                // It is necessary to enter PTS Context when executing any PTS methods.
                try
                {
                    if (enterContext)
                    {
                        Enter();
                    }
                    PTS.Validate(PTS.FsDestroyPage(_ptsHost.Context, ptsPage.Value));
                }
                finally
                {
                    if (enterContext)
                    {
                        Leave();
                    }
                    _pages.Remove(ptsPage.Value);
                }
            }
        }
Beispiel #8
0
 static BaseUriHelper()
 {
     _baseUri = new SecurityCriticalDataForSet<Uri>(_packAppBaseUri);
     // Add an instance of the ResourceContainer to PreloadedPackages so that PackWebRequestFactory can find it
     // and mark it as thread-safe so PackWebResponse won't protect returned streams with a synchronizing wrapper
     PreloadedPackages.AddPackage(PackUriHelper.GetPackageUri(SiteOfOriginBaseUri), new SiteOfOriginContainer(), true);
 }
Beispiel #9
0
        /// <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);
        }
Beispiel #10
0
        internal PixelFormat(PixelFormatEnum format)
        {
            _format = format;

            _flags        = GetPixelFormatFlagsFromEnum(format);
            _bitsPerPixel = GetBitsPerPixelFromEnum(format);
            _guidFormat   = new SecurityCriticalDataForSet <Guid> (PixelFormat.GetGuidFromFormat(format));
        }
Beispiel #11
0
 // Token: 0x060068EB RID: 26859 RVA: 0x001D9960 File Offset: 0x001D7B60
 internal PageBreakRecord(PtsContext ptsContext, SecurityCriticalDataForSet <IntPtr> br, int pageNumber)
 {
     Invariant.Assert(ptsContext != null, "Invalid PtsContext object.");
     Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");
     this._br         = br;
     this._pageNumber = pageNumber;
     this._ptsContext = new WeakReference(ptsContext);
     ptsContext.OnPageBreakRecordCreated(this._br);
 }
Beispiel #12
0
        internal ByteStream(object underlyingStream, FileAccess openAccess)
        { 
            SecuritySuppressedIStream stream = underlyingStream as SecuritySuppressedIStream; 
            Debug.Assert(stream != null);
 
            _securitySuppressedIStream = new SecurityCriticalDataForSet<SecuritySuppressedIStream>(stream);

            _access = openAccess;
            // we only work for reading. 
            Debug.Assert(_access == FileAccess.Read);
        } 
Beispiel #13
0
        internal TextPenaltyModule(SecurityCriticalDataForSet<IntPtr> ploc) 
        { 
            IntPtr ploPenaltyModule;
            LsErr lserr = UnsafeNativeMethods.LoAcquirePenaltyModule(ploc.Value, out ploPenaltyModule); 
            if (lserr != LsErr.None)
            {
                TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.AcquirePenaltyModuleFailure, lserr), lserr);
            } 

            _ploPenaltyModule.Value = ploPenaltyModule; 
        } 
Beispiel #14
0
        internal TextPenaltyModule(SecurityCriticalDataForSet <IntPtr> ploc)
        {
            IntPtr ploPenaltyModule;
            LsErr  lserr = UnsafeNativeMethods.LoAcquirePenaltyModule(ploc.Value, out ploPenaltyModule);

            if (lserr != LsErr.None)
            {
                TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.AcquirePenaltyModuleFailure, lserr), lserr);
            }

            _ploPenaltyModule.Value = ploPenaltyModule;
        }
Beispiel #15
0
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------
        #region Constructors

        /// <summary>
        /// Constructs a ByteStream class from a supplied unmanaged stream with the specified access.
        /// </summary>
        /// <param name="underlyingStream"></param>
        /// <param name="openAccess"></param>
        internal ByteStream(object underlyingStream, FileAccess openAccess)
        {
            SecuritySuppressedIStream stream = underlyingStream as SecuritySuppressedIStream;

            Debug.Assert(stream != null);

            _securitySuppressedIStream = new SecurityCriticalDataForSet <SecuritySuppressedIStream>(stream);

            _access = openAccess;
            // we only work for reading.
            Debug.Assert(_access == FileAccess.Read);
        }
Beispiel #16
0
        private void Initialize(bool fTrusted)
        {
            _fTrusted = new SecurityCriticalDataForSet <bool> (fTrusted);

            _hwndSubclassHook      = new HwndWrapperHook(SubclassWndProc);
            _handlerLayoutUpdated  = new EventHandler(OnLayoutUpdated);
            _handlerEnabledChanged = new DependencyPropertyChangedEventHandler(OnEnabledChanged);
            _handlerVisibleChanged = new DependencyPropertyChangedEventHandler(OnVisibleChanged);
            PresentationSource.AddSourceChangedHandler(this, new SourceChangedEventHandler(OnSourceChanged));

            _weakEventDispatcherShutdown = new WeakEventDispatcherShutdown(this, this.Dispatcher);
        }
 // Token: 0x0600691B RID: 26907 RVA: 0x001DBEE8 File Offset: 0x001DA0E8
 internal void OnPageDisposed(SecurityCriticalDataForSet <IntPtr> ptsPage, bool disposing, bool enterContext)
 {
     Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");
     if (disposing)
     {
         this.OnDestroyPage(ptsPage, enterContext);
         return;
     }
     if (!this.Disposed && !base.Dispatcher.HasShutdownStarted)
     {
         base.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(this.OnDestroyPage), ptsPage);
     }
 }
 // Token: 0x0600691D RID: 26909 RVA: 0x001DBFC8 File Offset: 0x001DA1C8
 internal void OnPageBreakRecordDisposed(SecurityCriticalDataForSet <IntPtr> br, bool disposing)
 {
     Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");
     if (disposing)
     {
         this.OnDestroyBreakRecord(br);
         return;
     }
     if (!this.Disposed && !base.Dispatcher.HasShutdownStarted)
     {
         base.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(this.OnDestroyBreakRecord), br);
     }
 }
Beispiel #19
0
        //--------------------------------------------------------------------------
        // Constructors
        //-------------------------------------------------------------------------

        /// <summary>
        /// Requires an existing open Package; and returns a package which will
        /// capture changes with out applying them to the original.
        /// See the class description for details.
        /// </summary>
        /// <exception cref="System.ArgumentNullException" />
        /// <example>
        /// Package package = new TransactionalPackage(
        ///     Package.Open(source, FileMode.Open, FileAccess.Read));
        /// </example>
        /// <param name="originalPackage">An open package.</param>
        internal TransactionalPackage(Stream original)
            : base(FileAccess.ReadWrite)
        {
            if (original == null)
            {
                throw new ArgumentNullException("original");
            }

            Package originalPackage = Package.Open(original);

            _originalPackage = new SecurityCriticalDataForSet <Package>(originalPackage);
            _tempPackage     = new SecurityCriticalDataForSet <Package>(null);
        }
        /// <summary>
        /// Internallly construct the line break
        /// </summary>
        internal TextLineBreak(
            TextModifierScope                   currentScope,
            SecurityCriticalDataForSet<IntPtr>  breakRecord
            )
        {
            _currentScope = currentScope;
            _breakRecord = breakRecord;

            if (breakRecord.Value == IntPtr.Zero)
            {
                // this object does not hold unmanaged resource,
                // remove it from the finalizer queue.
                GC.SuppressFinalize(this);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Internallly construct the line break
        /// </summary>
        internal TextLineBreak(
            TextModifierScope currentScope,
            SecurityCriticalDataForSet <IntPtr> breakRecord
            )
        {
            _currentScope = currentScope;
            _breakRecord  = breakRecord;

            if (breakRecord.Value == IntPtr.Zero)
            {
                // this object does not hold unmanaged resource,
                // remove it from the finalizer queue.
                GC.SuppressFinalize(this);
            }
        }
Beispiel #22
0
        private FullTextBreakpoint(
            FullTextState fullText,
            int firstCharIndex,
            int maxLineWidth,
            ref LsBreaks lsbreaks,
            int breakIndex
            ) : this()
        {
            // According to antons: PTS only uses the width of a feasible break to avoid
            // clipping in subpage. At the moment, there is no good solution as of how
            // PTS client would be able to compute this width efficiently using LS.
            // The work around - although could be conceived would simply be too slow.
            // The width should therefore be set to the paragraph width for the time being.
            //
            // Client of text formatter would simply pass the value of TextBreakpoint.Width
            // back to PTS pfnFormatLineVariants call.
            LsLineWidths lineWidths = new LsLineWidths();

            lineWidths.upLimLine          = maxLineWidth;
            lineWidths.upStartMainText    = fullText.TextStore.Settings.TextIndent;
            lineWidths.upStartMarker      = lineWidths.upStartMainText;
            lineWidths.upStartTrailing    = lineWidths.upLimLine;
            lineWidths.upMinStartTrailing = lineWidths.upStartTrailing;

            // construct the correspondent text metrics
            unsafe
            {
                _metrics.Compute(
                    fullText,
                    firstCharIndex,
                    maxLineWidth,
                    null,   // collapsingSymbol
                    ref lineWidths,
                    &lsbreaks.plslinfoArray[breakIndex]
                    );

                _ploline = new SecurityCriticalDataForSet <IntPtr>(lsbreaks.pplolineArray[breakIndex]);

                // keep the line penalty handle
                _penaltyResource = new SecurityCriticalDataForSet <IntPtr>(lsbreaks.plinepenaltyArray[breakIndex]);

                if (lsbreaks.plslinfoArray[breakIndex].fForcedBreak != 0)
                {
                    _isLineTruncated = true;
                }
            }
        }
        //-------------------------------------------------------------------
        //
        //  Constructors
        //
        //-------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="ptsContext">Current PTS Context.</param>
        /// <param name="br">PTS page break record.</param>
        /// <param name="pageNumber">Page number.</param>
        internal PageBreakRecord(PtsContext ptsContext, SecurityCriticalDataForSet<IntPtr> br, int pageNumber)
        {
            Invariant.Assert(ptsContext != null, "Invalid PtsContext object.");
            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");

            _br = br;
            _pageNumber = pageNumber;

            // In the finalizer we may need to reference an object instance
            // to do the right cleanup. For this reason store a WeakReference
            // to such object.
            _ptsContext = new WeakReference(ptsContext);

            // BreakRecord contains unmanaged resources that need to be released when
            // BreakRecord is destroyed or Dispatcher is closing. For this reason keep 
            // track of this BreakRecord in PtsContext. 
            ptsContext.OnPageBreakRecordCreated(_br);
        }
        //-------------------------------------------------------------------
        //
        //  Constructors
        //
        //-------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="ptsContext">Current PTS Context.</param>
        /// <param name="br">PTS page break record.</param>
        /// <param name="pageNumber">Page number.</param>
        internal PageBreakRecord(PtsContext ptsContext, SecurityCriticalDataForSet <IntPtr> br, int pageNumber)
        {
            Invariant.Assert(ptsContext != null, "Invalid PtsContext object.");
            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");

            _br         = br;
            _pageNumber = pageNumber;

            // In the finalizer we may need to reference an object instance
            // to do the right cleanup. For this reason store a WeakReference
            // to such object.
            _ptsContext = new WeakReference(ptsContext);

            // BreakRecord contains unmanaged resources that need to be released when
            // BreakRecord is destroyed or Dispatcher is closing. For this reason keep
            // track of this BreakRecord in PtsContext.
            ptsContext.OnPageBreakRecordCreated(_br);
        }
Beispiel #25
0
        /// <summary>
        /// Initializes the interaction engine
        /// </summary>
        /// <param name="stylusDevice"></param>
        /// <param name="configuration"></param>
        internal PointerInteractionEngine(PointerStylusDevice stylusDevice, List <UnsafeNativeMethods.INTERACTION_CONTEXT_CONFIGURATION> configuration = null)
        {
            _stylusDevice = stylusDevice;

            // Only create a flick engine for Pen devices
            if (_stylusDevice.TabletDevice.Type == TabletDeviceType.Stylus)
            {
                // Currently disabled pending decision about flick support in Windows 10 RS3
                //_flickEngine = new PointerFlickEngine(_stylusDevice);
            }

            // Create our interaction context for gesture recognition
            IntPtr interactionContext = IntPtr.Zero;

            UnsafeNativeMethods.CreateInteractionContext(out interactionContext);
            _interactionContext = new SecurityCriticalDataForSet <IntPtr>(interactionContext);

            if (configuration == null)
            {
                configuration = DefaultConfiguration;
            }

            if (_interactionContext.Value != IntPtr.Zero)
            {
                // We do not want to filter specific pointers
                UnsafeNativeMethods.SetPropertyInteractionContext(_interactionContext.Value,
                                                                  UnsafeNativeMethods.INTERACTION_CONTEXT_PROPERTY.INTERACTION_CONTEXT_PROPERTY_FILTER_POINTERS,
                                                                  Convert.ToUInt32(false));

                // Use screen measurements here as this makes certain math easier for us
                UnsafeNativeMethods.SetPropertyInteractionContext(_interactionContext.Value,
                                                                  UnsafeNativeMethods.INTERACTION_CONTEXT_PROPERTY.INTERACTION_CONTEXT_PROPERTY_MEASUREMENT_UNITS,
                                                                  (UInt32)UnsafeNativeMethods.InteractionMeasurementUnits.Screen);

                // Configure the context
                UnsafeNativeMethods.SetInteractionConfigurationInteractionContext(_interactionContext.Value, (uint)configuration.Count, configuration.ToArray());

                // Store the delegate so it can be accessed over time
                _callbackDelegate = Callback;

                // Register for interaction notifications
                UnsafeNativeMethods.RegisterOutputCallbackInteractionContext(_interactionContext.Value, _callbackDelegate);
            }
        }
Beispiel #26
0
        //-------------------------------------------------------------------------
        // Internal Methods
        //-------------------------------------------------------------------------

        /// <exception cref="System.ArgumentNullException" />
        internal void EnableEditMode(Stream workspace)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException("workspace");
            }

            if (!workspace.CanWrite)
            {
                throw new ArgumentException(
                          SR.Get(SRID.PackagingWriteNotSupported),
                          "workspace");
            }

            Package temporaryPackage = Package.Open(
                workspace, FileMode.Create, FileAccess.ReadWrite);

            _tempPackage = new SecurityCriticalDataForSet <Package>(temporaryPackage);
        }
Beispiel #27
0
        /// <summary>
        /// Destroys PTS break record.
        /// </summary>
        /// <param name="br">Pointer to PTS Page BR object that should be destroyed.</param>
        /// <param name="disposing">Whether dispose is caused by explicit call to Dispose.</param>
        internal void OnPageBreakRecordDisposed(SecurityCriticalDataForSet <IntPtr> br, bool disposing)
        {
            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");

            // If explicitly disposing (not called during finalization), synchronously
            // destroy the page break record.
            if (disposing)
            {
                OnDestroyBreakRecord((object)br);
            }
            else
            {
                // If PtsContext has been already disposed, ignore this call.
                if (!this.Disposed && !this.Dispatcher.HasShutdownStarted)
                {
                    // Schedule background operation to destroy the page.
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(OnDestroyBreakRecord), br);
                }
            }
        }
Beispiel #28
0
        internal PixelFormat(Guid guidPixelFormat)
        {
            unsafe
            {
                Guid  guidWicPixelFormat = WICPixelFormatGUIDs.WICPixelFormatDontCare;
                byte *pGuidPixelFormat   = (byte *)&guidPixelFormat;
                byte *pGuidBuiltIn       = (byte *)&guidWicPixelFormat;

                // Compare only the first 15 bytes of the GUID.  If the first
                // 15 bytes match the WIC pixel formats, then the 16th byte
                // will be the format enum value.
                Debug.Assert(Marshal.SizeOf(typeof(Guid)) == 16);
                int compareCount = 15;

                bool fBuiltIn = true;
                for (int i = 0; i < compareCount; ++i)
                {
                    if (pGuidPixelFormat[i] != pGuidBuiltIn[i])
                    {
                        fBuiltIn = false;
                        break;
                    }
                }

                // If it looks like a built-in WIC pixel format, verify that
                // the format enum value is known to us.
                if (fBuiltIn && pGuidPixelFormat[compareCount] <= (byte)PixelFormatEnum.Cmyk32)
                {
                    _format = (PixelFormatEnum)pGuidPixelFormat[compareCount];
                }
                else
                {
                    _format = PixelFormatEnum.Extended;
                }
            }

            _flags        = GetPixelFormatFlagsFromEnum(_format) | GetPixelFormatFlagsFromGuid(guidPixelFormat);
            _bitsPerPixel = GetBitsPerPixelFromEnum(_format);
            _guidFormat   = new SecurityCriticalDataForSet <Guid> (guidPixelFormat);
        }
        private object OnDestroyBreakRecord(object args)
        {
            SecurityCriticalDataForSet <IntPtr> securityCriticalDataForSet = (SecurityCriticalDataForSet <IntPtr>)args;

            Invariant.Assert(securityCriticalDataForSet.Value != IntPtr.Zero, "Invalid break record object.");
            if (!this.Disposed)
            {
                Invariant.Assert(this._pageBreakRecords != null, "Collection of break records does not exist.");
                Invariant.Assert(this._pageBreakRecords.Contains(securityCriticalDataForSet.Value), "Break record does not exist.");
                try
                {
                    this.Enter();
                    PTS.Validate(PTS.FsDestroyPageBreakRecord(this._ptsHost.Context, securityCriticalDataForSet.Value));
                }
                finally
                {
                    this.Leave();
                    this._pageBreakRecords.Remove(securityCriticalDataForSet.Value);
                }
            }
            return(null);
        }
Beispiel #30
0
 internal PtsHost()
 {
     _context = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
 }
 public TextFormatterContext() 
 {
     _ploc =  new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
     Init();
 } 
Beispiel #32
0
 /// <summary>
 /// Serialization constructor. Marked Protected so derived classes can be deserialized correctly
 /// The base implementation needs to be called if this class is overridden
 /// </summary>
 protected JournalEntryPageFunctionType(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     _typeName = new SecurityCriticalDataForSet <string>(info.GetString("_typeName"));
 }
        private void Initialize( bool fTrusted )
        {
            _fTrusted = new SecurityCriticalDataForSet<bool> ( fTrusted ) ;

            _hwndSubclassHook = new HwndWrapperHook(SubclassWndProc);
            _handlerLayoutUpdated = new EventHandler(OnLayoutUpdated);
            _handlerEnabledChanged = new DependencyPropertyChangedEventHandler(OnEnabledChanged);
            _handlerVisibleChanged = new DependencyPropertyChangedEventHandler(OnVisibleChanged);
            PresentationSource.AddSourceChangedHandler(this, new SourceChangedEventHandler(OnSourceChanged));

            _weakEventDispatcherShutdown = new WeakEventDispatcherShutdown(this, this.Dispatcher);
        }
 private static void DemandIfImageBlocked()
 {
     if(!isImageDisabledInitialized)
     {
         // a performance optimization to ensure we hit the registry only once in the lifetime of the application
         isImageDisabled = new SecurityCriticalDataForSet<bool>(SafeSecurityHelper.IsFeatureDisabled(SafeSecurityHelper.KeyToRead.MediaImageDisable));
         isImageDisabledInitialized = true;
     }
     if (isImageDisabled.Value)
     {
         // in case the registry key is '1' then demand MediaPermissionImage.AllImage - not granted in Partial Trust
         SecurityHelper.DemandMediaPermission(MediaPermissionAudio.NoAudio,
                                              MediaPermissionVideo.NoVideo,
                                              MediaPermissionImage.AllImage);
     }
     else
     {
         // Images are enabled. Then, demand permissions for safe imaging - granted in Partial Trust by default
         SecurityHelper.DemandMediaPermission(MediaPermissionAudio.NoAudio,
                                              MediaPermissionVideo.NoVideo,
                                              MediaPermissionImage.SafeImage);
     }
 }
Beispiel #35
0
        /// <summary>
        /// Destroys PTS break record.
        /// </summary>
        /// <param name="br">Pointer to PTS Page BR object that should be destroyed.</param>
        /// <param name="disposing">Whether dispose is caused by explicit call to Dispose.</param>
        internal void OnPageBreakRecordDisposed(SecurityCriticalDataForSet<IntPtr> br, bool disposing)
        {
            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");

            // If explicitly disposing (not called during finalization), synchronously
            // destroy the page break record.
            if (disposing)
            {
                OnDestroyBreakRecord((object)br);
            }
            else
            {
                // If PtsContext has been already disposed, ignore this call.
                if (!this.Disposed && !this.Dispatcher.HasShutdownStarted)
                {
                    // Schedule background operation to destroy the page.
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(OnDestroyBreakRecord), br);
                }
            }
        }
Beispiel #36
0
        private void OnDestroyPage(SecurityCriticalDataForSet<IntPtr> ptsPage, bool enterContext)
        {
            Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");

            // Dispatcher may invoke this operation when PtsContext is already explicitly
            // disposed.
            if (!this.Disposed)
            {
                Invariant.Assert(_pages != null, "Collection of pages does not exist.");
                Invariant.Assert(_pages.Contains(ptsPage.Value), "Page does not exist.");

                // Destroy given page.
                // It is necessary to enter PTS Context when executing any PTS methods.
                try
                {
                    if (enterContext)
                    {
                        Enter();
                    }
                    PTS.Validate(PTS.FsDestroyPage(_ptsHost.Context, ptsPage.Value));
                }
                finally
                {
                    if (enterContext)
                    {
                        Leave();
                    }
                    _pages.Remove(ptsPage.Value);
                }
            }
        }
 private FullTextLine(TextFormattingMode textFormattingMode, bool justify)
 {
     _textFormattingMode = textFormattingMode;
     if (justify)
     {
         _statusFlags |= StatusFlags.IsJustified;
     }
     _metrics = new TextMetrics();
     _ploline = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
 }
Beispiel #38
0
        /// <summary>
        /// Construct a pixel format from a string that represents the format.
        /// The purpose of this method is only for deserialization of PixelFormat.
        /// The preferred way to construct a PixelFormat is with the PixelFormats class.
        /// </summary>
        /// <param name="pixelFormatString"></param>
        internal PixelFormat(string pixelFormatString)
        {
            PixelFormatEnum format = PixelFormatEnum.Default;

            if (pixelFormatString == null)
            {
                throw new System.ArgumentNullException("pixelFormatString");
            }

            string upperPixelFormatString = pixelFormatString.ToUpper(System.Globalization.CultureInfo.InvariantCulture);

            switch (upperPixelFormatString)
            {
            case "DEFAULT":
                format = PixelFormatEnum.Default;
                break;

            case "EXTENDED":
                format = PixelFormatEnum.Extended;
                break;

            case "INDEXED1":
                format = PixelFormatEnum.Indexed1;
                break;

            case "INDEXED2":
                format = PixelFormatEnum.Indexed2;
                break;

            case "INDEXED4":
                format = PixelFormatEnum.Indexed4;
                break;

            case "INDEXED8":
                format = PixelFormatEnum.Indexed8;
                break;

            case "BLACKWHITE":
                format = PixelFormatEnum.BlackWhite;
                break;

            case "GRAY2":
                format = PixelFormatEnum.Gray2;
                break;

            case "GRAY4":
                format = PixelFormatEnum.Gray4;
                break;

            case "GRAY8":
                format = PixelFormatEnum.Gray8;
                break;

            case "BGR555":
                format = PixelFormatEnum.Bgr555;
                break;

            case "BGR565":
                format = PixelFormatEnum.Bgr565;
                break;

            case "BGR24":
                format = PixelFormatEnum.Bgr24;
                break;

            case "RGB24":
                format = PixelFormatEnum.Rgb24;
                break;

            case "BGR101010":
                format = PixelFormatEnum.Bgr101010;
                break;

            case "BGR32":
                format = PixelFormatEnum.Bgr32;
                break;

            case "BGRA32":
                format = PixelFormatEnum.Bgra32;
                break;

            case "PBGRA32":
                format = PixelFormatEnum.Pbgra32;
                break;

            case "RGB48":
                format = PixelFormatEnum.Rgb48;
                break;

            case "RGBA64":
                format = PixelFormatEnum.Rgba64;
                break;

            case "PRGBA64":
                format = PixelFormatEnum.Prgba64;
                break;

            case "GRAY16":
                format = PixelFormatEnum.Gray16;
                break;

            case "GRAY32FLOAT":
                format = PixelFormatEnum.Gray32Float;
                break;

            case "RGB128FLOAT":
                format = PixelFormatEnum.Rgb128Float;
                break;

            case "RGBA128FLOAT":
                format = PixelFormatEnum.Rgba128Float;
                break;

            case "PRGBA128FLOAT":
                format = PixelFormatEnum.Prgba128Float;
                break;

            case "CMYK32":
                format = PixelFormatEnum.Cmyk32;
                break;

            default:
                throw new System.ArgumentException(SR.Get(SRID.Image_BadPixelFormat, pixelFormatString),
                                                   "pixelFormatString");
            }

            _format = format;

            _flags        = GetPixelFormatFlagsFromEnum(format);
            _bitsPerPixel = GetBitsPerPixelFromEnum(format);
            _guidFormat   = new SecurityCriticalDataForSet <Guid> (PixelFormat.GetGuidFromFormat(format));
        }
Beispiel #39
0
        internal void OnPageCreated(SecurityCriticalDataForSet<IntPtr> ptsPage)
        {
            Invariant.Assert(ptsPage.Value != IntPtr.Zero, "Invalid page object.");
            Invariant.Assert(!this.Disposed, "PtsContext is already disposed.");
            Invariant.Assert(!_pages.Contains(ptsPage.Value), "Page already exists.");

            _pages.Add(ptsPage.Value);
        }
Beispiel #40
0
        private FullTextBreakpoint(
            FullTextState           fullText,
            int                     firstCharIndex,
            int                     maxLineWidth,
            ref LsBreaks            lsbreaks,
            int                     breakIndex
            ) : this()
        {
            // According to antons: PTS only uses the width of a feasible break to avoid
            // clipping in subpage. At the moment, there is no good solution as of how
            // PTS client would be able to compute this width efficiently using LS. 
            // The work around - although could be conceived would simply be too slow.
            // The width should therefore be set to the paragraph width for the time being.
            //
            // Client of text formatter would simply pass the value of TextBreakpoint.Width
            // back to PTS pfnFormatLineVariants call.
            LsLineWidths lineWidths = new LsLineWidths();
            lineWidths.upLimLine = maxLineWidth;
            lineWidths.upStartMainText = fullText.TextStore.Settings.TextIndent;
            lineWidths.upStartMarker = lineWidths.upStartMainText;
            lineWidths.upStartTrailing = lineWidths.upLimLine;
            lineWidths.upMinStartTrailing = lineWidths.upStartTrailing;

            // construct the correspondent text metrics
            unsafe
            {
                _metrics.Compute(
                    fullText,
                    firstCharIndex,
                    maxLineWidth,
                    null,   // collapsingSymbol
                    ref lineWidths,
                    &lsbreaks.plslinfoArray[breakIndex]
                    );

                _ploline = new SecurityCriticalDataForSet<IntPtr>(lsbreaks.pplolineArray[breakIndex]);

                // keep the line penalty handle
                _penaltyResource = new SecurityCriticalDataForSet<IntPtr>(lsbreaks.plinepenaltyArray[breakIndex]);

                if (lsbreaks.plslinfoArray[breakIndex].fForcedBreak != 0)
                    _isLineTruncated = true;
            }
        }
 protected JournalEntryPageFunctionType(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     _typeName = new SecurityCriticalDataForSet<string>(info.GetString("_typeName"));
 }
Beispiel #42
0
        internal void OnPageBreakRecordCreated(SecurityCriticalDataForSet<IntPtr> br)
        {
            Invariant.Assert(br.Value != IntPtr.Zero, "Invalid break record object.");
            Invariant.Assert(!this.Disposed, "PtsContext is already disposed.");
            Invariant.Assert(!_pageBreakRecords.Contains(br.Value), "Break record already exists.");

            _pageBreakRecords.Add(br.Value);
        }
Beispiel #43
0
 public CommandWithArgument(RoutedCommand command, object argument)
 {
     _command  = new SecurityCriticalDataForSet <RoutedCommand>(command);
     _argument = argument;
 }
Beispiel #44
0
 public CommandWithArgument(RoutedCommand command, object argument)
 {
     _command = new SecurityCriticalDataForSet<RoutedCommand>(command);
     _argument = argument;
 }
Beispiel #45
0
 internal TraceProvider()
 {
     _registrationHandle = new SecurityCriticalDataForSet<ulong>(0);
 }
Beispiel #46
0
 /// <summary>
 ///
 /// </summary>
 internal AccessKeyEventArgs(string key, bool isMultiple, bool userInitiated)
 {
     _key           = key;
     _isMultiple    = isMultiple;
     _userInitiated = new SecurityCriticalDataForSet <bool>(userInitiated);
 }
            private void FormatLine(
                FullTextState           fullText,
                int                     cpFirst,
                int                     lineLength,
                int                     formatWidth,
                int                     finiteFormatWidth,
                int                     paragraphWidth,
                LineFlags               lineFlags,
                FormattedTextSymbols    collapsingSymbol
                )
            {
                _metrics._formatter = fullText.Formatter;
                Debug.Assert(_metrics._formatter != null);

                TextStore store = fullText.TextStore;
                TextStore markerStore = fullText.TextMarkerStore;
                FormatSettings settings = store.Settings;
                ParaProp pap = settings.Pap;

                _paragraphTextDecorations = pap.TextDecorations;
                if (_paragraphTextDecorations != null)
                {
                    if (_paragraphTextDecorations.Count != 0)
                    {
                        _defaultTextDecorationsBrush = pap.DefaultTextDecorationsBrush;
                    }
                    else
                    {
                        _paragraphTextDecorations = null;
                    }
                }

                // acquiring LS context
                TextFormatterContext context = _metrics._formatter.AcquireContext(fullText, IntPtr.Zero);

                LsLInfo plslineInfo = new LsLInfo();
                LsLineWidths lineWidths = new LsLineWidths();

                fullText.SetTabs(context);

                int lscpLineLength = 0; // line length in LSCP
                if (lineLength > 0)
                {
                    // line length is previously known (e.g. during optimal paragraph formatting),
                    // prefetch lsruns up to the specified line length.
                    lscpLineLength = PrefetchLSRuns(store, cpFirst, lineLength);
                }

                IntPtr ploline;
                LsErr lserr = context.CreateLine(
                    cpFirst,
                    lscpLineLength,
                    formatWidth,
                    lineFlags,
                    IntPtr.Zero,    // single-line formatting does not require break record
                    out ploline,
                    out plslineInfo,
                    out _depthQueryMax,
                    out lineWidths
                    );

                // Did we exceed the LineServices maximum line width?
                if (lserr == LsErr.TooLongParagraph)
                {
                    // Determine where to insert a fake line break. FullTextState.CpMeasured
                    // is a reasonable estimate since we know the nominal widths up to that
                    // point fit within the margin.
                    int cpLimit = fullText.CpMeasured;
                    int subtract = 1;

                    for (;;)
                    {
                        // The line must contain at least one character position.
                        if (cpLimit < 1)
                        {
                            cpLimit = 1;
                        }

                        store.InsertFakeLineBreak(cpLimit);

                        lserr = context.CreateLine(
                            cpFirst,
                            lscpLineLength,
                            formatWidth,
                            lineFlags,
                            IntPtr.Zero,    // single-line formatting does not require break record
                            out ploline,
                            out plslineInfo,
                            out _depthQueryMax,
                            out lineWidths
                            );

                        if (lserr != LsErr.TooLongParagraph || cpLimit == 1)
                        {
                            // We're done or can't chop off any more text.
                            break;
                        }
                        else
                        {
                            // Chop off more text and try again. Double the amount of
                            // text we chop off each time so we retry too many times.
                            cpLimit = fullText.CpMeasured - subtract;
                            subtract *= 2;
                        }
                    }
                }

                _ploline.Value = ploline;

                // get the exception in context before it is released
                Exception callbackException = context.CallbackException;

                // release the context
                context.Release();

                if(lserr != LsErr.None)
                {
                    GC.SuppressFinalize(this);
                    if(callbackException != null)
                    {
                        // rethrow exception thrown in callbacks
                        throw WrapException(callbackException);
                    }
                    else
                    {
                        // throw with LS error codes
                        TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.CreateLineFailure, lserr), lserr);
                    }
                }

                // keep context alive at least till here
                GC.KeepAlive(context);

                unsafe
                {
                    // construct text metrics for the line
                    _metrics.Compute(
                        fullText,
                        cpFirst,
                        paragraphWidth,
                        collapsingSymbol,
                        ref lineWidths,
                        &plslineInfo
                        );
                }

                // keep record for min width as we may be formatting min/max
                _textMinWidthAtTrailing = lineWidths.upMinStartTrailing - _metrics._textStart;

                if (collapsingSymbol != null)
                {
                    _collapsingSymbol = collapsingSymbol;
                    _textMinWidthAtTrailing += TextFormatterImp.RealToIdeal(collapsingSymbol.Width);
                }
                else
                {
                    // overflow detection for potential collapsible line
                    if (_metrics._textStart + _metrics._textWidthAtTrailing > finiteFormatWidth)
                    {
                        bool hasOverflowed = true;
                        if (_textFormattingMode == TextFormattingMode.Display)
                        {
                            // apply display-mode rounding before checking for overflow
                            double realWidth = Width;
                            double realFormatWidth = _metrics._formatter.IdealToReal(finiteFormatWidth);
                            hasOverflowed = (TextFormatterImp.CompareReal(realWidth, realFormatWidth, _textFormattingMode) > 0);
                        }

                        if (hasOverflowed)
                        {
                            // line has overflowed
                            _statusFlags |= StatusFlags.HasOverflowed;

                            // let's keep the full text state around. We'll need it later for collapsing
                            _fullText = fullText;
                        }
                    }
                }

                if (    fullText != null
                    &&  (   fullText.KeepState
                        ||  (_statusFlags & StatusFlags.KeepState) != 0
                        )
                    )
                {
                    // the state of full text is to be kept after formatting is done
                    _fullText = fullText;
                }

                // retain all line properties for interactive operations
                _ploc = context.Ploc;
                _cpFirst = cpFirst;
                _paragraphWidth = paragraphWidth;

                if (pap.RightToLeft)
                    _statusFlags |= StatusFlags.RightToLeft;

                if (plslineInfo.fForcedBreak != 0)
                    _statusFlags |= StatusFlags.IsTruncated;

                // retain the state of plsruns
                _plsrunVector = store.PlsrunVector;
                _lsrunsMainText = store.LsrunList;

                if (markerStore != null)
                    _lsrunsMarkerText = markerStore.LsrunList;

                // we store the text source in the line in case drawing code calls
                // the TextSource to find out the text effect index.
                // 
                _textSource = settings.TextSource;
            }
Beispiel #48
0
        [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);
 protected BaseParaClient(BaseParagraph paragraph) : base(paragraph.PtsContext)
 {
     _paraHandle = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
     _paragraph = paragraph;
 }
Beispiel #50
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);
        }
Beispiel #51
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);
        }
 public TextFormatterContext()
 {
     _ploc = new SecurityCriticalDataForSet <IntPtr>(IntPtr.Zero);
     Init();
 }
Beispiel #53
0
 internal AccessKeyEventArgs(string key, bool isMultiple, bool userInitiated)
 {
     _key = key;
     _isMultiple = isMultiple;
     _userInitiated = new SecurityCriticalDataForSet<bool>(userInitiated);
 }
Beispiel #54
0
 private PtsPage()
 {
     _ptsPage = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
 }
Beispiel #55
0
 static  AssemblyFilter() 
 { 
     _disallowedListExtracted = new SecurityCriticalDataForSet<bool>(false);
     _assemblyList = new SecurityCriticalDataForSet<System.Collections.Generic.List<string>>(new System.Collections.Generic.List<string>()); 
 }