Code:
/ DotNET / DotNET / 8.0 / untmp / WIN_WINDOWS / lh_tools_devdiv_wpf / Windows / wcp / Print / Reach / Serialization / VisualTreeFlattener.cs / 1 / VisualTreeFlattener.cs
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, all rights reserved
//
// File: VisualTreeFlattener.cs
//
// History:
// [....]: 01/25/2005 Split from VisualSerializer.cs
//
//-----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.ComponentModel;
using System.Security;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Internal.AlphaFlattener;
using System.Windows.Xps.Serialization;
using System.Windows.Xps.Packaging;
namespace MS.Internal.ReachFramework
{
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Property |
AttributeTargets.Method |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Interface |
AttributeTargets.Delegate |
AttributeTargets.Constructor,
AllowMultiple = false,
Inherited = true)
]
internal sealed class FriendAccessAllowedAttribute : Attribute
{
}
internal class MyColorTypeConverter : ColorTypeConverter
{
public
override
object
ConvertTo(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType
)
{
Color color = (Color)value;
return color.ToString(culture);
}
}
internal class LooseImageSourceTypeConverter : ImageSourceTypeConverter
{
int m_bitmapId;
String m_mainFile;
public LooseImageSourceTypeConverter(String mainFile)
{
m_mainFile = mainFile;
}
///
/// Critical - Calling image encoding, save to local files, used only by testing code path
/// TreatAsSafe - we demand Unmanaged code permission which is not granted in partial trust
///
[SecurityCritical, SecurityTreatAsSafe]
public
override
object
ConvertTo(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType
)
{
SecurityHelper.DemandUnmanagedCode();
string bitmapName = "bitmap" + m_bitmapId;
BitmapEncoder encoder = null;
m_bitmapId++;
BitmapFrame bmpd = value as BitmapFrame;
if (bmpd != null)
{
BitmapCodecInfo codec = null;
if (bmpd.Decoder != null)
{
codec = bmpd.Decoder.CodecInfo;
}
if (codec != null)
{
encoder = BitmapEncoder.Create(codec.ContainerFormat);
string extension = "";
if (encoder is BmpBitmapEncoder)
{
extension = "bmp";
}
else if (encoder is JpegBitmapEncoder)
{
extension = "jpg";
}
else if (encoder is PngBitmapEncoder)
{
extension = "png";
}
else if (encoder is TiffBitmapEncoder)
{
extension = "tif";
}
else
{
encoder = null;
}
if (encoder != null)
{
bitmapName = bitmapName + '.' + extension;
}
}
}
if (encoder == null)
{
if (Microsoft.Internal.AlphaFlattener.Utility.NeedPremultiplyAlpha(value as BitmapSource))
{
encoder = new WmpBitmapEncoder();
bitmapName = bitmapName + ".wmp";
}
else
{
encoder = new PngBitmapEncoder();
bitmapName = bitmapName + ".png";
}
}
if (value is BitmapFrame)
{
encoder.Frames.Add((BitmapFrame)value);
}
else
{
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)value));
}
int index = m_mainFile.LastIndexOf('.');
if (index < 0)
{
index = m_mainFile.Length;
}
string uri = m_mainFile.Substring(0, index) + "_" + bitmapName;
Stream bitmapStreamDest = new System.IO.FileStream(uri, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
#if DEBUG
Console.WriteLine("Saving " + uri);
#endif
encoder.Save(bitmapStreamDest);
bitmapStreamDest.Close();
return new Uri(BaseUriHelper.SiteOfOriginBaseUri, uri);
}
}
internal class LooseFileSerializationManager : PackageSerializationManager
{
String m_mainFile;
LooseImageSourceTypeConverter m_imageConverter;
public LooseFileSerializationManager(String mainFile)
{
m_mainFile = mainFile;
}
public override void SaveAsXaml(Object serializedObject)
{
}
internal override String GetXmlNSForType(Type objectType)
{
return null;
}
internal override XmlWriter AcquireXmlWriter(Type writerType)
{
return null;
}
internal override void ReleaseXmlWriter(Type writerType)
{
return;
}
internal override XpsResourceStream AcquireResourceStream(Type resourceType)
{
return null;
}
internal override XpsResourceStream AcquireResourceStream(Type resourceType, String resourceID)
{
return null;
}
internal override void ReleaseResourceStream(Type resourceType)
{
return;
}
internal override void ReleaseResourceStream(Type resourceType, String resourceID)
{
return;
}
internal override void AddRelationshipToCurrentPage(Uri targetUri, string relationshipName)
{
return;
}
internal override BasePackagingPolicy PackagingPolicy
{
get
{
return null;
}
}
internal
override
XpsResourcePolicy
ResourcePolicy
{
get
{
return null;
}
}
internal override TypeConverter GetTypeConverter(Object serializedObject)
{
return null;
}
internal override TypeConverter GetTypeConverter(Type objType)
{
if (typeof(Color).IsAssignableFrom(objType))
{
return new MyColorTypeConverter();
}
else if (typeof(BitmapSource).IsAssignableFrom(objType))
{
if (m_imageConverter == null)
{
m_imageConverter = new LooseImageSourceTypeConverter(m_mainFile);
}
return m_imageConverter;
}
return null;
}
}
}
namespace System.Windows.Xps.Serialization
{
#if SAMPLE
// Sample code for serializing a Visual tree one node at a time
public void SaveAsXml(Visual visual, System.Xml.XmlWriter resWriter, System.Xml.XmlWriter bodyWriter, string fileName)
{
resWriter.WriteStartElement("Canvas.Resources");
VisualTreeFlattener flattener = new VisualTreeFlattener(resWriter, bodyWriter, fileName);
Walk(flattener, visual);
resWriter.WriteEndElement();
}
internal void Walk(VisualTreeFlattener flattener, Visual visual)
{
if (flattener.StartVisual(visual))
{
int count = VisualTreeHelper.GetChildrenCount(visual);
for(int i = 0; i < count; i++)
{
Walk(flattener, VisualTreeHelper.GetChild(visual,i));
}
flattener.EndVisual();
}
}
#endif
///
/// Main class for converting visual tree to fixed DrawingContext primitives
///
#region public class VisualTreeFlattener
[MS.Internal.ReachFramework.FriendAccessAllowed]
internal class VisualTreeFlattener
{
#region Private Fields
DrawingContextFlattener _dcf;
Dictionary _nameList;
//
// Fix bug 1514270: Any VisualBrush.Visual rasterization occurs in brush-space, which
// leads to fidelity issues if the brush is transformed to cover a large region.
// This stores transformation above the brush to serve as hint for final size of
// VisualBrush's content.
//
private Matrix _inheritedTransformHint = Matrix.Identity;
// Depth of StartVisual call. Zero corresponds to highest level.
private int _visualDepth = 0;
#endregion
#region Public Properties
///
/// Transformation above this VisualTreeFlattener instance; currently only used
/// when reducing VisualBrush to DrawingBrush.
///
public Matrix InheritedTransformHint
{
get
{
return _inheritedTransformHint;
}
set
{
_inheritedTransformHint = value;
}
}
#endregion
#region Constructors
///
/// Constructor
///
///
/// Raw size of parent fixed page in pixels. Does not account for margins
internal VisualTreeFlattener(IMetroDrawingContext dc, Size pageSize)
{
// DrawingContextFlattener flattens calls to DrawingContext
_dcf = new DrawingContextFlattener(dc, pageSize);
}
///
/// Constructor
///
///
///
///
/// Raw size of parent fixed page in pixels. Does not account for margins
internal VisualTreeFlattener(System.Xml.XmlWriter resWriter, System.Xml.XmlWriter bodyWriter, PackageSerializationManager manager, Size pageSize)
{
VisualSerializer dc = new VisualSerializer(resWriter, bodyWriter, manager);
_dcf = new DrawingContextFlattener(dc, pageSize);
}
#endregion
#region Private Static Methods
///
/// Evalulate complexity of a Drawing
/// 0: empty
/// 1: single primitive
/// 2: complex
///
static int Complexity(System.Windows.Media.Drawing drawing)
{
if (drawing == null)
{
return 0;
}
DrawingGroup dg = drawing as DrawingGroup;
if (dg != null)
{
if (Utility.IsTransparent(dg.Opacity))
{
return 0;
}
if ((dg.Transform != null) || (dg.ClipGeometry != null) || (!Utility.IsOne(dg.Opacity)))
{
return 2;
}
DrawingCollection children = dg.Children;
int complexity = 0;
foreach (System.Windows.Media.Drawing d in children)
{
complexity += Complexity(d);
if (complexity >= 2)
{
break;
}
}
return complexity;
}
return 1;
}
#endregion
#region Internal Methods
///
/// S0 header/body handling for a visual
///
/// Visual input
/// returns true if Visual's children should be walked
internal bool StartVisual(Visual visual)
{
#if DEBUG
_dcf.Comment(visual.GetType().ToString());
#endif
System.Windows.Media.Drawing content = VisualTreeHelper.GetDrawing(visual);
bool single = false;
if ((VisualTreeHelper.GetChildrenCount(visual) == 0) && (Complexity(content) <= 1))
{
single = true;
}
// Get Visual properties in the order they're applied to the content.
// Note that BitmapEffect may replace the content.
Brush mask = VisualTreeHelper.GetOpacityMask(visual);
double opacity = VisualTreeHelper.GetOpacity(visual);
BitmapEffect effect = VisualTreeHelper.GetBitmapEffect(visual);
Geometry clip = VisualTreeHelper.GetClip(visual);
Transform trans = Utility.GetVisualTransform(visual);
Rect bounds = VisualTreeHelper.GetDescendantBounds(visual);
// Check for invisible Visual subtree.
{
// Skip invalid transformation
if (trans != null && !Utility.IsValid(trans.Value))
{
return false;
}
// Skip empty subtree
if (!Utility.IsRenderVisible(bounds))
{
return false;
}
// Skip complete clipped subtree
if ((clip != null) && !Utility.IsRenderVisible(clip.Bounds))
{
return false;
}
// Skip total transparent subtree
// Fix bug 1553961: BitmapEffect replaces all content, including opacity, so
// do not skip transparent opacity if effect applied.
if (effect == null && (Utility.IsTransparent(opacity) || BrushProxy.IsEmpty(mask)))
{
return false;
}
}
// Ignore opaque opacity mask
if ((mask != null) && Utility.IsBrushOpaque(mask))
{
mask = null;
}
FrameworkElement fe = visual as FrameworkElement;
String nameAttr = null;
// we will presever the name for this element if
// 1. It is FrameworkElement and Name is non empty.
// 2. It is not FixedPage(because NameProperty of FixedPage is already reserved)
// 3. It is not from template. TemplatedParent is null.
if (fe != null && !String.IsNullOrEmpty(fe.Name) &&
!(visual is System.Windows.Documents.FixedPage) &&
fe.TemplatedParent == null)
{
if (_nameList == null)
{
_nameList = new Dictionary();
}
int dummy;
// Some classes like DocumentViewer, in its visual tree, will implicitly generate
// some named elements. We will avoid create the duplicate names.
if (_nameList.TryGetValue(fe.Name, out dummy) == false)
{
nameAttr = fe.Name;
_nameList.Add(fe.Name, 0);
}
}
// Preserve FixedPage.NavigateUri.
UIElement uiElement = visual as UIElement;
Uri navigateUri = null;
if (uiElement != null)
{
navigateUri = FixedPage.GetNavigateUri(uiElement);
}
// Preserve RenderOptions.EdgeMode.
EdgeMode edgeMode = RenderOptions.GetEdgeMode(visual);
// Rasterize all Viewport3DVisuals, and Visuals with BitmapEffect applied
bool walkChildren;
if (effect != null || visual is Viewport3DVisual)
{
// rasterization also handles opacity and children
Matrix worldTransform = _dcf.Transform;
if (trans != null)
{
worldTransform.Prepend(trans.Value);
}
// get inherited clipping
bool empty;
Geometry inheritedClipping = _dcf.Clip;
if (inheritedClipping == null || !inheritedClipping.IsEmpty())
{
// transform current clip to world space
if (clip != null)
{
Matrix clipToWorldSpace = _dcf.Transform;
if (trans != null)
{
clipToWorldSpace.Prepend(trans.Value);
}
clip = Utility.TransformGeometry(clip, clipToWorldSpace);
}
// intersect with inherited clipping
clip = Utility.Intersect(inheritedClipping, clip, Matrix.Identity, out empty);
if (!empty)
{
// clipping is in world space
_dcf.DrawRasterizedVisual(
visual,
nameAttr,
navigateUri,
edgeMode,
trans,
worldTransform,
_inheritedTransformHint,
clip,
effect
);
}
}
walkChildren = false;
}
else
{
//
// Fix bug 1576135: XPS serialization: round trip causes inflation by one Path element per page per trip
//
// Avoid emitting FixedPage white drawing content, since FixedPage with white background
// is already emitted by the serializer prior to visual walk.
//
bool walkDrawing = true;
if (_visualDepth == 0)
{
FixedPage fixedPage = visual as FixedPage;
if (fixedPage != null)
{
SolidColorBrush colorBrush = fixedPage.Background as SolidColorBrush;
if (colorBrush != null)
{
Color color = colorBrush.Color;
if ((color.R == 255 && color.G == 255 && color.B == 255) ||
color.A == 0)
{
walkDrawing = false;
}
}
}
}
//
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- ComplexType.cs
- ProfileBuildProvider.cs
- DoubleCollectionConverter.cs
- Route.cs
- Point3DAnimationUsingKeyFrames.cs
- InputReportEventArgs.cs
- _AutoWebProxyScriptEngine.cs
- CurrentTimeZone.cs
- XmlDataCollection.cs
- SecurityResources.cs
- TableLayoutPanelCodeDomSerializer.cs
- PersonalizationAdministration.cs
- XmlArrayItemAttributes.cs
- FusionWrap.cs
- Mappings.cs
- StructuredType.cs
- TemplateParser.cs
- oledbmetadatacolumnnames.cs
- AsyncPostBackErrorEventArgs.cs
- CustomSignedXml.cs
- Deflater.cs
- parserscommon.cs
- WebPartMinimizeVerb.cs
- DetailsViewInsertEventArgs.cs
- DecimalConstantAttribute.cs
- RijndaelManaged.cs
- XmlTextWriter.cs
- TimeSpanMinutesConverter.cs
- GestureRecognitionResult.cs
- RadioButtonStandardAdapter.cs
- ZipPackage.cs
- safesecurityhelperavalon.cs
- SchemaImporterExtensionElement.cs
- SequentialOutput.cs
- AddInController.cs
- PropertyEmitterBase.cs
- QuaternionAnimation.cs
- ListViewDeleteEventArgs.cs
- ScriptMethodAttribute.cs
- TimeSpanValidator.cs
- ErrorHandler.cs
- DictionaryTraceRecord.cs
- InvalidMessageContractException.cs
- TextRangeEdit.cs
- XsdBuildProvider.cs
- DemultiplexingClientMessageFormatter.cs
- BindingExpression.cs
- IPAddressCollection.cs
- EditorZone.cs
- TreeNodeStyleCollection.cs
- ConsumerConnectionPoint.cs
- exports.cs
- AspCompat.cs
- NameObjectCollectionBase.cs
- Tokenizer.cs
- TypeRestriction.cs
- StylusCaptureWithinProperty.cs
- DeadCharTextComposition.cs
- ButtonFlatAdapter.cs
- Rect3DValueSerializer.cs
- CryptoKeySecurity.cs
- VectorCollection.cs
- GridViewColumnHeader.cs
- CollectionType.cs
- KeyFrames.cs
- TextServicesDisplayAttributePropertyRanges.cs
- FixedNode.cs
- ChannelBinding.cs
- DaylightTime.cs
- InstalledFontCollection.cs
- ToolStripMenuItem.cs
- XmlReader.cs
- Queue.cs
- SessionState.cs
- MetadataArtifactLoaderComposite.cs
- AQNBuilder.cs
- SessionPageStatePersister.cs
- InputLanguageProfileNotifySink.cs
- SynchronizationContextHelper.cs
- PageWrapper.cs
- ResourceDescriptionAttribute.cs
- InitialServerConnectionReader.cs
- StatusBarDrawItemEvent.cs
- IdnMapping.cs
- DataGridViewSortCompareEventArgs.cs
- _PooledStream.cs
- CodePrimitiveExpression.cs
- PtsPage.cs
- ZipIOLocalFileHeader.cs
- SystemUdpStatistics.cs
- formatter.cs
- FrameDimension.cs
- InheritanceContextChangedEventManager.cs
- Calendar.cs
- TemplateFactory.cs
- TaskFileService.cs
- EmbeddedObject.cs
- AssemblyCollection.cs
- _LocalDataStore.cs
- ConfigXmlWhitespace.cs