/// <summary>Transforms the ink and also changes the StylusTip</summary> /// <param name="transformMatrix">Matrix to transform the stroke by</param> /// <param name="applyToStylusTip">Boolean if true the transform matrix will be applied to StylusTip</param> public virtual void Transform(Matrix transformMatrix, bool applyToStylusTip) { if (transformMatrix.IsIdentity) { return; } if (!transformMatrix.HasInverse) { throw new ArgumentException(SR.Get(SRID.MatrixNotInvertible), "transformMatrix"); } else if (MatrixHelper.ContainsNaN(transformMatrix)) { throw new ArgumentException(SR.Get(SRID.InvalidMatrixContainsNaN), "transformMatrix"); } else if (MatrixHelper.ContainsInfinity(transformMatrix)) { throw new ArgumentException(SR.Get(SRID.InvalidMatrixContainsInfinity), "transformMatrix"); } else { // we need to force a recaculation of the cached path geometry right after the // DrawingAttributes changed, beforet the events are raised. _cachedGeometry = null; // Set the cached bounds to empty, which will force a re-calculation of the _cachedBounds upon next GetBounds call. _cachedBounds = Rect.Empty; if (applyToStylusTip) { //we use this flag to prevent this method from causing two //invalidates, which causes a good deal of memory thrash when //the strokes are being rendered _delayRaiseInvalidated = true; } try { _stylusPoints.Transform(new System.Windows.Media.MatrixTransform(transformMatrix)); if (applyToStylusTip) { Matrix newMatrix = _drawingAttributes.StylusTipTransform; // Don't allow a Translation in the matrix transformMatrix.OffsetX = 0; transformMatrix.OffsetY = 0; newMatrix *= transformMatrix; //only persist the StylusTipTransform if there is an inverse. //there are cases where two invertible xf's result in a non-invertible one //we decided not to throw here because it is so unobvious if (newMatrix.HasInverse) { _drawingAttributes.StylusTipTransform = newMatrix; } } if (_delayRaiseInvalidated) { OnInvalidated(EventArgs.Empty); } //else OnInvalidated was already raised } finally { //We do this in a finally block to reset //our state in the event that an exception is thrown. _delayRaiseInvalidated = false; } } }
/// <summary> /// </summary> unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, System.Array pixels, int stride ) : base(true) // Use base class virtuals { if (pixels == null) { throw new System.ArgumentNullException("pixels"); } if (pixels.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank), "pixels"); } int elementSize = -1; if (pixels is byte[]) { elementSize = 1; } else if (pixels is short[] || pixels is ushort[]) { elementSize = 2; } else if (pixels is int[] || pixels is uint[] || pixels is float[]) { elementSize = 4; } else if (pixels is double[]) { elementSize = 8; } if (elementSize == -1) { throw new ArgumentException(SR.Get(SRID.Image_InvalidArrayForPixel)); } int destBufferSize = elementSize * pixels.Length; if (pixels is byte[]) { fixed(void *pixelArray = (byte[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is short[]) { fixed(void *pixelArray = (short[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is ushort[]) { fixed(void *pixelArray = (ushort[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is int[]) { fixed(void *pixelArray = (int[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is uint[]) { fixed(void *pixelArray = (uint[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is float[]) { fixed(void *pixelArray = (float[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is double[]) { fixed(void *pixelArray = (double[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.Cut: KeyGesture.AddGesturesFromResourceStrings( CutKey, SR.Get(SRID.CutKeyDisplayString), gestures); break; case CommandId.Copy: KeyGesture.AddGesturesFromResourceStrings( CopyKey, SR.Get(SRID.CopyKeyDisplayString), gestures); break; case CommandId.Paste: KeyGesture.AddGesturesFromResourceStrings( PasteKey, SR.Get(SRID.PasteKeyDisplayString), gestures); break; case CommandId.Undo: KeyGesture.AddGesturesFromResourceStrings( UndoKey, SR.Get(SRID.UndoKeyDisplayString), gestures); break; case CommandId.Redo: KeyGesture.AddGesturesFromResourceStrings( RedoKey, SR.Get(SRID.RedoKeyDisplayString), gestures); break; case CommandId.Delete: KeyGesture.AddGesturesFromResourceStrings( DeleteKey, SR.Get(SRID.DeleteKeyDisplayString), gestures); break; case CommandId.Find: KeyGesture.AddGesturesFromResourceStrings( FindKey, SR.Get(SRID.FindKeyDisplayString), gestures); break; case CommandId.Replace: KeyGesture.AddGesturesFromResourceStrings( ReplaceKey, SR.Get(SRID.ReplaceKeyDisplayString), gestures); break; case CommandId.SelectAll: KeyGesture.AddGesturesFromResourceStrings( SelectAllKey, SR.Get(SRID.SelectAllKeyDisplayString), gestures); break; case CommandId.Help: KeyGesture.AddGesturesFromResourceStrings( HelpKey, SR.Get(SRID.HelpKeyDisplayString), gestures); break; case CommandId.New: KeyGesture.AddGesturesFromResourceStrings( NewKey, SR.Get(SRID.NewKeyDisplayString), gestures); break; case CommandId.Open: KeyGesture.AddGesturesFromResourceStrings( OpenKey, SR.Get(SRID.OpenKeyDisplayString), gestures); break; case CommandId.Save: KeyGesture.AddGesturesFromResourceStrings( SaveKey, SR.Get(SRID.SaveKeyDisplayString), gestures); break; case CommandId.SaveAs: break; // there are no default bindings for CommandId.SaveAs case CommandId.Print: KeyGesture.AddGesturesFromResourceStrings( PrintKey, SR.Get(SRID.PrintKeyDisplayString), gestures); break; case CommandId.CancelPrint: break; // there are no default bindings for CommandId.CancelPrint case CommandId.PrintPreview: KeyGesture.AddGesturesFromResourceStrings( PrintPreviewKey, SR.Get(SRID.PrintPreviewKeyDisplayString), gestures); break; case CommandId.Close: break; // there are no default bindings for CommandId.Close case CommandId.ContextMenu: KeyGesture.AddGesturesFromResourceStrings( ContextMenuKey, SR.Get(SRID.ContextMenuKeyDisplayString), gestures); break; case CommandId.CorrectionList: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.CorrectionListKey), SR.Get(SRID.CorrectionListKeyDisplayString), gestures); break; case CommandId.Properties: KeyGesture.AddGesturesFromResourceStrings( PropertiesKey, SR.Get(SRID.PropertiesKeyDisplayString), gestures); break; case CommandId.Stop: KeyGesture.AddGesturesFromResourceStrings( StopKey, SR.Get(SRID.StopKeyDisplayString), gestures); break; case CommandId.NotACommand: break; // there are no default bindings for CommandId.NotACommand } return(gestures); }
public void Add(double value) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
public bool Remove(double item) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
internal void Render(Visual visual, Matrix worldTransform, Rect windowClip) { if (visual == null) { throw new ArgumentNullException("visual"); } // If the bitmapTarget we're writing to is frozen then we can't proceed. Note that // it's possible for the BitmapVisualManager to be constructed with a mutable BitmapImage // and for the app to later freeze it. Such an application is misbehaving if // they subsequently try to render to the BitmapImage. if (_bitmapTarget.IsFrozen) { throw new ArgumentException(SR.Get(SRID.Image_CantBeFrozen)); } int sizeX = _bitmapTarget.PixelWidth; int sizeY = _bitmapTarget.PixelHeight; double dpiX = _bitmapTarget.DpiX; double dpiY = _bitmapTarget.DpiY; Debug.Assert((sizeX > 0) && (sizeY > 0)); Debug.Assert((dpiX > 0) && (dpiY > 0)); // validate the data if ((sizeX <= 0) || (sizeY <= 0)) { return; // nothing to draw } if ((dpiX <= 0) || (dpiY <= 0)) { dpiX = 96; dpiY = 96; } SafeMILHandle renderTargetBitmap = _bitmapTarget.MILRenderTarget; Debug.Assert(renderTargetBitmap != null, "Render Target is null"); IntPtr pIRenderTargetBitmap = IntPtr.Zero; try { // // Allocate a fresh synchronous channel. // MediaContext mctx = MediaContext.CurrentMediaContext; DUCE.Channel channel = mctx.AllocateSyncChannel(); // // Acquire the target bitmap. // Guid iidRTB = MILGuidData.IID_IMILRenderTargetBitmap; HRESULT.Check(UnsafeNativeMethods.MILUnknown.QueryInterface( renderTargetBitmap, ref iidRTB, out pIRenderTargetBitmap)); // // Render the visual on the synchronous channel. // Renderer.Render( pIRenderTargetBitmap, channel, visual, sizeX, sizeY, dpiX, dpiY, worldTransform, windowClip); // // Release the synchronous channel. This way we can // re-use that channel later. // mctx.ReleaseSyncChannel(channel); } finally { UnsafeNativeMethods.MILUnknown.ReleaseInterface(ref pIRenderTargetBitmap); } _bitmapTarget.RenderTargetContentsChanged(); }
/// <summary> /// Fail because of an incorrect attribute value. /// </summary> private void FailAttributeValue() { Fail(SR.Get( SRID.CompositeFontAttributeValue1, _reader.LocalName)); }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.ScrollPageUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ScrollPageUpKey), SR.Get(SRID.ScrollPageUpKeyDisplayString), gestures); break; case CommandId.ScrollPageDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ScrollPageDownKey), SR.Get(SRID.ScrollPageDownKeyDisplayString), gestures); break; case CommandId.ScrollPageLeft: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ScrollPageLeftKey), SR.Get(SRID.ScrollPageLeftKeyDisplayString), gestures); break; case CommandId.ScrollPageRight: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ScrollPageRightKey), SR.Get(SRID.ScrollPageRightKeyDisplayString), gestures); break; case CommandId.ScrollByLine: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ScrollByLineKey), SR.Get(SRID.ScrollByLineKeyDisplayString), gestures); break; case CommandId.MoveLeft: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveLeftKey), SR.Get(SRID.MoveLeftKeyDisplayString), gestures); break; case CommandId.MoveRight: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveRightKey), SR.Get(SRID.MoveRightKeyDisplayString), gestures); break; case CommandId.MoveUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveUpKey), SR.Get(SRID.MoveUpKeyDisplayString), gestures); break; case CommandId.MoveDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveDownKey), SR.Get(SRID.MoveDownKeyDisplayString), gestures); break; case CommandId.ExtendSelectionUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ExtendSelectionUpKey), SR.Get(SRID.ExtendSelectionUpKeyDisplayString), gestures); break; case CommandId.ExtendSelectionDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ExtendSelectionDownKey), SR.Get(SRID.ExtendSelectionDownKeyDisplayString), gestures); break; case CommandId.ExtendSelectionLeft: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ExtendSelectionLeftKey), SR.Get(SRID.ExtendSelectionLeftKeyDisplayString), gestures); break; case CommandId.ExtendSelectionRight: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ExtendSelectionRightKey), SR.Get(SRID.ExtendSelectionRightKeyDisplayString), gestures); break; case CommandId.MoveToHome: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveToHomeKey), SR.Get(SRID.MoveToHomeKeyDisplayString), gestures); break; case CommandId.MoveToEnd: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveToEndKey), SR.Get(SRID.MoveToEndKeyDisplayString), gestures); break; case CommandId.MoveToPageUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveToPageUpKey), SR.Get(SRID.MoveToPageUpKeyDisplayString), gestures); break; case CommandId.MoveToPageDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveToPageDownKey), SR.Get(SRID.MoveToPageDownKeyDisplayString), gestures); break; case CommandId.SelectToHome: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SelectToHomeKey), SR.Get(SRID.SelectToHomeKeyDisplayString), gestures); break; case CommandId.SelectToEnd: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SelectToEndKey), SR.Get(SRID.SelectToEndKeyDisplayString), gestures); break; case CommandId.SelectToPageDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SelectToPageDownKey), SR.Get(SRID.SelectToPageDownKeyDisplayString), gestures); break; case CommandId.SelectToPageUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SelectToPageUpKey), SR.Get(SRID.SelectToPageUpKeyDisplayString), gestures); break; case CommandId.MoveFocusUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusUpKey), SR.Get(SRID.MoveFocusUpKeyDisplayString), gestures); break; case CommandId.MoveFocusDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusDownKey), SR.Get(SRID.MoveFocusDownKeyDisplayString), gestures); break; case CommandId.MoveFocusBack: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusBackKey), SR.Get(SRID.MoveFocusBackKeyDisplayString), gestures); break; case CommandId.MoveFocusForward: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusForwardKey), SR.Get(SRID.MoveFocusForwardKeyDisplayString), gestures); break; case CommandId.MoveFocusPageUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusPageUpKey), SR.Get(SRID.MoveFocusPageUpKeyDisplayString), gestures); break; case CommandId.MoveFocusPageDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MoveFocusPageDownKey), SR.Get(SRID.MoveFocusPageDownKeyDisplayString), gestures); break; } return(gestures); }
internal override RayHitTestParameters RayFromViewportPoint(Point p, Size viewSize, Rect3D boundingRect, out double distanceAdjustment) { // // Compute rayParameters // // Find the point on the projection plane in post-projective space where // the viewport maps to a 2x2 square from (-1,1)-(1,-1). Point np = M3DUtil.GetNormalizedPoint(p, viewSize); // This ray is consistent with a left-handed camera // MatrixCamera should be right-handed and should be updated to be so. // So (conceptually) the user clicked on the point (np.X, // np.Y, 0) in post-projection clipping space and the ray // extends in the direction (0, 0, 1) because our ray // after projection looks down the positive z axis. We // need to convert this ray and direction back to world // space. Matrix3D worldToCamera = GetViewMatrix() * ProjectionMatrix; Matrix3D cameraToWorld = worldToCamera; if (!cameraToWorld.HasInverse) { // When the following issue is addressed we should // investigate if the custom code paths in Orthographic and PerspectiveCamera // are worth keeping. They may not be buying us anything aside from handling // singular matrices. // Need to handle singular matrix cameras throw new NotSupportedException(SR.Get(SRID.HitTest_Singular)); } cameraToWorld.Invert(); Point4D origin4D = new Point4D(np.X, np.Y, 0, 1) * cameraToWorld; Point3D origin = new Point3D(origin4D.X / origin4D.W, origin4D.Y / origin4D.W, origin4D.Z / origin4D.W); // To transform the direction we use the Jacobian of // cameraToWorld at the point np.X,np.Y,0 that we just // transformed. // // The Jacobian of the homogeneous matrix M is a 3x3 matrix. // // Let x be the point we are computing the Jacobian at, and y be the // result of transforming x by M, i.e. // (wy w) = (x 1) M // Where (wy w) is the homogeneous point representing y with w as its homogeneous coordinate // And (x 1) is the homogeneous point representing x with 1 as its homogeneous coordinate // // Then the i,j component of the Jacobian (at x) is // (M_ij - M_i4 y_j) / w // // Since we're only concerned with the direction of the // transformed vector and not its magnitude, we can scale // this matrix by a POSITIVE factor. The computation // below computes the Jacobian scaled by 1/w and then // after we normalize the final vector we flip it around // if w is negative. // // To transform a vector we just right multiply it by this Jacobian matrix. // // Compute the Jacobian at np.X,np.Y,0 ignoring the constant factor of w. // Here's the pattern // // double Jij = cameraToWorld.Mij - cameraToWorld.Mi4 * origin.j // // but we only need J31,J32,&J33 because we're only // transforming the vector 0,0,1 double J31 = cameraToWorld.M31 - cameraToWorld.M34 * origin.X; double J32 = cameraToWorld.M32 - cameraToWorld.M34 * origin.Y; double J33 = cameraToWorld.M33 - cameraToWorld.M34 * origin.Z; // Then multiply that matrix by (0, 0, 1) which is // the direction of the ray in post-projection space. Vector3D direction = new Vector3D(J31, J32, J33); direction.Normalize(); // We multiplied by the Jacobian times W, so we need to // account for whether that flipped our result or not. if (origin4D.W < 0) { direction = -direction; } RayHitTestParameters rayParameters = new RayHitTestParameters(origin, direction); // // Compute HitTestProjectionMatrix // // The viewportMatrix will take normalized clip space into // viewport coordinates, with an additional 2D translation // to put the ray at the origin. Matrix3D viewportMatrix = new Matrix3D(); viewportMatrix.TranslatePrepend(new Vector3D(-p.X, viewSize.Height - p.Y, 0)); viewportMatrix.ScalePrepend(new Vector3D(viewSize.Width / 2, -viewSize.Height / 2, 1)); viewportMatrix.TranslatePrepend(new Vector3D(1, 1, 0)); // First, world-to-camera, then camera's projection, then normalized clip space to viewport. rayParameters.HitTestProjectionMatrix = worldToCamera * viewportMatrix; // // MatrixCamera does not allow for Near/Far plane adjustment, so // the distanceAdjustment remains 0. // distanceAdjustment = 0.0; return(rayParameters); }
/// <summary> /// Read a specified number of bits from the stream into a single byte /// </summary> /// <param name="countOfBits">The number of bits to unpack</param> /// <returns>A single byte that contains up to 8 packed bits</returns> /// <remarks>For example, if 2 bits are read from the stream, then a full byte /// will be created with the least significant bits set to the 2 unpacked bits /// from the stream</remarks> internal byte ReadByte(int countOfBits) { // if the end of the stream has been reached, then throw an exception if (EndOfStream) { throw new System.IO.EndOfStreamException(SR.Get(SRID.EndOfStreamReached)); } // we only support 1-8 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerByte || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } if (countOfBits > _bufferLengthInBits) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsGreatThanRemainingBits)); } _bufferLengthInBits -= (uint)countOfBits; // initialize return byte to 0 before reading from the cache byte returnByte = 0; // if the partial bit cache contains more bits than requested, then read the // cache only if (_cbitsInPartialByte >= countOfBits) { // retrieve the requested count of most significant bits from the cache // and store them in the least significant positions in the return byte int rightShiftPartialByteBy = Native.BitsPerByte - countOfBits; returnByte = (byte)(_partialByte >> rightShiftPartialByteBy); // reposition any unused portion of the cache in the most significant part of the bit cache unchecked // disable overflow checking since we are intentionally throwing away // the significant bits { _partialByte <<= countOfBits; } // update the bit count in the cache _cbitsInPartialByte -= countOfBits; } // otherwise, we need to retrieve more full bytes from the stream else { // retrieve the next full byte from the stream byte nextByte = _byteArray[_byteArrayIndex]; _byteArrayIndex++; //right shift partial byte to get it ready to or with the partial next byte int rightShiftPartialByteBy = Native.BitsPerByte - countOfBits; returnByte = (byte)(_partialByte >> rightShiftPartialByteBy); // now copy the remaining chunk of the newly retrieved full byte int rightShiftNextByteBy = Math.Abs((countOfBits - _cbitsInPartialByte) - Native.BitsPerByte); returnByte |= (byte)(nextByte >> rightShiftNextByteBy); // update the partial bit cache with the remainder of the newly retrieved full byte unchecked // disable overflow checking since we are intentionally throwing away // the significant bits { _partialByte = (byte)(nextByte << (countOfBits - _cbitsInPartialByte)); } _cbitsInPartialByte = Native.BitsPerByte - (countOfBits - _cbitsInPartialByte); } return(returnByte); }
internal static string GetUIText(byte commandId) { string uiText = String.Empty; switch ((CommandId)commandId) { case CommandId.ScrollPageUp: uiText = SR.Get(SRID.ScrollPageUpText); break; case CommandId.ScrollPageDown: uiText = SR.Get(SRID.ScrollPageDownText); break; case CommandId.ScrollPageLeft: uiText = SR.Get(SRID.ScrollPageLeftText); break; case CommandId.ScrollPageRight: uiText = SR.Get(SRID.ScrollPageRightText); break; case CommandId.ScrollByLine: uiText = SR.Get(SRID.ScrollByLineText); break; case CommandId.MoveLeft: uiText = SR.Get(SRID.MoveLeftText); break; case CommandId.MoveRight: uiText = SR.Get(SRID.MoveRightText); break; case CommandId.MoveUp: uiText = SR.Get(SRID.MoveUpText); break; case CommandId.MoveDown: uiText = SR.Get(SRID.MoveDownText); break; case CommandId.ExtendSelectionUp: uiText = SR.Get(SRID.ExtendSelectionUpText); break; case CommandId.ExtendSelectionDown: uiText = SR.Get(SRID.ExtendSelectionDownText); break; case CommandId.ExtendSelectionLeft: uiText = SR.Get(SRID.ExtendSelectionLeftText); break; case CommandId.ExtendSelectionRight: uiText = SR.Get(SRID.ExtendSelectionRightText); break; case CommandId.MoveToHome: uiText = SR.Get(SRID.MoveToHomeText); break; case CommandId.MoveToEnd: uiText = SR.Get(SRID.MoveToEndText); break; case CommandId.MoveToPageUp: uiText = SR.Get(SRID.MoveToPageUpText); break; case CommandId.MoveToPageDown: uiText = SR.Get(SRID.MoveToPageDownText); break; case CommandId.SelectToHome: uiText = SR.Get(SRID.SelectToHomeText); break; case CommandId.SelectToEnd: uiText = SR.Get(SRID.SelectToEndText); break; case CommandId.SelectToPageDown: uiText = SR.Get(SRID.SelectToPageDownText); break; case CommandId.SelectToPageUp: uiText = SR.Get(SRID.SelectToPageUpText); break; case CommandId.MoveFocusUp: uiText = SR.Get(SRID.MoveFocusUpText); break; case CommandId.MoveFocusDown: uiText = SR.Get(SRID.MoveFocusDownText); break; case CommandId.MoveFocusBack: uiText = SR.Get(SRID.MoveFocusBackText); break; case CommandId.MoveFocusForward: uiText = SR.Get(SRID.MoveFocusForwardText); break; case CommandId.MoveFocusPageUp: uiText = SR.Get(SRID.MoveFocusPageUpText); break; case CommandId.MoveFocusPageDown: uiText = SR.Get(SRID.MoveFocusPageDownText); break; } return(uiText); }
protected virtual void AddText(string childText) { throw new InvalidOperationException(SR.Get(SRID.Timing_NoTextChildren)); }
/// <summary> /// Internal constructor of TextContent /// </summary> private TextCharacters( CharacterBufferReference characterBufferReference, int length, TextRunProperties textRunProperties ) { if (length <= 0) { throw new ArgumentOutOfRangeException("length", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } if (textRunProperties == null) { throw new ArgumentNullException("textRunProperties"); } if (textRunProperties.Typeface == null) { throw new ArgumentNullException("textRunProperties.Typeface"); } if (textRunProperties.CultureInfo == null) { throw new ArgumentNullException("textRunProperties.CultureInfo"); } if (textRunProperties.FontRenderingEmSize <= 0) { throw new ArgumentOutOfRangeException("textRunProperties.FontRenderingEmSize", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } _characterBufferReference = characterBufferReference; _length = length; _textRunProperties = textRunProperties; }
public virtual void Save(System.IO.Stream stream) { VerifyAccess(); EnsureBuiltIn(); EnsureUnmanagedEncoder(); // No-op to get rid of build error if (_encodeState == EncodeState.None) { } if (_hasSaved) { throw new InvalidOperationException(SR.Get(SRID.Image_OnlyOneSave)); } if (_frames == null) { throw new System.NotSupportedException(SR.Get(SRID.Image_NoFrames, null)); } int count = _frames.Count; if (count <= 0) { throw new System.NotSupportedException(SR.Get(SRID.Image_NoFrames, null)); } IntPtr comStream = IntPtr.Zero; SafeMILHandle encoderHandle = _encoderHandle; try { comStream = StreamAsIStream.IStreamFrom(stream); // does this addref the stream? HRESULT.Check(UnsafeNativeMethods.WICBitmapEncoder.Initialize( encoderHandle, comStream, WICBitmapEncodeCacheOption.WICBitmapEncodeNoCache )); // Helpful for debugging stress and remote dumps _encodeState = EncodeState.EncoderInitialized; // Save global thumbnail if any. if (_thumbnail != null) { Debug.Assert(_supportsGlobalThumbnail); SafeMILHandle thumbnailBitmapSource = _thumbnail.WicSourceHandle; lock (_thumbnail.SyncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapEncoder.SetThumbnail( encoderHandle, thumbnailBitmapSource )); // Helpful for debugging stress and remote dumps _encodeState = EncodeState.EncoderThumbnailSet; } } // Save global palette if any. if (_palette != null && _palette.Colors.Count > 0) { SafeMILHandle paletteHandle = _palette.InternalPalette; HRESULT.Check(UnsafeNativeMethods.WICBitmapEncoder.SetPalette( encoderHandle, paletteHandle )); // Helpful for debugging stress and remote dumps _encodeState = EncodeState.EncoderPaletteSet; } // Save global metadata if any. if (_metadata != null && _metadata.GuidFormat == ContainerFormat) { Debug.Assert(_supportsGlobalMetadata); EnsureMetadata(false); if (_metadata.InternalMetadataHandle != _metadataHandle) { PROPVARIANT propVar = new PROPVARIANT(); try { propVar.Init(_metadata); lock (_metadata.SyncObject) { HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName( _metadataHandle, "/", ref propVar )); } } finally { propVar.Clear(); } } } for (int i = 0; i < count; i++) { SafeMILHandle frameEncodeHandle = new SafeMILHandle(); SafeMILHandle encoderOptions = new SafeMILHandle(); HRESULT.Check(UnsafeNativeMethods.WICBitmapEncoder.CreateNewFrame( encoderHandle, out frameEncodeHandle, out encoderOptions )); // Helpful for debugging stress and remote dumps _encodeState = EncodeState.EncoderCreatedNewFrame; _frameHandles.Add(frameEncodeHandle); SaveFrame(frameEncodeHandle, encoderOptions, _frames[i]); // If multiple frames are not supported, break out if (!_supportsMultipleFrames) { break; } } // Now let the encoder know we are done encoding the file. HRESULT.Check(UnsafeNativeMethods.WICBitmapEncoder.Commit(encoderHandle)); // Helpful for debugging stress and remote dumps _encodeState = EncodeState.EncoderCommitted; } finally { UnsafeNativeMethods.MILUnknown.ReleaseInterface(ref comStream); } _hasSaved = true; }
/// <summary> /// Helper that transforms and scales in one go /// </summary> internal StylusPointCollection Reformat(StylusPointDescription subsetToReformatTo, GeneralTransform transform) { if (!subsetToReformatTo.IsSubsetOf(this.Description)) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointDescriptionSubset), "subsetToReformatTo"); } StylusPointDescription subsetToReformatToWithCurrentMetrics = StylusPointDescription.GetCommonDescription(subsetToReformatTo, this.Description); //preserve metrics from this spd if (StylusPointDescription.AreCompatible(this.Description, subsetToReformatToWithCurrentMetrics) && (transform is Transform) && ((Transform)transform).IsIdentity) { //subsetToReformatTo might have different x, y, p metrics return(this.Clone(transform, subsetToReformatToWithCurrentMetrics)); } // // we really need to reformat this... // StylusPointCollection newCollection = new StylusPointCollection(subsetToReformatToWithCurrentMetrics, this.Count); int additionalDataCount = subsetToReformatToWithCurrentMetrics.GetExpectedAdditionalDataCount(); ReadOnlyCollection <StylusPointPropertyInfo> properties = subsetToReformatToWithCurrentMetrics.GetStylusPointProperties(); bool isIdentity = (transform is Transform) ? ((Transform)transform).IsIdentity : false; for (int i = 0; i < this.Count; i++) { StylusPoint stylusPoint = this[i]; double xCoord = stylusPoint.X; double yCoord = stylusPoint.Y; float pressure = stylusPoint.GetUntruncatedPressureFactor(); if (!isIdentity) { Point p = new Point(xCoord, yCoord); transform.TryTransform(p, out p); xCoord = p.X; yCoord = p.Y; } int[] newData = null; if (additionalDataCount > 0) { //don't init, we'll do that below newData = new int[additionalDataCount]; } StylusPoint newStylusPoint = new StylusPoint(xCoord, yCoord, pressure, subsetToReformatToWithCurrentMetrics, newData, false, false); //start at 3, skipping x, y, pressure for (int x = StylusPointDescription.RequiredCountOfProperties /*3*/; x < properties.Count; x++) { int value = stylusPoint.GetPropertyValue(properties[x]); newStylusPoint.SetPropertyValue(properties[x], value, false /*copy on write*/); } //bypass validation ((List <StylusPoint>)newCollection.Items).Add(newStylusPoint); } return(newCollection); }
internal static Exception ConvertHRToException(int hr) { Exception exceptionForHR = Marshal.GetExceptionForHR(hr, (IntPtr)(-1)); if ((hr & FACILITY_NT_BIT) == FACILITY_NT_BIT) { // Convert HRESULT to NTSTATUS code. switch (hr & ~FACILITY_NT_BIT) { case (int)NtStatusErrors.NT_STATUS_NO_MEMORY: return(new OutOfMemoryException()); default: return(exceptionForHR); } } else { switch (hr) { case (int)NtStatusErrors.NT_STATUS_NO_MEMORY: return(new System.OutOfMemoryException()); case (int)WinCodecErrors.WINCODEC_ERR_WRONGSTATE: return(new System.InvalidOperationException(SR.Get(SRID.Image_WrongState), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_VALUEOUTOFRANGE: case (int)WinCodecErrors.WINCODEC_ERR_VALUEOVERFLOW: return(new System.OverflowException(SR.Get(SRID.Image_Overflow), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNKNOWNIMAGEFORMAT: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_UnknownFormat), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNSUPPORTEDVERSION: return(new System.IO.FileLoadException(SR.Get(SRID.MilErr_UnsupportedVersion), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_NOTINITIALIZED: return(new System.InvalidOperationException(SR.Get(SRID.WIC_NotInitialized), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_PROPERTYNOTFOUND: return(new System.ArgumentException(SR.Get(SRID.Image_PropertyNotFound), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_PROPERTYNOTSUPPORTED: return(new System.NotSupportedException(SR.Get(SRID.Image_PropertyNotSupported), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_PROPERTYSIZE: return(new System.ArgumentException(SR.Get(SRID.Image_PropertySize), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_CODECPRESENT: return(new System.InvalidOperationException(SR.Get(SRID.Image_CodecPresent), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_CODECNOTHUMBNAIL: return(new System.NotSupportedException(SR.Get(SRID.Image_NoThumbnail), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_PALETTEUNAVAILABLE: return(new System.InvalidOperationException(SR.Get(SRID.Image_NoPalette), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_CODECTOOMANYSCANLINES: return(new System.ArgumentException(SR.Get(SRID.Image_TooManyScanlines), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_INTERNALERROR: return(new System.InvalidOperationException(SR.Get(SRID.Image_InternalError), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS: return(new System.ArgumentException(SR.Get(SRID.Image_BadDimensions), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: case (int)WinCodecErrors.WINCODEC_ERR_COMPONENTNOTFOUND: return(new System.NotSupportedException(SR.Get(SRID.Image_ComponentNotFound), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNEXPECTEDSIZE: case (int)WinCodecErrors.WINCODEC_ERR_BADIMAGE: // error decoding image file return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_DecoderError), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_BADHEADER: // error decoding header return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_HeaderError), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_FRAMEMISSING: return(new System.ArgumentException(SR.Get(SRID.Image_FrameMissing), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_BADMETADATAHEADER: return(new System.ArgumentException(SR.Get(SRID.Image_BadMetadataHeader), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_BADSTREAMDATA: return(new System.ArgumentException(SR.Get(SRID.Image_BadStreamData), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_STREAMWRITE: return(new System.InvalidOperationException(SR.Get(SRID.Image_StreamWrite), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT: return(new System.NotSupportedException(SR.Get(SRID.Image_UnsupportedPixelFormat), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNSUPPORTEDOPERATION: return(new System.NotSupportedException(SR.Get(SRID.Image_UnsupportedOperation), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_IMAGESIZEOUTOFRANGE: return(new System.ArgumentException(SR.Get(SRID.Image_SizeOutOfRange), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_STREAMREAD: return(new System.IO.IOException(SR.Get(SRID.Image_StreamRead), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_INVALIDQUERYREQUEST: return(new System.IO.IOException(SR.Get(SRID.Image_InvalidQueryRequest), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_UNEXPECTEDMETADATATYPE: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_UnexpectedMetadataType), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_RequestOnlyValidAtMetadataRoot), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_INVALIDQUERYCHARACTER: return(new System.IO.IOException(SR.Get(SRID.Image_InvalidQueryCharacter), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_DUPLICATEMETADATAPRESENT: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_DuplicateMetadataPresent), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_PropertyUnexpectedType), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_TOOMUCHMETADATA: return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_TooMuchMetadata), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_STREAMNOTAVAILABLE: return(new System.NotSupportedException(SR.Get(SRID.Image_StreamNotAvailable), exceptionForHR)); case (int)WinCodecErrors.WINCODEC_ERR_INSUFFICIENTBUFFER: return(new System.ArgumentException(SR.Get(SRID.Image_InsufficientBuffer), exceptionForHR)); case unchecked ((int)0x80070057): return(new System.ArgumentException(SR.Get(SRID.Media_InvalidArgument, null), exceptionForHR)); case unchecked ((int)0x800707db): return(new System.IO.FileFormatException(null, SR.Get(SRID.Image_InvalidColorContext), exceptionForHR)); case (int)MILErrors.WGXERR_DISPLAYSTATEINVALID: return(new System.InvalidOperationException(SR.Get(SRID.Image_DisplayStateInvalid), exceptionForHR)); case (int)MILErrors.WGXERR_NONINVERTIBLEMATRIX: return(new System.ArithmeticException(SR.Get(SRID.Image_SingularMatrix), exceptionForHR)); case (int)MILErrors.WGXERR_AV_INVALIDWMPVERSION: return(new System.Windows.Media.InvalidWmpVersionException(SR.Get(SRID.Media_InvalidWmpVersion, null), exceptionForHR)); case (int)MILErrors.WGXERR_AV_INSUFFICIENTVIDEORESOURCES: return(new System.NotSupportedException(SR.Get(SRID.Media_InsufficientVideoResources, null), exceptionForHR)); case (int)MILErrors.WGXERR_AV_VIDEOACCELERATIONNOTAVAILABLE: return(new System.NotSupportedException(SR.Get(SRID.Media_HardwareVideoAccelerationNotAvailable, null), exceptionForHR)); case (int)MILErrors.WGXERR_AV_MEDIAPLAYERCLOSED: return(new System.NotSupportedException(SR.Get(SRID.Media_PlayerIsClosed, null), exceptionForHR)); case (int)MediaPlayerErrors.NS_E_WMP_URLDOWNLOADFAILED: return(new System.IO.FileNotFoundException(SR.Get(SRID.Media_DownloadFailed, null), exceptionForHR)); case (int)MediaPlayerErrors.NS_E_WMP_LOGON_FAILURE: return(new System.Security.SecurityException(SR.Get(SRID.Media_LogonFailure), exceptionForHR)); case (int)MediaPlayerErrors.NS_E_WMP_CANNOT_FIND_FILE: return(new System.IO.FileNotFoundException(SR.Get(SRID.Media_FileNotFound), exceptionForHR)); case (int)MediaPlayerErrors.NS_E_WMP_UNSUPPORTED_FORMAT: case (int)MediaPlayerErrors.NS_E_WMP_DSHOW_UNSUPPORTED_FORMAT: return(new System.IO.FileFormatException(SR.Get(SRID.Media_FileFormatNotSupported), exceptionForHR)); case (int)MediaPlayerErrors.NS_E_WMP_INVALID_ASX: return(new System.IO.FileFormatException(SR.Get(SRID.Media_PlaylistFormatNotSupported), exceptionForHR)); case (int)MILErrors.WGXERR_BADNUMBER: return(new System.ArithmeticException(SR.Get(SRID.Geometry_BadNumber), exceptionForHR)); case (int)MILErrors.WGXERR_D3DI_INVALIDSURFACEUSAGE: return(new System.ArgumentException(SR.Get(SRID.D3DImage_InvalidUsage), exceptionForHR)); case (int)MILErrors.WGXERR_D3DI_INVALIDSURFACESIZE: return(new System.ArgumentException(SR.Get(SRID.D3DImage_SurfaceTooBig), exceptionForHR)); case (int)MILErrors.WGXERR_D3DI_INVALIDSURFACEPOOL: return(new System.ArgumentException(SR.Get(SRID.D3DImage_InvalidPool), exceptionForHR)); case (int)MILErrors.WGXERR_D3DI_INVALIDSURFACEDEVICE: return(new System.ArgumentException(SR.Get(SRID.D3DImage_InvalidDevice), exceptionForHR)); case (int)MILErrors.WGXERR_D3DI_INVALIDANTIALIASINGSETTINGS: return(new System.ArgumentException(SR.Get(SRID.D3DImage_AARequires9Ex), exceptionForHR)); default: return(exceptionForHR); } } }
private static double[] ParseMetrics(string s) { double[] metrics = new double[NumFields]; int i = 0, fieldIndex = 0; for (; ;) { // Let i be first non-whitespace character or end-of-string. while (i < s.Length && s[i] == ' ') { ++i; } // Let j be delimiter or end-of-string. int j = i; while (j < s.Length && s[j] != ',') { ++j; } // Let k be end-of-field without trailing whitespace. int k = j; while (k > i && s[k - 1] == ' ') { --k; } if (k > i) { // Non-empty field; convert it to double. ReadOnlySpan <char> field = s.AsSpan(i, k - i); if (!double.TryParse( field, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS, out metrics[fieldIndex] )) { throw new ArgumentException(SR.Get(SRID.CannotConvertStringToType, field.ToString(), "double")); } } else if (fieldIndex < NumRequiredFields) { // Empty field; make sure it's an optional one. throw new ArgumentException(SR.Get(SRID.CharacterMetrics_MissingRequiredField)); } ++fieldIndex; if (j < s.Length) { // There's a comma so check if we've exceeded the number of fields. if (fieldIndex == NumFields) { throw new ArgumentException(SR.Get(SRID.CharacterMetrics_TooManyFields)); } // Initialize character index for next iteration. i = j + 1; } else { // No more fields; check if we have all required fields. if (fieldIndex < NumRequiredFields) { throw new ArgumentException(SR.Get(SRID.CharacterMetrics_MissingRequiredField)); } break; } } return(metrics); }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.BrowseBack: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.BrowseBackKey), SR.Get(SRID.BrowseBackKeyDisplayString), gestures); break; case CommandId.BrowseForward: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.BrowseForwardKey), SR.Get(SRID.BrowseForwardKeyDisplayString), gestures); break; case CommandId.BrowseHome: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.BrowseHomeKey), SR.Get(SRID.BrowseHomeKeyDisplayString), gestures); break; case CommandId.BrowseStop: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.BrowseStopKey), SR.Get(SRID.BrowseStopKeyDisplayString), gestures); break; case CommandId.Refresh: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.RefreshKey), SR.Get(SRID.RefreshKeyDisplayString), gestures); break; case CommandId.Favorites: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.FavoritesKey), SR.Get(SRID.FavoritesKeyDisplayString), gestures); break; case CommandId.Search: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SearchKey), SR.Get(SRID.SearchKeyDisplayString), gestures); break; case CommandId.IncreaseZoom: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.IncreaseZoomKey), SR.Get(SRID.IncreaseZoomKeyDisplayString), gestures); break; case CommandId.DecreaseZoom: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.DecreaseZoomKey), SR.Get(SRID.DecreaseZoomKeyDisplayString), gestures); break; case CommandId.Zoom: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ZoomKey), SR.Get(SRID.ZoomKeyDisplayString), gestures); break; case CommandId.NextPage: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.NextPageKey), SR.Get(SRID.NextPageKeyDisplayString), gestures); break; case CommandId.PreviousPage: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.PreviousPageKey), SR.Get(SRID.PreviousPageKeyDisplayString), gestures); break; case CommandId.FirstPage: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.FirstPageKey), SR.Get(SRID.FirstPageKeyDisplayString), gestures); break; case CommandId.LastPage: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.LastPageKey), SR.Get(SRID.LastPageKeyDisplayString), gestures); break; case CommandId.GoToPage: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.GoToPageKey), SR.Get(SRID.GoToPageKeyDisplayString), gestures); break; case CommandId.NavigateJournal: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.NavigateJournalKey), SR.Get(SRID.NavigateJournalKeyDisplayString), gestures); break; } return(gestures); }
/// <summary> /// Fetch cached textrun /// </summary> internal TextRun FetchTextRun( FormatSettings settings, int cpFetch, int cpFirst, out int offsetToFirstCp, out int runLength ) { SpanRider textRunSpanRider = new SpanRider(_textRunVector, _latestPosition, cpFetch); _latestPosition = textRunSpanRider.SpanPosition; TextRun textRun = (TextRun)textRunSpanRider.CurrentElement; if (textRun == null) { // run not already cached, fetch new run and cache it textRun = settings.TextSource.GetTextRun(cpFetch); if (textRun.Length < 1) { throw new ArgumentOutOfRangeException("textRun.Length", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } Plsrun plsrun = TextRunInfo.GetRunType(textRun); if (plsrun == Plsrun.Text || plsrun == Plsrun.InlineObject) { TextRunProperties properties = textRun.Properties; if (properties == null) { throw new ArgumentException(SR.Get(SRID.TextRunPropertiesCannotBeNull)); } if (properties.FontRenderingEmSize <= 0) { throw new ArgumentException(SR.Get(SRID.PropertyOfClassMustBeGreaterThanZero, "FontRenderingEmSize", "TextRunProperties")); } double realMaxFontRenderingEmSize = Constants.RealInfiniteWidth / Constants.GreatestMutiplierOfEm; if (properties.FontRenderingEmSize > realMaxFontRenderingEmSize) { throw new ArgumentException(SR.Get(SRID.PropertyOfClassCannotBeGreaterThan, "FontRenderingEmSize", "TextRunProperties", realMaxFontRenderingEmSize)); } CultureInfo culture = CultureMapper.GetSpecificCulture(properties.CultureInfo); if (culture == null) { throw new ArgumentException(SR.Get(SRID.PropertyOfClassCannotBeNull, "CultureInfo", "TextRunProperties")); } if (properties.Typeface == null) { throw new ArgumentException(SR.Get(SRID.PropertyOfClassCannotBeNull, "Typeface", "TextRunProperties")); } } // // TextRun is specifial to SpanVector because TextRun also encodes position which needs to be // consistent with the positions encoded by SpanVector. In run cache, the begining of a span // should always correspond to the begining of a cached text run. If the end of the currently fetched // run overlaps with the begining of an already cached run, the begining of the cached run needs to be // adjusted as well as its span. Because we can't gurantee the correctness of the overlapped range // so we'll simply remove the overlapped runs here. // // Move the rider to the end of the current run textRunSpanRider.At(cpFetch + textRun.Length - 1); _latestPosition = textRunSpanRider.SpanPosition; if (textRunSpanRider.CurrentElement != _textRunVector.Default) { // The end overlaps with one or more cached runs, clear the range from the // begining of the current fetched run to the end of the last overlapped cached run. _latestPosition = _textRunVector.SetReference( cpFetch, textRunSpanRider.CurrentPosition + textRunSpanRider.Length - cpFetch, _textRunVector.Default, _latestPosition ); } _latestPosition = _textRunVector.SetReference(cpFetch, textRun.Length, textRun, _latestPosition); // Refresh the rider's SpanPosition following previous SpanVector.SetReference calls textRunSpanRider.At(_latestPosition, cpFetch); } offsetToFirstCp = textRunSpanRider.CurrentPosition - textRunSpanRider.CurrentSpanStart; runLength = textRunSpanRider.Length; Debug.Assert(textRun != null && runLength > 0, "Invalid run!"); bool isText = textRun is ITextSymbols; if (isText) { // Chop text run to optimal length so we dont spend forever analysing // them all at once. int looseCharLength = TextStore.TypicalCharactersPerLine - cpFetch + cpFirst; if (looseCharLength <= 0) { // this line already exceeds typical line length, incremental fetch goes // about a quarter of the typical length. looseCharLength = (int)Math.Round(TextStore.TypicalCharactersPerLine * 0.25); } if (runLength > looseCharLength) { if (TextRunInfo.GetRunType(textRun) == Plsrun.Text) { // // When chopping the run at the typical line length, // - don't chop in between of higher & lower surrogate // - don't chop combining mark away from its base character // - don't chop joiner from surrounding characters // // Starting from the initial chopping point, we look ahead to find a safe position. We stop at // a limit in case the run consists of many combining mark & joiner. That is rare and doesn't make // much sense in shaping already. // CharacterBufferReference charBufferRef = textRun.CharacterBufferReference; // We look ahead by one more line at most. It is not normal to have // so many combining mark or joiner characters in a row. It doesn't make sense to // look further if so. int lookAheadLimit = Math.Min(runLength, looseCharLength + TextStore.TypicalCharactersPerLine); int sizeOfChar = 0; int endOffset = 0; bool canBreakAfterPrecedingChar = false; for (endOffset = looseCharLength - 1; endOffset < lookAheadLimit; endOffset += sizeOfChar) { CharacterBufferRange charString = new CharacterBufferRange( charBufferRef.CharacterBuffer, charBufferRef.OffsetToFirstChar + offsetToFirstCp + endOffset, runLength - endOffset ); int ch = Classification.UnicodeScalar(charString, out sizeOfChar); // We can only safely break if the preceding char is not a joiner character (i.e. can-break-after), // and the current char is not combining or joiner (i.e. can-break-before). if (canBreakAfterPrecedingChar && !Classification.IsCombining(ch) && !Classification.IsJoiner(ch)) { break; } canBreakAfterPrecedingChar = !Classification.IsJoiner(ch); } looseCharLength = Math.Min(runLength, endOffset); } runLength = looseCharLength; } } Debug.Assert( // valid run found runLength > 0 // non-text run always fetched at run start && (isText || textRunSpanRider.CurrentSpanStart - textRunSpanRider.CurrentPosition == 0) // span rider of both text and format point to valid position && (textRunSpanRider.Length > 0 && textRunSpanRider.CurrentElement != null), "Text run fetching error!" ); return(textRun); }
/// <summary> /// Loads a single ExtendedProperty from the stream and add that to the list. Tag may be passed as in /// the case of Stroke ExtendedPropertyCollection where tag is stored in the stroke descriptor or 0 when tag /// is embeded in the stream /// </summary> /// <param name="stream">Memory buffer to load from</param> /// <param name="cbSize">Maximum length of buffer to read</param> /// <param name="guidList">Guid cache to read from</param> /// <param name="tag">Guid tag to lookup</param> /// <param name="guid">Guid of property</param> /// <param name="data">Data of property</param> /// <returns>Length of buffer read</returns> #endif internal static uint DecodeAsISF(Stream stream, uint cbSize, GuidList guidList, KnownTagCache.KnownTagIndex tag, ref Guid guid, out object data) { uint cb, cbRead = 0; uint cbTotal = cbSize; if (0 == cbSize) { throw new InvalidOperationException(SR.Get(SRID.EmptyDataToLoad)); } if (0 == tag) // no tag is passed, it must be embedded in the data { uint uiTag; cb = SerializationHelper.Decode(stream, out uiTag); tag = (KnownTagCache.KnownTagIndex)uiTag; if (cb > cbTotal) { throw new ArgumentException(SR.Get(SRID.InvalidSizeSpecified), "cbSize"); } cbTotal -= cb; cbRead += cb; System.Diagnostics.Debug.Assert(guid == Guid.Empty); guid = guidList.FindGuid(tag); } if (guid == Guid.Empty) { throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("Custom Attribute tag embedded in ISF stream does not match guid table"), "tag"); } // Try and find the size uint size = GuidList.GetDataSizeIfKnownGuid(guid); if (size > cbTotal) { throw new ArgumentException(SR.Get(SRID.InvalidSizeSpecified), "cbSize"); } // if the size is 0 if (0 == size) { // Size must be embedded in the stream. Find out the compressed data size cb = SerializationHelper.Decode(stream, out size); uint cbInsize = size + 1; cbRead += cb; cbTotal -= cb; if (cbInsize > cbTotal) { throw new ArgumentException(); } byte[] bytes = new byte[cbInsize]; uint bytesRead = (uint)stream.Read(bytes, 0, (int)cbInsize); if (cbInsize != bytesRead) { throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("Read different size from stream then expected"), "cbSize"); } cbRead += cbInsize; cbTotal -= cbInsize; //Find out the Decompressed buffer size using (MemoryStream decompressedStream = new MemoryStream(Compressor.DecompressPropertyData(bytes))) { // Add the property data = ExtendedPropertySerializer.DecodeAttribute(guid, decompressedStream); } } else { // For known size data, we just read the data directly from the stream byte[] bytes = new byte[size]; uint bytesRead = (uint)stream.Read(bytes, 0, (int)size); if (size != bytesRead) { throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("Read different size from stream then expected"), "cbSize"); } using (MemoryStream subStream = new MemoryStream(bytes)) { data = ExtendedPropertySerializer.DecodeAttribute(guid, subStream); } cbTotal -= size; cbRead += size; } return(cbRead); }
/// <summary> /// Fail because a required attribute is not present. /// </summary> /// <param name="name"></param> private void FailMissingAttribute(string name) { Fail(SR.Get(SRID.CompositeFontMissingAttribute, name)); }
/// <summary> /// Decodes a byte array (stored in the memory stream) into an object /// If the GUID is one of the internal versions, then the type is assumed /// to be byte array. /// If however, the guid is of unknown origin or not v1 internal, then the type /// information is assumed to be stored in the first 2 bytes of the stream. /// </summary> /// <param name="guid">Guid of property - to detect origin</param> /// <param name="memStream">Buffer of data</param> /// <param name="type">the type info stored in the stream</param> /// <returns>object stored in data buffer</returns> /// <remarks>The buffer stream passed in to the method will be closed after reading</remarks> internal static object DecodeAttribute(Guid guid, Stream memStream, out VarEnum type) { // First determine the object type using (BinaryReader br = new BinaryReader(memStream)) { // // if usesEmbeddedTypeInfo is true, we do not // read the variant type from the ISF stream. Instead, // we assume it to be a byte[] // bool usesEmbeddedTypeInfo = UsesEmbeddedTypeInformation(guid); // if the Id has embedded type information then retrieve it from the stream if (usesEmbeddedTypeInfo) { // We must read the data type from the stream type = (VarEnum)br.ReadUInt16(); } else { // The data is stored as byte array type = (VarEnum.VT_ARRAY | VarEnum.VT_UI1); } switch (type) { case (VarEnum.VT_ARRAY | VarEnum.VT_I1): return(br.ReadChars((int)(memStream.Length - 2))); case (VarEnum.VT_ARRAY | VarEnum.VT_UI1): { // // note: for (VarEnum.VT_ARRAY | VarEnum.VT_UI1), // we might be reading data that didn't have the // type embedded in the ISF stream, in which case // we must not assume we've already read two bytes // int previouslyReadBytes = 2; if (!usesEmbeddedTypeInfo) { previouslyReadBytes = 0; } return(br.ReadBytes((int)(memStream.Length - previouslyReadBytes))); } case (VarEnum.VT_ARRAY | VarEnum.VT_I2): { int count = (int)(memStream.Length - 2) / 2; // 2 is the size of one element short[] val = new short[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadInt16(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_UI2): { int count = (int)(memStream.Length - 2) / 2; // 2 is the size of one element ushort[] val = new ushort[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadUInt16(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_I4): { int count = (int)(memStream.Length - 2) / 4; // 2 is the size of one element int[] val = new int[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadInt32(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_UI4): { int count = (int)(memStream.Length - 2) / 4; // size of one element uint[] val = new uint[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadUInt32(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_I8): { int count = (int)(memStream.Length - 2) / Native.BitsPerByte; // size of one element long[] val = new long[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadInt64(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_UI8): { int count = (int)(memStream.Length - 2) / Native.BitsPerByte; // size of one element ulong[] val = new ulong[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadUInt64(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_R4): { int count = (int)(memStream.Length - 2) / 4; // size of one element float[] val = new float[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadSingle(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_R8): { int count = (int)(memStream.Length - 2) / Native.BitsPerByte; // size of one element double[] val = new double[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadDouble(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_DATE): { int count = (int)(memStream.Length - 2) / Native.BitsPerByte; // size of one element DateTime[] val = new DateTime[count]; for (int i = 0; i < count; i++) { val[i] = DateTime.FromOADate(br.ReadDouble()); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_BOOL): { int count = (int)(memStream.Length - 2); // size of one element bool[] val = new bool[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadBoolean(); } return(val); } case (VarEnum.VT_ARRAY | VarEnum.VT_DECIMAL): { int count = (int)((memStream.Length - 2) / Native.SizeOfDecimal); // size of one element decimal[] val = new decimal[count]; for (int i = 0; i < count; i++) { val[i] = br.ReadDecimal(); } return(val); } case (VarEnum.VT_I1): return(br.ReadChar()); case (VarEnum.VT_UI1): return(br.ReadByte()); case (VarEnum.VT_I2): return(br.ReadInt16()); case (VarEnum.VT_UI2): return(br.ReadUInt16()); case (VarEnum.VT_I4): return(br.ReadInt32()); case (VarEnum.VT_UI4): return(br.ReadUInt32()); case (VarEnum.VT_I8): return(br.ReadInt64()); case (VarEnum.VT_UI8): return(br.ReadUInt64()); case (VarEnum.VT_R4): return(br.ReadSingle()); case (VarEnum.VT_R8): return(br.ReadDouble()); case (VarEnum.VT_DATE): return(DateTime.FromOADate(br.ReadDouble())); case (VarEnum.VT_BOOL): return(br.ReadBoolean()); case (VarEnum.VT_DECIMAL): return(br.ReadDecimal()); case (VarEnum.VT_BSTR): { byte[] bytestring = br.ReadBytes((int)memStream.Length); return(System.Text.Encoding.Unicode.GetString(bytestring)); } default: { throw new InvalidOperationException(SR.Get(SRID.InvalidEpInIsf)); } } } }
public void Insert(int index, double item) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
/// <summary> /// This function returns the Data bytes that accurately describes the object /// </summary> /// <returns></returns> internal static void EncodeAttribute(Guid guid, object value, VarEnum type, Stream stream) { // samgeo - Presharp issue // Presharp gives a warning when local IDisposable variables are not closed // in this case, we can't call Dispose since it will also close the underlying stream // which still needs to be written to #pragma warning disable 1634, 1691 #pragma warning disable 6518 BinaryWriter bw = new BinaryWriter(stream); // if this guid used the legacy internal attribute persistence APIs, // then it doesn't include embedded type information (it's always a byte array) if (UsesEmbeddedTypeInformation(guid)) { // ushort datatype = (ushort)type; bw.Write(datatype); } // We know the type of the object. We must serialize it accordingly. switch (type) { case (VarEnum.VT_ARRAY | VarEnum.VT_I1): //8208 { char[] data = (char[])value; bw.Write(data); break; } case (VarEnum.VT_ARRAY | VarEnum.VT_UI1): //8209 { byte[] data = (byte[])value; bw.Write(data); break; } case (VarEnum.VT_ARRAY | VarEnum.VT_I2): //8194 { short [] data = (short[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_UI2): //8210 { ushort [] data = (ushort[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_I4): //8195 { int [] data = (int[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_UI4): //8211 { uint [] data = (uint[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_I8): //8212 { long [] data = (long[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_UI8): //8213 { ulong [] data = (ulong[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_R4): //8196 { float [] data = (float[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_R8): //8197 { double [] data = (double[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_DATE): //8199 { DateTime [] data = (DateTime[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i].ToOADate()); } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_BOOL): //8203 { bool [] data = (bool[])value; for (int i = 0; i < data.Length; i++) { if (data[i]) { //true is two consecutive all bits on bytes bw.Write((byte)0xFF); bw.Write((byte)0xFF); } else { //false is two consecutive all bits off bw.Write((byte)0); bw.Write((byte)0); } } break; } case (VarEnum.VT_ARRAY | VarEnum.VT_DECIMAL): //8206 { decimal [] data = (decimal[])value; for (int i = 0; i < data.Length; i++) { bw.Write(data[i]); } break; } case (VarEnum.VT_I1): //16 { char data = (char)value; bw.Write(data); break; } case (VarEnum.VT_UI1): //17 { byte data = (byte)value; bw.Write(data); break; } case (VarEnum.VT_I2): //2 { short data = (short)value; bw.Write(data); break; } case (VarEnum.VT_UI2): //18 { ushort data = (ushort)value; bw.Write(data); break; } case (VarEnum.VT_I4): //3 { int data = (int)value; bw.Write(data); break; } case (VarEnum.VT_UI4): //19 { uint data = (uint)value; bw.Write(data); break; } case (VarEnum.VT_I8): //20 { long data = (long)value; bw.Write(data); break; } case (VarEnum.VT_UI8): //21 { ulong data = (ulong)value; bw.Write(data); break; } case (VarEnum.VT_R4): //4 { float data = (float)value; bw.Write(data); break; } case (VarEnum.VT_R8): //5 { double data = (double)value; bw.Write(data); break; } case (VarEnum.VT_DATE): //7 { DateTime data = (DateTime)value; bw.Write(data.ToOADate()); break; } case (VarEnum.VT_BOOL): //11 { bool data = (bool)value; if (data) { //true is two consecutive all bits on bytes bw.Write((byte)0xFF); bw.Write((byte)0xFF); } else { //false is two consecutive all bits off bytes bw.Write((byte)0); bw.Write((byte)0); } break; } case (VarEnum.VT_DECIMAL): //14 { decimal data = (decimal)value; bw.Write(data); break; } case (VarEnum.VT_BSTR): //8 { string data = (string)value; bw.Write(System.Text.Encoding.Unicode.GetBytes(data)); break; } default: { throw new InvalidOperationException(SR.Get(SRID.InvalidEpInIsf)); } } #pragma warning restore 6518 #pragma warning restore 1634, 1691 }
public void RemoveAt(int index) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
/// <summary> /// Validates the data to be associated with a ExtendedProperty id /// </summary> /// <param name="id">ExtendedProperty identifier</param> /// <param name="value">data</param> /// <remarks>Ignores Ids that are not known (e.g. ExtendedProperties)</remarks> internal static void Validate(Guid id, object value) { if (id == Guid.Empty) { throw new ArgumentException(SR.Get(SRID.InvalidGuid)); } if (id == KnownIds.Color) { if (!(value is System.Windows.Media.Color)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(System.Windows.Media.Color)), "value"); } } // int attributes else if (id == KnownIds.CurveFittingError) { if (!(value.GetType() == typeof(int))) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(int)), "value"); } } else if (id == KnownIds.DrawingFlags) { // ignore validation of flags if (value.GetType() != typeof(DrawingFlags)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(DrawingFlags)), "value"); } } else if (id == KnownIds.StylusTip) { Type valueType = value.GetType(); bool fStylusTipType = (valueType == typeof(StylusTip)); bool fIntType = (valueType == typeof(int)); if (!fStylusTipType && !fIntType) { throw new ArgumentException(SR.Get(SRID.InvalidValueType1, typeof(StylusTip), typeof(int)), "value"); } else if (!StylusTipHelper.IsDefined((StylusTip)value)) { throw new ArgumentException(SR.Get(SRID.InvalidValueOfType, value, typeof(StylusTip)), "value"); } } else if (id == KnownIds.StylusTipTransform) { // // StylusTipTransform gets serialized as a String, but at runtime is a Matrix // Type t = value.GetType(); if (t != typeof(String) && t != typeof(Matrix)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType1, typeof(String), typeof(Matrix)), "value"); } else if (t == typeof(Matrix)) { Matrix matrix = (Matrix)value; if (!matrix.HasInverse) { throw new ArgumentException(SR.Get(SRID.MatrixNotInvertible), "value"); } if (MatrixHelper.ContainsNaN(matrix)) { throw new ArgumentException(SR.Get(SRID.InvalidMatrixContainsNaN), "value"); } if (MatrixHelper.ContainsInfinity(matrix)) { throw new ArgumentException(SR.Get(SRID.InvalidMatrixContainsInfinity), "value"); } } } else if (id == KnownIds.IsHighlighter) { if (value.GetType() != typeof(bool)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(bool)), "value"); } } else if (id == KnownIds.StylusHeight || id == KnownIds.StylusWidth) { if (value.GetType() != typeof(double)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(double)), "value"); } double dVal = (double)value; if (id == KnownIds.StylusHeight) { if (Double.IsNaN(dVal) || dVal < DrawingAttributes.MinHeight || dVal > DrawingAttributes.MaxHeight) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.InvalidDrawingAttributesHeight)); } } else { if (Double.IsNaN(dVal) || dVal < DrawingAttributes.MinWidth || dVal > DrawingAttributes.MaxWidth) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.InvalidDrawingAttributesWidth)); } } } else if (id == KnownIds.Transparency) { if (value.GetType() != typeof(byte)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(byte)), "value"); } double dVal = (double)value; } else { if (!UsesEmbeddedTypeInformation(id)) { // if this guid used the legacy internal attribute persistence APIs, // then it doesn't include embedded type information (it's always a byte array) if (value.GetType() != typeof(byte[])) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(byte[])), "value"); } } else { // if there is any unsupported type, this call will throw. VarEnum varEnum = SerializationHelper.ConvertToVarEnum(value.GetType(), true); switch (varEnum) { case (VarEnum.VT_ARRAY | VarEnum.VT_I1): //8208 case (VarEnum.VT_I1): //16 case (VarEnum.VT_ARRAY | VarEnum.VT_DATE): //8199 case (VarEnum.VT_DATE): //7 { //we have a char or char[], datetime or datetime[], //we need to write them to a Stream using a BinaryWriter //to see if an exception is thrown so that the exception //happens now, and not at serialization time... using (MemoryStream stream = new MemoryStream(32)) //reasonable default { using (BinaryWriter writer = new BinaryWriter(stream)) { try { switch (varEnum) { case (VarEnum.VT_ARRAY | VarEnum.VT_I1): //8208 { writer.Write((char[])value); break; } case (VarEnum.VT_I1): //16 { writer.Write((char)value); break; } case (VarEnum.VT_ARRAY | VarEnum.VT_DATE): //8199 { DateTime[] data = (DateTime[])value; for (int i = 0; i < data.Length; i++) { writer.Write(data[i].ToOADate()); } break; } case (VarEnum.VT_DATE): //7 { DateTime data = (DateTime)value; writer.Write(data.ToOADate()); break; } default: { Debug.Assert(false, "Missing case statement!"); break; } } } catch (ArgumentException ex) { //catches bad char & char[] throw new ArgumentException(SR.Get(SRID.InvalidDataInISF), ex); } catch (OverflowException ex) { //catches bad DateTime throw new ArgumentException(SR.Get(SRID.InvalidDataInISF), ex); } } } break; } //do nothing in the default case... } } return; } }
/// /// Create from memory /// private void InitFromMemoryPtr( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) { if (pixelFormat.Palettized == true && palette == null) { throw new InvalidOperationException(SR.Get(SRID.Image_IndexedPixelFormatRequiresPalette)); } if (pixelFormat.Format == PixelFormatEnum.Default && pixelFormat.Guid == WICPixelFormatGUIDs.WICPixelFormatDontCare) { throw new System.ArgumentException( SR.Get(SRID.Effect_PixelFormat, pixelFormat), "pixelFormat" ); } _bitmapInit.BeginInit(); try { BitmapSourceSafeMILHandle wicBitmap; // Create the unmanaged resources Guid guidFmt = pixelFormat.Guid; using (FactoryMaker factoryMaker = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromMemory( factoryMaker.ImagingFactoryPtr, (uint)pixelWidth, (uint)pixelHeight, ref guidFmt, (uint)stride, (uint)bufferSize, buffer, out wicBitmap)); wicBitmap.CalculateSize(); } HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetResolution( wicBitmap, dpiX, dpiY)); if (pixelFormat.Palettized) { HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetPalette( wicBitmap, palette.InternalPalette)); } WicSourceHandle = wicBitmap; _isSourceCached = true; } catch { _bitmapInit.Reset(); throw; } _createOptions = BitmapCreateOptions.PreservePixelFormat; _cacheOption = BitmapCacheOption.OnLoad; _syncObject = WicSourceHandle; _bitmapInit.EndInit(); UpdateCachedSettings(); }
internal override void BuildClockSubTreeFromTimeline( Timeline timeline, bool hasControllableRoot) { // This is not currently necessary //base.BuildClockSubTreeFromTimeline(timeline); // Only TimelineGroup has children TimelineGroup timelineGroup = timeline as TimelineGroup; // Only a TimelineGroup should have allocated a ClockGroup. Debug.Assert(timelineGroup != null); // Create a clock for each of the children of the timeline TimelineCollection timelineChildren = timelineGroup.Children; if (timelineChildren != null && timelineChildren.Count > 0) { Clock childClock; // Create a collection for the children of the clock _children = new List <Clock>(); // Create clocks for the children for (int index = 0; index < timelineChildren.Count; index++) { childClock = AllocateClock(timelineChildren[index], hasControllableRoot); childClock._parent = this; // We connect the child to the subtree before calling BuildClockSubtreeFromTimeline childClock.BuildClockSubTreeFromTimeline(timelineChildren[index], hasControllableRoot); _children.Add(childClock); childClock._childIndex = index; } // If we have SlipBehavior, check if we have any childen with which to slip. if (_timeline is ParallelTimeline && ((ParallelTimeline)_timeline).SlipBehavior == SlipBehavior.Slip) { // Verify that we only use SlipBehavior in supported scenarios if (!IsRoot || (_timeline.RepeatBehavior.HasDuration) || (_timeline.AutoReverse == true) || (_timeline.AccelerationRatio > 0) || (_timeline.DecelerationRatio > 0)) { throw new NotSupportedException(SR.Get(SRID.Timing_SlipBehavior_SlipOnlyOnSimpleTimelines)); } for (int index = 0; index < _children.Count; index++) { Clock child = _children[index]; if (child.CanSlip) { Duration duration = child.ResolvedDuration; // A sync clock with duration of zero or no begin time has no effect, so do skip it if ((!duration.HasTimeSpan || duration.TimeSpan > TimeSpan.Zero) && child._timeline.BeginTime.HasValue) { _syncData = new SyncData(child); child._syncData = null; // The child will no longer self-sync } break; // We only want the first child with CanSlip } } } } }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.Play: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaPlayKey), SR.Get(SRID.MediaPlayKeyDisplayString), gestures); break; case CommandId.Pause: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaPauseKey), SR.Get(SRID.MediaPauseKeyDisplayString), gestures); break; case CommandId.Stop: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaStopKey), SR.Get(SRID.MediaStopKeyDisplayString), gestures); break; case CommandId.Record: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaRecordKey), SR.Get(SRID.MediaRecordKeyDisplayString), gestures); break; case CommandId.NextTrack: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaNextTrackKey), SR.Get(SRID.MediaNextTrackKeyDisplayString), gestures); break; case CommandId.PreviousTrack: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaPreviousTrackKey), SR.Get(SRID.MediaPreviousTrackKeyDisplayString), gestures); break; case CommandId.FastForward: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaFastForwardKey), SR.Get(SRID.MediaFastForwardKeyDisplayString), gestures); break; case CommandId.Rewind: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaRewindKey), SR.Get(SRID.MediaRewindKeyDisplayString), gestures); break; case CommandId.ChannelUp: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaChannelUpKey), SR.Get(SRID.MediaChannelUpKeyDisplayString), gestures); break; case CommandId.ChannelDown: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaChannelDownKey), SR.Get(SRID.MediaChannelDownKeyDisplayString), gestures); break; case CommandId.TogglePlayPause: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaTogglePlayPauseKey), SR.Get(SRID.MediaTogglePlayPauseKeyDisplayString), gestures); break; case CommandId.IncreaseVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaIncreaseVolumeKey), SR.Get(SRID.MediaIncreaseVolumeKeyDisplayString), gestures); break; case CommandId.DecreaseVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaDecreaseVolumeKey), SR.Get(SRID.MediaDecreaseVolumeKeyDisplayString), gestures); break; case CommandId.MuteVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaMuteVolumeKey), SR.Get(SRID.MediaMuteVolumeKeyDisplayString), gestures); break; case CommandId.IncreaseTreble: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaIncreaseTrebleKey), SR.Get(SRID.MediaIncreaseTrebleKeyDisplayString), gestures); break; case CommandId.DecreaseTreble: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaDecreaseTrebleKey), SR.Get(SRID.MediaDecreaseTrebleKeyDisplayString), gestures); break; case CommandId.IncreaseBass: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaIncreaseBassKey), SR.Get(SRID.MediaIncreaseBassKeyDisplayString), gestures); break; case CommandId.DecreaseBass: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaDecreaseBassKey), SR.Get(SRID.MediaDecreaseBassKeyDisplayString), gestures); break; case CommandId.BoostBass: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaBoostBassKey), SR.Get(SRID.MediaBoostBassKeyDisplayString), gestures); break; case CommandId.IncreaseMicrophoneVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaIncreaseMicrophoneVolumeKey), SR.Get(SRID.MediaIncreaseMicrophoneVolumeKeyDisplayString), gestures); break; case CommandId.DecreaseMicrophoneVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaDecreaseMicrophoneVolumeKey), SR.Get(SRID.MediaDecreaseMicrophoneVolumeKeyDisplayString), gestures); break; case CommandId.MuteMicrophoneVolume: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaMuteMicrophoneVolumeKey), SR.Get(SRID.MediaMuteMicrophoneVolumeKeyDisplayString), gestures); break; case CommandId.ToggleMicrophoneOnOff: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaToggleMicrophoneOnOffKey), SR.Get(SRID.MediaToggleMicrophoneOnOffKeyDisplayString), gestures); break; case CommandId.Select: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.MediaSelectKey), SR.Get(SRID.MediaSelectKeyDisplayString), gestures); break; } return(gestures); }
private void ManualUpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { if (PixelShader == null) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderPixelShaderSet)); } checked { DUCE.MILCMD_SHADEREFFECT data; data.Type = MILCMD.MilCmdShaderEffect; data.Handle = _duceResource.GetHandle(channel); data.TopPadding = _topPadding; data.BottomPadding = _bottomPadding; data.LeftPadding = _leftPadding; data.RightPadding = _rightPadding; data.DdxUvDdyUvRegisterIndex = this.DdxUvDdyUvRegisterIndex; data.hPixelShader = ((DUCE.IResource)PixelShader).GetHandle(channel); unsafe { data.ShaderConstantFloatRegistersSize = (uint)(sizeof(Int16) * _floatCount); data.DependencyPropertyFloatValuesSize = (uint)(4 * sizeof(Single) * _floatCount); data.ShaderConstantIntRegistersSize = (uint)(sizeof(Int16) * _intCount); data.DependencyPropertyIntValuesSize = (uint)(4 * sizeof(Int32) * _intCount); data.ShaderConstantBoolRegistersSize = (uint)(sizeof(Int16) * _boolCount); // // Note: the multiply by 4 is not because the boolean register holds 4 // values, but to compensate for the difference between sizeof(bool) // in managed code (1) and sizeof(BOOL) in native code (4). // data.DependencyPropertyBoolValuesSize = (uint)(4 * sizeof(bool) * _boolCount); data.ShaderSamplerRegistrationInfoSize = (uint)(2 * sizeof(uint) * _samplerCount); // 2 pieces of data per sampler. data.DependencyPropertySamplerValuesSize = (uint)(1 * sizeof(DUCE.ResourceHandle) * _samplerCount); channel.BeginCommand( (byte *)&data, sizeof(DUCE.MILCMD_SHADEREFFECT), (int)(data.ShaderConstantFloatRegistersSize + data.DependencyPropertyFloatValuesSize + data.ShaderConstantIntRegistersSize + data.DependencyPropertyIntValuesSize + data.ShaderConstantBoolRegistersSize + data.DependencyPropertyBoolValuesSize + data.ShaderSamplerRegistrationInfoSize + data.DependencyPropertySamplerValuesSize) ); // Arrays appear in this order: // 1) float register indices // 2) float dp values // 3) int register indices // 4) int dp values // 5) bool register indices // 6) bool dp values // 7) sampler registration info // 8) sampler dp values // 1) float register indices AppendRegisters(channel, _floatRegisters); // 2) float dp values if (_floatRegisters != null) { for (int i = 0; i < _floatRegisters.Count; i++) { MilColorF?v = _floatRegisters[i]; if (v.HasValue) { MilColorF valueToPush = v.Value; channel.AppendCommandData((byte *)&valueToPush, sizeof(MilColorF)); } } } // 3) int register indices AppendRegisters(channel, _intRegisters); // 4) int dp values if (_intRegisters != null) { for (int i = 0; i < _intRegisters.Count; i++) { MilColorI?v = _intRegisters[i]; if (v.HasValue) { MilColorI valueToPush = v.Value; channel.AppendCommandData((byte *)&valueToPush, sizeof(MilColorI)); } } } // 5) bool register indices AppendRegisters(channel, _boolRegisters); // 6) bool dp values if (_boolRegisters != null) { for (int i = 0; i < _boolRegisters.Count; i++) { bool?v = _boolRegisters[i]; if (v.HasValue) { // // Note: need 4 bytes for the bool, because the render thread // unmarshals it into a 4-byte BOOL. See the comment above for // DependencyPropertyBoolValuesSize for more details. // Int32 valueToPush = v.Value ? 1 : 0; channel.AppendCommandData((byte *)&valueToPush, sizeof(Int32)); } } } // 7) sampler registration info if (_samplerCount > 0) { int count = _samplerData.Count; for (int i = 0; i < count; i++) { SamplerData?ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; // add as a 2-tuple (SamplerRegisterIndex, // SamplingMode) channel.AppendCommandData((byte *)&i, sizeof(int)); int value = (int)(ss._samplingMode); channel.AppendCommandData((byte *)&value, sizeof(int)); } } } // 8) sampler dp values if (_samplerCount > 0) { for (int i = 0; i < _samplerData.Count; i++) { SamplerData?ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; // Making this assumption by storing a collection of // handles as an Int32Collection Debug.Assert(sizeof(DUCE.ResourceHandle) == sizeof(Int32)); DUCE.ResourceHandle hBrush = ss._brush != null ? ((DUCE.IResource)ss._brush).GetHandle(channel) : DUCE.ResourceHandle.Null; Debug.Assert(!hBrush.IsNull || ss._brush == null, "If brush isn't null, hBrush better not be"); channel.AppendCommandData((byte *)&hBrush, sizeof(DUCE.ResourceHandle)); } } } // That's it... channel.EndCommand(); } } } }