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); }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.BrowseBack: KeyGesture.AddGesturesFromResourceStrings( BrowseBackKey, SR.Get(SRID.BrowseBackKeyDisplayString), gestures); break; case CommandId.BrowseForward: KeyGesture.AddGesturesFromResourceStrings( BrowseForwardKey, SR.Get(SRID.BrowseForwardKeyDisplayString), gestures); break; case CommandId.BrowseHome: KeyGesture.AddGesturesFromResourceStrings( BrowseHomeKey, SR.Get(SRID.BrowseHomeKeyDisplayString), gestures); break; case CommandId.BrowseStop: KeyGesture.AddGesturesFromResourceStrings( BrowseStopKey, SR.Get(SRID.BrowseStopKeyDisplayString), gestures); break; case CommandId.Refresh: KeyGesture.AddGesturesFromResourceStrings( RefreshKey, SR.Get(SRID.RefreshKeyDisplayString), gestures); break; case CommandId.Favorites: KeyGesture.AddGesturesFromResourceStrings( FavoritesKey, SR.Get(SRID.FavoritesKeyDisplayString), gestures); break; case CommandId.Search: KeyGesture.AddGesturesFromResourceStrings( 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); }
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); } } }
/// <summary> /// Construct a pixel format from a string that represents the format. /// The purpose of this method is only for deserialization of PixelFormat. /// The preferred way to construct a PixelFormat is with the PixelFormats class. /// </summary> /// <param name="pixelFormatString"></param> internal PixelFormat(string pixelFormatString) { PixelFormatEnum format = PixelFormatEnum.Default; if (pixelFormatString == null) { throw new System.ArgumentNullException("pixelFormatString"); } string upperPixelFormatString = pixelFormatString.ToUpper(System.Globalization.CultureInfo.InvariantCulture); switch (upperPixelFormatString) { case "DEFAULT": format = PixelFormatEnum.Default; break; case "EXTENDED": format = PixelFormatEnum.Extended; break; case "INDEXED1": format = PixelFormatEnum.Indexed1; break; case "INDEXED2": format = PixelFormatEnum.Indexed2; break; case "INDEXED4": format = PixelFormatEnum.Indexed4; break; case "INDEXED8": format = PixelFormatEnum.Indexed8; break; case "BLACKWHITE": format = PixelFormatEnum.BlackWhite; break; case "GRAY2": format = PixelFormatEnum.Gray2; break; case "GRAY4": format = PixelFormatEnum.Gray4; break; case "GRAY8": format = PixelFormatEnum.Gray8; break; case "BGR555": format = PixelFormatEnum.Bgr555; break; case "BGR565": format = PixelFormatEnum.Bgr565; break; case "BGR24": format = PixelFormatEnum.Bgr24; break; case "RGB24": format = PixelFormatEnum.Rgb24; break; case "BGR101010": format = PixelFormatEnum.Bgr101010; break; case "BGR32": format = PixelFormatEnum.Bgr32; break; case "BGRA32": format = PixelFormatEnum.Bgra32; break; case "PBGRA32": format = PixelFormatEnum.Pbgra32; break; case "RGB48": format = PixelFormatEnum.Rgb48; break; case "RGBA64": format = PixelFormatEnum.Rgba64; break; case "PRGBA64": format = PixelFormatEnum.Prgba64; break; case "GRAY16": format = PixelFormatEnum.Gray16; break; case "GRAY32FLOAT": format = PixelFormatEnum.Gray32Float; break; case "RGB128FLOAT": format = PixelFormatEnum.Rgb128Float; break; case "RGBA128FLOAT": format = PixelFormatEnum.Rgba128Float; break; case "PRGBA128FLOAT": format = PixelFormatEnum.Prgba128Float; break; case "CMYK32": format = PixelFormatEnum.Cmyk32; break; default: throw new System.ArgumentException(SR.Get(SRID.Image_BadPixelFormat, pixelFormatString), "pixelFormatString"); } _format = format; _flags = GetPixelFormatFlagsFromEnum(format); _bitsPerPixel = GetBitsPerPixelFromEnum(format); _guidFormat = new SecurityCriticalDataForSet <Guid> (PixelFormat.GetGuidFromFormat(format)); }
// Updates the shader constant referred to by the DP. Converts to the // form that the HLSL shaders want, and stores that value, since it will // be sent on every update. // We WritePreamble/Postscript here since this method is called by the user with the callback // created in PixelShaderConstantCallback. private void UpdateShaderConstant(DependencyProperty dp, object newValue, int registerIndex) { WritePreamble(); Type t = DetermineShaderConstantType(dp.PropertyType, PixelShader); if (t == null) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderConstantType, dp.PropertyType.Name)); } else { // // Treat as a float constant in ps_2_0 by default // int registerMax = PS_2_0_FLOAT_REGISTER_LIMIT; string srid = SRID.Effect_Shader20ConstantRegisterLimit; if (PixelShader != null && PixelShader.ShaderMajorVersion >= 3) { // // If there's a ps_3_0 shader, the limit depends on the type // if (t == typeof(float)) { registerMax = PS_3_0_FLOAT_REGISTER_LIMIT; srid = SRID.Effect_Shader30FloatConstantRegisterLimit; } else if (t == typeof(int)) { registerMax = PS_3_0_INT_REGISTER_LIMIT; srid = SRID.Effect_Shader30IntConstantRegisterLimit; } else if (t == typeof(bool)) { registerMax = PS_3_0_BOOL_REGISTER_LIMIT; srid = SRID.Effect_Shader30BoolConstantRegisterLimit; } } if (registerIndex >= registerMax || registerIndex < 0) { throw new ArgumentException(SR.Get(srid), "dp"); } if (t == typeof(float)) { MilColorF fourTuple; ConvertValueToMilColorF(newValue, out fourTuple); StashInPosition(ref _floatRegisters, registerIndex, fourTuple, registerMax, ref _floatCount); } else if (t == typeof(int)) { MilColorI fourTuple; ConvertValueToMilColorI(newValue, out fourTuple); StashInPosition(ref _intRegisters, registerIndex, fourTuple, registerMax, ref _intCount); } else if (t == typeof(bool)) { StashInPosition(ref _boolRegisters, registerIndex, (bool)newValue, registerMax, ref _boolCount); } else { // We should have converted all acceptable types. Debug.Assert(false); } } // Propagate dirty this.PropertyChanged(dp); WritePostscript(); }
/// <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; } }
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(); }
public bool Remove(double item) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
public void RemoveAt(int index) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
public void Add(double value) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
public void Insert(int index, double item) { // not supported, same as double[] throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize)); }
/// <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); }
/// <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); } // If the TextRun was obtained from the cache, make sure it has the right PixelsPerDip set on its properties. if (textRun.Properties != null) { textRun.Properties.PixelsPerDip = settings.TextSource.PixelsPerDip; } 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); }
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); }
/// <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)); } } } }
/// <summary> /// Optimization that lets the ctor call setvalue repeatly without causing a copy of the int[] /// </summary> /// <param name="stylusPointProperty">stylusPointProperty</param> /// <param name="value">value</param> /// <param name="copyBeforeWrite"></param> internal void SetPropertyValue(StylusPointProperty stylusPointProperty, int value, bool copyBeforeWrite) { if (null == stylusPointProperty) { throw new ArgumentNullException("stylusPointProperty"); } if (stylusPointProperty.Id == StylusPointPropertyIds.X) { double dVal = (double)value; // // only accept values between MaxXY and MinXY // we don't throw when passed a value outside of that range, we just silently trunctate // _x = GetClampedXYValue(dVal); } else if (stylusPointProperty.Id == StylusPointPropertyIds.Y) { double dVal = (double)value; // // only accept values between MaxXY and MinXY // we don't throw when passed a value outside of that range, we just silently trunctate // _y = GetClampedXYValue(dVal); } else if (stylusPointProperty.Id == StylusPointPropertyIds.NormalPressure) { StylusPointPropertyInfo info = this.Description.GetPropertyInfo(StylusPointProperties.NormalPressure); int min = info.Minimum; int max = info.Maximum; if (max == 0) { _pressureFactor = 0.0f; } else { _pressureFactor = (float)(Convert.ToSingle(min + value) / Convert.ToSingle(max)); } } else { int propertyIndex = this.Description.GetPropertyIndex(stylusPointProperty.Id); if (-1 == propertyIndex) { throw new ArgumentException(SR.Get(SRID.InvalidStylusPointProperty), "propertyId"); } if (stylusPointProperty.IsButton) { if (value < 0 || value > 1) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.InvalidMinMaxForButton)); } if (copyBeforeWrite) { CopyAdditionalData(); } // // we get button data from a single int in the array // int buttonData = _additionalValues[_additionalValues.Length - 1]; int buttonBitPosition = this.Description.GetButtonBitPosition(stylusPointProperty); int bit = 1 << buttonBitPosition; if (value == 0) { //turn the bit off buttonData &= ~bit; } else { //turn the bit on buttonData |= bit; } _additionalValues[_additionalValues.Length - 1] = buttonData; } else { if (copyBeforeWrite) { CopyAdditionalData(); } _additionalValues[propertyIndex - 3] = value; } } }
/// <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) { // 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)) { // StylusTip is being serialized as a ushort, is this ok? 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 }
/// <summary> /// internal ctor /// </summary> internal StylusPoint( double x, double y, float pressureFactor, StylusPointDescription stylusPointDescription, int[] additionalValues, bool validateAdditionalData, bool validatePressureFactor) { if (Double.IsNaN(x)) { throw new ArgumentOutOfRangeException("x", SR.Get(SRID.InvalidStylusPointXYNaN)); } if (Double.IsNaN(y)) { throw new ArgumentOutOfRangeException("y", SR.Get(SRID.InvalidStylusPointXYNaN)); } //we don't validate pressure when called by StylusPointDescription.Reformat if (validatePressureFactor && (pressureFactor == Single.NaN || pressureFactor < 0.0f || pressureFactor > 1.0f)) { throw new ArgumentOutOfRangeException("pressureFactor", SR.Get(SRID.InvalidPressureValue)); } // // only accept values between MaxXY and MinXY // we don't throw when passed a value outside of that range, we just silently trunctate // _x = GetClampedXYValue(x); _y = GetClampedXYValue(y); _stylusPointDescription = stylusPointDescription; _additionalValues = additionalValues; _pressureFactor = pressureFactor; if (validateAdditionalData) { // // called from the public verbose ctor // if (null == stylusPointDescription) { throw new ArgumentNullException("stylusPointDescription"); } // // additionalValues can be null if PropertyCount == 3 (X, Y, P) // if (stylusPointDescription.PropertyCount > StylusPointDescription.RequiredCountOfProperties && null == additionalValues) { throw new ArgumentNullException("additionalValues"); } if (additionalValues != null) { ReadOnlyCollection <StylusPointPropertyInfo> properties = stylusPointDescription.GetStylusPointProperties(); int expectedAdditionalValues = properties.Count - StylusPointDescription.RequiredCountOfProperties; //for x, y, pressure if (additionalValues.Length != expectedAdditionalValues) { throw new ArgumentException(SR.Get(SRID.InvalidAdditionalDataForStylusPoint), "additionalValues"); } // // any buttons passed in must each be in their own int. We need to // pack them all into one int here // int[] newAdditionalValues = new int[stylusPointDescription.GetExpectedAdditionalDataCount()]; _additionalValues = newAdditionalValues; for (int i = StylusPointDescription.RequiredCountOfProperties, j = 0; i < properties.Count; i++, j++) { // // use SetPropertyValue, it validates buttons, but does not copy the // int[] on writes (since we pass the bool flag) // SetPropertyValue(properties[i], additionalValues[j], false /*copy on write*/); } } } }
/// <summary> /// Converts the CLR type information into a COM-compatible type enumeration /// </summary> /// <param name="type">The CLR type information of the object to convert</param> /// <param name="throwOnError">Throw an exception if unknown type is used</param> /// <returns>The COM-compatible type enumeration</returns> /// <remarks>Only supports the types of data that are supported in ISF ExtendedProperties</remarks> public static VarEnum ConvertToVarEnum(Type type, bool throwOnError) { if (typeof(char) == type) { return(VarEnum.VT_I1); } else if (typeof(char[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_I1); } else if (typeof(byte) == type) { return(VarEnum.VT_UI1); } else if (typeof(byte[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_UI1); } else if (typeof(Int16) == type) { return(VarEnum.VT_I2); } else if (typeof(Int16[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_I2); } else if (typeof(UInt16) == type) { return(VarEnum.VT_UI2); } else if (typeof(UInt16[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_UI2); } else if (typeof(Int32) == type) { return(VarEnum.VT_I4); } else if (typeof(Int32[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_I4); } else if (typeof(UInt32) == type) { return(VarEnum.VT_UI4); } else if (typeof(UInt32[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_UI4); } else if (typeof(Int64) == type) { return(VarEnum.VT_I8); } else if (typeof(Int64[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_I8); } else if (typeof(UInt64) == type) { return(VarEnum.VT_UI8); } else if (typeof(UInt64[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_UI8); } else if (typeof(Single) == type) { return(VarEnum.VT_R4); } else if (typeof(Single[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_R4); } else if (typeof(Double) == type) { return(VarEnum.VT_R8); } else if (typeof(Double[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_R8); } else if (typeof(DateTime) == type) { return(VarEnum.VT_DATE); } else if (typeof(DateTime[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_DATE); } else if (typeof(Boolean) == type) { return(VarEnum.VT_BOOL); } else if (typeof(Boolean[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_BOOL); } else if (typeof(String) == type) { return(VarEnum.VT_BSTR); } else if (typeof(Decimal) == type) { return(VarEnum.VT_DECIMAL); } else if (typeof(Decimal[]) == type) { return(VarEnum.VT_ARRAY | VarEnum.VT_DECIMAL); } else { if (throwOnError) { throw new ArgumentException(SR.Get(SRID.InvalidDataTypeForExtendedProperty)); } else { return(VarEnum.VT_UNKNOWN); } } }
private static void ThrowInvalidUnicodeRange() { throw new FormatException(SR.Get(SRID.CompositeFontInvalidUnicodeRange)); }
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); }
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 [....] 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-[....] } break; // We only want the first child with CanSlip } } } } }
static private Guid GetGuidFromFormat(PixelFormatEnum format) { switch (format) { case PixelFormatEnum.Default: return(WICPixelFormatGUIDs.WICPixelFormatDontCare); case PixelFormatEnum.Indexed1: return(WICPixelFormatGUIDs.WICPixelFormat1bppIndexed); case PixelFormatEnum.Indexed2: return(WICPixelFormatGUIDs.WICPixelFormat2bppIndexed); case PixelFormatEnum.Indexed4: return(WICPixelFormatGUIDs.WICPixelFormat4bppIndexed); case PixelFormatEnum.Indexed8: return(WICPixelFormatGUIDs.WICPixelFormat8bppIndexed); case PixelFormatEnum.BlackWhite: return(WICPixelFormatGUIDs.WICPixelFormatBlackWhite); case PixelFormatEnum.Gray2: return(WICPixelFormatGUIDs.WICPixelFormat2bppGray); case PixelFormatEnum.Gray4: return(WICPixelFormatGUIDs.WICPixelFormat4bppGray); case PixelFormatEnum.Gray8: return(WICPixelFormatGUIDs.WICPixelFormat8bppGray); case PixelFormatEnum.Bgr555: return(WICPixelFormatGUIDs.WICPixelFormat16bppBGR555); case PixelFormatEnum.Bgr565: return(WICPixelFormatGUIDs.WICPixelFormat16bppBGR565); case PixelFormatEnum.Bgr24: return(WICPixelFormatGUIDs.WICPixelFormat24bppBGR); case PixelFormatEnum.Rgb24: return(WICPixelFormatGUIDs.WICPixelFormat24bppRGB); case PixelFormatEnum.Bgr101010: return(WICPixelFormatGUIDs.WICPixelFormat32bppBGR101010); case PixelFormatEnum.Bgr32: return(WICPixelFormatGUIDs.WICPixelFormat32bppBGR); case PixelFormatEnum.Bgra32: return(WICPixelFormatGUIDs.WICPixelFormat32bppBGRA); case PixelFormatEnum.Pbgra32: return(WICPixelFormatGUIDs.WICPixelFormat32bppPBGRA); case PixelFormatEnum.Rgb48: return(WICPixelFormatGUIDs.WICPixelFormat48bppRGB); case PixelFormatEnum.Rgba64: return(WICPixelFormatGUIDs.WICPixelFormat64bppRGBA); case PixelFormatEnum.Prgba64: return(WICPixelFormatGUIDs.WICPixelFormat64bppPRGBA); case PixelFormatEnum.Gray16: return(WICPixelFormatGUIDs.WICPixelFormat16bppGray); case PixelFormatEnum.Gray32Float: return(WICPixelFormatGUIDs.WICPixelFormat32bppGrayFloat); case PixelFormatEnum.Rgb128Float: return(WICPixelFormatGUIDs.WICPixelFormat128bppRGBFloat); case PixelFormatEnum.Rgba128Float: return(WICPixelFormatGUIDs.WICPixelFormat128bppRGBAFloat); case PixelFormatEnum.Prgba128Float: return(WICPixelFormatGUIDs.WICPixelFormat128bppPRGBAFloat); case PixelFormatEnum.Cmyk32: return(WICPixelFormatGUIDs.WICPixelFormat32bppCMYK); } throw new System.ArgumentException(SR.Get(SRID.Image_BadPixelFormat, format), "format"); }
/// <summary> /// Save (encode) the bitmap to the specified stream. /// </summary> /// <param name="stream">Stream to save into</param> 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; }
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(); } } } }
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. string field = s.Substring(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, "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); }
/// <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> /// 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> #else /// <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); }
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId) { InputGestureCollection gestures = new InputGestureCollection(); //Standard Commands switch ((CommandId)commandId) { case CommandId.Cut: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.CutKey), SR.Get(SRID.CutKeyDisplayString), gestures); break; case CommandId.Copy: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.CopyKey), SR.Get(SRID.CopyKeyDisplayString), gestures); break; case CommandId.Paste: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.PasteKey), SR.Get(SRID.PasteKeyDisplayString), gestures); break; case CommandId.Undo: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.UndoKey), SR.Get(SRID.UndoKeyDisplayString), gestures); break; case CommandId.Redo: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.RedoKey), SR.Get(SRID.RedoKeyDisplayString), gestures); break; case CommandId.Delete: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.DeleteKey), SR.Get(SRID.DeleteKeyDisplayString), gestures); break; case CommandId.Find: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.FindKey), SR.Get(SRID.FindKeyDisplayString), gestures); break; case CommandId.Replace: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.ReplaceKey), SR.Get(SRID.ReplaceKeyDisplayString), gestures); break; case CommandId.SelectAll: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SelectAllKey), SR.Get(SRID.SelectAllKeyDisplayString), gestures); break; case CommandId.Help: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.HelpKey), SR.Get(SRID.HelpKeyDisplayString), gestures); break; case CommandId.New: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.NewKey), SR.Get(SRID.NewKeyDisplayString), gestures); break; case CommandId.Open: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.OpenKey), SR.Get(SRID.OpenKeyDisplayString), gestures); break; case CommandId.Save: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.SaveKey), SR.Get(SRID.SaveKeyDisplayString), gestures); break; case CommandId.SaveAs: break; // there are no default bindings for CommandId.SaveAs case CommandId.Print: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.PrintKey), SR.Get(SRID.PrintKeyDisplayString), gestures); break; case CommandId.CancelPrint: break; // there are no default bindings for CommandId.CancelPrint case CommandId.PrintPreview: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.PrintPreviewKey), SR.Get(SRID.PrintPreviewKeyDisplayString), gestures); break; case CommandId.Close: break; // there are no default bindings for CommandId.Close case CommandId.ContextMenu: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.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( SR.Get(SRID.PropertiesKey), SR.Get(SRID.PropertiesKeyDisplayString), gestures); break; case CommandId.Stop: KeyGesture.AddGesturesFromResourceStrings( SR.Get(SRID.StopKey), SR.Get(SRID.StopKeyDisplayString), gestures); break; case CommandId.NotACommand: break; // there are no default bindings for CommandId.NotACommand } return(gestures); }
/// <summary> /// DecompressPacketData - take a byte[] or a subset of a byte[] and decompresses it into /// an int[] of packet data (for example, x's in a Stroke) /// </summary> /// <param name="compressedInput">The byte[] to decompress</param> /// <param name="size">In: the max size of the subset of compressedInput to read, out: size read</param> /// <param name="decompressedPackets">The int[] to write the packet data to</param> #endif internal static void DecompressPacketData( #if OLD_ISF Compressor compressor, #endif byte[] compressedInput, ref uint size, int[] decompressedPackets) { #if OLD_ISF // // lock to prevent multi-threaded vulnerabilities // lock (_compressSync) { #endif if (compressedInput == null || size > compressedInput.Length || decompressedPackets == null) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage(SR.Get(SRID.DecompressPacketDataFailed))); } #if OLD_ISF uint size2 = size; #endif size = AlgoModule.DecompressPacketData(compressedInput, decompressedPackets); #if OLD_ISF MS.Win32.Penimc.CompressorSafeHandle safeCompressorHandle = (compressor == null) ? MS.Win32.Penimc.CompressorSafeHandle.Null : compressor._compressorHandle; int[] decompressedPackets2 = new int[decompressedPackets.Length]; byte algo = AlgoModule.NoCompression; int hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfDecompressPacketData(safeCompressorHandle, compressedInput, ref size2, (uint)decompressedPackets2.Length, decompressedPackets2, ref algo); if (0 != hr) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage("IsfDecompressPacketData returned: " + hr.ToString(CultureInfo.InvariantCulture))); } if (size != size2) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data bytes read didn't match with new uncompression"); } for (int i = 0; i < decompressedPackets.Length; i++) { if (decompressedPackets[i] != decompressedPackets2[i]) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data didn't match with new uncompression at index " + i.ToString()); } } } #endif }