-
Notifications
You must be signed in to change notification settings - Fork 20
/
Functions.cs
265 lines (234 loc) · 9.4 KB
/
Functions.cs
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
using Newtonsoft.Json;
namespace OtterGui;
public static class Functions
{
// Iterate through a list executing actions on each element by its mode.
public static void IteratePairwise<T>(IReadOnlyList<T> list, Action<T> action1, Action inBetween, Action<T>? action2 = null)
{
var odd = (list.Count & 1) == 1;
var size = list.Count - 1;
action2 ??= action1;
for (var i = 0; i < size; i += 2)
{
action1(list[i]);
inBetween();
action2(list[i + 1]);
}
if (odd)
action1(list[size]);
}
// Iterate through a list executing bool returning functions on each element by its mode and return the or'd result.
public static bool IteratePairwise<T>(IReadOnlyList<T> list, Func<T, bool> func1, Action inBetween, Func<T, bool>? func2 = null)
{
var odd = (list.Count & 1) == 1;
var size = list.Count - 1;
func2 ??= func1;
var ret = false;
for (var i = 0; i < size; i += 2)
{
ret |= func1(list[i]);
inBetween();
ret |= func2(list[i + 1]);
}
return ret | (odd && func1(list[size]));
}
// Split a uint into four bytes, e.g. for RGBA colors.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static (byte Lowest, byte Second, byte Third, byte Highest) SplitBytes(uint value)
{
var byte4 = (byte)(value >> 24);
var byte3 = (byte)(value >> 16);
var byte2 = (byte)(value >> 8);
var byte1 = (byte)value;
return (byte1, byte2, byte3, byte4);
}
// Obtain a descriptive hex-string of a RGBA color.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static string ColorBytes(uint color)
{
var (r, g, b, a) = SplitBytes(color);
return $"#{r:X2}{g:X2}{b:X2}{a:X2}";
}
// Reorder a ABGR color to RGBA.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static uint ReorderColor(uint seColor)
{
var (a, b, g, r) = SplitBytes(seColor);
return r | ((uint)g << 8) | ((uint)b << 16) | ((uint)a << 24);
}
// Average two given colors.
public static uint AverageColor(uint c1, uint c2)
{
var (r1, g1, b1, a1) = SplitBytes(c1);
var (r2, g2, b2, a2) = SplitBytes(c2);
var r = (uint)(r1 + r2) / 2;
var g = (uint)(g1 + g2) / 2;
var b = (uint)(b1 + b2) / 2;
var a = (uint)(a1 + a2) / 2;
return r | (g << 8) | (b << 16) | (a << 24);
}
// Remove a single bit, moving all further bits one down.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static uint RemoveBit(uint config, int bit)
{
var lowMask = (1u << bit) - 1u;
var highMask = ~((1u << (bit + 1)) - 1u);
var low = config & lowMask;
var high = (config & highMask) >> 1;
return low | high;
}
// Remove a single bit, moving all further bits one down.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static ulong RemoveBit(ulong config, int bit)
{
var lowMask = (1ul << bit) - 1ul;
var highMask = ~((1ul << (bit + 1)) - 1ul);
var low = config & lowMask;
var high = (config & highMask) >> 1;
return low | high;
}
// Move a bit in an uint from its position to another, shifting other bits accordingly.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static uint MoveBit(uint config, int bit1, int bit2)
{
var enabled = (config & (1 << bit1)) != 0 ? 1u << bit2 : 0u;
config = RemoveBit(config, bit1);
var lowMask = (1u << bit2) - 1u;
var low = config & lowMask;
var high = (config & ~lowMask) << 1;
return low | enabled | high;
}
// Move a bit in an uint from its position to another, shifting other bits accordingly.
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static ulong MoveBit(ulong config, int bit1, int bit2)
{
var enabled = (config & (1ul << bit1)) != 0 ? 1ul << bit2 : 0ul;
config = RemoveBit(config, bit1);
var lowMask = (1ul << bit2) - 1ul;
var low = config & lowMask;
var high = (config & ~lowMask) << 1;
return low | enabled | high;
}
// Return a human readable form of the size using the given format (which should be a float identifier followed by a placeholder).
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static string HumanReadableSize(long size, string format = "{0:0.#} {1}")
{
var order = 0;
double s = size;
while (s >= 1024 && order < ByteAbbreviations.Length - 1)
{
order++;
s /= 1024;
}
return string.Format(format, s, ByteAbbreviations[order]);
}
private static readonly string[] ByteAbbreviations =
{
"B",
"KB",
"MB",
"GB",
"TB",
"PB",
"EB",
};
// Compress any type to a base64 encoding of its compressed json representation, prepended with a version byte.
// Returns an empty string on failure.
public static unsafe string ToCompressedBase64<T>(T data, byte version)
{
try
{
var json = JsonConvert.SerializeObject(data, Formatting.None);
var bytes = Encoding.UTF8.GetBytes(json);
using var compressedStream = new MemoryStream();
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(new ReadOnlySpan<byte>(&version, 1));
zipStream.Write(bytes, 0, bytes.Length);
}
return Convert.ToBase64String(compressedStream.ToArray());
}
catch
{
return string.Empty;
}
}
// Decompress a base64 encoded string to the given type and a prepended version byte if possible.
// On failure, data will be default and version will be byte.MaxValue.
public static byte FromCompressedBase64<T>(string base64, out T? data)
{
var version = byte.MaxValue;
try
{
var bytes = Convert.FromBase64String(base64);
using var compressedStream = new MemoryStream(bytes);
using var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress);
using var resultStream = new MemoryStream();
zipStream.CopyTo(resultStream);
bytes = resultStream.ToArray();
version = bytes[0];
var json = Encoding.UTF8.GetString(bytes, 1, bytes.Length - 1);
data = JsonConvert.DeserializeObject<T>(json);
}
catch
{
data = default;
}
return version;
}
// If vec doesn't fit within max, return the largest vector of the same aspect ratio that does.
public static Vector2 Contain(this Vector2 vec, Vector2 max)
{
if (vec.X > max.X)
vec = max with { Y = vec.Y * max.X / vec.X };
if (vec.Y > max.Y)
vec = max with { X = vec.X * max.Y / vec.Y };
return vec;
}
// Try to obtain the list of Quick Access folders from your system.
public static bool GetQuickAccessFolders(out List<(string Name, string Path)> folders)
{
folders = new List<(string Name, string Path)>();
try
{
var shellAppType = Type.GetTypeFromProgID("Shell.Application");
if (shellAppType == null)
return false;
var shell = Activator.CreateInstance(shellAppType);
var obj = shellAppType.InvokeMember("NameSpace", BindingFlags.InvokeMethod, null, shell, new object[]
{
"shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}",
});
if (obj == null)
return false;
foreach (var fi in ((dynamic)obj).Items())
{
if (!fi.IsLink && !fi.IsFolder)
continue;
folders.Add((fi.Name, fi.Path));
}
return true;
}
catch
{
return false;
}
}
// Try to obtain the Downloads folder from your system.
public static bool GetDownloadsFolder(out string folder)
{
folder = string.Empty;
try
{
var guid = new Guid("374DE290-123F-4565-9164-39C4925E467B");
folder = SHGetKnownFolderPath(guid, 0);
return folder.Length > 0;
}
catch
{
return false;
}
}
[DllImport("shell32", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
private static extern string SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, nint hToken = 0);
}