public override Task <List <CanFullyNavigateResult> > CanFullyNavigateFrom( ICollection <CanFullyNavigateTarget> starts, Vector3 target, ushort zoneid) { return(Original.CanFullyNavigateFrom(starts, target, zoneid)); }
/// <summary> /// Invokes the original method, no matter the current redirection state. /// </summary> public object InvokeOriginal(object obj, params object[] args) { IntPtr methodStart = originalMethodStart; bool wasRedirecting = isRedirecting; if (wasRedirecting) { CopyToStart(originalBytes, methodStart); } try { if (obj == null && Original.IsConstructor) { return(((ConstructorInfo)Original).Invoke(args)); } return(Original.Invoke(obj, args)); } finally { if (wasRedirecting) { CopyToStart(replacementBytes, methodStart); } } }
public void RiverCheck() { n = NumWords; each_word_len = new int[n]; string[] words = Original.Split(' '); int sum = 0, max = 0; for (int i = 0; i < n; i++) { each_word_len[i] = words[i].Length; sum += each_word_len[i]; max = Math.Max(max, each_word_len[i]); } // Put all the words in one line. int res = -1, resw = 0; // Brute force over all widths, update when an answer is strictly better. for (int w = max; w <= sum + n - 1; w++) { int tmp = Check(w); if (tmp > res) { res = tmp; resw = w; } } LineWidth = resw; RiverLength = res; }
public async Task DeleteAsync(RequestOptions options = null) { if (Original != null) { await Original.DeleteAsync(options); } }
private void Init() { try { var methodField = UnhollowerUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(Original); if (methodField == null) { throw new Exception($"No IL2CPP equivalent found for {Original.FullDescription()}. The target might have been automatically generated by Unhollower (e.g. field accessor)."); } // Get the native MethodInfo struct for the target method originalNativeMethodInfo = (Il2CppMethodInfo *)(IntPtr)methodField.GetValue(null); // Create a trampoline from the original target method var trampolinePtr = DetourGenerator.CreateTrampolineFromFunction(originalNativeMethodInfo->methodPointer, out _, out _); // Create a modified native MethodInfo struct to point towards the trampoline modifiedNativeMethodInfo = (Il2CppMethodInfo *)Marshal.AllocHGlobal(Marshal.SizeOf <Il2CppMethodInfo>()); Marshal.StructureToPtr(*originalNativeMethodInfo, (IntPtr)modifiedNativeMethodInfo, false); modifiedNativeMethodInfo->methodPointer = trampolinePtr; isValid = true; } catch (Exception e) { DetourLogger.LogWarning($"Failed to init IL2CPP patch backend for {Original.FullDescription()}, using normal patch handlers: {e.Message}"); } }
public async Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions options = null) { if (Original != null) { await Original.RemoveReactionAsync(emote, user, options); } }
public async Task ModifyAsync(Action <MessageProperties> func, RequestOptions options = null) { if (Original != null) { await Original.ModifyAsync(func, options); } }
public TValue this[TKey key] { get { TValue value; if (!TryGetValue(key, out value)) { throw new KeyNotFoundException("Key not found in delta dictionary."); } return(value); } set { this.removed.Remove(key); TValue originalValue; if (Original.TryGetValue(key, out originalValue) && Equals(originalValue, value)) { this.replaced.Remove(key); } else { this.replaced[key] = value; } SetDirty(); } }
public void Save(string f) { if (Original == null) { if (!string.IsNullOrEmpty(StoredGraph)) { Original = new Graph("temp"); Original.FromJson(StoredGraph); } else { return; } } string cwd = System.IO.Path.GetDirectoryName(f); string name = System.IO.Path.GetFileNameWithoutExtension(f); Original.Name = name; Original.CopyResources(cwd); System.IO.File.WriteAllText(f, GetGraphData()); Modified = false; }
public override MoveResult MoveTo(MoveToParameters location) { //if (AvoidanceManager.IsRunningOutOfAvoid) // return MoveResult.Moving; if (!DutyManager.InInstance) { return(Original.MoveTo(location)); } //if we aren't in POTD default to the original mover right away. if (!Constants.Maps.ContainsKey(WorldManager.RawZoneId)) { return(Original.MoveTo(location)); } SetupDetour(); AddBlackspots(); WallCheck(); location.WorldState = new WorldState { MapId = WorldManager.ZoneId, Walls = wallList, Avoids = trapList }; return(Original.MoveTo(location)); }
public IVerifierCollection BuildVerifierCollection(string name) { IVerifierCollection verifierCollection = Original.BuildVerifierCollection(name); verifierCollection.BilingualVerifiers.Add(new VerifierMain()); return(verifierCollection); }
private void DebugCheck() { if (!MelonDebug.IsEnabled()) { return; } PatchInfo patchInfo = Original.GetPatchInfo(); Patch basePatch = ((patchInfo.prefixes.Count() > 0) ? patchInfo.prefixes.First() : ((patchInfo.postfixes.Count() > 0) ? patchInfo.postfixes.First() : ((patchInfo.transpilers.Count() > 0) ? patchInfo.transpilers.First() : ((patchInfo.finalizers.Count() > 0) ? patchInfo.finalizers.First() : null)))); string melonName = FindMelon(melon => ((basePatch != null) && melon.HarmonyInstance.Id.Equals(basePatch.owner))); if ((melonName == null) && (basePatch != null)) { // Patching using a custom Harmony instance; try to infer the melon assembly from the container type, prefix, postfix, or transpiler. Assembly melonAssembly = basePatch.PatchMethod.DeclaringType?.Assembly; if (melonAssembly != null) { melonName = FindMelon(melon => melon.Assembly == melonAssembly); } } WarnIfHasTranspiler(patchInfo, melonName); WarnIfOriginalMethodIsInlined(melonName); }
private void Parse() { if (string.IsNullOrEmpty(Original)) { return; } char[] switchChars = { '/', '-' }; if (!switchChars.Contains(Original[0])) { return; } string switchString = Original.Substring(1); string subArgsString = string.Empty; int colon = switchString.IndexOf(':'); if (colon >= 0) { subArgsString = switchString.Substring(colon + 1); switchString = switchString.Substring(0, colon); } Switch = switchString; if (!string.IsNullOrEmpty(subArgsString)) { subArguments.AddRange(subArgsString.Split(';')); } }
private void Init() { if (AccessTools.IsNetCoreRuntime) { Logger.Log(Logger.LogChannel.Warn, () => $"Patch target {Original.FullDescription()} is marked as extern. " + "Extern methods may not be patched because of inlining behaviour of coreclr (refer to https://github.com/dotnet/coreclr/pull/8263)." + "If you need to patch externs, consider using pure NativeDetour instead."); } var orig = Original; var args = orig.GetParameters(); var offs = orig.IsStatic ? 0 : 1; argTypes = new Type[args.Length + offs]; argTypeNames = new string[args.Length + offs]; returnType = (orig as MethodInfo)?.ReturnType; if (!orig.IsStatic) { argTypes[0] = orig.GetThisParamType(); argTypeNames[0] = "this"; } for (var i = 0; i < args.Length; i++) { argTypes[i + offs] = args[i].ParameterType; argTypeNames[i + offs] = args[i].Name; } trampolineDelegateType = DelegateTypeFactory.instance.CreateDelegateType(returnType, argTypes); invokeTrampolineMethod = AccessTools.Method(trampolineDelegateType, "Invoke"); }
private bool Equals(string s, int offset, int length) { if (string.IsNullOrEmpty(Original) || string.IsNullOrEmpty(s)) { if (Original.Equals(null) && s.Equals(null)) { return(true); } else if (Original.Equals(string.Empty) && s.Equals(string.Empty)) { return(true); } else { return(false); } } if (length != this.Length) { return(false); } if (length == 0) { return(true); } if (object.ReferenceEquals(s, Original) && offset == Offset && length == Length) { return(true); fixed(char *p1 = this.Original, p2 = s) { return(EqualsHelper(p1 + this.Offset, p2 + offset, length)); } }
public void TestCopy_Primitives_Succeeds() { const string Original = "Test Copy"; var copy = Original.DeepCopy(); Assert.AreEqual(Original, copy); }
public void MergeFrom(AnalyzeRequest other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.original_ != null) { if (original_ == null) { original_ = new global::CompatibilityAnalyzer.Models.Protobuf.RequestItem(); } Original.MergeFrom(other.Original); } if (other.updated_ != null) { if (updated_ == null) { updated_ = new global::CompatibilityAnalyzer.Models.Protobuf.RequestItem(); } Updated.MergeFrom(other.Updated); } }
public void OpenFile() { Paragraph = ""; numlocation = Input.IndexOf(" "); NumWords = Convert.ToInt32(Input.Substring(0, numlocation)); Original = Input.Substring(numlocation + 1); string[] words = Original.Split(' '); numwordscheck = words.Length; if (numwordscheck == NumWords) { NumberWords = "Green"; NumberWordsThick = 3; } else { NumberWords = "Red"; NumberWordsThick = 3; } Paragraph = Original; }
public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator() { return (Original.Where(x => !(this.removed.Contains(x.Key) || this.replaced.ContainsKey(x.Key))) .Concat(this.replaced) .GetEnumerator()); }
private void DebugCheck() { if (!MelonDebug.IsEnabled() || hasWarned) { return; } hasWarned = true; PatchInfo patchInfo = Original.GetPatchInfo(); Patch basePatch = patchInfo.prefixes.Count() > 0 ? patchInfo.prefixes.First() : patchInfo.postfixes.Count() > 0 ? patchInfo.postfixes.First() : patchInfo.transpilers.Count() > 0 ? patchInfo.transpilers.First() : patchInfo.finalizers.Count() > 0 ? patchInfo.finalizers.First() : null; MelonLogger.Instance loggerInstance = FindMelon(melon => basePatch != null && melon.HarmonyInstance.Id.Equals(basePatch.owner)); if (loggerInstance == null && basePatch != null) { // Patching using a custom Harmony instance; try to infer the melon assembly from the container type, prefix, postfix, or transpiler. Assembly melonAssembly = basePatch.PatchMethod.DeclaringType?.Assembly; if (melonAssembly != null) { loggerInstance = FindMelon(melon => melon.Assembly == melonAssembly); } } WarnIfHasTranspiler(patchInfo, loggerInstance); WarnIfOriginalMethodIsInlined(loggerInstance); }
public void Release() { if (UINodeParameters.Instance != null) { UINodeParameters.Instance.ClearView(); } foreach (UINode n in GraphNodes) { ViewPort.Children.Remove(n); } lookup.Clear(); GraphNodes.Clear(); if (Graph != null) { Graph.OnGraphUpdated -= Graph_OnGraphUpdated; Graph.Dispose(); Graph = null; } if (Original != null) { Original.Dispose(); Original = null; } ViewPort.Children.Clear(); }
public override MethodBase DetourTo(MethodBase replacement) { DebugCheck(); DynamicMethodDefinition newreplacementdmd = CopyOriginal(); HarmonyManipulator.Manipulate(Original, Original.GetPatchInfo(), new ILContext(newreplacementdmd.Definition)); MethodInfo newreplacement = newreplacementdmd.Generate(); MethodInfo il2CppShim = CreateIl2CppShim(newreplacement).Generate(); Type il2CppShimDelegateType = DelegateTypeFactory.instance.CreateDelegateType(il2CppShim, CallingConvention.Cdecl); Delegate il2CppShimDelegate = il2CppShim.CreateDelegate(il2CppShimDelegateType); IntPtr il2CppShimDelegatePtr = il2CppShimDelegate.GetFunctionPointer(); if (methodDetourPointer != IntPtr.Zero) { MelonUtils.NativeHookDetach(copiedMethodInfoPointer, methodDetourPointer); } MelonUtils.NativeHookAttach(copiedMethodInfoPointer, il2CppShimDelegatePtr); methodDetourPointer = il2CppShimDelegatePtr; PatchTools_RememberObject(Original, new LemonTuple <MethodInfo, MethodInfo, Delegate> { Item1 = newreplacement, Item2 = il2CppShim, Item3 = il2CppShimDelegate }); return(newreplacement); }
public void SanitizeMessageTrimsLeadingAndTraliningSpaces() { const string Original = " name with spaces "; string sanitized = Original.SanitizeMessage(); Assert.Equal(Original.Trim(), sanitized); }
public override DynamicMethodDefinition CopyOriginal() { DynamicMethodDefinition method = Original.ToNewDynamicMethodDefinition(); method.Definition.Name += "_wrapper"; ILContext ilcontext = new ILContext(method.Definition); ILCursor ilcursor = new ILCursor(ilcontext); FieldReference tempfieldreference = null; if (ilcursor.TryGotoNext(x => x.MatchLdsfld(out tempfieldreference), x => x.MatchCall(UnhollowerSupport.IL2CPPType, "il2cpp_object_get_virtual_method"))) { // Virtual method: Replace the sequence // - ldarg.0 // - call native int[UnhollowerBaseLib] UnhollowerBaseLib.IL2CPP::Il2CppObjectBaseToPtr(class [UnhollowerBaseLib] UnhollowerBaseLib.Il2CppObjectBase) // - ldsfld native int SomeClass::NativeMethodInfoPtr_Etc // - call native int[UnhollowerBaseLib] UnhollowerBaseLib.IL2CPP::il2cpp_object_get_virtual_method(native int, native int) ilcursor.Index -= 2; ilcursor.RemoveRange(4); } else if (ilcursor.TryGotoNext(x => x.MatchLdsfld(UnhollowerSupport.MethodBaseToIl2CppFieldInfo(Original)))) { ilcursor.Remove(); } else { MelonLogger.Error("Harmony Patcher could not rewrite Il2Cpp Unhollowed Method. Expect a stack overflow."); return(method); } ilcursor.Emit(Mono.Cecil.Cil.OpCodes.Ldc_I8, copiedMethodInfoPointer.ToInt64()); ilcursor.Emit(Mono.Cecil.Cil.OpCodes.Conv_I); return(method); }
public async Task RemoveAllReactionsAsync(RequestOptions options = null) { if (Original != null) { await Original.RemoveAllReactionsAsync(options); } }
public VirtualPiece Clone() { // Clone the basic information VirtualPiece clone = new VirtualPiece(); clone.ID = ID; clone.Original = Original.Clone(); clone._subPieceID = _subPieceID; clone._meshesPerOrientation = _meshesPerOrientation.Select(e => e.Clone()).ToArray(); clone.FixedPosition = FixedPosition.Clone(); clone.FixedOrientation = FixedOrientation; // Update parent information for mesh-points foreach (var vertexID in MeshConstants.VERTEX_IDS) { clone.Original.BoundingBox[vertexID].ParentPiece = clone; foreach (var component in clone.Original.Components) { component[vertexID].ParentPiece = clone; } } foreach (var orientation in MeshConstants.ORIENTATIONS) { foreach (var vertexID in MeshConstants.VERTEX_IDS) { clone[orientation].BoundingBox[vertexID].ParentPiece = clone; foreach (var component in clone[orientation].Components) { component[vertexID].ParentPiece = clone; } } } // Return return(clone); }
public async Task AddReactionAsync(IEmote emote, RequestOptions options = null) { if (Original != null) { await Original.AddReactionAsync(emote, options); } }
public override MoveResult MoveTo(MoveToParameters location) { //if we aren't in POTD default to the original mover right away. if (!Constants.Maps.ContainsKey(WorldManager.RawZoneId)) { return(Original.MoveTo(location)); } SetupDetour(); AddBlackspots(); WallCheck(); if (AvoidanceManager.Avoids.Any(r => r.IsPointInAvoid(location.Location))) { Logger.Warn("Location is in sidestep avoidance - ##AVOID##"); if (!AvoidanceManager.Avoids.Any(r => r.IsPointInAvoid(Core.Me.Location))) { Logger.Error("Forcing stop"); MovementManager.MoveStop(); } // CommonTasks.StopMoving("Wait for avoidance"); return(MoveResult.PathGenerationFailed); } location.WorldState = new WorldState { MapId = WorldManager.ZoneId, Walls = wallList, Avoids = trapList }; return(Original.MoveTo(location)); }
public void TestHashCloneIsCorrect() { IHash Original, Copy; byte[] MainData, ChunkOne, ChunkTwo; Int32 Count; string ActualString, ExpectedString; MainData = Converters.ConvertStringToBytes(TestConstants.DefaultData, Encoding.UTF8); Count = MainData.Length - 3; ChunkOne = new byte[Count]; ChunkTwo = new byte[MainData.Length - Count]; Utils.Utils.Memcopy(ref ChunkOne, MainData, Count); Utils.Utils.Memcopy(ref ChunkTwo, MainData, MainData.Length - Count, Count); foreach (var Idx in WorkingIndex) { GetWorkingValue(Idx); Original = crcObj; Original.Initialize(); Original.TransformBytes(ChunkOne); // Make Copy Of Current State Copy = Original.Clone(); Original.TransformBytes(ChunkTwo); ExpectedString = Original.TransformFinal().ToString(); Copy.TransformBytes(ChunkTwo); ActualString = Copy.TransformFinal().ToString(); Assert.AreEqual(ActualString, ExpectedString); } // end foreach }
public IVerifierCollection BuildVerifierCollection(string name) { var verifierCollection = Original.BuildVerifierCollection(name); verifierCollection.NativeVerifiers.Add(new XMLCheckerMain()); return(verifierCollection); }
private int AddToHandle(Original original, Bitmap bitmap) { IntPtr monochromeMask = ControlPaint.CreateHBitmapTransparencyMask(bitmap); IntPtr handle = ControlPaint.CreateHBitmapColorMask(bitmap, monochromeMask); int num = System.Windows.Forms.SafeNativeMethods.ImageList_Add(new HandleRef(this, this.Handle), new HandleRef(null, handle), new HandleRef(null, monochromeMask)); System.Windows.Forms.SafeNativeMethods.DeleteObject(new HandleRef(null, handle)); System.Windows.Forms.SafeNativeMethods.DeleteObject(new HandleRef(null, monochromeMask)); if (num == -1) { throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ImageListAddFailed")); } return num; }
private int AddIconToHandle(Original original, Icon icon) { int num2; try { int num = System.Windows.Forms.SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, this.Handle), -1, new HandleRef(icon, icon.Handle)); if (num == -1) { throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ImageListAddFailed")); } num2 = num; } finally { if ((original.options & OriginalOptions.OwnsImage) != OriginalOptions.Default) { icon.Dispose(); } } return num2; }
public Original GetOriginal(int OriginalId) { Original oOriginal = new Original(); DbCommand oDbCommand = DbProviderHelper.CreateCommand("SELECTOriginal",CommandType.StoredProcedure); oDbCommand.Parameters.Add(DbProviderHelper.CreateParameter("@OriginalId",DbType.Int32,OriginalId)); DbDataReader oDbDataReader = DbProviderHelper.ExecuteReader(oDbCommand); while (oDbDataReader.Read()) { oOriginal.OriginalId = Convert.ToInt32(oDbDataReader["OriginalId"]); oOriginal.OriginalGuid = (Guid) oDbDataReader["OriginalGuid"]; oOriginal.OriginalText = Convert.ToString(oDbDataReader["OriginalText"]); if(oDbDataReader["HyperLink"] != DBNull.Value) oOriginal.HyperLink = Convert.ToString(oDbDataReader["HyperLink"]); if(oDbDataReader["ToolTip"] != DBNull.Value) oOriginal.ToolTip = Convert.ToString(oDbDataReader["ToolTip"]); } oDbDataReader.Close(); return oOriginal; }
public List<Original> GetOriginals() { List<Original> lstOriginals = new List<Original>(); DbCommand oDbCommand = DbProviderHelper.CreateCommand("SELECTOriginals",CommandType.StoredProcedure); DbDataReader oDbDataReader = DbProviderHelper.ExecuteReader(oDbCommand); while (oDbDataReader.Read()) { Original oOriginal = new Original(); oOriginal.OriginalId = Convert.ToInt32(oDbDataReader["OriginalId"]); oOriginal.OriginalGuid = (Guid) oDbDataReader["OriginalGuid"]; oOriginal.OriginalText = Convert.ToString(oDbDataReader["OriginalText"]); if(oDbDataReader["HyperLink"] != DBNull.Value) oOriginal.HyperLink = Convert.ToString(oDbDataReader["HyperLink"]); if(oDbDataReader["ToolTip"] != DBNull.Value) oOriginal.ToolTip = Convert.ToString(oDbDataReader["ToolTip"]); lstOriginals.Add(oOriginal); } oDbDataReader.Close(); return lstOriginals; }
private Bitmap CreateBitmap(Original original, out bool ownsBitmap) { Bitmap image; Color transparentColor = this.transparentColor; ownsBitmap = false; if ((original.options & OriginalOptions.CustomTransparentColor) != OriginalOptions.Default) { transparentColor = original.customTransparentColor; } if (original.image is Bitmap) { image = (Bitmap) original.image; } else if (original.image is Icon) { image = ((Icon) original.image).ToBitmap(); ownsBitmap = true; } else { image = new Bitmap((Image) original.image); ownsBitmap = true; } if (transparentColor.A > 0) { Bitmap bitmap2 = image; image = (Bitmap) image.Clone(); image.MakeTransparent(transparentColor); if (ownsBitmap) { bitmap2.Dispose(); } ownsBitmap = true; } Size size = image.Size; if ((original.options & OriginalOptions.ImageStrip) != OriginalOptions.Default) { if ((size.Width == 0) || ((size.Width % this.imageSize.Width) != 0)) { throw new ArgumentException(System.Windows.Forms.SR.GetString("ImageListStripBadWidth"), "original"); } if (size.Height != this.imageSize.Height) { throw new ArgumentException(System.Windows.Forms.SR.GetString("ImageListImageTooShort"), "original"); } return image; } if (!size.Equals(this.ImageSize)) { Bitmap bitmap3 = image; image = new Bitmap(bitmap3, this.ImageSize); if (ownsBitmap) { bitmap3.Dispose(); } ownsBitmap = true; } return image; }
/// <include file='doc\ImageList.uex' path='docs/doc[@for="ImageCollection.Add3"]/*' /> /// <devdoc> /// <para>Adds an icon to the end of the image list with a key accessor.</para> /// </devdoc> public void Add(string key, Icon icon) { Debug.Assert((this.Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. ImageInfo imageInfo = new ImageInfo(); imageInfo.Name = key; // Add the image to the IList Original original = new Original(icon, OriginalOptions.Default); Add(original, imageInfo); }
/// <include file='doc\ImageList.uex' path='docs/doc[@for="ImageList.ImageCollection.Add2"]/*' /> /// <devdoc> /// Add the given image to the ImageList, using the given color /// to generate the mask. The number of images to add is inferred from /// the width of the given image. /// </devdoc> public int Add(Image value, Color transparentColor) { if (value == null) { throw new ArgumentNullException("value"); } Original original = new Original(value, OriginalOptions.CustomTransparentColor, transparentColor); return Add(original, null); }
/// <include file='doc\ImageList.uex' path='docs/doc[@for="ImageList.ImageCollection.Add1"]/*' /> /// <devdoc> /// Add the given image to the ImageList. /// </devdoc> public void Add(Image value) { if (value == null) { throw new ArgumentNullException("value"); } Original original = new Original(value, OriginalOptions.Default); Add(original, null); }
private int Add(Original original, ImageInfo imageInfo) { if (original == null || original.image == null) { throw new ArgumentNullException("original"); } int index = -1; AssertInvariant(); if (original.image is Bitmap) { if (owner.originals != null) { index = owner.originals.Add(original); } if (owner.HandleCreated) { bool ownsBitmap = false; Bitmap bitmapValue = owner.CreateBitmap(original, out ownsBitmap); index = owner.AddToHandle(original, bitmapValue); if(ownsBitmap) bitmapValue.Dispose(); } } else if (original.image is Icon) { if (owner.originals != null) { index = owner.originals.Add(original); } if (owner.HandleCreated) { index = owner.AddIconToHandle(original, (Icon)original.image); // NOTE: if we own the icon (it's been created by us) this WILL dispose the icon to avoid a GDI leak // **** original.image is NOT LONGER VALID AFTER THIS POINT *** } } else { throw new ArgumentException(SR.GetString(SR.ImageListBitmap)); } // update the imageInfoCollection // support AddStrip if ((original.options & OriginalOptions.ImageStrip) != 0) { for (int i = 0; i < original.nImages; i++) { imageInfoCollection.Add(new ImageInfo()); } } else { if (imageInfo == null) imageInfo = new ImageInfo(); imageInfoCollection.Add(imageInfo); } if (!owner.inAddRange) owner.OnChangeHandle(new EventArgs()); return index; }
/// <include file='doc\ImageList.uex' path='docs/doc[@for="ImageList.ImageCollection.AddStrip"]/*' /> /// <devdoc> /// Add an image strip the given image to the ImageList. A strip is a single Image /// which is treated as multiple images arranged side-by-side. /// </devdoc> public int AddStrip(Image value) { if (value == null) { throw new ArgumentNullException("value"); } // strip width must be a positive multiple of image list width // if (value.Width == 0 || (value.Width % owner.ImageSize.Width) != 0) throw new ArgumentException(SR.GetString(SR.ImageListStripBadWidth), "value"); if (value.Height != owner.ImageSize.Height) throw new ArgumentException(SR.GetString(SR.ImageListImageTooShort), "value"); int nImages = value.Width / owner.ImageSize.Width; Original original = new Original(value, OriginalOptions.ImageStrip, nImages); return Add(original, null); }
private Bitmap CreateBitmap(Original original, out bool ownsBitmap) { Color transparent = transparentColor; ownsBitmap = false; if ((original.options & OriginalOptions.CustomTransparentColor) != 0) transparent = original.customTransparentColor; Bitmap bitmap; if (original.image is Bitmap) { bitmap = (Bitmap) original.image; } else if (original.image is Icon) { bitmap = ((Icon)original.image).ToBitmap(); ownsBitmap = true; } else { bitmap = new Bitmap((Image)original.image); ownsBitmap = true; } if (transparent.A > 0) { // ImageList_AddMasked doesn't work on high color bitmaps, // so we always create the mask ourselves Bitmap source = bitmap; bitmap = (Bitmap) bitmap.Clone(); bitmap.MakeTransparent(transparent); if(ownsBitmap) source.Dispose(); ownsBitmap = true; } Size size = bitmap.Size; if ((original.options & OriginalOptions.ImageStrip) != 0) { // strip width must be a positive multiple of image list width if (size.Width == 0 || (size.Width % imageSize.Width) != 0) throw new ArgumentException(SR.GetString(SR.ImageListStripBadWidth), "original"); if (size.Height != imageSize.Height) throw new ArgumentException(SR.GetString(SR.ImageListImageTooShort), "original"); } else if (!size.Equals(ImageSize)) { Bitmap source = bitmap; bitmap = new Bitmap(source, ImageSize); if(ownsBitmap) source.Dispose(); ownsBitmap = true; } return bitmap; }
private int AddIconToHandle(Original original, Icon icon) { try { Debug.Assert(HandleCreated, "Calling AddIconToHandle when there is no handle"); int index = SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, Handle), -1, new HandleRef(icon, icon.Handle)); if (index == -1) throw new InvalidOperationException(SR.GetString(SR.ImageListAddFailed)); return index; } finally { if((original.options & OriginalOptions.OwnsImage) != 0) { /// this is to handle the case were we clone the icon (see WHY WHY WHY below) icon.Dispose(); } } }
// Adds bitmap to the Imagelist handle... // private int AddToHandle(Original original, Bitmap bitmap) { Debug.Assert(HandleCreated, "Calling AddToHandle when there is no handle"); IntPtr hMask = ControlPaint.CreateHBitmapTransparencyMask(bitmap); // Calls GDI to create Bitmap. IntPtr hBitmap = ControlPaint.CreateHBitmapColorMask(bitmap, hMask); // Calls GDI+ to create Bitmap. Need to add handle to HandleCollector. int index = SafeNativeMethods.ImageList_Add(new HandleRef(this, Handle), new HandleRef(null, hBitmap), new HandleRef(null, hMask)); SafeNativeMethods.DeleteObject(new HandleRef(null, hBitmap)); SafeNativeMethods.DeleteObject(new HandleRef(null, hMask)); if (index == -1) throw new InvalidOperationException(SR.GetString(SR.ImageListAddFailed)); return index; }