-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathEditorGUIUtility.cs
1913 lines (1635 loc) · 71.9 KB
/
EditorGUIUtility.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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using UnityEditorInternal;
using UnityEngine.Events;
using UnityEngine.Internal;
using UnityEngine.Scripting;
using UnityEngineInternal;
using UnityEditor.StyleSheets;
using UnityEditor.Experimental;
using UnityEditor.SceneManagement;
using UnityEngine.Bindings;
using UnityEngine.Pool;
using UnityEngine.UIElements;
using UnityObject = UnityEngine.Object;
namespace UnityEditor
{
public sealed partial class EditorGUIUtility : GUIUtility
{
internal static void RegisterResourceForCleanupOnDomainReload(UnityObject obj)
{
AppDomain.CurrentDomain.DomainUnload += (object sender, EventArgs e) => { UnityObject.DestroyImmediate(obj); };
}
public class PropertyCallbackScope : IDisposable
{
Action<Rect, SerializedProperty> m_Callback;
public PropertyCallbackScope(Action<Rect, SerializedProperty> callback)
{
m_Callback = callback;
if (m_Callback != null)
EditorGUIUtility.beginProperty += callback;
}
public void Dispose()
{
if (m_Callback != null)
EditorGUIUtility.beginProperty -= m_Callback;
}
}
public class IconSizeScope : GUI.Scope
{
private readonly Vector2 m_OriginalIconSize;
public IconSizeScope(Vector2 iconSizeWithinScope)
{
m_OriginalIconSize = GetIconSize();
SetIconSize(iconSizeWithinScope);
}
protected override void CloseScope()
{
SetIconSize(m_OriginalIconSize);
}
}
internal static Material s_GUITextureBlit2SRGBMaterial;
internal static Material GUITextureBlit2SRGBMaterial
{
get
{
if (!s_GUITextureBlit2SRGBMaterial)
{
Shader shader = LoadRequired("SceneView/GUITextureBlit2SRGB.shader") as Shader;
s_GUITextureBlit2SRGBMaterial = new Material(shader);
s_GUITextureBlit2SRGBMaterial.hideFlags |= HideFlags.DontSaveInEditor;
RegisterResourceForCleanupOnDomainReload(s_GUITextureBlit2SRGBMaterial);
}
s_GUITextureBlit2SRGBMaterial.SetFloat("_ManualTex2SRGB", QualitySettings.activeColorSpace == ColorSpace.Linear ? 1.0f : 0.0f);
return s_GUITextureBlit2SRGBMaterial;
}
}
internal static Material s_GUITextureBlitSceneGUI;
internal static Material GUITextureBlitSceneGUIMaterial
{
get
{
if (!s_GUITextureBlitSceneGUI)
{
Shader shader = LoadRequired("SceneView/GUITextureBlitSceneGUI.shader") as Shader;
s_GUITextureBlitSceneGUI = new Material(shader);
s_GUITextureBlitSceneGUI.hideFlags |= HideFlags.DontSaveInEditor;
RegisterResourceForCleanupOnDomainReload(s_GUITextureBlitSceneGUI);
}
return s_GUITextureBlitSceneGUI;
}
}
internal static int s_FontIsBold = -1;
internal static int s_LastControlID = 0;
private static float s_LabelWidth = 0f;
private static ScalableGUIContent s_InfoIcon;
private static ScalableGUIContent s_WarningIcon;
private static ScalableGUIContent s_ErrorIcon;
private static GUIStyle s_WhiteTextureStyle;
private static GUIStyle s_BasicTextureStyle;
static Hashtable s_TextGUIContents = new Hashtable();
static Hashtable s_GUIContents = new Hashtable();
static Hashtable s_IconGUIContents = new Hashtable();
static Hashtable s_SkinnedIcons = new Hashtable();
private static readonly GUIContent s_ObjectContent = new GUIContent();
private static readonly GUIContent s_Text = new GUIContent();
private static readonly GUIContent s_Image = new GUIContent();
private static readonly GUIContent s_TextImage = new GUIContent();
private static GUIContent s_SceneMismatch = TrTextContent("Scene mismatch (cross scene references not supported)");
private static GUIContent s_TypeMismatch = TrTextContent("Type mismatch");
internal static readonly SVC<Color> kViewBackgroundColor = new SVC<Color>("view", StyleCatalogKeyword.backgroundColor, GetDefaultBackgroundColor);
/// The current UI scaling factor for high-DPI displays. For instance, 2.0 on a retina display
public new static float pixelsPerPoint => GUIUtility.pixelsPerPoint;
static EditorGUIUtility()
{
GUISkin.m_SkinChanged += SkinChanged;
s_HasCurrentWindowKeyFocusFunc = HasCurrentWindowKeyFocus;
}
// this method gets called on right clicking a property regardless of GUI.enable value.
internal static event Action<GenericMenu, SerializedProperty> contextualPropertyMenu;
internal static event Action<Rect, SerializedProperty> beginProperty;
internal static void BeginPropertyCallback(Rect totalRect, SerializedProperty property)
{
beginProperty?.Invoke(totalRect, property);
}
internal static void ContextualPropertyMenuCallback(GenericMenu gm, SerializedProperty prop)
{
if (contextualPropertyMenu != null)
{
if (gm.GetItemCount() > 0)
gm.AddSeparator("");
contextualPropertyMenu(gm, prop);
}
}
// returns position and size of the main Unity Editor window
public static Rect GetMainWindowPosition()
{
foreach (var win in ContainerWindow.windows)
{
if (win.IsMainWindow())
return win.position;
}
return new Rect(0, 0, 1000, 600);
}
// sets position and size of the main Unity Editor window
public static void SetMainWindowPosition(Rect position)
{
foreach (var win in ContainerWindow.windows)
{
if (win.IsMainWindow())
{
win.position = position;
break;
}
}
}
internal static Rect GetCenteredWindowPosition(Rect parentWindowPosition, Vector2 size)
{
var pos = new Rect
{
x = 0,
y = 0,
width = Mathf.Min(size.x, parentWindowPosition.width * 0.90f),
height = Mathf.Min(size.y, parentWindowPosition.height * 0.90f)
};
var w = (parentWindowPosition.width - pos.width) * 0.5f;
var h = (parentWindowPosition.height - pos.height) * 0.5f;
pos.x = parentWindowPosition.x + w;
pos.y = parentWindowPosition.y + h;
return pos;
}
internal static void RepaintCurrentWindow()
{
CheckOnGUI();
GUIView.current.Repaint();
}
internal static bool HasCurrentWindowKeyFocus()
{
CheckOnGUI();
return GUIView.current != null && GUIView.current.hasFocus;
}
public static Rect PointsToPixels(Rect rect)
{
var cachedPixelsPerPoint = pixelsPerPoint;
rect.x *= cachedPixelsPerPoint;
rect.y *= cachedPixelsPerPoint;
rect.width *= cachedPixelsPerPoint;
rect.height *= cachedPixelsPerPoint;
return rect;
}
public static Rect PixelsToPoints(Rect rect)
{
var cachedInvPixelsPerPoint = 1f / pixelsPerPoint;
rect.x *= cachedInvPixelsPerPoint;
rect.y *= cachedInvPixelsPerPoint;
rect.width *= cachedInvPixelsPerPoint;
rect.height *= cachedInvPixelsPerPoint;
return rect;
}
public static Vector2 PointsToPixels(Vector2 position)
{
var cachedPixelsPerPoint = pixelsPerPoint;
position.x *= cachedPixelsPerPoint;
position.y *= cachedPixelsPerPoint;
return position;
}
public static Vector2 PixelsToPoints(Vector2 position)
{
var cachedInvPixelsPerPoint = 1f / pixelsPerPoint;
position.x *= cachedInvPixelsPerPoint;
position.y *= cachedInvPixelsPerPoint;
return position;
}
// Given a rectangle, GUI style and a list of items, lay them out sequentially;
// left to right, top to bottom.
public static List<Rect> GetFlowLayoutedRects(Rect rect, GUIStyle style, float horizontalSpacing, float verticalSpacing, List<string> items)
{
var result = new List<Rect>(items.Count);
var curPos = rect.position;
foreach (string item in items)
{
var gc = TempContent(item);
var itemSize = style.CalcSize(gc);
var itemRect = new Rect(curPos, itemSize);
// Reached right side, go to next row
if (curPos.x + itemSize.x + horizontalSpacing >= rect.xMax)
{
curPos.x = rect.x;
curPos.y += itemSize.y + verticalSpacing;
itemRect.position = curPos;
}
result.Add(itemRect);
// Move next item to the left
curPos.x += itemSize.x + horizontalSpacing;
}
return result;
}
internal class SkinnedColor
{
Color normalColor;
Color proColor;
public SkinnedColor(Color color, Color proColor)
{
normalColor = color;
this.proColor = proColor;
}
public SkinnedColor(Color color)
{
normalColor = color;
proColor = color;
}
public Color color
{
get { return isProSkin ? proColor : normalColor; }
set
{
if (isProSkin)
proColor = value;
else
normalColor = value;
}
}
public static implicit operator Color(SkinnedColor colorSkin)
{
return colorSkin.color;
}
}
private delegate bool HeaderItemDelegate(Rect rectangle, UnityObject[] targets);
private static List<HeaderItemDelegate> s_EditorHeaderItemsMethods = null;
internal static Rect DrawEditorHeaderItems(Rect rectangle, UnityObject[] targetObjs, float spacing = 0)
{
if (targetObjs.Length == 0 || (targetObjs.Length == 1 && targetObjs[0].GetType() == typeof(System.Object)))
return rectangle;
if (comparisonViewMode != ComparisonViewMode.None)
return rectangle;
if (s_EditorHeaderItemsMethods == null)
{
List<Type> targetObjTypes = new List<Type>();
var type = targetObjs[0].GetType();
while (type.BaseType != null)
{
targetObjTypes.Add(type);
type = type.BaseType;
}
AttributeHelper.MethodInfoSorter methods = AttributeHelper.GetMethodsWithAttribute<EditorHeaderItemAttribute>(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
Func<EditorHeaderItemAttribute, bool> filter = (a) => targetObjTypes.Any(c => a.TargetType == c);
var methodInfos = methods.FilterAndSortOnAttribute(filter, (a) => a.callbackOrder);
s_EditorHeaderItemsMethods = new List<HeaderItemDelegate>();
foreach (MethodInfo methodInfo in methodInfos)
{
s_EditorHeaderItemsMethods.Add((HeaderItemDelegate)Delegate.CreateDelegate(typeof(HeaderItemDelegate), methodInfo));
}
}
float spacingToRemove = 0;
foreach (HeaderItemDelegate @delegate in s_EditorHeaderItemsMethods)
{
if (@delegate(rectangle, targetObjs))
{
rectangle.x -= rectangle.width + spacing;
spacingToRemove = rectangle.width + spacing;
}
}
rectangle.x += spacingToRemove; // the spacing after a delegate is used to position the next element to draw but the last one is not used so we must remove it before exiting the method
return rectangle;
}
/// <summary>
/// Use this container and helper class when implementing lock behaviour on a window when also using an <see cref="ActiveEditorTracker"/>.
/// </summary>
[Serializable]
internal class EditorLockTrackerWithActiveEditorTracker : EditorLockTracker
{
internal override bool isLocked
{
get
{
if (m_Tracker != null)
{
base.isLocked = m_Tracker.isLocked;
return m_Tracker.isLocked;
}
return base.isLocked;
}
set
{
if (m_Tracker != null)
{
m_Tracker.isLocked = value;
}
base.isLocked = value;
}
}
[SerializeField, HideInInspector]
ActiveEditorTracker m_Tracker;
internal ActiveEditorTracker tracker
{
get { return m_Tracker; }
set
{
m_Tracker = value;
if (m_Tracker != null)
{
isLocked = m_Tracker.isLocked;
}
}
}
}
/// <summary>
/// Use this container and helper class when implementing lock behaviour on a window.
/// </summary>
[Serializable]
internal class EditorLockTracker
{
[Serializable] public class LockStateEvent : UnityEvent<bool> {}
[HideInInspector]
internal LockStateEvent lockStateChanged = new LockStateEvent();
const string k_LockMenuText = "Lock";
static readonly GUIContent k_LockMenuGUIContent = TextContent(k_LockMenuText);
/// <summary>
/// don't set or get this directly unless from within the <see cref="isLocked"/> property,
/// as that property also keeps track of the potentially existing tracker in <see cref="EditorLockTrackerWithActiveEditorTracker"/>
/// </summary>
[SerializeField, HideInInspector]
bool m_IsLocked;
PingData m_Ping = new PingData();
internal virtual bool isLocked
{
get
{
return m_IsLocked;
}
set
{
bool wasLocked = m_IsLocked;
m_IsLocked = value;
if (wasLocked != m_IsLocked)
{
lockStateChanged.Invoke(m_IsLocked);
}
}
}
internal virtual void AddItemsToMenu(GenericMenu menu, bool disabled = false)
{
if (disabled)
{
menu.AddDisabledItem(k_LockMenuGUIContent);
}
else
{
menu.AddItem(k_LockMenuGUIContent, isLocked, FlipLocked);
}
}
internal virtual void PingIcon()
{
m_Ping.isPinging = true;
if (m_Ping.m_PingStyle == null)
{
m_Ping.m_PingStyle = new GUIStyle("TV Ping");
// The default padding is too high for such a small icon and causes the animation to become offset to the left.
m_Ping.m_PingStyle.padding = new RectOffset(8, 0, 0, 0);
}
}
internal virtual void StopPingIcon()
{
m_Ping.isPinging = false;
}
internal bool ShowButton(Rect position, GUIStyle lockButtonStyle, bool disabled = false)
{
using (new EditorGUI.DisabledScope(disabled))
{
EditorGUI.BeginChangeCheck();
bool newLock = GUI.Toggle(position, isLocked, GUIContent.none, lockButtonStyle);
if (m_Ping.isPinging && Event.current.type == EventType.Layout)
{
m_Ping.m_ContentRect = position;
m_Ping.m_ContentRect.width *= 2f;
m_Ping.m_AvailableWidth = GUIView.current.position.width;
m_Ping.m_ContentDraw = r =>
{
GUI.Toggle(r, newLock, GUIContent.none, lockButtonStyle);
};
}
m_Ping.HandlePing();
if (EditorGUI.EndChangeCheck())
{
if (newLock != isLocked)
{
FlipLocked();
m_Ping.isPinging = false;
}
}
}
return m_Ping.isPinging;
}
void FlipLocked()
{
isLocked = !isLocked;
}
}
// Get a texture from its source filename
public static Texture2D FindTexture(string name)
{
return FindTextureByName(name);
}
// Get texture from managed type
internal static Texture2D FindTexture(Type type)
{
return FindTextureByType(type);
}
public static GUIContent TrTextContent(string key, string text, string tooltip, Texture icon)
{
GUIContent gc = (GUIContent)s_GUIContents[key];
if (gc == null)
{
gc = new GUIContent(L10n.Tr(text));
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
}
if (icon != null)
{
gc.image = icon;
}
s_GUIContents[key] = gc;
}
return gc;
}
public static GUIContent TrTextContent(string text, string tooltip = null, Texture icon = null)
{
string key = string.Format("{0}|{1}", text ?? "", tooltip ?? "");
return TrTextContent(key, text, tooltip, icon);
}
public static GUIContent TrTextContent(string text, string tooltip, string iconName)
{
string key = iconName == null ? string.Format("{0}|{1}", text ?? "", tooltip ?? "") :
string.Format("{0}|{1}|{2}|{3}", text ?? "", tooltip ?? "", iconName, pixelsPerPoint);
return TrTextContent(key, text, tooltip, LoadIconRequired(iconName));
}
public static GUIContent TrTextContent(string text, Texture icon)
{
return TrTextContent(text, null, icon);
}
public static GUIContent TrTextContentWithIcon(string text, Texture icon)
{
return TrTextContent(text, null, icon);
}
public static GUIContent TrTextContentWithIcon(string text, string iconName)
{
return TrTextContent(text, null, iconName);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, string iconName)
{
return TrTextContent(text, tooltip, iconName);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, Texture icon)
{
return TrTextContent(text, tooltip, icon);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, MessageType messageType)
{
return TrTextContent(text, tooltip, GetHelpIcon(messageType));
}
public static GUIContent TrTextContentWithIcon(string text, MessageType messageType)
{
return TrTextContentWithIcon(text, null, messageType);
}
internal static Texture2D LightenTexture(Texture2D texture)
{
if (!texture)
return texture;
Texture2D outTexture = new Texture2D(texture.width, texture.height);
var outColorArray = outTexture.GetPixels();
var colorArray = texture.GetPixels();
for (var i = 0; i < colorArray.Length; ++i)
outColorArray[i] = LightenColor(colorArray[i]);
outTexture.hideFlags = HideFlags.HideAndDontSave;
outTexture.SetPixels(outColorArray);
outTexture.Apply();
return outTexture;
}
internal static Color LightenColor(Color color)
{
Color.RGBToHSV(color, out var h, out _, out _);
var outColor = Color.HSVToRGB((h + 0.5f) % 1, 0f, 0.8f);
outColor.a = color.a;
return outColor;
}
public static GUIContent TrIconContent(string iconName, string tooltip = null)
{
return TrIconContent(iconName, tooltip, false);
}
internal static GUIContent TrIconContent(string iconName, string tooltip, bool lightenTexture)
{
string key = tooltip == null ? string.Format("{0}|{1}", iconName, pixelsPerPoint) :
string.Format("{0}|{1}|{2}", iconName, tooltip, pixelsPerPoint);
GUIContent gc = (GUIContent)s_IconGUIContents[key];
if (gc != null)
{
return gc;
}
gc = new GUIContent();
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
}
gc.image = LoadIconRequired(iconName);
if (lightenTexture && gc.image is Texture2D tex2D)
gc.image = LightenTexture(tex2D);
s_IconGUIContents[key] = gc;
return gc;
}
public static GUIContent TrIconContent(Texture icon, string tooltip = null)
{
GUIContent gc = (tooltip != null) ? (GUIContent)s_IconGUIContents[tooltip] : null;
if (gc != null)
{
return gc;
}
gc = new GUIContent { image = icon };
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
s_IconGUIContents[tooltip] = gc;
}
return gc;
}
[ExcludeFromDocs]
public static GUIContent TrTempContent(string t)
{
return TempContent(L10n.Tr(t));
}
[ExcludeFromDocs]
public static GUIContent[] TrTempContent(string[] texts)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(L10n.Tr(texts[i]));
return retval;
}
[ExcludeFromDocs]
public static GUIContent[] TrTempContent(string[] texts, string[] tooltips)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(L10n.Tr(texts[i]), L10n.Tr(tooltips[i]));
return retval;
}
internal static GUIContent TrIconContent<T>(string tooltip = null) where T : UnityObject
{
return TrIconContent(FindTexture(typeof(T)), tooltip);
}
public static float singleLineHeight => EditorGUI.kSingleLineHeight;
public static float standardVerticalSpacing => EditorGUI.kControlVerticalSpacing;
internal static SliderLabels sliderLabels = new SliderLabels();
internal static GUIContent TextContent(string textAndTooltip)
{
if (textAndTooltip == null)
textAndTooltip = "";
string key = textAndTooltip;
GUIContent gc = (GUIContent)s_TextGUIContents[key];
if (gc == null)
{
string[] strings = GetNameAndTooltipString(textAndTooltip);
gc = new GUIContent(strings[1]);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_TextGUIContents[key] = gc;
}
return gc;
}
internal static GUIContent TextContentWithIcon(string textAndTooltip, string icon)
{
if (textAndTooltip == null)
textAndTooltip = "";
if (icon == null)
icon = "";
string key = string.Format("{0}|{1}|{2}", textAndTooltip, icon, pixelsPerPoint);
GUIContent gc = (GUIContent)s_TextGUIContents[key];
if (gc == null)
{
string[] strings = GetNameAndTooltipString(textAndTooltip);
gc = new GUIContent(strings[1]) { image = LoadIconRequired(icon) };
// We want to catch missing icons so we can fix them (therefore using LoadIconRequired)
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_TextGUIContents[key] = gc;
}
return gc;
}
private static Color GetDefaultBackgroundColor()
{
float kViewBackgroundIntensity = isProSkin ? 0.22f : 0.76f;
return new Color(kViewBackgroundIntensity, kViewBackgroundIntensity, kViewBackgroundIntensity, 1f);
}
// [0] original name, [1] localized name, [2] localized tooltip
internal static string[] GetNameAndTooltipString(string nameAndTooltip)
{
string[] retval = new string[3];
string[] s1 = nameAndTooltip.Split('|');
switch (s1.Length)
{
case 0:
retval[0] = "";
retval[1] = "";
break;
case 1:
retval[0] = s1[0].Trim();
retval[1] = retval[0];
break;
case 2:
retval[0] = s1[0].Trim();
retval[1] = retval[0];
retval[2] = s1[1].Trim();
break;
default:
Debug.LogError("Error in Tooltips: Too many strings in line beginning with '" + s1[0] + "'");
break;
}
return retval;
}
internal static Texture2D LoadIconRequired(string name)
{
Texture2D tex = LoadIcon(name);
if (!tex)
Debug.LogErrorFormat("Unable to load the icon: '{0}'.\nNote that either full project path should be used (with extension) " +
"or just the icon name if the icon is located in the following location: '{1}' (without extension, since png is assumed)",
name, EditorResources.editorDefaultResourcesPath + EditorResources.iconsPath);
return tex;
}
// Automatically loads version of icon that matches current skin.
// Equivalent to Texture2DNamed in ObjectImages.cpp
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static Texture2D LoadIcon(string name)
{
return LoadIconForSkin(name, skinIndex);
}
static readonly List<string> k_UserSideSupportedImageExtensions = new List<string> {".png"};
// Attempts to load a higher resolution icon if needed
internal static Texture2D LoadGeneratedIconOrNormalIcon(string name)
{
Texture2D icon = null;
if (GUIUtility.pixelsPerPoint > 1.0f)
{
var imageExtension = Path.GetExtension(name);
if (k_UserSideSupportedImageExtensions.Contains(imageExtension))
{
var newName = $"{Path.GetFileNameWithoutExtension(name)}@2x{imageExtension}";
var dirName = Path.GetDirectoryName(name);
if (!string.IsNullOrEmpty(dirName))
newName = $"{dirName}/{newName}";
icon = InnerLoadGeneratedIconOrNormalIcon(newName);
}
else
{
icon = InnerLoadGeneratedIconOrNormalIcon(name + "@2x");
}
if (icon != null)
icon.pixelsPerPoint = 2.0f;
}
if (icon == null)
{
icon = InnerLoadGeneratedIconOrNormalIcon(name);
}
if (icon != null &&
!Mathf.Approximately(icon.pixelsPerPoint, GUIUtility.pixelsPerPoint) && //scaling are different
!Mathf.Approximately(GUIUtility.pixelsPerPoint % 1, 0)) //screen scaling is non-integer
{
icon.filterMode = FilterMode.Bilinear;
}
return icon;
}
// Takes a name that already includes d_ if dark skin version is desired.
// Equivalent to Texture2DSkinNamed in ObjectImages.cpp
static Texture2D InnerLoadGeneratedIconOrNormalIcon(string name)
{
Texture2D tex = Load(EditorResources.generatedIconsPath + name + ".asset") as Texture2D;
if (!tex)
{
tex = Load(EditorResources.iconsPath + name + ".png") as Texture2D;
}
if (!tex)
{
tex = Load(name) as Texture2D; // Allow users to specify their own project path to an icon (e.g see EditorWindowTitleAttribute)
}
return tex;
}
internal static Texture2D LoadIconForSkin(string name, int in_SkinIndex)
{
if (String.IsNullOrEmpty(name))
return null;
if (in_SkinIndex == 0)
return LoadGeneratedIconOrNormalIcon(name);
//Remap file name for dark skin
var newName = "d_" + Path.GetFileName(name);
var dirName = Path.GetDirectoryName(name);
if (!string.IsNullOrEmpty(dirName))
newName = $"{dirName}/{newName}";
Texture2D tex = LoadGeneratedIconOrNormalIcon(newName);
if (!tex)
tex = LoadGeneratedIconOrNormalIcon(name);
return tex;
}
[UsedByNativeCode]
internal static string GetIconPathFromAttribute(Type type)
{
if (Attribute.IsDefined(type, typeof(IconAttribute)))
{
var attributes = type.GetCustomAttributes(typeof(IconAttribute), true);
for (int i = 0, c = attributes.Length; i < c; i++)
if (attributes[i] is IconAttribute)
return ((IconAttribute)attributes[i]).path;
}
return null;
}
internal static GUIContent IconContent<T>(string text = null) where T : UnityObject
{
return IconContent(FindTexture(typeof(T)), text);
}
[ExcludeFromDocs]
public static GUIContent IconContent(string name)
{
return IconContent(name, null, true);
}
internal static GUIContent IconContent(string name, bool logError)
{
return IconContent(name, null, logError);
}
public static GUIContent IconContent(string name, [DefaultValue("null")] string text)
{
return IconContent(name, text, true);
}
internal static GUIContent IconContent(string name, [DefaultValue("null")] string text, bool logError)
{
GUIContent gc = (GUIContent)s_IconGUIContents[name];
if (gc != null)
{
return gc;
}
gc = new GUIContent();
if (text != null)
{
string[] strings = GetNameAndTooltipString(text);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
}
gc.image = logError ? LoadIconRequired(name) : LoadIcon(name);
s_IconGUIContents[name] = gc;
return gc;
}
static GUIContent IconContent(Texture icon, string text)
{
GUIContent gc = text != null ? (GUIContent)s_IconGUIContents[text] : null;
if (gc != null)
{
return gc;
}
gc = new GUIContent { image = icon };
if (text != null)
{
string[] strings = GetNameAndTooltipString(text);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_IconGUIContents[text] = gc;
}
return gc;
}
// Is the user currently using the pro skin? (RO)
public static bool isProSkin => skinIndex == 1;
internal static void Internal_SwitchSkin()
{
skinIndex = 1 - skinIndex;
}
// Return a GUIContent object with the name and icon of an Object.
public static GUIContent ObjectContent(UnityObject obj, Type type)
{
return ObjectContent(obj, type, ReferenceEquals(obj, null) ? 0 : obj.GetInstanceID());
}
internal static GUIContent ObjectContent(UnityObject obj, Type type, bool showNullIcon)
{
return ObjectContent(obj, type, ReferenceEquals(obj, null) ? 0 : obj.GetInstanceID(), showNullIcon);
}
internal static GUIContent ObjectContent(UnityObject obj, Type type, int instanceID, bool showNullIcon = true)
{
if (obj)
{
s_ObjectContent.text = GetObjectNameWithInfo(obj);
s_ObjectContent.image = AssetPreview.GetMiniThumbnail(obj);
}
else if (type != null)
{
s_ObjectContent.text = GetTypeNameWithInfo(type.Name, instanceID);
s_ObjectContent.image = showNullIcon ? AssetPreview.GetMiniTypeThumbnail(type) : null;
}
else
{
s_ObjectContent.text = "<no type>";
s_ObjectContent.image = null;
}
return s_ObjectContent;
}
internal static GUIContent ObjectContent(UnityObject obj, Type type, SerializedProperty property, EditorGUI.ObjectFieldValidator validator = null)
{
if (validator == null)
validator = EditorGUI.ValidateObjectFieldAssignment;
GUIContent temp;
// If obj or objType are both null, we have to rely on
// property.objectReferenceStringValue to display None/Missing and the
// correct type. But if not, EditorGUIUtility.ObjectContent is more reliable.