-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFancyTextSimpleLabelHook.cs
More file actions
627 lines (543 loc) · 24.7 KB
/
Copy pathFancyTextSimpleLabelHook.cs
File metadata and controls
627 lines (543 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using LiveSplit.UI;
namespace LiveSplit.UI.Components
{
internal static class FancyTextSimpleLabelHook
{
private static readonly object Sync = new object();
private static bool _attemptedInstall;
public static bool IsInstalled { get; private set; }
public static string LastError { get; private set; }
public static void Install()
{
if (IsInstalled)
{
return;
}
lock (Sync)
{
if (IsInstalled || _attemptedInstall)
{
return;
}
_attemptedInstall = true;
try
{
MethodInfo target = typeof(SimpleLabel).GetMethod(
"Draw",
BindingFlags.Instance | BindingFlags.Public,
null,
new[] { typeof(Graphics) },
null);
MethodInfo replacement = typeof(FancyTextSimpleLabelHook).GetMethod(
"DrawReplacement",
BindingFlags.Static | BindingFlags.NonPublic);
if (target == null || replacement == null)
{
LastError = "Could not find SimpleLabel.Draw or FancyText replacement method.";
return;
}
RedirectMethod(target, replacement);
IsInstalled = true;
}
catch (Exception ex)
{
LastError = ex.Message;
}
}
}
private static void RedirectMethod(MethodInfo target, MethodInfo replacement)
{
RuntimeHelpers.PrepareMethod(target.MethodHandle);
RuntimeHelpers.PrepareMethod(replacement.MethodHandle);
IntPtr targetAddress = target.MethodHandle.GetFunctionPointer();
IntPtr replacementAddress = replacement.MethodHandle.GetFunctionPointer();
byte[] patch = CreateJumpPatch(targetAddress, replacementAddress);
uint oldProtect;
if (!VirtualProtect(targetAddress, (UIntPtr)patch.Length, PageExecuteReadWrite, out oldProtect))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
try
{
Marshal.Copy(patch, 0, targetAddress, patch.Length);
FlushInstructionCache(GetCurrentProcess(), targetAddress, (UIntPtr)patch.Length);
}
finally
{
uint ignored;
VirtualProtect(targetAddress, (UIntPtr)patch.Length, oldProtect, out ignored);
}
}
private static byte[] CreateJumpPatch(IntPtr targetAddress, IntPtr replacementAddress)
{
if (IntPtr.Size == 8)
{
byte[] patch = new byte[12];
patch[0] = 0x48;
patch[1] = 0xB8;
BitConverter.GetBytes(replacementAddress.ToInt64()).CopyTo(patch, 2);
patch[10] = 0xFF;
patch[11] = 0xE0;
return patch;
}
int relative = replacementAddress.ToInt32() - targetAddress.ToInt32() - 5;
byte[] x86Patch = new byte[5];
x86Patch[0] = 0xE9;
BitConverter.GetBytes(relative).CopyTo(x86Patch, 1);
return x86Patch;
}
private const uint PageExecuteReadWrite = 0x40;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll")]
private static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, UIntPtr dwSize);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static void DrawReplacement(SimpleLabel label, Graphics g)
{
if (label == null || g == null)
{
return;
}
using (StringFormat format = CreateFormat(label.HorizontalAlignment, label.VerticalAlignment))
{
if (!label.IsMonospaced)
{
string actualText = CalculateAlternateText(label, g, label.Width, format);
DrawText(label, actualText, g, label.X, label.Y, label.Width, label.Height, format);
return;
}
}
using (StringFormat monoFormat = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = label.VerticalAlignment
})
{
int digitWidth = MeasureGlyphWidth(label, g, "0");
string cutOffText = CutOff(label, g);
float offset = label.Width - MeasureActualWidth(label, cutOffText, g);
if (label.HorizontalAlignment != StringAlignment.Far)
{
offset = 0f;
}
for (int charIndex = 0; charIndex < cutOffText.Length; charIndex++)
{
char curChar = cutOffText[charIndex];
float curOffset = char.IsDigit(curChar)
? digitWidth
: MeasureGlyphWidth(label, g, curChar.ToString());
DrawText(label, curChar.ToString(), g, label.X + offset - (curOffset / 2f), label.Y, curOffset * 2f, label.Height, monoFormat);
offset += curOffset;
}
}
}
private static StringFormat CreateFormat(StringAlignment horizontalAlignment, StringAlignment verticalAlignment)
{
return new StringFormat
{
Alignment = horizontalAlignment,
LineAlignment = verticalAlignment,
FormatFlags = StringFormatFlags.NoWrap,
Trimming = StringTrimming.EllipsisCharacter
};
}
private static string CalculateAlternateText(SimpleLabel label, Graphics g, float width, StringFormat format)
{
string actualText = label.Text;
label.ActualWidth = g.MeasureString(label.Text, label.Font, 9999, format).Width;
IEnumerable<string> alternates = label.AlternateText ?? new string[0];
foreach (string curText in alternates.OrderByDescending(x => x.Length))
{
if (width < label.ActualWidth)
{
actualText = curText;
label.ActualWidth = g.MeasureString(actualText, label.Font, 9999, format).Width;
}
else
{
break;
}
}
return actualText;
}
private static string CutOff(SimpleLabel label, Graphics g)
{
label.ActualWidth = MeasureActualWidth(label, label.Text, g);
if (label.ActualWidth < label.Width)
{
return label.Text;
}
string cutOffText = label.Text;
while (label.ActualWidth >= label.Width && !string.IsNullOrEmpty(cutOffText))
{
cutOffText = cutOffText.Remove(cutOffText.Length - 1, 1);
label.ActualWidth = MeasureActualWidth(label, cutOffText + "...", g);
}
return label.ActualWidth >= label.Width ? string.Empty : cutOffText + "...";
}
private static float MeasureActualWidth(SimpleLabel label, string text, Graphics g)
{
int digitWidth = MeasureGlyphWidth(label, g, "0");
int offset = 0;
foreach (char curChar in text)
{
offset += char.IsDigit(curChar)
? digitWidth
: MeasureGlyphWidth(label, g, curChar.ToString());
}
return offset;
}
private static int MeasureGlyphWidth(SimpleLabel label, Graphics g, string text)
{
return TextRenderer.MeasureText(
g,
text,
label.Font,
new Size((int)(label.Width + 0.5f), (int)(label.Height + 0.5f)),
TextFormatFlags.NoPadding).Width;
}
private static void DrawText(SimpleLabel label, string text, Graphics g, float x, float y, float width, float height, StringFormat format)
{
if (text == null)
{
return;
}
FancyTextResolvedEffects effects = FancyTextRuntime.GetCurrentEffects();
bool overrideOutline = effects != null && effects.OverrideOutline;
bool overrideShadow = effects != null && effects.OverrideShadow;
bool hasGradient = effects != null && effects.HasGradient;
bool hasShadow = overrideShadow ? effects.ShadowEnabled : label.HasShadow;
Color shadowColor = overrideShadow ? effects.ShadowColor : label.ShadowColor;
Color outlineColor = overrideOutline ? effects.OutlineColor : label.OutlineColor;
float fontSize = GetFontSize(label, g);
float outlineSize = overrideOutline
? Math.Max(0f, effects.OutlineSize)
: GetDefaultOutlineSize(fontSize);
bool usePath = overrideShadow
|| hasGradient
|| (g.TextRenderingHint == TextRenderingHint.AntiAlias && (outlineColor.A > 0 || overrideOutline));
if (usePath)
{
using (GraphicsPath path = new GraphicsPath())
{
if (hasShadow && shadowColor.A > 0)
{
if (overrideShadow)
{
DrawCustomShadow(label, text, g, fontSize, x, y, width, height, format, effects);
}
else
{
DrawDefaultPathShadow(label, text, g, fontSize, x, y, width, height, format, shadowColor);
}
}
path.AddString(text, label.Font.FontFamily, (int)label.Font.Style, fontSize, new RectangleF(x, y, width, height), format);
if (outlineColor.A > 0 && outlineSize > 0f)
{
using (Pen outline = new Pen(outlineColor, outlineSize) { LineJoin = LineJoin.Round })
{
g.DrawPath(outline, path);
}
}
using (Brush fill = CreateFillBrush(label, effects, x, y, width, height))
{
g.FillPath(fill, path);
}
}
return;
}
if (hasShadow && shadowColor.A > 0)
{
using (SolidBrush shadowBrush = new SolidBrush(shadowColor))
{
g.DrawString(text, label.Font, shadowBrush, new RectangleF(x + 1f, y + 1f, width, height), format);
g.DrawString(text, label.Font, shadowBrush, new RectangleF(x + 2f, y + 2f, width, height), format);
}
}
using (Brush fill = CreateFillBrush(label, effects, x, y, width, height))
{
g.DrawString(text, label.Font, fill, new RectangleF(x, y, width, height), format);
}
}
private static void DrawDefaultPathShadow(SimpleLabel label, string text, Graphics g, float fontSize, float x, float y, float width, float height, StringFormat format, Color shadowColor)
{
using (SolidBrush shadowBrush = new SolidBrush(shadowColor))
using (GraphicsPath shadowPath = new GraphicsPath())
{
shadowPath.AddString(text, label.Font.FontFamily, (int)label.Font.Style, fontSize, new RectangleF(x + 1f, y + 1f, width, height), format);
g.FillPath(shadowBrush, shadowPath);
shadowPath.Reset();
shadowPath.AddString(text, label.Font.FontFamily, (int)label.Font.Style, fontSize, new RectangleF(x + 2f, y + 2f, width, height), format);
g.FillPath(shadowBrush, shadowPath);
}
}
private static void DrawCustomShadow(SimpleLabel label, string text, Graphics g, float fontSize, float x, float y, float width, float height, StringFormat format, FancyTextResolvedEffects effects)
{
if (effects.ShadowNormalEnabled)
DrawCustomShadowLayer(label, text, g, fontSize, x, y, width, height, format, effects, FancyTextBackgroundShadowMode.Behind);
if (effects.ShadowOutsideEnabled)
DrawCustomShadowLayer(label, text, g, fontSize, x, y, width, height, format, effects, FancyTextBackgroundShadowMode.OutsideOnly);
if (effects.ShadowInsideEnabled)
DrawCustomShadowLayer(label, text, g, fontSize, x, y, width, height, format, effects, FancyTextBackgroundShadowMode.InsideOnly);
}
private static void DrawCustomShadowLayer(SimpleLabel label, string text, Graphics g, float fontSize, float x, float y, float width, float height, StringFormat format, FancyTextResolvedEffects effects, FancyTextBackgroundShadowMode mode)
{
float blurRadius = Math.Max(0f, effects.ShadowBlur);
float offset = Math.Max(0f, effects.ShadowSize);
if (offset <= 0f && blurRadius <= 0f)
{
return;
}
using (GraphicsPath textPath = new GraphicsPath())
{
textPath.AddString(text, label.Font.FontFamily, (int)label.Font.Style, fontSize, new RectangleF(x, y, width, height), format);
if (blurRadius <= 0f)
{
using (GraphicsPath shadowPath = new GraphicsPath())
using (SolidBrush shadowBrush = new SolidBrush(effects.ShadowColor))
{
shadowPath.AddString(
text,
label.Font.FontFamily,
(int)label.Font.Style,
fontSize,
new RectangleF(x + offset, y + offset, width, height),
format);
FillShadowPath(g, shadowPath, textPath, shadowBrush, mode);
}
return;
}
int padding = Math.Max(4, (int)Math.Ceiling(blurRadius * 3f) + (int)Math.Ceiling(offset) + 4);
RectangleF shadowBounds = new RectangleF(x + offset, y + offset, width, height);
shadowBounds.Inflate(padding, padding);
int bitmapWidth = Math.Max(1, Math.Min(4096, (int)Math.Ceiling(shadowBounds.Width)));
int bitmapHeight = Math.Max(1, Math.Min(4096, (int)Math.Ceiling(shadowBounds.Height)));
if (bitmapWidth <= 1 || bitmapHeight <= 1)
{
return;
}
using (Bitmap shadowBitmap = new Bitmap(bitmapWidth, bitmapHeight, PixelFormat.Format32bppArgb))
{
using (Graphics shadowGraphics = Graphics.FromImage(shadowBitmap))
using (GraphicsPath shadowPath = new GraphicsPath())
using (SolidBrush shadowBrush = new SolidBrush(effects.ShadowColor))
{
shadowGraphics.SmoothingMode = SmoothingMode.AntiAlias;
shadowGraphics.TextRenderingHint = g.TextRenderingHint;
RectangleF localTextRect = new RectangleF(
x + offset - shadowBounds.Left,
y + offset - shadowBounds.Top,
width,
height);
shadowPath.AddString(text, label.Font.FontFamily, (int)label.Font.Style, fontSize, localTextRect, format);
shadowGraphics.FillPath(shadowBrush, shadowPath);
}
BlurAlpha(shadowBitmap, blurRadius, effects.ShadowColor, Math.Max(1, Math.Min(8, effects.ShadowPasses)));
DrawShadowImage(g, shadowBitmap, shadowBounds, bitmapWidth, bitmapHeight, textPath, mode);
}
}
}
private static void DrawShadowImage(Graphics g, Image image, RectangleF bounds, int width, int height, GraphicsPath textPath, FancyTextBackgroundShadowMode mode)
{
if (mode == FancyTextBackgroundShadowMode.Behind)
{
g.DrawImage(image, bounds.Left, bounds.Top, width, height);
return;
}
GraphicsState saved = g.Save();
try
{
g.SetClip(textPath, mode == FancyTextBackgroundShadowMode.OutsideOnly ? CombineMode.Exclude : CombineMode.Intersect);
g.DrawImage(image, bounds.Left, bounds.Top, width, height);
}
finally
{
g.Restore(saved);
}
}
private static void FillShadowPath(Graphics g, GraphicsPath shadowPath, GraphicsPath textPath, Brush brush, FancyTextBackgroundShadowMode mode)
{
if (mode == FancyTextBackgroundShadowMode.Behind)
{
g.FillPath(brush, shadowPath);
return;
}
using (var region = mode == FancyTextBackgroundShadowMode.OutsideOnly ? new Region(shadowPath) : new Region(textPath))
{
if (mode == FancyTextBackgroundShadowMode.OutsideOnly)
region.Exclude(textPath);
else
region.Intersect(shadowPath);
g.FillRegion(brush, region);
}
}
private static void BlurAlpha(Bitmap bitmap, float radius, Color color, int passes)
{
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
try
{
int stride = data.Stride;
int height = bitmap.Height;
int width = bitmap.Width;
byte[] pixels = new byte[stride * height];
Marshal.Copy(data.Scan0, pixels, 0, pixels.Length);
byte[] originalAlpha = new byte[width * height];
for (int y = 0; y < height; y++)
{
int row = y * stride;
int alphaRow = y * width;
for (int x = 0; x < width; x++)
{
originalAlpha[alphaRow + x] = pixels[row + (x * 4) + 3];
}
}
int intRadius = Math.Max(1, (int)Math.Ceiling(radius));
float blend = Math.Max(0f, Math.Min(1f, radius / intRadius));
byte[] alpha = originalAlpha;
for (int pass = 0; pass < passes; pass++)
alpha = BoxBlur(alpha, width, height, intRadius);
for (int y = 0; y < height; y++)
{
int row = y * stride;
int alphaRow = y * width;
for (int x = 0; x < width; x++)
{
int pixel = row + (x * 4);
pixels[pixel] = color.B;
pixels[pixel + 1] = color.G;
pixels[pixel + 2] = color.R;
int original = originalAlpha[alphaRow + x];
int blurred = alpha[alphaRow + x];
int finalAlpha = (int)(original + ((blurred - original) * blend));
pixels[pixel + 3] = (byte)Math.Max(0, Math.Min(255, finalAlpha));
}
}
Marshal.Copy(pixels, 0, data.Scan0, pixels.Length);
}
finally
{
bitmap.UnlockBits(data);
}
}
private static byte[] BoxBlur(byte[] source, int width, int height, int radius)
{
int[] temp = new int[width * height];
byte[] dest = new byte[width * height];
int window = (radius * 2) + 1;
for (int y = 0; y < height; y++)
{
int row = y * width;
int sum = 0;
for (int i = -radius; i <= radius; i++)
{
sum += source[row + Clamp(i, 0, width - 1)];
}
for (int x = 0; x < width; x++)
{
temp[row + x] = sum / window;
int remove = Clamp(x - radius, 0, width - 1);
int add = Clamp(x + radius + 1, 0, width - 1);
sum += source[row + add] - source[row + remove];
}
}
for (int x = 0; x < width; x++)
{
int sum = 0;
for (int i = -radius; i <= radius; i++)
{
sum += temp[(Clamp(i, 0, height - 1) * width) + x];
}
for (int y = 0; y < height; y++)
{
dest[(y * width) + x] = (byte)(sum / window);
int remove = Clamp(y - radius, 0, height - 1);
int add = Clamp(y + radius + 1, 0, height - 1);
sum += temp[(add * width) + x] - temp[(remove * width) + x];
}
}
return dest;
}
private static int Clamp(int value, int min, int max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
private static Brush CreateFillBrush(SimpleLabel label, FancyTextResolvedEffects effects, float x, float y, float width, float height)
{
if (effects == null || !effects.HasGradient)
{
SolidBrush solid = label.Brush as SolidBrush;
return solid != null ? new SolidBrush(solid.Color) : (Brush)label.Brush.Clone();
}
RectangleF rect = new RectangleF(x, y, Math.Max(1f, width), Math.Max(1f, height));
PointF start;
PointF end;
switch (effects.GradientDirection)
{
case FancyTextGradientDirection.Horizontal:
start = new PointF(rect.Left, rect.Top);
end = new PointF(rect.Right, rect.Top);
break;
case FancyTextGradientDirection.DiagonalDown:
start = new PointF(rect.Left, rect.Top);
end = new PointF(rect.Right, rect.Bottom);
break;
case FancyTextGradientDirection.DiagonalUp:
start = new PointF(rect.Left, rect.Bottom);
end = new PointF(rect.Right, rect.Top);
break;
default:
start = new PointF(rect.Left, rect.Top);
end = new PointF(rect.Left, rect.Bottom);
break;
}
Color middleColor = effects.UseExistingColorMiddle
? GetBaseTextColor(label)
: effects.GradientColor2;
var brush = new LinearGradientBrush(start, end, effects.GradientColor1, effects.GradientColor3);
brush.InterpolationColors = new ColorBlend
{
Positions = new[] { 0f, 0.5f, 1f },
Colors = new[] { effects.GradientColor1, middleColor, effects.GradientColor3 }
};
return brush;
}
private static Color GetBaseTextColor(SimpleLabel label)
{
SolidBrush solid = label.Brush as SolidBrush;
return solid != null ? solid.Color : Color.White;
}
private static float GetDefaultOutlineSize(float fontSize)
{
return 2.1f + (fontSize * 0.055f);
}
private static float GetFontSize(SimpleLabel label, Graphics g)
{
return label.Font.Unit == GraphicsUnit.Point
? label.Font.Size * g.DpiY / 72f
: label.Font.Size;
}
}
}