Code:
/ Net / Net / 3.5.50727.3053 / DEVDIV / depot / DevDiv / releases / Orcas / SP / wpf / src / Core / CSharp / System / Windows / Media / textformatting / TextParagraphCache.cs / 1 / TextParagraphCache.cs
//------------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation
//
// File: TextParagraphCache.cs
//
// Contents: Cache object of paragraph content used to improve performance
// of optimal paragraph formatting
//
// Spec: http://team/sites/Avalon/Specs/Text%20Formatting%20API.doc
//
// Created: 2-4-2005 Worachai Chaoweeraprasit (Wchao)
//
//-----------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security;
using System.Windows;
using System.Windows.Media;
using MS.Internal;
using MS.Internal.TextFormatting;
using MS.Internal.PresentationCore;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media.TextFormatting
{
///
/// Text formatter caches all potential breakpoints within a paragraph in this cache object
/// during FormatParagraphContent call. This object is to be managed by text layout client.
/// The use of this cache is to improve performance of line construction in optimal paragraph
/// line formatting.
///
#if OPTIMALBREAK_API
public sealed class TextParagraphCache : IDisposable
#else
[FriendAccessAllowed]
internal sealed class TextParagraphCache : IDisposable
#endif
{
private FullTextState _fullText; // full text state of the whole paragraph
private SecurityCriticalDataForSet _ploparabreak; // unmanaged LS resource for parabreak session
private int _finiteFormatWidth; // finite formatting ideal width
private bool _penalizedAsJustified; // flag indicating whether the paragraph should be penalized as fully-justified one
///
/// Construct a paragraph cache to be used during optimal paragraph formatting
///
///
/// Critical - as this calls the setter for _ploparabreak.Value which is type SecurityCriticalDataForSet.
/// Safe - as it doesn't set security critical data to a random value passed in but rather to a value returned
/// by a safe function TextFormatterContext.CreateParaBreakingSession().
///
[SecurityCritical, SecurityTreatAsSafe]
internal TextParagraphCache(
FormatSettings settings,
int firstCharIndex,
int paragraphWidth
)
{
Invariant.Assert(settings != null);
// create full text
_finiteFormatWidth = settings.GetFiniteFormatWidth(paragraphWidth);
_fullText = FullTextState.Create(settings, firstCharIndex, _finiteFormatWidth);
// acquiring LS context
TextFormatterContext context = settings.Formatter.AcquireContext(_fullText, IntPtr.Zero);
_fullText.SetTabs(context);
IntPtr ploparabreakValue = IntPtr.Zero;
LsErr lserr = context.CreateParaBreakingSession(
firstCharIndex,
_finiteFormatWidth,
// breakrec is not needed before the first cp of para cache
// since we handle Bidi break ourselves.
IntPtr.Zero,
ref ploparabreakValue,
ref _penalizedAsJustified
);
// 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 new InvalidOperationException(SR.Get(SRID.CreateParaBreakingSessionFailure, lserr), callbackException);
}
else
{
// throw with LS error codes
TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.CreateParaBreakingSessionFailure, lserr), lserr);
}
}
_ploparabreak.Value = ploparabreakValue;
// keep context alive till here
GC.KeepAlive(context);
}
///
/// Finalizing paragraph content cache
///
~TextParagraphCache()
{
Dispose(false);
}
///
/// Disposing paragraph content cache
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Client to format all feasible breakpoints for a line started at the specified character position.
/// The number of breakpoints returned is restricted by penalty restr
///
///
/// This method is provided for direct access of PTS during optimal paragraph process. The breakpoint
/// restriction handle is passed as part of the parameter to PTS callback pfnFormatLineVariants. The
/// value comes from earlier steps in PTS code to compute the accumulated penalty of the entire paragraph
/// using 'best-fit' algorithm.
///
internal IList FormatBreakpoints(
int firstCharIndex,
TextLineBreak previousLineBreak,
IntPtr breakpointRestrictionHandle,
double maxLineWidth,
out int bestFitIndex
)
{
// format all potential breakpoints starting from the specified firstCharIndex.
// The number of breakpoints returned is restricted by penaltyRestriction.
return FullTextBreakpoint.CreateMultiple(
this,
firstCharIndex,
VerifyMaxLineWidth(maxLineWidth),
previousLineBreak,
breakpointRestrictionHandle,
out bestFitIndex
);
}
///
/// Releasing LS unmanaged resource on paragraph content
///
///
/// Critical - as this sets critical data _ploparabreak
/// Safe - as it does not set critical data thru incoming parameter
///
[SecurityCritical, SecurityTreatAsSafe]
private void Dispose(bool disposing)
{
if(_ploparabreak.Value != IntPtr.Zero)
{
UnsafeNativeMethods.LoDisposeParaBreakingSession(_ploparabreak.Value, !disposing);
_ploparabreak.Value = IntPtr.Zero;
GC.KeepAlive(this);
}
}
///
/// Verify that the input line format width is within the maximum ideal value
///
private int VerifyMaxLineWidth(double maxLineWidth)
{
double realInfiniteWidth = FullText.Formatter.IdealToReal(Constants.InfiniteWidth);
if (DoubleUtil.IsNaN(maxLineWidth))
throw new ArgumentOutOfRangeException("maxLineWidth", SR.Get(SRID.ParameterValueCannotBeNaN));
if (maxLineWidth == 0 || double.IsPositiveInfinity(maxLineWidth))
{
// consider 0 or positive infinity as maximum ideal width
return Constants.InfiniteWidth;
}
if ( maxLineWidth < 0
|| maxLineWidth > realInfiniteWidth)
{
throw new ArgumentOutOfRangeException("maxLineWidth", SR.Get(SRID.ParameterMustBeBetween, 0, realInfiniteWidth));
}
// convert real value to ideal value
return FullText.Formatter.RealToIdeal(maxLineWidth);
}
///
/// Full text state of the paragraph
///
internal FullTextState FullText
{
get { return _fullText; }
}
///
/// Unmanaged LS parabreak session object
///
internal SecurityCriticalDataForSet Ploparabreak
{
get { return _ploparabreak; }
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation
//
// File: TextParagraphCache.cs
//
// Contents: Cache object of paragraph content used to improve performance
// of optimal paragraph formatting
//
// Spec: http://team/sites/Avalon/Specs/Text%20Formatting%20API.doc
//
// Created: 2-4-2005 Worachai Chaoweeraprasit (Wchao)
//
//-----------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security;
using System.Windows;
using System.Windows.Media;
using MS.Internal;
using MS.Internal.TextFormatting;
using MS.Internal.PresentationCore;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media.TextFormatting
{
///
/// Text formatter caches all potential breakpoints within a paragraph in this cache object
/// during FormatParagraphContent call. This object is to be managed by text layout client.
/// The use of this cache is to improve performance of line construction in optimal paragraph
/// line formatting.
///
#if OPTIMALBREAK_API
public sealed class TextParagraphCache : IDisposable
#else
[FriendAccessAllowed]
internal sealed class TextParagraphCache : IDisposable
#endif
{
private FullTextState _fullText; // full text state of the whole paragraph
private SecurityCriticalDataForSet _ploparabreak; // unmanaged LS resource for parabreak session
private int _finiteFormatWidth; // finite formatting ideal width
private bool _penalizedAsJustified; // flag indicating whether the paragraph should be penalized as fully-justified one
///
/// Construct a paragraph cache to be used during optimal paragraph formatting
///
///
/// Critical - as this calls the setter for _ploparabreak.Value which is type SecurityCriticalDataForSet.
/// Safe - as it doesn't set security critical data to a random value passed in but rather to a value returned
/// by a safe function TextFormatterContext.CreateParaBreakingSession().
///
[SecurityCritical, SecurityTreatAsSafe]
internal TextParagraphCache(
FormatSettings settings,
int firstCharIndex,
int paragraphWidth
)
{
Invariant.Assert(settings != null);
// create full text
_finiteFormatWidth = settings.GetFiniteFormatWidth(paragraphWidth);
_fullText = FullTextState.Create(settings, firstCharIndex, _finiteFormatWidth);
// acquiring LS context
TextFormatterContext context = settings.Formatter.AcquireContext(_fullText, IntPtr.Zero);
_fullText.SetTabs(context);
IntPtr ploparabreakValue = IntPtr.Zero;
LsErr lserr = context.CreateParaBreakingSession(
firstCharIndex,
_finiteFormatWidth,
// breakrec is not needed before the first cp of para cache
// since we handle Bidi break ourselves.
IntPtr.Zero,
ref ploparabreakValue,
ref _penalizedAsJustified
);
// 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 new InvalidOperationException(SR.Get(SRID.CreateParaBreakingSessionFailure, lserr), callbackException);
}
else
{
// throw with LS error codes
TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.CreateParaBreakingSessionFailure, lserr), lserr);
}
}
_ploparabreak.Value = ploparabreakValue;
// keep context alive till here
GC.KeepAlive(context);
}
///
/// Finalizing paragraph content cache
///
~TextParagraphCache()
{
Dispose(false);
}
///
/// Disposing paragraph content cache
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Client to format all feasible breakpoints for a line started at the specified character position.
/// The number of breakpoints returned is restricted by penalty restr
///
///
/// This method is provided for direct access of PTS during optimal paragraph process. The breakpoint
/// restriction handle is passed as part of the parameter to PTS callback pfnFormatLineVariants. The
/// value comes from earlier steps in PTS code to compute the accumulated penalty of the entire paragraph
/// using 'best-fit' algorithm.
///
internal IList FormatBreakpoints(
int firstCharIndex,
TextLineBreak previousLineBreak,
IntPtr breakpointRestrictionHandle,
double maxLineWidth,
out int bestFitIndex
)
{
// format all potential breakpoints starting from the specified firstCharIndex.
// The number of breakpoints returned is restricted by penaltyRestriction.
return FullTextBreakpoint.CreateMultiple(
this,
firstCharIndex,
VerifyMaxLineWidth(maxLineWidth),
previousLineBreak,
breakpointRestrictionHandle,
out bestFitIndex
);
}
///
/// Releasing LS unmanaged resource on paragraph content
///
///
/// Critical - as this sets critical data _ploparabreak
/// Safe - as it does not set critical data thru incoming parameter
///
[SecurityCritical, SecurityTreatAsSafe]
private void Dispose(bool disposing)
{
if(_ploparabreak.Value != IntPtr.Zero)
{
UnsafeNativeMethods.LoDisposeParaBreakingSession(_ploparabreak.Value, !disposing);
_ploparabreak.Value = IntPtr.Zero;
GC.KeepAlive(this);
}
}
///
/// Verify that the input line format width is within the maximum ideal value
///
private int VerifyMaxLineWidth(double maxLineWidth)
{
double realInfiniteWidth = FullText.Formatter.IdealToReal(Constants.InfiniteWidth);
if (DoubleUtil.IsNaN(maxLineWidth))
throw new ArgumentOutOfRangeException("maxLineWidth", SR.Get(SRID.ParameterValueCannotBeNaN));
if (maxLineWidth == 0 || double.IsPositiveInfinity(maxLineWidth))
{
// consider 0 or positive infinity as maximum ideal width
return Constants.InfiniteWidth;
}
if ( maxLineWidth < 0
|| maxLineWidth > realInfiniteWidth)
{
throw new ArgumentOutOfRangeException("maxLineWidth", SR.Get(SRID.ParameterMustBeBetween, 0, realInfiniteWidth));
}
// convert real value to ideal value
return FullText.Formatter.RealToIdeal(maxLineWidth);
}
///
/// Full text state of the paragraph
///
internal FullTextState FullText
{
get { return _fullText; }
}
///
/// Unmanaged LS parabreak session object
///
internal SecurityCriticalDataForSet Ploparabreak
{
get { return _ploparabreak; }
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- Clock.cs
- SqlWorkflowPersistenceService.cs
- ContractAdapter.cs
- SessionEndedEventArgs.cs
- ColorInterpolationModeValidation.cs
- ListViewItemMouseHoverEvent.cs
- WindowsSecurityToken.cs
- BatchServiceHost.cs
- TypedElement.cs
- Exception.cs
- SafeFileHandle.cs
- FirewallWrapper.cs
- ListBoxItem.cs
- MaxValueConverter.cs
- ComponentChangedEvent.cs
- SafeMemoryMappedFileHandle.cs
- HostingEnvironmentSection.cs
- ReferenceEqualityComparer.cs
- OutputCacheProviderCollection.cs
- TryExpression.cs
- XmlIlGenerator.cs
- SQLBinary.cs
- XmlSiteMapProvider.cs
- _TransmitFileOverlappedAsyncResult.cs
- TypedDataSourceCodeGenerator.cs
- StringUtil.cs
- ConfigXmlWhitespace.cs
- CodeSnippetCompileUnit.cs
- Attributes.cs
- ValueUtilsSmi.cs
- DynamicResourceExtension.cs
- CompositeKey.cs
- METAHEADER.cs
- ControlsConfig.cs
- StreamUpdate.cs
- DesignerView.xaml.cs
- ActivityValidationServices.cs
- diagnosticsswitches.cs
- UserControl.cs
- DataRowExtensions.cs
- JsonEnumDataContract.cs
- VectorCollectionConverter.cs
- HasCopySemanticsAttribute.cs
- RowCache.cs
- DbMetaDataFactory.cs
- AnnotationComponentChooser.cs
- SplineQuaternionKeyFrame.cs
- EntityKeyElement.cs
- UpdatePanel.cs
- WebPermission.cs
- controlskin.cs
- TableLayoutSettingsTypeConverter.cs
- StackBuilderSink.cs
- TemplateXamlParser.cs
- XmlElement.cs
- Reference.cs
- ListViewDataItem.cs
- DrawingGroupDrawingContext.cs
- GroupItemAutomationPeer.cs
- BaseDataListComponentEditor.cs
- GeometryDrawing.cs
- StrokeSerializer.cs
- DateTimeUtil.cs
- SplineQuaternionKeyFrame.cs
- xmlformatgeneratorstatics.cs
- ListDictionaryInternal.cs
- DataServiceRequestArgs.cs
- bindurihelper.cs
- OleDbEnumerator.cs
- StyleBamlTreeBuilder.cs
- DependencyStoreSurrogate.cs
- versioninfo.cs
- FunctionQuery.cs
- HttpPostedFile.cs
- DesignTimeValidationFeature.cs
- ListInitExpression.cs
- StylusTip.cs
- XmlNodeChangedEventArgs.cs
- SessionStateSection.cs
- DataGridViewCellValidatingEventArgs.cs
- WhitespaceRuleReader.cs
- BaseResourcesBuildProvider.cs
- AutomationFocusChangedEventArgs.cs
- TouchDevice.cs
- MaskedTextBoxDesigner.cs
- RunInstallerAttribute.cs
- __Filters.cs
- Button.cs
- VScrollBar.cs
- EventArgs.cs
- TemplateControlCodeDomTreeGenerator.cs
- TextFindEngine.cs
- WindowsToolbar.cs
- PropertyChangingEventArgs.cs
- SpellerInterop.cs
- HandledEventArgs.cs
- ImageIndexConverter.cs
- Int32EqualityComparer.cs
- TransformValueSerializer.cs
- DataGridViewRowPostPaintEventArgs.cs