/// <summary> /// Called from an event reporting that the drop happened. /// </summary> internal void TargetOnDrop(DragEventArgs e) { // if (!AllowDragDrop(e)) { return; } ITextSelection selection = _textEditor.Selection; Invariant.Assert(selection != null); if (e.Data == null || e.AllowedEffects == DragDropEffects.None) { e.Effects = DragDropEffects.None; return; } if ((int)(e.KeyStates & DragDropKeyStates.ControlKey) != 0) { e.Effects = DragDropEffects.Copy; } else if (e.Effects != DragDropEffects.Copy) { e.Effects = DragDropEffects.Move; } // Force a layout update on the content so the GetTextPositionFromPoint // call following can succeed. if (!_textEditor.TextView.Validate(e.GetPosition(_textEditor.TextView.RenderScope))) { e.Effects = DragDropEffects.None; return; } // Get the text position from the text target point. ITextPointer dropPosition = GetDropPosition(_textEditor.TextView.RenderScope as Visual, e.GetPosition(_textEditor.TextView.RenderScope)); if (dropPosition != null) { if (_dragSourceTextRange != null && _dragSourceTextRange.Start.TextContainer == selection.Start.TextContainer && !selection.IsEmpty && IsSelectionContainsDropPosition(selection, dropPosition)) { // When we drop inside of selected area, we // should not select dropped content, // otherwise it looks for end user as if // nothing happened. // Set caret to this position. selection.SetCaretToPosition(dropPosition, LogicalDirection.Backward, /*allowStopAtLineEnd:*/ false, /*allowStopNearSpace:*/ true); // Indicate the resulting effect of an action // Note that dropResult may stay equal to DragDropResult.Drop e.Effects = DragDropEffects.None; // Mark the event as handled e.Handled = true; } else { using (selection.DeclareChangeBlock()) { // For MaxLength filter work correctly in case // when we dragdrop within the same TextContainer, // we need to delete dragged content first - // before dropping when filtering will occur. // Note, that this will duplicate operation on // source side, but it will be void deletion action if ((e.Effects & DragDropEffects.Move) != 0 && // _dragSourceTextRange != null && _dragSourceTextRange.Start.TextContainer == selection.Start.TextContainer) { _dragSourceTextRange.Text = String.Empty; } // When we drop outside of selection, // we should ignore current selection and // move ip into dropping point. selection.SetCaretToPosition(dropPosition, LogicalDirection.Backward, /*allowStopAtLineEnd:*/ false, /*allowStopNearSpace:*/ true); // _DoPaste raises a public event -- could raise recoverable exception. e.Handled = TextEditorCopyPaste._DoPaste(_textEditor, e.Data, /*isDragDrop:*/ true); // } } if (e.Handled) { // Set the drop target as the foreground window. Win32SetForegroundWindow(); // Set the focus into the drop target. _textEditor.UiScope.Focus(); } else { // When a target did not handle a drop event, we must // prevent from deleting a content on source end - // otherwise we'll have data loss e.Effects = DragDropEffects.None; } } }
// Removes text from the block array. // consider merging blocks after the remove. Not yet clear if // this is desirable. internal static void RemoveText(TextTreeRootTextBlock rootTextBlock, int offset, int count) { int firstBlockLocalOffset; TextTreeTextBlock firstBlock; int lastBlockLocalOffset; TextTreeTextBlock lastBlock; SplayTreeNode firstRemoveBlock; SplayTreeNode lastRemoveBlock; int firstCount; if (count == 0) { // Early out on count == 0 so we don't get in trouble at the // very end of the array. return; } // Get the block matching the offset. firstBlock = FindBlock(rootTextBlock, offset, out firstBlockLocalOffset); if (firstBlock.Count == firstBlockLocalOffset) { // FindIndexForOffset always returns the lower block if we ask // for a cp between two blocks. // For a remove, we want to work with the following block, which // actually contains the content. firstBlock = (TextTreeTextBlock)firstBlock.GetNextNode(); Invariant.Assert(firstBlock != null); firstBlockLocalOffset = 0; } // And the block matching the offset + count. lastBlock = FindBlock(rootTextBlock, offset + count, out lastBlockLocalOffset); if (firstBlockLocalOffset > 0 || count < firstBlock.Count) { // Remove text from the first block. firstCount = Math.Min(count, firstBlock.Count - firstBlockLocalOffset); firstBlock.RemoveText(firstBlockLocalOffset, firstCount); // Don't remove the first block, since some text was left behind. firstRemoveBlock = firstBlock.GetNextNode(); } else { // All text in the first block covered -- just remove it entirely. firstCount = 0; firstRemoveBlock = firstBlock; } if (count > firstCount) { int lastCount; if (lastBlockLocalOffset < lastBlock.Count) { lastCount = lastBlockLocalOffset; // Remove some text. lastBlock.RemoveText(0, lastBlockLocalOffset); // There's text left over in the last block, so don't remove // the block. lastRemoveBlock = lastBlock.GetPreviousNode(); } else { lastCount = 0; // All text in the last block covered -- just remove it entirely. lastRemoveBlock = lastBlock; } // If firstRemoveBlock == lastBlock && lastRemoveBlock == firstBlock, // then there are no more blocks to remove -- we removed a portion // from the first and last block and they are direct neighbors. if (firstCount + lastCount < count) { // Remove any blocks in the middle of first, last. Remove((TextTreeTextBlock)firstRemoveBlock, (TextTreeTextBlock)lastRemoveBlock); } } }
private void SetFontSources() { if (_fontSources != null) { return; } lock (this) { List <Text.TextInterface.IFontSource> fontSources; if (_uri.IsFile) { ICollection <string> files; bool isOnlyCompositeFontFiles = false; if (_isFileSystemFolder) { if (_isWindowsFonts) { PermissionSet permissionSet = new PermissionSet(null); // Read and path discovery permission for the %windir%\font path. permissionSet.AddPermission(new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Util.WindowsFontsUriObject.LocalPath)); // Registry read permissions for the Fonts system registry entry. permissionSet.AddPermission(new RegistryPermission( RegistryPermissionAccess.Read, InstalledWindowsFontsRegistryKeyFullPath)); permissionSet.Assert(); // BlessedAssert try { if (_tryGetCompositeFontsOnly) { files = Directory.GetFiles(_uri.LocalPath, "*" + Util.CompositeFontExtension); isOnlyCompositeFontFiles = true; } else { // fontPaths accumulates font file paths obtained from the registry and the file system // This collection is a set, i.e. only keys matter, not values. Dictionary <string, object> fontPaths = new Dictionary <string, object>(512, StringComparer.OrdinalIgnoreCase); using (RegistryKey fontsKey = Registry.LocalMachine.OpenSubKey(InstalledWindowsFontsRegistryKey)) { // The registry key should be present on a valid Windows installation. Invariant.Assert(fontsKey != null); foreach (string fontValue in fontsKey.GetValueNames()) { string fileName = fontsKey.GetValue(fontValue) as string; if (fileName != null) { // See if the path doesn't contain any directory information. // Shell uses the same method to determine whether to prepend the path with %windir%\fonts. if (Path.GetFileName(fileName) == fileName) { fileName = Path.Combine(Util.WindowsFontsLocalPath, fileName); } fontPaths[fileName] = null; } } } foreach (string file in Directory.GetFiles(_uri.LocalPath)) { fontPaths[file] = null; } files = fontPaths.Keys; } } finally { if (_isWindowsFonts) { CodeAccessPermission.RevertAssert(); } } } else { if (_tryGetCompositeFontsOnly) { files = Directory.GetFiles(_uri.LocalPath, "*" + Util.CompositeFontExtension); isOnlyCompositeFontFiles = true; } else { files = Directory.GetFiles(_uri.LocalPath); } } } else { files = new string[1] { _uri.LocalPath }; } fontSources = new List <Text.TextInterface.IFontSource>(files.Count); if (isOnlyCompositeFontFiles) { foreach (string file in files) { fontSources.Add(new FontSource(new Uri(file, UriKind.Absolute), _isWindowsFonts, true)); } } else { bool isComposite; foreach (string file in files) { if (Util.IsSupportedFontExtension(Path.GetExtension(file), out isComposite)) { fontSources.Add(new FontSource(new Uri(file, UriKind.Absolute), _isWindowsFonts, isComposite)); } } } } else { List <string> resourceEntries = FontResourceCache.LookupFolder(_uri); if (resourceEntries == null) { fontSources = new List <Text.TextInterface.IFontSource>(0); } else { bool isComposite = false; // Enumerate application resources, content files and container structure. fontSources = new List <Text.TextInterface.IFontSource>(resourceEntries.Count); foreach (string resourceName in resourceEntries) { // If resourceName is an empty string, this means that the _uri is a full file name; // otherwise resourceName is a file name within a folder. if (String.IsNullOrEmpty(resourceName)) { isComposite = Util.IsCompositeFont(Path.GetExtension(_uri.AbsoluteUri)); fontSources.Add(new FontSource(_uri, _isWindowsFonts, isComposite)); } else { isComposite = Util.IsCompositeFont(Path.GetExtension(resourceName)); fontSources.Add(new FontSource(new Uri(_uri, resourceName), _isWindowsFonts, isComposite)); } } } } _fontSources = fontSources; } }
internal unsafe void GetCells( int cCells, IntPtr *rgnmCell, PTS.FSTABLEKCELLMERGE *rgkcellmerge) { Invariant.Assert(cCells == Row.FormatCellCount); // To protect against a buffer overflow, we must check that we aren't writing more // cells than were allocated. So we check against the cell count we have - // Row.FormatCellCount. But that's calculated elsewhere. What if it's stale? // There aren't any direct values available to compare against at the start of // this function, so we need two separate asserts. Bug 1149633. Invariant.Assert(cCells >= Row.Cells.Count); // Protect against buffer overflow int i = 0; // first, submit all non vertically merged cells for (int j = 0; j < Row.Cells.Count; ++j) { TableCell cell = Row.Cells[j]; if (cell.RowSpan == 1) { rgnmCell[i] = _cellParagraphs[j].Handle; rgkcellmerge[i] = PTS.FSTABLEKCELLMERGE.fskcellmergeNo; i++; } } // i now contains the exact number of non-rowspan cells on this row. Use it to verify // total number of cells, before we possibly write off end of allocated array. Invariant.Assert(cCells == i + _spannedCells.Length); // Protect against buffer overflow // second, submit all vertically merged cells if (_spannedCells.Length > 0) { bool lastRow = Row.Index == Row.RowGroup.Rows.Count - 1; for (int j = 0; j < _spannedCells.Length; ++j) { Debug.Assert(_spannedCells[j] != null); TableCell cell = _spannedCells[j].Cell; rgnmCell[i] = _spannedCells[j].Handle; if (cell.RowIndex == Row.Index) { rgkcellmerge[i] = lastRow ? PTS.FSTABLEKCELLMERGE.fskcellmergeNo : PTS.FSTABLEKCELLMERGE.fskcellmergeFirst; } else if (Row.Index - cell.RowIndex + 1 < cell.RowSpan) { rgkcellmerge[i] = lastRow ? PTS.FSTABLEKCELLMERGE.fskcellmergeLast : PTS.FSTABLEKCELLMERGE.fskcellmergeMiddle; } else { Debug.Assert(Row.Index - cell.RowIndex + 1 == cell.RowSpan); rgkcellmerge[i] = PTS.FSTABLEKCELLMERGE.fskcellmergeLast; } i++; } } }
//------------------------------------------------------------------- // CreateParaclient //------------------------------------------------------------------- internal override void CreateParaclient( out IntPtr paraClientHandle) // OUT: opaque to PTS paragraph client { Invariant.Assert(false); // No valid para client for a row paragraph. paraClientHandle = IntPtr.Zero; }
/// <summary> /// constructor that buils an issuance license from scratch /// </summary> private void Initialize( DateTime validFrom, DateTime validUntil, string referralInfoName, Uri referralInfoUri, ContentUser owner, string issuanceLicense, SafeRightsManagementHandle boundLicenseHandle, Guid contentId, ICollection <ContentGrant> grantCollection, IDictionary <int, LocalizedNameDescriptionPair> localizedNameDescriptionDictionary, IDictionary <string, string> applicationSpecificDataDictionary, int rightValidityIntervalDays, RevocationPoint revocationPoint) { // according to the unmanaged RM SDK spec only the following scenarios are supported: // 1. This can be called to create an issuance license from a template. // issuanceLicense An unsigned issuance license from // a file or by passing an issuance license // handle into DRMGetIssuanceLicenseTemplate // boundLicenseHandle NULL // // 2. This allows you to reuse rights information (the list follows this table). // issuance license A signed issuance license // boundLicenseHandle Handle to license bound by OWNER or VIEWRIGHTSDATA right // // 3. This creates an issuance license from scratch. It includes no users, rights, metadata, or policies. // issuance license NULL // boundLicenseHandle NULL Debug.Assert(!boundLicenseHandle.IsClosed); // it must be either present or not // closed handle is an indication of some internal error Invariant.Assert((boundLicenseHandle.IsInvalid) || (issuanceLicense != null)); SystemTime validFromSysTime = null; SystemTime validUntilSysTime = null; if ((validFrom != DateTime.MinValue) || (validUntil != DateTime.MaxValue)) { // we need to use non null values if at least one of the time boundaries isn't default // DRM SDK will not enforce date time unless both timeFrom and timeUnti are set validFromSysTime = new SystemTime((DateTime)validFrom); validUntilSysTime = new SystemTime((DateTime)validUntil); } string referralInfoUriStr = null; if (referralInfoUri != null) { referralInfoUriStr = referralInfoUri.ToString(); } // input parameter must be initialized to the invalid handle // attempt to pass in a null throws an exception from the Safe // Handle Marshalling code SafeRightsManagementPubHandle ownerHandle; if (owner != null) { ownerHandle = GetHandleFromUser(owner); } else { ownerHandle = SafeRightsManagementPubHandle.InvalidHandle; } int hr; _issuanceLicenseHandle = null; hr = SafeNativeMethods.DRMCreateIssuanceLicense( validFromSysTime, validUntilSysTime, referralInfoName, referralInfoUriStr, ownerHandle, issuanceLicense, boundLicenseHandle, out _issuanceLicenseHandle); Errors.ThrowOnErrorCode(hr); Invariant.Assert((_issuanceLicenseHandle != null) && (!_issuanceLicenseHandle.IsInvalid)); Debug.Assert(rightValidityIntervalDays >= 0); // our internal code makes the guarantee that is is not negative if (rightValidityIntervalDays > 0) { // If it is 0 we shouldn't override the value as it might be coming from a template SafeNativeMethods.DRMSetIntervalTime(_issuanceLicenseHandle, (uint)rightValidityIntervalDays); } if (grantCollection != null) { foreach (ContentGrant grant in grantCollection) { AddGrant(grant); } } // Set localized name description info if (localizedNameDescriptionDictionary != null) { foreach (KeyValuePair <int, LocalizedNameDescriptionPair> nameDescriptionEntry in localizedNameDescriptionDictionary) { AddNameDescription(nameDescriptionEntry.Key, nameDescriptionEntry.Value); } } // Set application specific data if (applicationSpecificDataDictionary != null) { foreach (KeyValuePair <string, string> applicationSpecificDataEntry in applicationSpecificDataDictionary) { AddApplicationSpecificData(applicationSpecificDataEntry.Key, applicationSpecificDataEntry.Value); } } // set metafata as required if (contentId != null) { hr = SafeNativeMethods.DRMSetMetaData( _issuanceLicenseHandle, contentId.ToString("B"), DefaultContentType, null, null, null, null); Errors.ThrowOnErrorCode(hr); } // set revocation point if required if (revocationPoint != null) { SetRevocationPoint(revocationPoint); } }
/// <summary> /// Generates a Reference tag that contains a Relationship transform /// </summary> /// <param name="manager">manager</param> /// <param name="relationshipPartName">name of the relationship part</param> /// <param name="xDoc">current xml document</param> /// <param name="hashAlgorithm">hash algorithm = digest method</param> /// <param name="relationshipSelectors">relationshipSelectors that represent the relationships to sign </param> /// <remarks>ContentType is known and part name can be derived from the relationship collection</remarks> private static XmlNode GenerateRelationshipSigningReference( PackageDigitalSignatureManager manager, XmlDocument xDoc, HashAlgorithm hashAlgorithm, Uri relationshipPartName, IEnumerable <PackageRelationshipSelector> relationshipSelectors) { string relPartContentType = PackagingUtilities.RelationshipPartContentType.ToString(); // <Reference> XmlElement reference = xDoc.CreateElement(XTable.Get(XTable.ID.ReferenceTagName), SignedXml.XmlDsigNamespaceUrl); // add Uri // persist the Uri of the associated Relationship part String relationshipPartString; if (PackUriHelper.ComparePartUri(relationshipPartName, PackageRelationship.ContainerRelationshipPartName) == 0) { relationshipPartString = PackageRelationship.ContainerRelationshipPartName.ToString(); } else { relationshipPartString = PackUriHelper.GetStringForPartUri(relationshipPartName); } XmlAttribute uriAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.UriAttrName)); uriAttr.Value = relationshipPartString + _contentTypeQueryStringPrefix + relPartContentType; reference.Attributes.Append(uriAttr); // add transforms tag (always necessary) // <Transforms> XmlElement transforms = xDoc.CreateElement(XTable.Get(XTable.ID.TransformsTagName), SignedXml.XmlDsigNamespaceUrl); // add Relationship transform String opcNamespace = XTable.Get(XTable.ID.OpcSignatureNamespace); String opcNamespacePrefix = XTable.Get(XTable.ID.OpcSignatureNamespacePrefix); XmlElement transform = xDoc.CreateElement(XTable.Get(XTable.ID.TransformTagName), SignedXml.XmlDsigNamespaceUrl); XmlAttribute algorithmAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.AlgorithmAttrName)); algorithmAttr.Value = XTable.Get(XTable.ID.RelationshipsTransformName); transform.Attributes.Append(algorithmAttr); // <RelationshipReference SourceId="abc" /> or // <RelationshipGroupReference SourceType="xyz" /> foreach (PackageRelationshipSelector relationshipSelector in relationshipSelectors) { switch (relationshipSelector.SelectorType) { case PackageRelationshipSelectorType.Id: { XmlNode relationshipNode = xDoc.CreateElement(opcNamespacePrefix, XTable.Get(XTable.ID.RelationshipReferenceTagName), opcNamespace); XmlAttribute idAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.SourceIdAttrName)); idAttr.Value = relationshipSelector.SelectionCriteria; relationshipNode.Attributes.Append(idAttr); transform.AppendChild(relationshipNode); } break; case PackageRelationshipSelectorType.Type: { XmlNode relationshipNode = xDoc.CreateElement(opcNamespacePrefix, XTable.Get(XTable.ID.RelationshipsGroupReferenceTagName), opcNamespace); XmlAttribute typeAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.SourceTypeAttrName)); typeAttr.Value = relationshipSelector.SelectionCriteria; relationshipNode.Attributes.Append(typeAttr); transform.AppendChild(relationshipNode); } break; default: Invariant.Assert(false, "This option should never be executed"); break; } } transforms.AppendChild(transform); // add non-Relationship transform (if any) String transformName = null; if (manager.TransformMapping.ContainsKey(relPartContentType)) { transformName = manager.TransformMapping[relPartContentType]; // let them override //Currently we only support two transforms and so we validate whether its //one of those if (transformName == null || transformName.Length == 0 || !XmlDigitalSignatureProcessor.IsValidXmlCanonicalizationTransform(transformName)) { throw new InvalidOperationException(SR.Get(SRID.UnsupportedTransformAlgorithm)); } // <Transform> transform = xDoc.CreateElement(XTable.Get(XTable.ID.TransformTagName), SignedXml.XmlDsigNamespaceUrl); algorithmAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.AlgorithmAttrName)); algorithmAttr.Value = transformName; transform.Attributes.Append(algorithmAttr); transforms.AppendChild(transform); } reference.AppendChild(transforms); // <DigestMethod> reference.AppendChild(GenerateDigestMethod(manager, xDoc)); // <DigestValue> - digest the virtual node list made from these Relationship tags using (Stream s = XmlDigitalSignatureProcessor.GenerateRelationshipNodeStream(GetRelationships(manager, relationshipSelectors))) // serialized node list { reference.AppendChild(GenerateDigestValueNode(xDoc, hashAlgorithm, s, transformName)); } return(reference); }
//------------------------------------------------------------------- // FormatFloaterContentBottomless //------------------------------------------------------------------- internal override void FormatFloaterContentBottomless( FloaterBaseParaClient paraClient, // IN: int fSuppressTopSpace, // IN: suppress empty space at the top of the page uint fswdir, // IN: direction of track int fAtMaxWidth, // IN: formating is at full width of column int durAvailable, // IN: width of available space int dvrAvailable, // IN: height of available space out PTS.FSFMTRBL fsfmtrbl, // OUT: result of formatting out IntPtr pfsFloatContent, // OUT: opaque for PTS pointer pointer to formatted content out int durFloaterWidth, // OUT: floater width out int dvrFloaterHeight, // OUT: floater height out PTS.FSBBOX fsbbox, // OUT: floater bbox out int cPolygons, // OUT: number of polygons out int cVertices) // OUT: total number of vertices in all polygons { uint fswdirPara = PTS.FlowDirectionToFswdir(((FlowDirection)Element.GetValue(FrameworkElement.FlowDirectionProperty))); Invariant.Assert(paraClient is FloaterParaClient); int subpageWidth, urSubpageMargin, durSubpageMargin, vrSubpageMargin; int dvrTopSpace, fPageBecomesUninterruptable; int cColumns; PTS.FSCOLUMNINFO[] columnInfoCollection; IntPtr pmcsclientOut; MbpInfo mbp; double specifiedWidth; // If horizontal alignment is Stretch and we are not formatting at max width, // we cannot proceed. if (IsFloaterRejected(PTS.ToBoolean(fAtMaxWidth), TextDpi.FromTextDpi(durAvailable))) { // Set foater width, height to be greater than available values to signal to PTS that floater does not fit in the space durFloaterWidth = durAvailable + 1; dvrFloaterHeight = dvrAvailable + 1; cPolygons = cVertices = 0; fsfmtrbl = PTS.FSFMTRBL.fmtrblInterrupted; fsbbox = new PTS.FSBBOX(); fsbbox.fDefined = PTS.False; pfsFloatContent = IntPtr.Zero; } else { // Initialize the subpage size. PTS subpage margin is always set to 0 for Floaters. // If width on floater is specified, use the specified value. // Margin, border and padding of the floater is extracted from available subpage width. mbp = MbpInfo.FromElement(Element, StructuralCache.TextFormatterHost.PixelsPerDip); specifiedWidth = CalculateWidth(TextDpi.FromTextDpi(durAvailable)); AdjustDurAvailable(specifiedWidth, ref durAvailable, out subpageWidth); durSubpageMargin = subpageWidth; urSubpageMargin = vrSubpageMargin = 0; // Initialize column info. Floater always has just 1 column. cColumns = 1; columnInfoCollection = new PTS.FSCOLUMNINFO[cColumns]; columnInfoCollection[0].durBefore = 0; columnInfoCollection[0].durWidth = subpageWidth; // Create subpage InvalidateMainTextSegment(); CreateSubpageBottomlessHelper(PtsContext, _mainTextSegment.Handle, PTS.True, fswdir, subpageWidth, urSubpageMargin, durSubpageMargin, vrSubpageMargin, cColumns, columnInfoCollection, out fsfmtrbl, out pfsFloatContent, out dvrFloaterHeight, out fsbbox, out pmcsclientOut, out dvrTopSpace, out fPageBecomesUninterruptable); if (fsfmtrbl != PTS.FSFMTRBL.fmtrblCollision) { // PTS subpage does not support autosizing, but Floater needs to autosize to its // content. To workaround this problem, second format of subpage is performed, if // necessary. It means that if the width of bounding box is smaller than subpage's // width, second formatting is performed. // However, if HorizontalAlignment is set to Stretch we should not reformat because // floater should be at full column width if (PTS.ToBoolean(fsbbox.fDefined)) { if (fsbbox.fsrc.du < subpageWidth && Double.IsNaN(specifiedWidth) && HorizontalAlignment != HorizontalAlignment.Stretch) { // There is a need to reformat PTS subpage, so destroy any resourcces allocated by PTS // during previous formatting. if (pfsFloatContent != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpage(PtsContext.Context, pfsFloatContent), PtsContext); } if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } // Create subpage with new width. subpageWidth = durSubpageMargin = fsbbox.fsrc.du + 1; // add 1/300px to avoid rounding errors columnInfoCollection[0].durWidth = subpageWidth; CreateSubpageBottomlessHelper(PtsContext, _mainTextSegment.Handle, PTS.True, fswdir, subpageWidth, urSubpageMargin, durSubpageMargin, vrSubpageMargin, cColumns, columnInfoCollection, out fsfmtrbl, out pfsFloatContent, out dvrFloaterHeight, out fsbbox, out pmcsclientOut, out dvrTopSpace, out fPageBecomesUninterruptable); } } else { subpageWidth = TextDpi.ToTextDpi(TextDpi.MinWidth); } // Destroy objects created by PTS, but not used here. if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } // Get the size of the floater. For height PTS already reports calculated value. // But width is the same as subpage width. durFloaterWidth = subpageWidth + mbp.MBPLeft + mbp.MBPRight; dvrFloaterHeight += mbp.MBPTop + mbp.MBPBottom; // Check if floater width fits in available width. It may exceed available width because borders // and padding are added. if (dvrFloaterHeight > dvrAvailable || (durFloaterWidth > durAvailable && !PTS.ToBoolean(fAtMaxWidth)) ) { // Get rid of any previous formatting if (pfsFloatContent != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpage(PtsContext.Context, pfsFloatContent), PtsContext); } Debug.Assert(pmcsclientOut == IntPtr.Zero); cPolygons = cVertices = 0; pfsFloatContent = IntPtr.Zero; } else { // Width and height are OK, format floater // Adjust bounding box to cover entire floater. fsbbox.fsrc.u = 0; fsbbox.fsrc.v = 0; fsbbox.fsrc.du = durFloaterWidth; fsbbox.fsrc.dv = dvrFloaterHeight; // Tight wrap is disabled for now. cPolygons = cVertices = 0; } } else { Debug.Assert(pmcsclientOut == IntPtr.Zero); durFloaterWidth = dvrFloaterHeight = 0; cPolygons = cVertices = 0; pfsFloatContent = IntPtr.Zero; } } // Update handle to PTS subpage. ((FloaterParaClient)paraClient).SubpageHandle = pfsFloatContent; }
/// <summary> /// factory method to create an AttachedAnnotationChangedEventArgs for the action Unloaded /// </summary> /// <param name="attachedAnnotation">the IAttachedAnnotation associated with the event</param> /// <returns>the constructed AttachedAnnotationChangedEventArgs</returns> internal static AttachedAnnotationChangedEventArgs Unloaded(IAttachedAnnotation attachedAnnotation) { Invariant.Assert(attachedAnnotation != null); return(new AttachedAnnotationChangedEventArgs(AttachedAnnotationAction.Unloaded, attachedAnnotation, null, AttachmentLevel.Unresolved)); }
//------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods /// <summary> /// Fetch the next run at text position. /// </summary> private TextRun HandleText(StaticTextPointer position) { // Calculate the end of the run by finding either: // a) the next intersection of highlight ranges, or // b) the natural end of this textrun StaticTextPointer endOfRunPosition = _owner.Host.TextContainer.Highlights.GetNextPropertyChangePosition(position, LogicalDirection.Forward); // Clamp the text run at an arbitrary limit, so we don't make // an unbounded allocation. if (position.GetOffsetToPosition(endOfRunPosition) > 4096) { endOfRunPosition = position.CreatePointer(4096); } var highlights = position.TextContainer.Highlights; // Factor in any speller error squiggles on the run. TextDecorationCollection highlightDecorations = highlights.GetHighlightValue(position, LogicalDirection.Forward, typeof(SpellerHighlightLayer)) as TextDecorationCollection; TextRunProperties properties = _lineProperties.DefaultTextRunProperties; if (highlightDecorations != null) { if (_spellerErrorProperties == null) { _spellerErrorProperties = new TextProperties((TextProperties)properties, highlightDecorations); } properties = _spellerErrorProperties; } var textEditor = position.TextContainer.TextSelection?.TextEditor; // DDVSO:405199 // Apply selection highlighting if needed if ((textEditor?.TextView?.RendersOwnSelection == true) && highlights.GetHighlightValue(position, LogicalDirection.Forward, typeof(TextSelection)) != DependencyProperty.UnsetValue) { // We need to create a new TextProperties instance here since we are going to change the Foreground and Background. var selectionProps = new TextProperties((TextProperties)properties, highlightDecorations); // The UiScope that owns this line should be the source for text/highlight properties var uiScope = textEditor?.UiScope; if (uiScope != null) { // All selection properties are taken from TextBoxBase bool isSelectionActive = (bool)uiScope.GetValue(TextBoxBase.IsSelectionActiveProperty); bool isInactiveSelectionHighlightEnabled = (bool)uiScope.GetValue(TextBoxBase.IsInactiveSelectionHighlightEnabledProperty); Brush selectionTextBrush = SystemColors.HighlightTextBrush; // If we have an inactive selection and we allow the highlight, set the appropriate brush for the text here. if (!isSelectionActive && isInactiveSelectionHighlightEnabled) { selectionTextBrush = SystemColors.InactiveSelectionHighlightTextBrush; } // Background should not be drawn since the selection is drawn below us selectionProps.SetBackgroundBrush(null); selectionProps.SetForegroundBrush(selectionTextBrush); } properties = selectionProps; } // Get character buffer for the text run. char[] textBuffer = new char[position.GetOffsetToPosition(endOfRunPosition)]; // Copy characters from text run into buffer. Since we are dealing with plain text content, // we expect to get all the characters from position to endOfRunPosition. int charactersCopied = position.GetTextInRun(LogicalDirection.Forward, textBuffer, 0, textBuffer.Length); Invariant.Assert(charactersCopied == textBuffer.Length); // Create text run, using characters copied as length return(new TextCharacters(textBuffer, 0, charactersCopied, properties)); }
//------------------------------------------------------------------- // FormatFloaterContentFinite //------------------------------------------------------------------- internal override void FormatFloaterContentFinite( FloaterBaseParaClient paraClient, // IN: IntPtr pbrkrecIn, // IN: break record---use if !IntPtr.Zero int fBRFromPreviousPage, // IN: break record was created on previous page IntPtr footnoteRejector, // IN: int fEmptyOk, // IN: is it OK not to add anything? int fSuppressTopSpace, // IN: suppress empty space at the top of the page uint fswdir, // IN: direction of Track int fAtMaxWidth, // IN: formating is at full width of column int durAvailable, // IN: width of available space int dvrAvailable, // IN: height of available space PTS.FSKSUPPRESSHARDBREAKBEFOREFIRSTPARA fsksuppresshardbreakbeforefirstparaIn, // IN: suppress breaks at track start? out PTS.FSFMTR fsfmtr, // OUT: result of formatting out IntPtr pfsFloatContent, // OUT: opaque for PTS pointer pointer to formatted content out IntPtr pbrkrecOut, // OUT: pointer to the floater content break record out int durFloaterWidth, // OUT: floater width out int dvrFloaterHeight, // OUT: floater height out PTS.FSBBOX fsbbox, // OUT: floater bbox out int cPolygons, // OUT: number of polygons out int cVertices) // OUT: total number of vertices in all polygons { uint fswdirPara = PTS.FlowDirectionToFswdir(((FlowDirection)Element.GetValue(FrameworkElement.FlowDirectionProperty))); int subpageWidth, subpageHeight; int dvrTopSpace; int cColumns; PTS.FSRECT fsrcSubpageMargin; PTS.FSCOLUMNINFO[] columnInfoCollection; IntPtr pmcsclientOut; double specifiedWidth; MbpInfo mbp; Invariant.Assert(paraClient is FloaterParaClient); // If horizontal alignment is Stretch and we are not formatting at max width, // we cannot proceed. if (IsFloaterRejected(PTS.ToBoolean(fAtMaxWidth), TextDpi.FromTextDpi(durAvailable))) { durFloaterWidth = dvrFloaterHeight = 0; cPolygons = cVertices = 0; fsfmtr = new PTS.FSFMTR(); fsfmtr.kstop = PTS.FSFMTRKSTOP.fmtrNoProgressOutOfSpace; fsfmtr.fContainsItemThatStoppedBeforeFootnote = PTS.False; fsfmtr.fForcedProgress = PTS.False; fsbbox = new PTS.FSBBOX(); fsbbox.fDefined = PTS.False; pbrkrecOut = IntPtr.Zero; pfsFloatContent = IntPtr.Zero; } else { // When formatting bottomless page, PTS may format paragraphs as finite. This happens // in case of multiple columns. In this case make sure that height is not too big. if (!StructuralCache.CurrentFormatContext.FinitePage) { if (Double.IsInfinity(StructuralCache.CurrentFormatContext.PageHeight)) { if (dvrAvailable > PTS.dvBottomUndefined / 2) { dvrAvailable = Math.Min(dvrAvailable, PTS.dvBottomUndefined / 2); fEmptyOk = PTS.False; } } else { dvrAvailable = Math.Min(dvrAvailable, TextDpi.ToTextDpi(StructuralCache.CurrentFormatContext.PageHeight)); } } // Initialize the subpage size. PTS subpage margin is always set to 0 for Floaters. // If width on floater is specified, use the specified value. // Margin, border and padding of the floater is extracted from available subpage height mbp = MbpInfo.FromElement(Element, StructuralCache.TextFormatterHost.PixelsPerDip); // We do not mirror margin as it's used to dist text left and right, and is unnecessary. // Clip Floater.Width to available width specifiedWidth = CalculateWidth(TextDpi.FromTextDpi(durAvailable)); AdjustDurAvailable(specifiedWidth, ref durAvailable, out subpageWidth); subpageHeight = Math.Max(1, dvrAvailable - (mbp.MBPTop + mbp.MBPBottom)); fsrcSubpageMargin = new PTS.FSRECT(); fsrcSubpageMargin.du = subpageWidth; fsrcSubpageMargin.dv = subpageHeight; // Initialize column info. Floater always has just 1 column. cColumns = 1; columnInfoCollection = new PTS.FSCOLUMNINFO[cColumns]; columnInfoCollection[0].durBefore = 0; columnInfoCollection[0].durWidth = subpageWidth; // Format subpage CreateSubpageFiniteHelper(PtsContext, pbrkrecIn, fBRFromPreviousPage, _mainTextSegment.Handle, footnoteRejector, fEmptyOk, PTS.True, fswdir, subpageWidth, subpageHeight, ref fsrcSubpageMargin, cColumns, columnInfoCollection, PTS.False, fsksuppresshardbreakbeforefirstparaIn, out fsfmtr, out pfsFloatContent, out pbrkrecOut, out dvrFloaterHeight, out fsbbox, out pmcsclientOut, out dvrTopSpace); // Initialize subpage metrics if (fsfmtr.kstop >= PTS.FSFMTRKSTOP.fmtrNoProgressOutOfSpace) // No progress or collision { Debug.Assert(pmcsclientOut == IntPtr.Zero); durFloaterWidth = dvrFloaterHeight = 0; cPolygons = cVertices = 0; //pbrkrecpara = IntPtr.Zero; } else { // PTS subpage does not support autosizing, but Floater needs to autosize to its // content. To workaround this problem, second format of subpage is performed, if // necessary. It means that if the width of bounding box is smaller than subpage's // width, second formatting is performed. // However, if HorizontalAlignment is set to Stretch we should not reformat because floater // should be at max width if (PTS.ToBoolean(fsbbox.fDefined)) { if (fsbbox.fsrc.du < subpageWidth && Double.IsNaN(specifiedWidth) && HorizontalAlignment != HorizontalAlignment.Stretch) { // There is a need to reformat PTS subpage, so destroy any resourcces allocated by PTS // during previous formatting. if (pfsFloatContent != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpage(PtsContext.Context, pfsFloatContent), PtsContext); pfsFloatContent = IntPtr.Zero; } if (pbrkrecOut != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpageBreakRecord(PtsContext.Context, pbrkrecOut), PtsContext); pbrkrecOut = IntPtr.Zero; } if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } // Create subpage with new width. subpageWidth = fsbbox.fsrc.du + 1; // add 1/300px to avoid rounding errors fsrcSubpageMargin.du = subpageWidth; fsrcSubpageMargin.dv = subpageHeight; columnInfoCollection[0].durWidth = subpageWidth; CreateSubpageFiniteHelper(PtsContext, pbrkrecIn, fBRFromPreviousPage, _mainTextSegment.Handle, footnoteRejector, fEmptyOk, PTS.True, fswdir, subpageWidth, subpageHeight, ref fsrcSubpageMargin, cColumns, columnInfoCollection, PTS.False, fsksuppresshardbreakbeforefirstparaIn, out fsfmtr, out pfsFloatContent, out pbrkrecOut, out dvrFloaterHeight, out fsbbox, out pmcsclientOut, out dvrTopSpace); } } else { subpageWidth = TextDpi.ToTextDpi(TextDpi.MinWidth); } // Destroy objects created by PTS, but not used here. if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } // Get the size of the floater. For height PTS already reports calculated value. // But width is the same as subpage width. Add margin values here since we do not use // distance to text anymore durFloaterWidth = subpageWidth + mbp.MBPLeft + mbp.MBPRight; // Add back all MBP values since we do not use dist to text dvrFloaterHeight += mbp.MBPTop + mbp.MBPBottom; // Check if floater width fits in available width. It may exceed available width because borders and // padding are added. fsbbox.fsrc.u = 0; fsbbox.fsrc.v = 0; fsbbox.fsrc.du = durFloaterWidth; fsbbox.fsrc.dv = dvrFloaterHeight; fsbbox.fDefined = PTS.True; // Tight wrap is disabled for now. cPolygons = cVertices = 0; if (durFloaterWidth > durAvailable || dvrFloaterHeight > dvrAvailable) { if (PTS.ToBoolean(fEmptyOk)) { // Get rid of any previous formatting if (pfsFloatContent != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpage(PtsContext.Context, pfsFloatContent), PtsContext); pfsFloatContent = IntPtr.Zero; } if (pbrkrecOut != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpageBreakRecord(PtsContext.Context, pbrkrecOut), PtsContext); pbrkrecOut = IntPtr.Zero; } cPolygons = cVertices = 0; fsfmtr.kstop = PTS.FSFMTRKSTOP.fmtrNoProgressOutOfSpace; } else { fsfmtr.fForcedProgress = PTS.True; } } } } // Update handle to PTS subpage. ((FloaterParaClient)paraClient).SubpageHandle = pfsFloatContent; }
/// <summary> /// Set the find text content from reading the text on the current text position. /// </summary> /// <returns> /// Returns the number of characters actually loaded into the findText array. /// </returns> private static int SetFindTextAndFindTextPositionMap( ITextPointer startPosition, ITextPointer endPosition, ITextPointer navigator, LogicalDirection direction, bool matchLast, char[] findText, int[] findTextPositionMap) { Invariant.Assert(startPosition.CompareTo(navigator) <= 0); Invariant.Assert(endPosition.CompareTo(navigator) >= 0); int runCount; int inlineCount = 0; int findTextLength = 0; // Set the first offset which is zero on TextBufferSize + 1 location of // the text position map in case of the backward searching if (matchLast && findTextLength == 0) { findTextPositionMap[findTextPositionMap.Length - 1] = 0; } while ((matchLast ? startPosition.CompareTo(navigator) : navigator.CompareTo(endPosition)) < 0) { switch (navigator.GetPointerContext(direction)) { case TextPointerContext.Text: runCount = navigator.GetTextRunLength(direction); runCount = Math.Min(runCount, findText.Length - findTextLength); if (!matchLast) { runCount = Math.Min(runCount, navigator.GetOffsetToPosition(endPosition)); navigator.GetTextInRun(direction, findText, findTextLength, runCount); for (int i = findTextLength; i < findTextLength + runCount; i++) { findTextPositionMap[i] = i + inlineCount; } } else { runCount = Math.Min(runCount, startPosition.GetOffsetToPosition(navigator)); navigator.GetTextInRun( direction, findText, findText.Length - findTextLength - runCount, runCount); // Set the text offest for the amount of runCount from the last index // of text position map int mapIndex = findText.Length - findTextLength - 1; for (int i = findTextLength; i < findTextLength + runCount; i++) { findTextPositionMap[mapIndex--] = i + inlineCount + 1; } } // Move the navigator position for the amount of runCount navigator.MoveByOffset(matchLast ? -runCount : runCount); findTextLength += runCount; break; case TextPointerContext.None: case TextPointerContext.ElementStart: case TextPointerContext.ElementEnd: if (IsAdjacentToFormatElement(navigator, direction)) { // Filter out formatting tags since find text content is plain. inlineCount++; } else { if (!matchLast) { // Stick in a line break to account for the block element. findText[findTextLength] = '\n'; findTextPositionMap[findTextLength] = findTextLength + inlineCount; findTextLength++; } else { // Increse the find text length first since adding text and map reversely findTextLength++; // Stick in a line break to account for the block element and // add text offset on the last index of text position map findText[findText.Length - findTextLength] = '\n'; findTextPositionMap[findText.Length - findTextLength] = findTextLength + inlineCount; } } navigator.MoveToNextContextPosition(direction); break; case TextPointerContext.EmbeddedElement: if (!matchLast) { findText[findTextLength] = '\xf8ff'; // Unicode private use. findTextPositionMap[findTextLength] = findTextLength + inlineCount; findTextLength++; } else { // Increse the find text length first since adding text and map reversely findTextLength++; // Set the private unicode value and text offset findText[findText.Length - findTextLength] = '\xf8ff'; findTextPositionMap[findText.Length - findTextLength] = findTextLength + inlineCount; } navigator.MoveToNextContextPosition(direction); break; } if (findTextLength >= findText.Length) { break; } } // Complete the adding the find text position to the position map for only the forward finding. // The backward finding(matchLast) is already added initially as the zero offset at the end of // text position map. if (!matchLast) { if (findTextLength > 0) { findTextPositionMap[findTextLength] = findTextPositionMap[findTextLength - 1] + 1; } else { findTextPositionMap[0] = 0; } } return(findTextLength); }
//--------------------------------------------------------------------- // // Private methods // //--------------------------------------------------------------------- #region Private Methods // Find the text with the specified find options. internal static TextRange InternalFind( ITextPointer startPosition, ITextPointer endPosition, string findPattern, CultureInfo cultureInfo, bool matchCase, bool matchWholeWord, bool matchLast, bool matchDiacritics, bool matchKashida, bool matchAlefHamza) { Invariant.Assert(startPosition.CompareTo(endPosition) <= 0); ITextPointer navigator; LogicalDirection direction; char[] findText; int[] findTextPositionMap; int findTextLength; if (matchLast) { navigator = endPosition; direction = LogicalDirection.Backward; } else { navigator = startPosition; direction = LogicalDirection.Forward; } // Set the text block size to read the find text content. // The block size must be bigger than the double of find pattern size // so that we can find matches intersected by neighboring blocks. // We need an additional x2 fudge factor to account for the matchDiacritics // option -- the findPattern may lack diacritics that will be ignored in // the text. int textBlockLength = Math.Max(TextBlockLength, findPattern.Length * 2 * 2); navigator = navigator.CreatePointer(); while ((matchLast ? startPosition.CompareTo(navigator) : navigator.CompareTo(endPosition)) < 0) { ITextPointer startFindTextPosition = navigator.CreatePointer(); findText = new char[textBlockLength]; findTextPositionMap = new int[textBlockLength + 1]; // Set the find text content from reading text of the current text position. // Set the find text position map as well to track of the text pointer of the text content. findTextLength = SetFindTextAndFindTextPositionMap( startPosition, endPosition, navigator, direction, matchLast, findText, findTextPositionMap); if (!matchDiacritics || findTextLength >= findPattern.Length) { int textStartIndex = matchLast ? findText.Length - findTextLength : 0; // Track whether or not the text array findText is bounded by // separator chars. We only look at these values when matchWholeWord // is true. bool hasPreceedingSeparatorChar = false; bool hasFollowingSeparatorChar = false; if (matchWholeWord) { GetContextualInformation(startFindTextPosition, matchLast ? -findTextPositionMap[findTextPositionMap.Length - findTextLength - 1] : findTextPositionMap[findTextLength], out hasPreceedingSeparatorChar, out hasFollowingSeparatorChar); } string textString = new string(findText, textStartIndex, findTextLength); int matchLength; // Now find text the matched index for the find pattern from the find text content int matchIndex = FindMatchIndexFromFindContent( textString, findPattern, cultureInfo, matchCase, matchWholeWord, matchLast, matchDiacritics, matchKashida, matchAlefHamza, hasPreceedingSeparatorChar, hasFollowingSeparatorChar, out matchLength); if (matchIndex != -1) { // Found the find pattern string from the find text content! // Return the text range for the matched find text position. ITextPointer startMatchPosition = startFindTextPosition.CreatePointer(); startMatchPosition.MoveByOffset(matchLast ? -findTextPositionMap[textStartIndex + matchIndex] : findTextPositionMap[matchIndex]); ITextPointer endMatchPosition = startFindTextPosition.CreatePointer(); endMatchPosition.MoveByOffset(matchLast ? -findTextPositionMap[textStartIndex + matchIndex + matchLength] : findTextPositionMap[matchIndex + matchLength]); return(new TextRange(startMatchPosition, endMatchPosition)); } // Move the text position for the size of finding pattern string not to miss // the matching text that is located on the boundary of the find text block. // Move back the position to N(findTextLength) - findPattern.Length if (findTextLength > findPattern.Length) { // Need to set new pointer to jump the correct place of backing offset of the findPattern length navigator = startFindTextPosition.CreatePointer(); navigator.MoveByOffset(matchLast ? -findTextPositionMap[findText.Length - findTextLength + findPattern.Length] : findTextPositionMap[findTextLength - findPattern.Length]); } } } return(null); }
internal _DragDropProcess(TextEditor textEditor) { Invariant.Assert(textEditor != null); _textEditor = textEditor; }
/// <summary> /// Creates a TextRange object spanning the portion of 'startNode' /// specified by 'locatorPart'. /// </summary> /// <param name="locatorPart">FixedTextRange locator part specifying start and end point of /// the TextRange</param> /// <param name="startNode">the FixedPage containing this locator part</param> /// <param name="attachmentLevel">set to AttachmentLevel.Full if the FixedPage for the locator /// part was found, AttachmentLevel.Unresolved otherwise</param> /// <returns>a TextRange spanning the text between start end end point in the FixedTextRange /// locator part /// , null if selection described by locator part could not be /// recreated</returns> /// <exception cref="ArgumentNullException">locatorPart or startNode are /// null</exception> /// <exception cref="ArgumentException">locatorPart is of the incorrect type</exception> /// <exception cref="ArgumentException">startNode is not a FixedPage</exception> /// <exception cref="ArgumentException">startNode does not belong to the DocumentViewer</exception> public override Object ResolveLocatorPart(ContentLocatorPart locatorPart, DependencyObject startNode, out AttachmentLevel attachmentLevel) { if (startNode == null) { throw new ArgumentNullException("startNode"); } DocumentPage docPage = null; FixedPage page = startNode as FixedPage; if (page != null) { docPage = GetDocumentPage(page); } else { // If we were passed a DPV because we are walking the visual tree, // extract the DocumentPage from it; its TextView will be used to // turn coordinates into text positions DocumentPageView dpv = startNode as DocumentPageView; if (dpv != null) { docPage = dpv.DocumentPage as FixedDocumentPage; if (docPage == null) { docPage = dpv.DocumentPage as FixedDocumentSequenceDocumentPage; } } } if (docPage == null) { throw new ArgumentException(SR.Get(SRID.StartNodeMustBeDocumentPageViewOrFixedPage), "startNode"); } if (locatorPart == null) { throw new ArgumentNullException("locatorPart"); } attachmentLevel = AttachmentLevel.Unresolved; ITextView tv = (ITextView)((IServiceProvider)docPage).GetService(typeof(ITextView)); Debug.Assert(tv != null); ReadOnlyCollection <TextSegment> ts = tv.TextSegments; //check first if a TextRange can be generated if (ts == null || ts.Count <= 0) { return(null); } TextAnchor resolvedAnchor = new TextAnchor(); if (docPage != null) { string stringCount = locatorPart.NameValuePairs["Count"]; if (stringCount == null) { throw new ArgumentException(SR.Get(SRID.InvalidLocatorPart, TextSelectionProcessor.CountAttribute)); } int count = Int32.Parse(stringCount, NumberFormatInfo.InvariantInfo); for (int i = 0; i < count; i++) { // First we extract the start and end Point from the locator part. Point start; Point end; GetLocatorPartSegmentValues(locatorPart, i, out start, out end); //calulate start ITextPointer ITextPointer segStart; if (double.IsNaN(start.X) || double.IsNaN(start.Y)) { //get start of the page segStart = FindStartVisibleTextPointer(docPage); } else { //convert Point to TextPointer segStart = tv.GetTextPositionFromPoint(start, true); } if (segStart == null) { //selStart can be null if there are no insertion points on this page continue; } //calulate end ITextPointer ITextPointer segEnd; if (double.IsNaN(end.X) || double.IsNaN(end.Y)) { segEnd = FindEndVisibleTextPointer(docPage); } else { //convert Point to TextPointer segEnd = tv.GetTextPositionFromPoint(end, true); } //end TP can not be null when start is not Invariant.Assert(segEnd != null, "end TP is null when start TP is not"); attachmentLevel = AttachmentLevel.Full; // Not always true right? resolvedAnchor.AddTextSegment(segStart, segEnd); } } if (resolvedAnchor.TextSegments.Count > 0) { return(resolvedAnchor); } else { return(null); } }
/// <summary> /// factory method to create an AttachedAnnotationChangedEventArgs for the action modified /// </summary> /// <param name="attachedAnnotation">the IAttachedAnnotation associated with the event</param> /// <param name="previousAttachedAnchor">the previous attached anchor for the attached annotation</param> /// <param name="previousAttachmentLevel">the previous attachment level for the attached annotation</param> /// <returns>the constructed AttachedAnnotationChangedEventArgs</returns> internal static AttachedAnnotationChangedEventArgs Modified(IAttachedAnnotation attachedAnnotation, object previousAttachedAnchor, AttachmentLevel previousAttachmentLevel) { Invariant.Assert(attachedAnnotation != null && previousAttachedAnchor != null); return(new AttachedAnnotationChangedEventArgs(AttachedAnnotationAction.AnchorModified, attachedAnnotation, previousAttachedAnchor, previousAttachmentLevel)); }
internal void UpdateUnsignedPublishLicense(UnsignedPublishLicense unsignedPublishLicense) { Invariant.Assert(unsignedPublishLicense != null); DateTime timeFrom; DateTime timeUntil; DistributionPointInfo distributionPointInfo = DistributionPointInfo.ReferralInfo; string distributionPointName; string distributionPointUri; ContentUser owner; bool officialFlag; GetIssuanceLicenseInfo(out timeFrom, out timeUntil, distributionPointInfo, out distributionPointName, out distributionPointUri, out owner, out officialFlag); unsignedPublishLicense.ReferralInfoName = distributionPointName; if (distributionPointUri != null) { unsignedPublishLicense.ReferralInfoUri = new Uri(distributionPointUri); } else { unsignedPublishLicense.ReferralInfoUri = null; } unsignedPublishLicense.Owner = owner; // Let's get the validity Iterval information (days) and save it in the license uint validityDays = 0; int hr = SafeNativeMethods.DRMGetIntervalTime(_issuanceLicenseHandle, ref validityDays); Errors.ThrowOnErrorCode(hr); checked { unsignedPublishLicense.RightValidityIntervalDays = (int)validityDays; } // let's get the rights information int userIndex = 0; while (true) // in this loop we are enumerating users mentioned in the license { SafeRightsManagementPubHandle userHandle = null; // extract the user based on the index ContentUser user = GetIssuanceLicenseUser(userIndex, out userHandle); if ((user == null) || (userHandle == null)) { break; } int rightIndex = 0; while (true) // now we can enumerate rights granted to the given user { SafeRightsManagementPubHandle rightHandle = null; DateTime validFrom; DateTime validUntil; // extract the right based on the index and the user Nullable <ContentRight> right = GetIssuanceLicenseUserRight (userHandle, rightIndex, out rightHandle, out validFrom, out validUntil); // 0 right handle is an indication of the end of the list if (rightHandle == null) { break; } // right == null is an indication of a right that we didn't recognize // we should still continue the enumeration if (right != null) { // Add the grant for the User Right pair here unsignedPublishLicense.Grants.Add( new ContentGrant(user, right.Value, validFrom, validUntil)); } rightIndex++; } userIndex++; } // let's get the localized name description pairs int nameIndex = 0; while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license { int localeId; // extract the user based on the index LocalizedNameDescriptionPair nameDescription = GetLocalizedNameDescriptionPair(nameIndex, out localeId); if (nameDescription == null) { break; } // Add the name description info to the license unsignedPublishLicense.LocalizedNameDescriptionDictionary.Add(localeId, nameDescription); nameIndex++; } // let's get the application specific data int appDataIndex = 0; while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license { // extract the user based on the index Nullable <KeyValuePair <string, string> > appSpecificDataEntry = GetApplicationSpecificData(appDataIndex); if (appSpecificDataEntry == null) { break; } // Add the name description info to the license unsignedPublishLicense.ApplicationSpecificDataDictionary.Add(appSpecificDataEntry.Value.Key, appSpecificDataEntry.Value.Value); appDataIndex++; } // Get the revocation Point information, it is optional and can be null unsignedPublishLicense.RevocationPoint = GetRevocationPoint(); }
/// <summary> /// build a localizable resource from a baml tree node /// </summary> internal BamlLocalizableResource BuildFromNode(BamlLocalizableResourceKey key, BamlTreeNode node) { if (node.Formatted) { // the content of the node has been formatted to be part of // parents' content, so no need to create a seperate entry for the // element return(null); } BamlLocalizableResource resource = null; LocalizabilityAttribute localizability = null; string formattingTag; // // variable controling what comments gets applied // BamlStartElementNode commentNode = null; // node containing comment string commentTargetName = null; // the target of the comment, e.g. $Content, FontSize, etc. // // step 1: Get the localizability attribute from the source files // switch (node.NodeType) { case BamlNodeType.StartElement: { // For element commentNode = (BamlStartElementNode)node; GetLocalizabilityForElementNode(commentNode, out localizability, out formattingTag); commentTargetName = BamlConst.ContentSuffix; break; } case BamlNodeType.LiteralContent: { // For literal content, get the attribute from parent element GetLocalizabilityForElementNode((BamlStartElementNode)node.Parent, out localizability, out formattingTag); commentNode = (BamlStartElementNode)node.Parent; commentTargetName = BamlConst.ContentSuffix; break; } case BamlNodeType.Property: { BamlStartComplexPropertyNode propertyNode = (BamlStartComplexPropertyNode)node; if (LocComments.IsLocCommentsProperty(propertyNode.OwnerTypeFullName, propertyNode.PropertyName) || LocComments.IsLocLocalizabilityProperty(propertyNode.OwnerTypeFullName, propertyNode.PropertyName) ) { // skip Localization.Comments and Localization.Attributes properties. They aren't localizable return(null); } // For property GetLocalizabilityForPropertyNode(propertyNode, out localizability); commentTargetName = propertyNode.PropertyName; commentNode = (BamlStartElementNode)node.Parent; break; } default: { Invariant.Assert(false); // no localizable resource for such node break; } } // // Step 2: Find out the inheritance value // // The node participates in localizability inheritance // let's fill things in localizability = CombineAndPropagateInheritanceValues( node as ILocalizabilityInheritable, localizability ); // // Step 3: We finalized the localizability values. We now apply. // string content = null; if (localizability.Category != LocalizationCategory.NeverLocalize && localizability.Category != LocalizationCategory.Ignore && TryGetContent(key, node, out content)) { // we only create one if it is localizable resource = new BamlLocalizableResource(); resource.Readable = (localizability.Readability == Readability.Readable); resource.Modifiable = (localizability.Modifiability == Modifiability.Modifiable); resource.Category = localizability.Category; // continue to fill in content. resource.Content = content; resource.Comments = _resolver.GetStringComment(commentNode, commentTargetName); } // return the resource return(resource); }
private Nullable <KeyValuePair <string, string> > GetApplicationSpecificData(int index) { Invariant.Assert(index >= 0); uint nameLength = 0; uint valueLength = 0; // check whether element with such index is present, // and if it is get the sizes of the name value strings int hr = SafeNativeMethods.DRMGetApplicationSpecificData( _issuanceLicenseHandle, (uint)index, // safe cast as the caller responsible for keeping this postive ref nameLength, null, ref valueLength, null); // there is a special code indicating end of the enumeration if (hr == (int)RightsManagementFailureCode.NoMoreData) { return(null); } // check for errors Errors.ThrowOnErrorCode(hr); StringBuilder tempName = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (nameLength > 0) { tempName = new StringBuilder(checked ((int)nameLength)); } StringBuilder tempValue = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (valueLength > 0) { tempValue = new StringBuilder(checked ((int)valueLength)); } // The second call supposed to return the actual string values fcheck whether element with such index is present, // and if it is get the sizes of the name value strings hr = SafeNativeMethods.DRMGetApplicationSpecificData( _issuanceLicenseHandle, (uint)index, // safe cast as the caller responsible for keeping this postive ref nameLength, tempName, ref valueLength, tempValue); // check for errors Errors.ThrowOnErrorCode(hr); // build strings from the StringBuilder instances string name = (tempName == null) ? null : tempName.ToString(); string value = (tempValue == null) ? null : tempValue.ToString(); KeyValuePair <string, string> result = new KeyValuePair <string, string>(name, value); return(result); }
// Internal methods ///////////////////////////////////////////////////////////////////// #region Internal methods internal override void SaveState(object contentObject) { Invariant.Assert(this.Source != null, "Can't journal by Uri without a Uri."); base.SaveState(contentObject); // Save controls state (JournalDataStreams). }
internal TextFormatterContext AcquireContext( object owner, IntPtr ploc ) { Invariant.Assert(owner != null); TextFormatterContext context = null; int c; int contextCount = _contextList.Count; for (c = 0; c < contextCount; c++) { context = (TextFormatterContext)_contextList[c]; if (ploc == IntPtr.Zero) { if (context.Owner == null) { break; } } else if (ploc == context.Ploc.Value) { // LS requires that we use the exact same context for line // destruction or hittesting (part of the reason is that LS // actually caches some run info in the context). So here // we use the actual PLSC as the context signature so we // locate the one we want. Debug.Assert(context.Owner == null); break; } } if (c == contextCount) { if (contextCount == 0 || !_multipleContextProhibited) { // no free one exists, create a new one context = new TextFormatterContext(); _contextList.Add(context); } else { // This instance of TextFormatter only allows a single context, reentering the // same TextFormatter in this case is not allowed. // // This requirement is currently enforced only during optimal break computation. // Client implementing nesting of optimal break content inside another must create // a separate TextFormatter instance for each content in different nesting level. throw new InvalidOperationException(SR.Get(SRID.TextFormatterReentranceProhibited)); } } Debug.Assert(context != null); context.Owner = owner; return(context); }
// Ctors ///////////////////////////////////////////////////////////////////// #region Ctors internal JournalEntryKeepAlive(JournalEntryGroupState jeGroupState, Uri uri, object keepAliveRoot) : base(jeGroupState, uri) { Invariant.Assert(keepAliveRoot != null); _keepAliveRoot = keepAliveRoot; }
//------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods //------------------------------------------------------------------- // GetParaProperties //------------------------------------------------------------------- internal override void GetParaProperties( ref PTS.FSPAP fspap) // OUT: paragraph properties { Invariant.Assert(false); // No para properties for row. }
internal override void SaveState(object contentObject) { Invariant.Assert(_keepAlivePageFunction == contentObject); // set by ctor // No call to base.SaveState() since it saves controls state, and this PF is KeepAlive. }
// Deserialize properties part. private void ParseCorePropertyPart(PackagePart part) { Stream stream = part.GetStream(FileMode.Open, FileAccess.Read); // Create a reader that uses _nameTable so as to use the set of tag literals // in effect as a set of atomic identifiers. XmlTextReader reader = new XmlTextReader(stream, _nameTable); //Prohibit DTD from the markup as per the OPC spec reader.ProhibitDtd = true; //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitailReadAndVerifyEncoding(reader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op if (reader.MoveToContent() != XmlNodeType.Element || (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace) || (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties)) { throw new XmlException(SR.Get(SRID.CorePropertiesElementExpected), null, reader.LineNumber, reader.LinePosition); } // The schema is closed and defines no attributes on the root element. if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0) { throw new XmlException(SR.Get(SRID.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, reader.LineNumber, reader.LinePosition); } // Iterate through property elements until EOF. Note the proper closing of all // open tags is checked by the reader itself. // This loop deals only with depth-1 start tags. Handling of element content // is delegated to dedicated functions. int attributesCount; while (reader.Read() && reader.MoveToContent() != XmlNodeType.None) { // Ignore end-tags. We check element errors on opening tags. if (reader.NodeType == XmlNodeType.EndElement) { continue; } // Any content markup that is not an element here is unexpected. if (reader.NodeType != XmlNodeType.Element) { throw new XmlException(SR.Get(SRID.PropertyStartTagExpected), null, reader.LineNumber, reader.LinePosition); } // Any element below the root should open at level 1 exclusively. if (reader.Depth != 1) { throw new XmlException(SR.Get(SRID.NoStructuredContentInsideProperties), null, reader.LineNumber, reader.LinePosition); } attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader); // Property elements can occur in any order (xsd:all). object localName = reader.LocalName; PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName); String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex); if (Array.IndexOf(_validProperties, xmlStringIndex) == -1) // An unexpected element is an error. { throw new XmlException( SR.Get(SRID.InvalidPropertyNameInCorePropertiesPart, reader.LocalName), null, reader.LineNumber, reader.LinePosition); } // Any element not in the valid core properties namespace is unexpected. // The following is an object comparison, not a string comparison. if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex))) { throw new XmlException(SR.Get(SRID.UnknownNamespaceInCorePropertiesPart), null, reader.LineNumber, reader.LinePosition); } if (String.CompareOrdinal(valueType, "String") == 0) { // The schema is closed and defines no attributes on this type of element. if (attributesCount != 0) { throw new XmlException(SR.Get(SRID.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, reader.LineNumber, reader.LinePosition); } RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader); } else if (String.CompareOrdinal(valueType, "DateTime") == 0) { int allowedAttributeCount = (object)reader.NamespaceURI == PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace) ? 1 : 0; // The schema is closed and defines no attributes on this type of element. if (attributesCount != allowedAttributeCount) { throw new XmlException(SR.Get(SRID.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, reader.LineNumber, reader.LinePosition); } if (allowedAttributeCount != 0) { ValidateXsiType(reader, PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace), _w3cdtf); } RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader); } else // An unexpected element is an error. { Invariant.Assert(false, "Unknown value type for properties"); } } }
/// internal GridViewCellAutomationPeer(TextBlock owner, ListViewAutomationPeer parent) : base(owner) { Invariant.Assert(parent != null); _listviewAP = parent; }
private void HandleStateChange() { MediaState mediaState = this._mediaState._value; bool flag = false; bool flag2 = false; if (this._isLoaded) { if (this._clock._value != null) { mediaState = MediaState.Manual; flag = true; } else if (this._loadedBehavior != MediaState.Manual) { mediaState = this._loadedBehavior; } else if (this._source._wasSet) { if (this._loadedBehavior != MediaState.Manual) { mediaState = MediaState.Play; } else { flag2 = true; } } } else if (this._unloadedBehavior != MediaState.Manual) { mediaState = this._unloadedBehavior; } else { Invariant.Assert(this._unloadedBehavior == MediaState.Manual); if (this._clock._value != null) { mediaState = MediaState.Manual; flag = true; } else { flag2 = true; } } bool flag3 = false; if (mediaState != MediaState.Close && mediaState != MediaState.Manual) { Invariant.Assert(!flag); if (this._mediaPlayer.Clock != null) { this._mediaPlayer.Clock = null; } if (this._currentState == MediaState.Close || this._source._isSet) { if (this._isScrubbingEnabled._wasSet) { this._mediaPlayer.ScrubbingEnabled = this._isScrubbingEnabled._value; this._isScrubbingEnabled._isSet = false; } if (this._clock._value == null) { this._mediaPlayer.Open(this.UriFromSourceUri(this._source._value)); } flag3 = true; } } else if (flag) { if (this._currentState == MediaState.Close || this._clock._isSet) { if (this._isScrubbingEnabled._wasSet) { this._mediaPlayer.ScrubbingEnabled = this._isScrubbingEnabled._value; this._isScrubbingEnabled._isSet = false; } this._mediaPlayer.Clock = this._clock._value; this._clock._isSet = false; flag3 = true; } } else if (mediaState == MediaState.Close && this._currentState != MediaState.Close) { this._mediaPlayer.Clock = null; this._mediaPlayer.Close(); this._currentState = MediaState.Close; } if (this._currentState != MediaState.Close | flag3) { if (this._position._isSet) { this._mediaPlayer.Position = this._position._value; this._position._isSet = false; } if (this._volume._isSet || (flag3 && this._volume._wasSet)) { this._mediaPlayer.Volume = this._volume._value; this._volume._isSet = false; } if (this._balance._isSet || (flag3 && this._balance._wasSet)) { this._mediaPlayer.Balance = this._balance._value; this._balance._isSet = false; } if (this._isMuted._isSet || (flag3 && this._isMuted._wasSet)) { this._mediaPlayer.IsMuted = this._isMuted._value; this._isMuted._isSet = false; } if (this._isScrubbingEnabled._isSet) { this._mediaPlayer.ScrubbingEnabled = this._isScrubbingEnabled._value; this._isScrubbingEnabled._isSet = false; } if (mediaState == MediaState.Play && this._source._isSet) { this._mediaPlayer.Play(); if (!this._speedRatio._wasSet) { this._mediaPlayer.SpeedRatio = 1.0; } this._source._isSet = false; this._mediaState._isSet = false; } else if (this._currentState != mediaState || (flag2 && this._mediaState._isSet)) { switch (mediaState) { case MediaState.Manual: goto IL_3BE; case MediaState.Play: this._mediaPlayer.Play(); goto IL_3BE; case MediaState.Pause: this._mediaPlayer.Pause(); goto IL_3BE; case MediaState.Stop: this._mediaPlayer.Stop(); goto IL_3BE; } Invariant.Assert(false, "Unexpected state request."); IL_3BE: if (flag2) { this._mediaState._isSet = false; } } this._currentState = mediaState; if (this._speedRatio._isSet || (flag3 && this._speedRatio._wasSet)) { this._mediaPlayer.SpeedRatio = this._speedRatio._value; this._speedRatio._isSet = false; } } }
/// <summary> /// Constructor /// </summary> /// <param name="owner">UIElement or ContentElement or UIElement3D this adaptor is associated with.</param> internal SynchronizedInputAdaptor(DependencyObject owner) { Invariant.Assert(owner != null); _owner = owner; }
/// <summary> /// Create a ColorContext from an unmanaged color context /// </summary> private ColorContext(SafeMILHandle colorContextHandle) { _colorContextHandle = colorContextHandle; // // For 3.* backwards compat, we aren't going to HRESULT.Check() anywhere because // that could introduce new exceptions. If anything fails, _colorContextHelper // will be invalid and we'll emulate the old failure behavior later in // OpenProfileStream() // IWICCC.WICColorContextType type; if (HRESULT.Failed(IWICCC.GetType(_colorContextHandle, out type))) { return; } switch (type) { case IWICCC.WICColorContextType.WICColorContextProfile: uint cbProfileActual; int hr = IWICCC.GetProfileBytes(_colorContextHandle, 0, null, out cbProfileActual); if (HRESULT.Succeeded(hr) && cbProfileActual != 0) { byte[] profileData = new byte[cbProfileActual]; if (HRESULT.Failed(IWICCC.GetProfileBytes( _colorContextHandle, cbProfileActual, profileData, out cbProfileActual)) ) { return; } FromRawBytes(profileData, (int)cbProfileActual, /* dontThrowException = */ true); } break; case IWICCC.WICColorContextType.WICColorContextExifColorSpace: uint colorSpace; if (HRESULT.Failed(IWICCC.GetExifColorSpace(_colorContextHandle, out colorSpace))) { return; } // // From MSDN: // "1" is sRGB. We will use our built-in sRGB profile. // "2" is Adobe RGB. WIC says we should never see this because they are nonstandard and instead a // real profile will be returned. // "3-65534" is unused. // // From the Exif spec: // B. Tag Relating to Color Space // ColorSpace // // The color space information tag (ColorSpace) is always recorded as the color space specifier. // Normally sRGB (=1) is used to define the color space based on the PC monitor conditions and environment. If a // color space other than sRGB is used, Uncalibrated (=FFFF.H) is set. Image data recorded as Uncalibrated can be // treated as sRGB when it is converted to Flashpix. On sRGB see Annex E. // Tag = 40961 (A001.H) // Type = SHORT // Count = 1 // 1 = sRGB // FFFF.H = Uncalibrated // // So for 65535 we will return sRGB since it is acceptible rather than having an invalid ColorContext. The Exif // CC should always be the second one so the real one is given priority. Alternatively, we could ignore the // uncalibrated CC but that would be a breaking change with 3.* (returning 1 instead of 2). // // If anything other than 1 or 65535 happens, _colorContextHelper will remain invalid and we will emulate // the old crash behavior in OpenProfileStream(). // if (colorSpace == 1 || colorSpace == 65535) { ResourceManager resourceManager = new ResourceManager( _colorProfileResources, Assembly.GetAssembly(typeof(ColorContext)) ); byte[] sRGBProfile = (byte[])resourceManager.GetObject(_sRGBProfileName); // The existing ColorContext has already been initialized as Exif so we can't initialize it again // and instead must create a new one. using (FactoryMaker factoryMaker = new FactoryMaker()) { _colorContextHandle.Dispose(); _colorContextHandle = null; if (HRESULT.Failed(UnsafeNativeMethodsMilCoreApi.WICCodec.CreateColorContext( factoryMaker.ImagingFactoryPtr, out _colorContextHandle)) ) { return; } if (HRESULT.Failed(IWICCC.InitializeFromMemory( _colorContextHandle, sRGBProfile, (uint)sRGBProfile.Length)) ) { return; } } // Finally, fill in _colorContextHelper FromRawBytes(sRGBProfile, sRGBProfile.Length, /* dontThrowException = */ true); } else if (Invariant.Strict) { Invariant.Assert(false, String.Format(CultureInfo.InvariantCulture, "IWICColorContext::GetExifColorSpace returned {0}.", colorSpace)); } break; default: if (Invariant.Strict) { Invariant.Assert(false, "IWICColorContext::GetType() returned WICColorContextUninitialized."); } break; } // SECURITY NOTE: This constructor does not set a Uri because the profile comes from raw file // data. Thus, we don't set _isProfileUriNotFromUser to true because we // don't want get_ProfileUri to demand permission to return null. Debug.Assert(_profileUri.Value == null); }
/// A handler for an event reporting that the drag over during drag-and-drop operation. internal void TargetOnDragOver(DragEventArgs e) { if (!AllowDragDrop(e)) { return; } // Ok, there's data to move or copy here. if ((e.AllowedEffects & DragDropEffects.Move) != 0) { e.Effects = DragDropEffects.Move; } bool ctrlKeyDown = ((int)(e.KeyStates & DragDropKeyStates.ControlKey) != 0); if (ctrlKeyDown) { e.Effects |= DragDropEffects.Copy; } // Show the caret on the drag over target position. if (_caretDragDrop != null) { // Update the layout to get the corrected text position. Otherwise, we can get the // incorrected text position. if (!_textEditor.TextView.Validate(e.GetPosition(_textEditor.TextView.RenderScope))) { return; } // Find the scroller from the render scope FrameworkElement scroller = _textEditor._Scroller; // Automatically scroll the dropable content(line or page up/down) if scroller is available if (scroller != null) { // Get the ScrollInfo to scroll a line or page up/down IScrollInfo scrollInfo = scroller as IScrollInfo; if (scrollInfo == null && scroller is ScrollViewer) { scrollInfo = ((ScrollViewer)scroller).ScrollInfo; } Invariant.Assert(scrollInfo != null); // Takes care of scrolling mechanism when vertical scrollbar is available, it creates a virtual // block within the viewport where if you position your mouse during drag leads to scrolling,here // it is of 16pixels and within first 8pixels it does scrolling by line and for next it scrolls by page. Point pointScroller = e.GetPosition((IInputElement)scroller); double pageHeight = (double)_textEditor.UiScope.GetValue(TextEditor.PageHeightProperty); double slowAreaHeight = ScrollViewer._scrollLineDelta; if (pointScroller.Y < slowAreaHeight) { // Drag position is on the scroll area that we need to scroll up if (pointScroller.Y > slowAreaHeight / 2) { // scroll a line up scrollInfo.LineUp(); } else { // scroll a page up scrollInfo.PageUp(); } } else if (pointScroller.Y > (pageHeight - slowAreaHeight)) { // Drag position is on the scroll area that we need to scroll down if (pointScroller.Y < (pageHeight - slowAreaHeight / 2)) { // scroll a line down scrollInfo.LineDown(); } else { // scroll a page down scrollInfo.PageDown(); } } } // Get the current text position from the dropable mouse point. _textEditor.TextView.RenderScope.UpdateLayout(); // REVIEW:benwest:6/27/2006: This should use TextView.Validate, and check the return value instead of using IsValid below. if (_textEditor.TextView.IsValid) { ITextPointer dragPosition = GetDropPosition(_textEditor.TextView.RenderScope as Visual, e.GetPosition(_textEditor.TextView.RenderScope)); if (dragPosition != null) { // Get the caret position to show the dropable point. Rect caretRectangle = this.TextView.GetRectangleFromTextPosition(dragPosition); // NOTE: We DO NOT use GetCurrentValue because springload formatting should NOT be involved for drop caret. object fontStylePropertyValue = dragPosition.GetValue(TextElement.FontStyleProperty); bool italic = (_textEditor.AcceptsRichContent && fontStylePropertyValue != DependencyProperty.UnsetValue && (FontStyle)fontStylePropertyValue == FontStyles.Italic); Brush caretBrush = TextSelection.GetCaretBrush(_textEditor); // Show the caret on the dropable position. _caretDragDrop.Update(/*visible:*/ true, caretRectangle, caretBrush, 0.5, italic, CaretScrollMethod.None, /*wordWrappingPosition*/ double.NaN); } } } }