// Token: 0x06003855 RID: 14421 RVA: 0x000FBE94 File Offset: 0x000FA094 internal static MemoryStream ConvertRtfToXaml(string rtfContent) { MemoryStream memoryStream = new MemoryStream(); WpfPayload wpfPayload = WpfPayload.CreateWpfPayload(memoryStream); using (wpfPayload.Package) { using (Stream stream = wpfPayload.CreateXamlStream()) { string text = new XamlRtfConverter { WpfPayload = wpfPayload }.ConvertRtfToXaml(rtfContent); if (text != string.Empty) { StreamWriter streamWriter = new StreamWriter(stream); using (streamWriter) { streamWriter.Write(text); return(memoryStream); } } memoryStream = null; } } return(memoryStream); }
// Converts an rtf content to xaml content. internal static MemoryStream ConvertRtfToXaml(string rtfContent) { MemoryStream memoryStream = new MemoryStream(); WpfPayload wpfPayload = WpfPayload.CreateWpfPayload(memoryStream); using (wpfPayload.Package) { using (Stream xamlStream = wpfPayload.CreateXamlStream()) { // Create XamlRtfConverter to process the converting from Rtf to Xaml XamlRtfConverter xamlRtfConverter = new XamlRtfConverter(); xamlRtfConverter.WpfPayload = wpfPayload; string xamlContent = xamlRtfConverter.ConvertRtfToXaml(rtfContent); if (xamlContent != string.Empty) { StreamWriter streamWriter = new StreamWriter(xamlStream); using (streamWriter) { streamWriter.Write(xamlContent); } } else { memoryStream = null; } } // This closes xamlStream } // This closes the package return(memoryStream); }
internal static MemoryStream SaveImage(BitmapSource bitmapSource, string imageContentType) { MemoryStream memoryStream = new MemoryStream(); WpfPayload wpfPayload = new WpfPayload(null); using (wpfPayload.CreatePackage(memoryStream)) { int imageIndex = 0; string imageReference = WpfPayload.GetImageReference(WpfPayload.GetImageName(imageIndex, imageContentType)); PackagePart packagePart = wpfPayload.CreateWpfEntryPart(); Stream stream = packagePart.GetStream(); using (stream) { StreamWriter streamWriter = new StreamWriter(stream); using (streamWriter) { string value = string.Concat(new object[] { "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><InlineUIContainer><Image Width=\"", bitmapSource.Width, "\" Height=\"", bitmapSource.Height, "\" ><Image.Source><BitmapImage CacheOption=\"OnLoad\" UriSource=\"", imageReference, "\"/></Image.Source></Image></InlineUIContainer></Span>" }); streamWriter.Write(value); } } wpfPayload.CreateImagePart(packagePart, bitmapSource, imageContentType, imageIndex); } return(memoryStream); }
/// <summary> /// Loads xaml content from a WPF package. /// </summary> /// <param name="stream"> /// Stream that must be accessible for reading and structured as /// a WPF container: part XamlEntryPart is expected as one of /// its entry parts. /// </param> /// <returns> /// Returns a xaml element loaded from the entry part of the package. /// </returns> /// <exception cref="ArgumentNullException"> /// Throws parsing exception when the xaml content does not comply with the xaml schema. /// </exception> /// <exception cref="ArgumentException"> /// Throws validation exception when the package is not well structured. /// </exception> /// <exception cref="Exception"> /// Throws uri exception when the pachageBaseUri is not correct absolute uri. /// </exception> /// <remarks> /// USED IN LEXICON VIA REFLECTION /// </remarks> internal static object LoadElement(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } object xamlObject; try { WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream); // Now load the package using (wpfPayload.Package) { // Validate WPF paypoad and get its entry part PackagePart xamlEntryPart = wpfPayload.ValidatePayload(); // Define a unique uri for this instance of PWF payload. // Uniqueness is required to make sure that cached images are not mixed up. int newWpfPayoutCount = Interlocked.Increment(ref _wpfPayloadCount); Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package // Set this temporary uri as a base uri for xaml parser ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; // Call xaml parser xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); } } catch (XamlParseException e) { // Incase of xaml parsing or package structure failure // we return null. Invariant.Assert(e != null); //to make compiler happy about not using a variable e. This variable is useful in debugging process though - to see a reason of a parsing failure xamlObject = null; } catch (System.IO.FileFormatException) { xamlObject = null; } catch (System.IO.FileLoadException) { xamlObject = null; } catch (System.OutOfMemoryException) { xamlObject = null; } return(xamlObject); }
// Token: 0x06003F2C RID: 16172 RVA: 0x00120E4C File Offset: 0x0011F04C internal Stream CreateImageStream(int imageCount, string contentType, out string imagePartUriString) { imagePartUriString = WpfPayload.GetImageName(imageCount, contentType); Uri partUri = new Uri("/Xaml" + imagePartUriString, UriKind.Relative); PackagePart packagePart = this._package.CreatePart(partUri, contentType, CompressionOption.NotCompressed); imagePartUriString = WpfPayload.GetImageReference(imagePartUriString); return(packagePart.GetStream()); }
/// <summary> /// Writes a content of current range in form of valid xml. /// Places an artificial element xaml:FlowDocument as a root of output xml. /// </summary> /// <param name="xmlWriter"> /// XmlWriter to which the range will be serialized /// </param> /// <param name="range"> /// TextRange whose content is copied into XmlWriter xmlWriter. /// </param> /// <param name="useFlowDocumentAsRoot"> /// true means that we need to serialize the whole FlowDocument - used in FileSave scenario; /// false means that we are in copy-paste scenario and will use Section or Span as a root - depending on context. /// </param> /// <param name="wpfPayload"> /// When this parameter is not null, images are serialized. When null, images are stripped out. /// </param> /// <param name="preserveTextElements"> /// When TRUE, TextElements are serialized as-is. When FALSE, they're upcast to their base type. /// </param> internal static void WriteXaml(XmlWriter xmlWriter, ITextRange range, bool useFlowDocumentAsRoot, WpfPayload wpfPayload, bool preserveTextElements) { // Set unindented formatting to avoid inserting insignificant whitespaces as significant ones Formatting saveWriterFormatting = Formatting.None; if (xmlWriter is XmlTextWriter) { saveWriterFormatting = ((XmlTextWriter)xmlWriter).Formatting; ((XmlTextWriter)xmlWriter).Formatting = Formatting.None; } // Get the default xamlTypeMapper. XamlTypeMapper xamlTypeMapper = XmlParserDefaults.DefaultMapper; // Identify structural scope of selection - nearest common ancestor ITextPointer commonAncestor = FindSerializationCommonAncestor(range); // Decide whether we need last paragraph merging or not bool lastParagraphMustBeMerged = !TextPointerBase.IsAfterLastParagraph(range.End) && range.End.GetPointerContext(LogicalDirection.Backward) != TextPointerContext.ElementStart; // Write wrapping element with contextual properties WriteRootFlowDocument(range, commonAncestor, xmlWriter, xamlTypeMapper, lastParagraphMustBeMerged, useFlowDocumentAsRoot); // The ignoreWriteHyperlinkEnd flag will be set after call WriteOpeningTags. // If ignoreWriteHyperlinkEnd is true, WriteXamlTextSegment won't write Hyperlink end element // since Hyperlink writing opening tag is ignored by selecting the partial of Hyperlink. bool ignoreWriteHyperlinkEnd; List<int> ignoreList = new List<int>(); // Start counting tags needed to be closed. // EmptyDocumentDepth==1 - counts FlowDocument opened in WriteRootFlowDocument above. int elementLevel = EmptyDocumentDepth + WriteOpeningTags(range, range.Start, commonAncestor, xmlWriter, xamlTypeMapper, /*reduceElement:*/wpfPayload == null, out ignoreWriteHyperlinkEnd, ref ignoreList, preserveTextElements); if (range.IsTableCellRange) { WriteXamlTableCellRange(xmlWriter, range, xamlTypeMapper, ref elementLevel, wpfPayload, preserveTextElements); } else { WriteXamlTextSegment(xmlWriter, range.Start, range.End, xamlTypeMapper, ref elementLevel, wpfPayload, ignoreWriteHyperlinkEnd, ignoreList, preserveTextElements); } // Close all remaining tags - scoping its End position Invariant.Assert(elementLevel >= 0, "elementLevel cannot be negative"); while (elementLevel-- > 0) { xmlWriter.WriteFullEndElement(); } // Restore xmlWriter's Formatting property if (xmlWriter is XmlTextWriter) { ((XmlTextWriter)xmlWriter).Formatting = saveWriterFormatting; } }
// Token: 0x06003854 RID: 14420 RVA: 0x000FBE68 File Offset: 0x000FA068 internal static string ConvertXamlToRtf(string xamlContent, Stream wpfContainerMemory) { XamlRtfConverter xamlRtfConverter = new XamlRtfConverter(); if (wpfContainerMemory != null) { xamlRtfConverter.WpfPayload = WpfPayload.OpenWpfPayload(wpfContainerMemory); } return(xamlRtfConverter.ConvertXamlToRtf(xamlContent)); }
/// <summary> /// Saves the content of the range in the given stream as a WPF payload. /// </summary> /// <param name="range"> /// The range whose content is to be serialized. /// </param> /// <param name="stream"> /// When the stream is not null, it is a request to unconditionally /// creatte WPF package in this stream. /// If this parameter is null, then the package is created /// only when necessary - when there are images in the range. /// The new MemoryStream is created in this case and assigned to this /// parameter on exit. /// </param> /// <param name="useFlowDocumentAsRoot"> /// </param> /// <param name="preserveTextElements"> /// If set false, custom TextElements will be upcasted to known types. /// </param> /// <returns> /// A xaml part of serialized content. /// </returns> internal static string SaveRange(ITextRange range, ref Stream stream, bool useFlowDocumentAsRoot, bool preserveTextElements) { if (range == null) { throw new ArgumentNullException("range"); } // Create the wpf package in the stream WpfPayload wpfPayload = new WpfPayload(/*package:*/ null); // Create a string representing serialized xaml StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, range, useFlowDocumentAsRoot, wpfPayload, preserveTextElements); string xamlText = stringWriter.ToString(); // Decide whether we need to create a package if (stream != null || wpfPayload._images != null) { // There are images in the content. Need to create a package if (stream == null) { stream = new MemoryStream(); } // Create a package in the stream using (wpfPayload.CreatePackage(stream)) { // Create the entry part for xaml content of the WPF package PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart(); // Write the part's content Stream xamlPartStream = xamlEntryPart.GetStream(); using (xamlPartStream) { StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream); using (xamlPartWriter) { xamlPartWriter.Write(xamlText); } } // Write relationships from xaml entry part to all images wpfPayload.CreateComponentParts(xamlEntryPart); } Invariant.Assert(wpfPayload._images == null); // must have beed cleared in CreateComponentParts } return(xamlText); }
private void CreateComponentParts(PackagePart sourcePart) { if (this._images != null) { for (int i = 0; i < this._images.Count; i++) { Image image = this._images[i]; string imageContentType = WpfPayload.GetImageContentType(image.Source.ToString()); this.CreateImagePart(sourcePart, this.GetBitmapSourceFromImage(image), imageContentType, i); } this._images = null; } }
// Converts xaml content to rtf content. internal static string ConvertXamlToRtf(string xamlContent, Stream wpfContainerMemory) { // Create XamlRtfConverter to process the converting from Xaml to Rtf XamlRtfConverter xamlRtfConverter = new XamlRtfConverter(); if (wpfContainerMemory != null) { xamlRtfConverter.WpfPayload = WpfPayload.OpenWpfPayload(wpfContainerMemory); } // Process Xaml-Rtf converting string rtfContent = xamlRtfConverter.ConvertXamlToRtf(xamlContent); return(rtfContent); }
private void CreateImagePart(PackagePart sourcePart, BitmapSource imageSource, string imageContentType, int imageIndex) { string imageName = WpfPayload.GetImageName(imageIndex, imageContentType); Uri uri = new Uri("/Xaml" + imageName, UriKind.Relative); PackagePart packagePart = this._package.CreatePart(uri, imageContentType, CompressionOption.NotCompressed); PackageRelationship packageRelationship = sourcePart.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/wpf/2005/10/xaml/component"); BitmapEncoder bitmapEncoder = WpfPayload.GetBitmapEncoder(imageContentType); bitmapEncoder.Frames.Add(BitmapFrame.Create(imageSource)); Stream stream = packagePart.GetStream(); using (stream) { bitmapEncoder.Save(stream); } }
// Token: 0x06003F20 RID: 16160 RVA: 0x0012075C File Offset: 0x0011E95C internal static object LoadElement(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } object result; try { WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream); using (wpfPayload.Package) { PackagePart packagePart = wpfPayload.ValidatePayload(); int num = Interlocked.Increment(ref WpfPayload._wpfPayloadCount); Uri packageUri = new Uri("payload://wpf" + num, UriKind.Absolute); Uri uri = PackUriHelper.Create(packageUri, packagePart.Uri); Uri packageUri2 = PackUriHelper.GetPackageUri(uri); PackageStore.AddPackage(packageUri2, wpfPayload.Package); ParserContext parserContext = new ParserContext(); parserContext.BaseUri = uri; bool useRestrictiveXamlReader = !Clipboard.UseLegacyDangerousClipboardDeserializationMode(); result = XamlReader.Load(packagePart.GetStream(), parserContext, useRestrictiveXamlReader); PackageStore.RemovePackage(packageUri2); } } catch (XamlParseException ex) { Invariant.Assert(ex != null); result = null; } catch (FileFormatException) { result = null; } catch (FileLoadException) { result = null; } catch (OutOfMemoryException) { result = null; } return(result); }
internal static MemoryStream SaveImage(BitmapSource bitmapSource, string imageContentType) { MemoryStream stream = new MemoryStream(); // Create the wpf package in the stream WpfPayload wpfPayload = new WpfPayload(/*package:*/ null); // Create a package in the stream using (wpfPayload.CreatePackage(stream)) { // Define a reference for the image int imageIndex = 0; string imageReference = GetImageReference(GetImageName(imageIndex, imageContentType)); // Create the entry part for xaml content of the WPF package PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart(); // Write the part's content Stream xamlPartStream = xamlEntryPart.GetStream(); using (xamlPartStream) { StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream); using (xamlPartWriter) { string xamlText = "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" + "<InlineUIContainer><Image " + "Width=\"" + bitmapSource.Width + "\" " + "Height=\"" + bitmapSource.Height + "\" " + "><Image.Source><BitmapImage CacheOption=\"OnLoad\" UriSource=\"" + imageReference + "\"/></Image.Source></Image></InlineUIContainer></Span>"; xamlPartWriter.Write(xamlText); } } // Add image to a package wpfPayload.CreateImagePart(xamlEntryPart, bitmapSource, imageContentType, imageIndex); } return(stream); }
// Token: 0x06003F1E RID: 16158 RVA: 0x0012055C File Offset: 0x0011E75C internal static string SaveRange(ITextRange range, ref Stream stream, bool useFlowDocumentAsRoot, bool preserveTextElements) { if (range == null) { throw new ArgumentNullException("range"); } WpfPayload wpfPayload = new WpfPayload(null); StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, range, useFlowDocumentAsRoot, wpfPayload, preserveTextElements); string text = stringWriter.ToString(); if (stream != null || wpfPayload._images != null) { if (stream == null) { stream = new MemoryStream(); } using (wpfPayload.CreatePackage(stream)) { PackagePart packagePart = wpfPayload.CreateWpfEntryPart(); Stream stream2 = packagePart.GetStream(); using (stream2) { StreamWriter streamWriter = new StreamWriter(stream2); using (streamWriter) { streamWriter.Write(text); } } wpfPayload.CreateComponentParts(packagePart); } Invariant.Assert(wpfPayload._images == null); } return(text); }
// Token: 0x06003F26 RID: 16166 RVA: 0x00120A2C File Offset: 0x0011EC2C internal string AddImage(Image image) { if (image == null) { throw new ArgumentNullException("image"); } if (image.Source == null) { throw new ArgumentNullException("image.Source"); } if (string.IsNullOrEmpty(image.Source.ToString())) { throw new ArgumentException(SR.Get("WpfPayload_InvalidImageSource")); } if (this._images == null) { this._images = new List <Image>(); } string text = null; string imageContentType = WpfPayload.GetImageContentType(image.Source.ToString()); for (int i = 0; i < this._images.Count; i++) { if (WpfPayload.ImagesAreIdentical(this.GetBitmapSourceFromImage(this._images[i]), this.GetBitmapSourceFromImage(image))) { Invariant.Assert(imageContentType == WpfPayload.GetImageContentType(this._images[i].Source.ToString()), "Image content types expected to be consistent: " + imageContentType + " vs. " + WpfPayload.GetImageContentType(this._images[i].Source.ToString())); text = WpfPayload.GetImageName(i, imageContentType); } } if (text == null) { text = WpfPayload.GetImageName(this._images.Count, imageContentType); this._images.Add(image); } return(WpfPayload.GetImageReference(text)); }
internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop) { new UIPermission(UIPermissionClipboard.AllClipboard).Assert(); DataObject dataObject; try { dataObject = new DataObject(); } finally { CodeAccessPermission.RevertAssert(); } string text = This.Selection.Text; if (text != string.Empty) { if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text)) { TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.Text, text); } if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText)) { TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.UnicodeText, text); } } if (This.AcceptsRichContent) { if (SecurityHelper.CheckUnmanagedCodePermission()) { Stream stream = null; string text2 = WpfPayload.SaveRange(This.Selection, ref stream, false); if (text2.Length > 0) { if (stream != null && TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage)) { dataObject.SetData(DataFormats.XamlPackage, stream); } if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf)) { string text3 = TextEditorCopyPaste.ConvertXamlToRtf(text2, stream); if (text3 != string.Empty) { dataObject.SetData(DataFormats.Rtf, text3, true); } } } Image image = This.Selection.GetUIElementSelected() as Image; if (image != null && image.Source is BitmapSource) { dataObject.SetImage((BitmapSource)image.Source); } } StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, false, null); string text4 = stringWriter.ToString(); if (text4.Length > 0 && TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Xaml)) { TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.Xaml, text4); PermissionSet permissionSet = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin(); string content = permissionSet.ToString(); TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.ApplicationTrust, content); } } DataObjectCopyingEventArgs dataObjectCopyingEventArgs = new DataObjectCopyingEventArgs(dataObject, isDragDrop); This.UiScope.RaiseEvent(dataObjectCopyingEventArgs); if (dataObjectCopyingEventArgs.CommandCancelled) { dataObject = null; } return(dataObject); }
// Token: 0x06003F1D RID: 16157 RVA: 0x0012054F File Offset: 0x0011E74F internal static string SaveRange(ITextRange range, ref Stream stream, bool useFlowDocumentAsRoot) { return(WpfPayload.SaveRange(range, ref stream, useFlowDocumentAsRoot, false)); }
// ------------------------------------------------------------- // // Internal Methods // // ------------------------------------------------------------- #region Internal Methods internal static void WriteXaml(XmlWriter xmlWriter, ITextRange range, bool useFlowDocumentAsRoot, WpfPayload wpfPayload) { WriteXaml(xmlWriter, range, useFlowDocumentAsRoot, wpfPayload, false); }
/// <summary> /// Serializes a rectagular table range /// </summary> private static void WriteXamlTableCellRange(XmlWriter xmlWriter, ITextRange range, XamlTypeMapper xamlTypeMapper, ref int elementLevel, WpfPayload wpfPayload, bool preserveTextElements) { Invariant.Assert(range.IsTableCellRange, "range is expected to be in IsTableCellRange state"); List<TextSegment> textSegments = range.TextSegments; int checkElementLevel = -1; // negative value as an indicator that it is not yet initialized // Set ignoreWriteHyperlinkEnd as false initially bool ignoreWriteHyperlinkEnd = false; List<int> ignoreList = new List<int>(); for (int i = 0; i < textSegments.Count; i++) { TextSegment textSegment = textSegments[i]; // Open a row for this segment (except for the very first one, for which we opened a row in a WriteOpeningTags method) if (i > 0) { ITextPointer pointer = textSegment.Start.CreatePointer(); while (!typeof(TableRow).IsAssignableFrom(pointer.ParentType)) { Invariant.Assert(typeof(TextElement).IsAssignableFrom(pointer.ParentType), "pointer must be still in a scope of TextElement"); pointer.MoveToElementEdge(ElementEdge.BeforeStart); } Invariant.Assert(typeof(TableRow).IsAssignableFrom(pointer.ParentType), "pointer must be in a scope of TableRow"); pointer.MoveToElementEdge(ElementEdge.BeforeStart); ITextRange textRange = new TextRange(textSegment.Start, textSegment.End); elementLevel += WriteOpeningTags(textRange, textSegment.Start, pointer, xmlWriter, xamlTypeMapper, /*reduceElement:*/wpfPayload == null, out ignoreWriteHyperlinkEnd, ref ignoreList, preserveTextElements); } // Output the cell segment for one row WriteXamlTextSegment(xmlWriter, textSegment.Start, textSegment.End, xamlTypeMapper, ref elementLevel, wpfPayload, ignoreWriteHyperlinkEnd, ignoreList, preserveTextElements); Invariant.Assert(elementLevel >= 4, "At the minimun we expected to stay within four elements: Section(wrapper),Table,TableRowGroup,TableRow"); if (checkElementLevel < 0) checkElementLevel = elementLevel; // initialize level checking variable Invariant.Assert(checkElementLevel == elementLevel, "elementLevel is supposed to be unchanged between segments of table cell range"); // Assuming that the element is TableRow - close it. // NOTE: Such assumption is valid because WriteXamlTextSegment moves end pointer out of all opening tags, // so it ends serialization immediately after the last cell's closing tag. // This means that we only need to close one level - for TableRow. // elementLevel--; xmlWriter.WriteFullEndElement(); } }
// ------------------------------------------------------------- // // Private Methods // // ------------------------------------------------------------- #region Private Methods // ............................................................. // // Serialization // // ............................................................. /// <summary> /// This function serializes text segment formed by rangeStart and rangeEnd to valid xml using xmlWriter. /// </summary> /// <SecurityNote> /// To mask the security exception from XamlWriter.Save in partial trust case, /// this function checks if the current call stack has the all clipboard permission. /// </SecurityNote> private static void WriteXamlTextSegment(XmlWriter xmlWriter, ITextPointer rangeStart, ITextPointer rangeEnd, XamlTypeMapper xamlTypeMapper, ref int elementLevel, WpfPayload wpfPayload, bool ignoreWriteHyperlinkEnd, List<int> ignoreList, bool preserveTextElements) { // Special case for pure text selection - we need a Run wrapper for it. if (elementLevel == EmptyDocumentDepth && typeof(Run).IsAssignableFrom(rangeStart.ParentType)) { elementLevel++; xmlWriter.WriteStartElement(typeof(Run).Name); } // Create text navigator for reading the range's content ITextPointer textReader = rangeStart.CreatePointer(); // Exclude last opening tag from serialization - we don't need to create extra element // is cases when we have whole paragraphs/cells selected. // NOTE: We do this slightly differently than in TextRangeEdit.AdjustRangeEnd, where we use normalization for adjusted position. // In this case normalized position does not work, because we need to keep information about crossed paragraph boundary. while (rangeEnd.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart) { rangeEnd = rangeEnd.GetNextContextPosition(LogicalDirection.Backward); } // Write the range internal contents while (textReader.CompareTo(rangeEnd) < 0) { TextPointerContext runType = textReader.GetPointerContext(LogicalDirection.Forward); switch (runType) { case TextPointerContext.ElementStart: TextElement nextElement = (TextElement)textReader.GetAdjacentElement(LogicalDirection.Forward); if (nextElement is Hyperlink) { // Don't write Hyperlink start element if Hyperlink is invalid // in case of having a UiElement except Image or stated the range end // position before the end position of the Hyperlink. if (IsHyperlinkInvalid(textReader, rangeEnd)) { ignoreWriteHyperlinkEnd = true; textReader.MoveToNextContextPosition(LogicalDirection.Forward); continue; } } else if (nextElement != null) { // TextElementEditingBehaviorAttribute att = (TextElementEditingBehaviorAttribute)Attribute.GetCustomAttribute(nextElement.GetType(), typeof(TextElementEditingBehaviorAttribute)); if (att != null && !att.IsTypographicOnly) { if (IsPartialNonTypographic(textReader, rangeEnd)) { // Add pointer to ignore list ITextPointer ptr = textReader.CreatePointer(); ptr.MoveToElementEdge(ElementEdge.BeforeEnd); ignoreList.Add(ptr.Offset); textReader.MoveToNextContextPosition(LogicalDirection.Forward); continue; } } } elementLevel++; textReader.MoveToNextContextPosition(LogicalDirection.Forward); WriteStartXamlElement(/*range:*/null, textReader, xmlWriter, xamlTypeMapper, /*reduceElement:*/wpfPayload == null, preserveTextElements); break; case TextPointerContext.ElementEnd: // Don't write Hyperlink end element if Hyperlink include the invalid // in case of having a UiElement except Image or stated the range end // before the end position of the Hyperlink or Hyperlink opening tag is // skipped from WriteOpeningTags by selecting of the partial of Hyperlink. if (ignoreWriteHyperlinkEnd && (textReader.GetAdjacentElement(LogicalDirection.Forward) is Hyperlink)) { // Reset the flag to keep walk up the next Hyperlink tag ignoreWriteHyperlinkEnd = false; textReader.MoveToNextContextPosition(LogicalDirection.Forward); continue; } // Check the ignore list ITextPointer endPointer = textReader.CreatePointer(); endPointer.MoveToElementEdge(ElementEdge.BeforeEnd); // if (ignoreList.Contains(endPointer.Offset)) { ignoreList.Remove(endPointer.Offset); textReader.MoveToNextContextPosition(LogicalDirection.Forward); continue; } elementLevel--; if (TextSchema.IsBreak(textReader.ParentType)) { // For LineBreak, etc. use empty element syntax xmlWriter.WriteEndElement(); } else { // // For all other textelements use explicit closing tag. xmlWriter.WriteFullEndElement(); } textReader.MoveToNextContextPosition(LogicalDirection.Forward); break; case TextPointerContext.Text: int textLength = textReader.GetTextRunLength(LogicalDirection.Forward); char[] text = new Char[textLength]; textLength = TextPointerBase.GetTextWithLimit(textReader, LogicalDirection.Forward, text, 0, textLength, rangeEnd); // XmlWriter will throw an ArgumentException if text contains // any invalid surrogates, so strip them out now. textLength = StripInvalidSurrogateChars(text, textLength); xmlWriter.WriteChars(text, 0, textLength); textReader.MoveToNextContextPosition(LogicalDirection.Forward); break; case TextPointerContext.EmbeddedElement: object embeddedObject = textReader.GetAdjacentElement(LogicalDirection.Forward); textReader.MoveToNextContextPosition(LogicalDirection.Forward); WriteEmbeddedObject(embeddedObject, xmlWriter, wpfPayload); break; default: Invariant.Assert(false, "unexpected value of runType"); textReader.MoveToNextContextPosition(LogicalDirection.Forward); break; } } }
/// <summary> /// Writes embeded object tag. /// </summary> /// <param name="embeddedObject"> /// </param> /// <param name="xmlWriter"> /// XmlWriter to output element opening tag. /// </param> /// <param name="wpfPayload"> /// </param> private static void WriteEmbeddedObject(object embeddedObject, XmlWriter xmlWriter, WpfPayload wpfPayload) { if (wpfPayload != null && embeddedObject is Image) { // Writing in WPF mode: need to create an image with a Source referring into a package Image image = (Image)embeddedObject; if (image.Source != null && !string.IsNullOrEmpty(image.Source.ToString())) { // Add the image to the Image collection in the package // and define the reference to image into the package string imageSource = wpfPayload.AddImage(image); if (imageSource != null) { Type elementTypeStandardized = typeof(Image); // Write opening tag for the element xmlWriter.WriteStartElement(elementTypeStandardized.Name); // Write all properties except for Source DependencyProperty[] imageProperties = TextSchema.ImageProperties; DependencyObject complexProperties = new DependencyObject(); for (int i = 0; i < imageProperties.Length; i++) { DependencyProperty property = imageProperties[i]; if (property != Image.SourceProperty) { object value = image.GetValue(property); // Write the property as attribute string or add it to a list of complex properties. WriteNoninheritableProperty(xmlWriter, property, value, elementTypeStandardized, /*onlyAffected:*/true, complexProperties, image.ReadLocalValue(property)); } } // Write Source property - as a local reference into the package container // Write Source property as the complex property to specify the BitmapImage // cache option as "OnLoad" instead of the default "OnDeman". Otherwise, // we couldn't load the image by disposing WpfPayload package. xmlWriter.WriteStartElement(typeof(Image).Name + "." + Image.SourceProperty.Name); xmlWriter.WriteStartElement(typeof(System.Windows.Media.Imaging.BitmapImage).Name); xmlWriter.WriteAttributeString(System.Windows.Media.Imaging.BitmapImage.UriSourceProperty.Name, imageSource); xmlWriter.WriteAttributeString(System.Windows.Media.Imaging.BitmapImage.CacheOptionProperty.Name, "OnLoad"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); // Write remaining complex properties WriteComplexProperties(xmlWriter, complexProperties, elementTypeStandardized); // Close the element xmlWriter.WriteEndElement(); } } } else { // In non-package mode we ignore all UIElements. // Output a space replacing this embedded element. // Note that in this mode (DataFormats.Xaml) InlineUIContainer was // replaced by Run and BlockUIContainer - by Paragraph, // so the space output here will be significant. xmlWriter.WriteString(" "); } }
// Token: 0x06003F33 RID: 16179 RVA: 0x00120FFC File Offset: 0x0011F1FC private static string GetImageName(int imageIndex, string imageContentType) { string imageFileExtension = WpfPayload.GetImageFileExtension(imageContentType); return("/Image" + (imageIndex + 1) + imageFileExtension); }
private static bool PasteContentData(TextEditor This, IDataObject dataObject, IDataObject dataObjectToApply, string formatToApply) { if (formatToApply == DataFormats.Bitmap && dataObjectToApply is DataObject && This.AcceptsRichContent && This.Selection is TextSelection && SecurityHelper.CheckUnmanagedCodePermission()) { BitmapSource bitmapSource = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.Bitmap) as BitmapSource; if (bitmapSource != null) { MemoryStream data = WpfPayload.SaveImage(bitmapSource, "image/bmp"); dataObjectToApply = new DataObject(); formatToApply = DataFormats.XamlPackage; dataObjectToApply.SetData(DataFormats.XamlPackage, data); } } if (formatToApply == DataFormats.XamlPackage) { if (This.AcceptsRichContent && This.Selection is TextSelection && SecurityHelper.CheckUnmanagedCodePermission()) { object pasteData = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.XamlPackage); MemoryStream memoryStream = pasteData as MemoryStream; if (memoryStream != null) { object obj = WpfPayload.LoadElement(memoryStream); if ((obj is Section || obj is Span) && TextEditorCopyPaste.PasteTextElement(This, (TextElement)obj)) { return(true); } if (obj is FrameworkElement) { ((TextSelection)This.Selection).InsertEmbeddedUIElement((FrameworkElement)obj); return(true); } } } dataObjectToApply = dataObject; if (dataObjectToApply.GetDataPresent(DataFormats.Xaml)) { formatToApply = DataFormats.Xaml; } else if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf)) { formatToApply = DataFormats.Rtf; } else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.Xaml) { if (This.AcceptsRichContent && This.Selection is TextSelection) { object pasteData2 = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.Xaml); if (pasteData2 != null && TextEditorCopyPaste.PasteXaml(This, pasteData2.ToString())) { return(true); } } dataObjectToApply = dataObject; if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf)) { formatToApply = DataFormats.Rtf; } else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.Rtf) { if (This.AcceptsRichContent && SecurityHelper.CheckUnmanagedCodePermission()) { object pasteData3 = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.Rtf); if (pasteData3 != null) { MemoryStream memoryStream2 = TextEditorCopyPaste.ConvertRtfToXaml(pasteData3.ToString()); if (memoryStream2 != null) { TextElement textElement = WpfPayload.LoadElement(memoryStream2) as TextElement; if ((textElement is Section || textElement is Span) && TextEditorCopyPaste.PasteTextElement(This, textElement)) { return(true); } } } } dataObjectToApply = dataObject; if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.UnicodeText) { object pasteData4 = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.UnicodeText); if (pasteData4 != null) { return(TextEditorCopyPaste.PastePlainText(This, pasteData4.ToString())); } if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; dataObjectToApply = dataObject; } } if (formatToApply == DataFormats.Text) { object pasteData5 = TextEditorCopyPaste.GetPasteData(dataObjectToApply, DataFormats.Text); if (pasteData5 != null && TextEditorCopyPaste.PastePlainText(This, pasteData5.ToString())) { return(true); } } return(false); }
/// <summary> /// Saves the content of the range in the given stream as a WPF payload. /// </summary> /// <param name="range"> /// The range whose content is to be serialized. /// </param> /// <param name="stream"> /// When the stream is not null, it is a request to unconditionally /// creatte WPF package in this stream. /// If this parameter is null, then the package is created /// only when necessary - when there are images in the range. /// The new MemoryStream is created in this case and assigned to this /// parameter on exit. /// </param> /// <param name="useFlowDocumentAsRoot"> /// </param> /// <param name="preserveTextElements"> /// If set false, custom TextElements will be upcasted to known types. /// </param> /// <returns> /// A xaml part of serialized content. /// </returns> internal static string SaveRange(ITextRange range, ref Stream stream, bool useFlowDocumentAsRoot, bool preserveTextElements) { if (range == null) { throw new ArgumentNullException("range"); } // Create the wpf package in the stream WpfPayload wpfPayload = new WpfPayload(/*package:*/null); // Create a string representing serialized xaml StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, range, useFlowDocumentAsRoot, wpfPayload, preserveTextElements); string xamlText = stringWriter.ToString(); // Decide whether we need to create a package if (stream != null || wpfPayload._images != null) { // There are images in the content. Need to create a package if (stream == null) { stream = new MemoryStream(); } // Create a package in the stream using (wpfPayload.CreatePackage(stream)) { // Create the entry part for xaml content of the WPF package PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart(); // Write the part's content Stream xamlPartStream = xamlEntryPart.GetStream(); using (xamlPartStream) { StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream); using (xamlPartWriter) { xamlPartWriter.Write(xamlText); } } // Write relationships from xaml entry part to all images wpfPayload.CreateComponentParts(xamlEntryPart); } Invariant.Assert(wpfPayload._images == null); // must have beed cleared in CreateComponentParts } return xamlText; }
/// <summary> /// Paste the content data(Text, Unicode, Xaml and Rtf) to the current text selection /// </summary> /// <param name="This"></param> /// <param name="dataObject"> /// data object containing data to paste /// </param> /// <param name="dataObjectToApply"> /// </param> /// <param name="formatToApply"> /// </param> /// <returns> /// true if successful, false otherwise /// </returns> private static bool PasteContentData(TextEditor This, IDataObject dataObject, IDataObject dataObjectToApply, string formatToApply) { // CF_BITMAP - pasting a single image. if (formatToApply == DataFormats.Bitmap && dataObjectToApply is DataObject) { // We check unmanaged code instead of all clipboard because in paste // there is a high level assert for all clipboard in commandmanager.cs if (This.AcceptsRichContent && This.Selection is TextSelection) { System.Windows.Media.Imaging.BitmapSource bitmapSource = GetPasteData(dataObjectToApply, DataFormats.Bitmap) as System.Windows.Media.Imaging.BitmapSource; if (bitmapSource != null) { // Pack the image into a WPF container MemoryStream packagedImage = WpfPayload.SaveImage(bitmapSource, WpfPayload.ImageBmpContentType); // Place it onto a data object dataObjectToApply = new DataObject(); formatToApply = DataFormats.XamlPackage; dataObjectToApply.SetData(DataFormats.XamlPackage, packagedImage); } } } if (formatToApply == DataFormats.XamlPackage) { // We check unmanaged code instead of all clipboard because in paste // there is a high level assert for all clipboard in commandmanager.cs if (This.AcceptsRichContent && This.Selection is TextSelection) { object pastedData = GetPasteData(dataObjectToApply, DataFormats.XamlPackage); MemoryStream pastedMemoryStream = pastedData as MemoryStream; if (pastedMemoryStream != null) { object element = WpfPayload.LoadElement(pastedMemoryStream); if ((element is Section || element is Span) && PasteTextElement(This, (TextElement)element)) { return(true); } else if (element is FrameworkElement) { ((TextSelection)This.Selection).InsertEmbeddedUIElement((FrameworkElement)element); return(true); } } } // Fall to Xaml: dataObjectToApply = dataObject; // go back to source data object if (dataObjectToApply.GetDataPresent(DataFormats.Xaml)) { formatToApply = DataFormats.Xaml; } else if (dataObjectToApply.GetDataPresent(DataFormats.Rtf)) { formatToApply = DataFormats.Rtf; } else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.Xaml) { if (This.AcceptsRichContent && This.Selection is TextSelection) { object pastedData = GetPasteData(dataObjectToApply, DataFormats.Xaml); if (pastedData != null && PasteXaml(This, pastedData.ToString())) { return(true); } } // Fall to Rtf: dataObjectToApply = dataObject; // go back to source data object if (dataObjectToApply.GetDataPresent(DataFormats.Rtf)) { formatToApply = DataFormats.Rtf; } else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.Rtf) { // This demand is present to explicitly disable RTF independant of any // asserts in the confines of partial trust // We check unmanaged code instead of all clipboard because in paste // there is a high level assert for all clipboard in commandmanager.cs if (This.AcceptsRichContent) { object pastedData = GetPasteData(dataObjectToApply, DataFormats.Rtf); // Convert rtf to xaml text to paste rtf data into the target. if (pastedData != null) { MemoryStream memoryStream = ConvertRtfToXaml(pastedData.ToString()); if (memoryStream != null) { TextElement textElement = WpfPayload.LoadElement(memoryStream) as TextElement; if ((textElement is Section || textElement is Span) && PasteTextElement(This, textElement)) { return(true); } } } } // Fall to plain text: dataObjectToApply = dataObject; // go back to source data object if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText)) { formatToApply = DataFormats.UnicodeText; } else if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; } } if (formatToApply == DataFormats.UnicodeText) { object pastedData = GetPasteData(dataObjectToApply, DataFormats.UnicodeText); if (pastedData == null) { if (dataObjectToApply.GetDataPresent(DataFormats.Text)) { formatToApply = DataFormats.Text; // fall to plain text dataObjectToApply = dataObject; // go back to source data object } } else { // Dont attempt to recover if pasting Unicode text fails because our only fallback is mbcs text, // which will either evaluate identically (at best) or // produce a string with unexpected text (worse!) from WideCharToMultiByte conversion. return(PastePlainText(This, pastedData.ToString())); } } if (formatToApply == DataFormats.Text) { object pastedData = GetPasteData(dataObjectToApply, DataFormats.Text); if (pastedData != null && PastePlainText(This, pastedData.ToString())) { return(true); } } return(false); }
internal static MemoryStream SaveImage(BitmapSource bitmapSource, string imageContentType) { MemoryStream stream = new MemoryStream(); // Create the wpf package in the stream WpfPayload wpfPayload = new WpfPayload(/*package:*/null); // Create a package in the stream using (wpfPayload.CreatePackage(stream)) { // Define a reference for the image int imageIndex = 0; string imageReference = GetImageReference(GetImageName(imageIndex, imageContentType)); // Create the entry part for xaml content of the WPF package PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart(); // Write the part's content Stream xamlPartStream = xamlEntryPart.GetStream(); using (xamlPartStream) { StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream); using (xamlPartWriter) { string xamlText = "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" + "<InlineUIContainer><Image " + "Width=\"" + bitmapSource.Width + "\" " + "Height=\"" + bitmapSource.Height + "\" " + "><Image.Source><BitmapImage CacheOption=\"OnLoad\" UriSource=\"" + imageReference + "\"/></Image.Source></Image></InlineUIContainer></Span>"; xamlPartWriter.Write(xamlText); } } // Add image to a package wpfPayload.CreateImagePart(xamlEntryPart, bitmapSource, imageContentType, imageIndex); } return stream; }
/// <summary> /// Creates DataObject for Copy and Drag operations /// </summary> internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop) { DataObject dataObject; // Create the data object for drag and drop. // We could provide more extensibility here - // by allowing application to create its own DataObject. // Without it our extensibility looks inconsistent: // the interface IDataObject suggests that you can // create your own implementation of it, but you // really cannot, because there is no way of // using it in our TextEditor.Copy/Drag. dataObject = new DataObject(); // Get plain text and copy it into the data object. string textString = This.Selection.Text; if (textString != String.Empty) { // Copy plain text into data object. // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text)) { dataObject.SetData(DataFormats.Text, textString, false); } // Copy unicode text into data object. // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText)) { dataObject.SetData(DataFormats.UnicodeText, textString, false); } } // Get the rtf and xaml text and then copy it into the data object after confirm data format. // We do this only if our content is rich if (This.AcceptsRichContent) { Stream wpfContainerMemory = null; // null wpfContainerMemory on entry means that container is optional // and will be not created when there is no images in the range. // Create in-memory wpf package, and serialize the content of selection into it string xamlTextWithImages = WpfPayload.SaveRange(This.Selection, ref wpfContainerMemory, /*useFlowDocumentAsRoot:*/ false); if (xamlTextWithImages.Length > 0) { // ConfirmDataFormatSetting raises a public event - could throw recoverable exception. if (wpfContainerMemory != null && ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage)) { dataObject.SetData(DataFormats.XamlPackage, wpfContainerMemory); } // ConfirmDataFormatSetting raises a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf)) { // Convert xaml to rtf text to set rtf data into data object. string rtfText = ConvertXamlToRtf(xamlTextWithImages, wpfContainerMemory); if (rtfText != String.Empty) { dataObject.SetData(DataFormats.Rtf, rtfText, true); } } // Add a CF_BITMAP if we have only one image selected. Image image = This.Selection.GetUIElementSelected() as Image; if (image != null && image.Source is System.Windows.Media.Imaging.BitmapSource) { dataObject.SetImage((System.Windows.Media.Imaging.BitmapSource)image.Source); } } // Xaml format is availabe both in Full Trust and in Partial Trust // Need to re-serialize xaml to avoid image references within a container: StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, /*useFlowDocumentAsRoot:*/ false, /*wpfPayload:*/ null); string xamlText = stringWriter.ToString(); // Use WpfPayload.SaveRangeAsXaml method to produce correct image.Source properties. if (xamlText.Length > 0) { // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Xaml)) { // Place Xaml data onto the dataobject using safe setter dataObject.SetData(DataFormats.Xaml, xamlText, false); } } } // Notify application about our data object preparation completion DataObjectCopyingEventArgs dataObjectCopyingEventArgs = new DataObjectCopyingEventArgs(dataObject, /*isDragDrop:*/ isDragDrop); This.UiScope.RaiseEvent(dataObjectCopyingEventArgs); if (dataObjectCopyingEventArgs.CommandCancelled) { dataObject = null; } return(dataObject); }
internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop) { DataObject dataObject; // Create the data object for drag and drop. // (new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert try { dataObject = new DataObject(); } finally { UIPermission.RevertAssert(); } // Get plain text and copy it into the data object. string textString = This.Selection.Text; if (textString != String.Empty) { // Copy plain text into data object. // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text)) { CriticalSetDataWrapper(dataObject, DataFormats.Text, textString); } // Copy unicode text into data object. // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText)) { CriticalSetDataWrapper(dataObject, DataFormats.UnicodeText, textString); } } // Get the rtf and xaml text and then copy it into the data object after confirm data format. // We do this only if our content is rich if (This.AcceptsRichContent) { // This ensures that in the confines of partial trust RTF is not enabled. // We use unmanaged code permission over clipboard permission since // the latter is available in intranet zone and this is something that will // fail in intranet too. if (SecurityHelper.CheckUnmanagedCodePermission()) { // In FullTrust we allow all rich formats on the clipboard Stream wpfContainerMemory = null; // null wpfContainerMemory on entry means that container is optional // and will be not created when there is no images in the range. // Create in-memory wpf package, and serialize the content of selection into it string xamlTextWithImages = WpfPayload.SaveRange(This.Selection, ref wpfContainerMemory, /*useFlowDocumentAsRoot:*/ false); if (xamlTextWithImages.Length > 0) { // ConfirmDataFormatSetting raises a public event - could throw recoverable exception. if (wpfContainerMemory != null && ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage)) { dataObject.SetData(DataFormats.XamlPackage, wpfContainerMemory); } // ConfirmDataFormatSetting raises a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf)) { // Convert xaml to rtf text to set rtf data into data object. string rtfText = ConvertXamlToRtf(xamlTextWithImages, wpfContainerMemory); if (rtfText != String.Empty) { dataObject.SetData(DataFormats.Rtf, rtfText, true); } } } // Add a CF_BITMAP if we have only one image selected. Image image = This.Selection.GetUIElementSelected() as Image; if (image != null && image.Source is System.Windows.Media.Imaging.BitmapSource) { dataObject.SetImage((System.Windows.Media.Imaging.BitmapSource)image.Source); } } // Xaml format is availabe both in Full Trust and in Partial Trust // Need to re-serialize xaml to avoid image references within a container: StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, /*useFlowDocumentAsRoot:*/ false, /*wpfPayload:*/ null); string xamlText = stringWriter.ToString(); // if (xamlText.Length > 0) { // ConfirmDataFormatSetting rasies a public event - could throw recoverable exception. if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Xaml)) { // Place Xaml data onto the dataobject using safe setter CriticalSetDataWrapper(dataObject, DataFormats.Xaml, xamlText); // The dataobject itself must hold an information about permission set // of the source appdomain. Set it there: // Package permission set for the current appdomain PermissionSet psCurrentAppDomain = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin(); string permissionSetCurrentAppDomain = psCurrentAppDomain.ToString(); CriticalSetDataWrapper(dataObject, DataFormats.ApplicationTrust, permissionSetCurrentAppDomain); } } } // Notify application about our data object preparation completion DataObjectCopyingEventArgs dataObjectCopyingEventArgs = new DataObjectCopyingEventArgs(dataObject, /*isDragDrop:*/ isDragDrop); This.UiScope.RaiseEvent(dataObjectCopyingEventArgs); if (dataObjectCopyingEventArgs.CommandCancelled) { dataObject = null; } return(dataObject); }