-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathFileBrowser.cs
2235 lines (1818 loc) · 60.8 KB
/
FileBrowser.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
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace SimpleFileBrowser
{
public class FileBrowser : MonoBehaviour, IListViewAdapter
{
public enum Permission { Denied = 0, Granted = 1, ShouldAsk = 2 };
#region Structs
#pragma warning disable 0649
[Serializable]
private struct FiletypeIcon
{
public string extension;
public Sprite icon;
}
[Serializable]
private struct QuickLink
{
#if UNITY_EDITOR || ( !UNITY_WSA && !UNITY_WSA_10_0 )
public Environment.SpecialFolder target;
#endif
public string name;
public Sprite icon;
}
#pragma warning restore 0649
#endregion
#region Inner Classes
public class Filter
{
public readonly string name;
public readonly HashSet<string> extensions;
public readonly string defaultExtension;
internal Filter( string name )
{
this.name = name;
extensions = null;
defaultExtension = null;
}
public Filter( string name, string extension )
{
this.name = name;
extension = extension.ToLowerInvariant();
extensions = new HashSet<string>() { extension };
defaultExtension = extension;
}
public Filter( string name, params string[] extensions )
{
this.name = name;
for( int i = 0; i < extensions.Length; i++ )
extensions[i] = extensions[i].ToLowerInvariant();
this.extensions = new HashSet<string>( extensions );
defaultExtension = extensions[0];
}
public override string ToString()
{
string result = string.Empty;
if( name != null )
result += name;
if( extensions != null )
{
if( name != null )
result += " (";
int index = 0;
foreach( string extension in extensions )
{
if( index++ > 0 )
result += ", " + extension;
else
result += extension;
}
if( name != null )
result += ")";
}
return result;
}
}
#endregion
#region Constants
private const string ALL_FILES_FILTER_TEXT = "All Files (.*)";
private const string FOLDERS_FILTER_TEXT = "Folders";
private string DEFAULT_PATH;
private const int FILENAME_INPUT_FIELD_MAX_FILE_COUNT = 7;
#if !UNITY_EDITOR && UNITY_ANDROID
private const string SAF_PICK_FOLDER_QUICK_LINK_TEXT = "Pick Folder";
private const string SAF_PICK_FOLDER_QUICK_LINK_PATH = "SAF_PICK_FOLDER";
#endif
#endregion
#region Static Variables
public static bool IsOpen { get; private set; }
public static bool Success { get; private set; }
public static string[] Result { get; private set; }
private static bool m_askPermissions = true;
public static bool AskPermissions
{
get { return m_askPermissions; }
set { m_askPermissions = value; }
}
private static bool m_singleClickMode = false;
public static bool SingleClickMode
{
get { return m_singleClickMode; }
set { m_singleClickMode = value; }
}
private static FileBrowser m_instance = null;
private static FileBrowser Instance
{
get
{
if( !m_instance )
{
m_instance = Instantiate( Resources.Load<GameObject>( "SimpleFileBrowserCanvas" ) ).GetComponent<FileBrowser>();
DontDestroyOnLoad( m_instance.gameObject );
m_instance.gameObject.SetActive( false );
}
return m_instance;
}
}
#endregion
#region Variables
#pragma warning disable 0649
[Header( "Settings" )]
[SerializeField]
internal Color normalFileColor = Color.white;
[SerializeField]
internal Color hoveredFileColor = new Color32( 225, 225, 255, 255 );
[SerializeField]
internal Color selectedFileColor = new Color32( 0, 175, 255, 255 );
[SerializeField]
internal Color wrongFilenameColor = new Color32( 255, 100, 100, 255 );
[SerializeField]
internal int minWidth = 380;
[SerializeField]
internal int minHeight = 300;
[SerializeField]
private float narrowScreenWidth = 380f;
[SerializeField]
private float quickLinksMaxWidthPercentage = 0.4f;
[SerializeField]
private string[] excludeExtensions;
#pragma warning disable 0414
[SerializeField]
private QuickLink[] quickLinks;
private static bool quickLinksInitialized;
#pragma warning restore 0414
private readonly HashSet<string> excludedExtensionsSet = new HashSet<string>();
private readonly HashSet<string> addedQuickLinksSet = new HashSet<string>();
[SerializeField]
private bool generateQuickLinksForDrives = true;
[SerializeField]
private bool contextMenuShowDeleteButton = true;
[SerializeField]
private bool contextMenuShowRenameButton = true;
[SerializeField]
private bool showResizeCursor = true;
[Header( "Icons" )]
[SerializeField]
private Sprite folderIcon;
[SerializeField]
private Sprite driveIcon;
[SerializeField]
private Sprite defaultIcon;
[SerializeField]
private FiletypeIcon[] filetypeIcons;
private Dictionary<string, Sprite> filetypeToIcon;
[SerializeField]
internal Sprite multiSelectionToggleOffIcon;
[SerializeField]
internal Sprite multiSelectionToggleOnIcon;
[Header( "Internal References" )]
[SerializeField]
private FileBrowserMovement window;
private RectTransform windowTR;
[SerializeField]
private RectTransform topViewNarrowScreen;
[SerializeField]
private RectTransform middleView;
private Vector2 middleViewOriginalPosition;
private Vector2 middleViewOriginalSize;
[SerializeField]
private RectTransform middleViewQuickLinks;
private Vector2 middleViewQuickLinksOriginalSize;
[SerializeField]
private RectTransform middleViewFiles;
[SerializeField]
private RectTransform middleViewSeparator;
[SerializeField]
private FileBrowserItem itemPrefab;
private readonly List<FileBrowserItem> allItems = new List<FileBrowserItem>( 16 );
private float itemHeight;
[SerializeField]
private FileBrowserQuickLink quickLinkPrefab;
[SerializeField]
private Text titleText;
[SerializeField]
private Button backButton;
[SerializeField]
private Button forwardButton;
[SerializeField]
private Button upButton;
[SerializeField]
private InputField pathInputField;
[SerializeField]
private RectTransform pathInputFieldSlotTop;
[SerializeField]
private RectTransform pathInputFieldSlotBottom;
[SerializeField]
private InputField searchInputField;
[SerializeField]
private RectTransform quickLinksContainer;
[SerializeField]
private RectTransform filesContainer;
[SerializeField]
private ScrollRect filesScrollRect;
[SerializeField]
private RecycledListView listView;
[SerializeField]
private InputField filenameInputField;
[SerializeField]
private Text filenameInputFieldOverlayText;
[SerializeField]
private Image filenameImage;
[SerializeField]
private Dropdown filtersDropdown;
[SerializeField]
private RectTransform filtersDropdownContainer;
[SerializeField]
private Text filterItemTemplate;
[SerializeField]
private Toggle showHiddenFilesToggle;
[SerializeField]
private Text submitButtonText;
[SerializeField]
private RectTransform moreOptionsContextMenuPosition;
[SerializeField]
private FileBrowserRenamedItem renameItem;
[SerializeField]
private FileBrowserContextMenu contextMenu;
[SerializeField]
private FileBrowserDeleteConfirmationPanel deleteConfirmationPanel;
[SerializeField]
private FileBrowserCursorHandler resizeCursorHandler;
#pragma warning restore 0649
internal RectTransform rectTransform;
private Canvas canvas;
private FileAttributes ignoredFileAttributes = FileAttributes.System;
private FileSystemEntry[] allFileEntries;
private readonly List<FileSystemEntry> validFileEntries = new List<FileSystemEntry>();
private readonly List<int> selectedFileEntries = new List<int>( 4 );
private readonly List<string> pendingFileEntrySelection = new List<string>();
#pragma warning disable 0414 // Value is assigned but never used on Android & iOS
private int multiSelectionPivotFileEntry;
#pragma warning restore 0414
private StringBuilder multiSelectionFilenameBuilder;
private readonly List<Filter> filters = new List<Filter>();
private Filter allFilesFilter;
private bool showAllFilesFilter = true;
private int currentPathIndex = -1;
private readonly List<string> pathsFollowed = new List<string>();
private bool canvasDimensionsChanged;
// Required in RefreshFiles() function
private PointerEventData nullPointerEventData;
#endregion
#region Properties
private string m_currentPath = string.Empty;
private string CurrentPath
{
get { return m_currentPath; }
set
{
#if !UNITY_EDITOR && UNITY_ANDROID
if( !FileBrowserHelpers.ShouldUseSAF )
#endif
if( value != null )
value = GetPathWithoutTrailingDirectorySeparator( value.Trim() );
if( string.IsNullOrEmpty( value ) )
{
pathInputField.text = m_currentPath;
return;
}
if( m_currentPath != value )
{
if( !FileBrowserHelpers.DirectoryExists( value ) )
{
pathInputField.text = m_currentPath;
return;
}
m_currentPath = value;
pathInputField.text = m_currentPath;
if( currentPathIndex == -1 || pathsFollowed[currentPathIndex] != m_currentPath )
{
currentPathIndex++;
if( currentPathIndex < pathsFollowed.Count )
{
pathsFollowed[currentPathIndex] = value;
for( int i = pathsFollowed.Count - 1; i >= currentPathIndex + 1; i-- )
pathsFollowed.RemoveAt( i );
}
else
pathsFollowed.Add( m_currentPath );
}
backButton.interactable = currentPathIndex > 0;
forwardButton.interactable = currentPathIndex < pathsFollowed.Count - 1;
#if !UNITY_EDITOR && UNITY_ANDROID
if( !FileBrowserHelpers.ShouldUseSAF )
#endif
upButton.interactable = Directory.GetParent( m_currentPath ) != null;
m_searchString = string.Empty;
searchInputField.text = m_searchString;
multiSelectionPivotFileEntry = 0;
filesScrollRect.verticalNormalizedPosition = 1;
filenameImage.color = Color.white;
if( m_folderSelectMode )
{
filenameInputField.text = string.Empty;
filenameInputField.interactable = true;
}
}
m_multiSelectionToggleSelectionMode = false;
RefreshFiles( true );
}
}
private string m_searchString = string.Empty;
private string SearchString
{
get
{
return m_searchString;
}
set
{
if( m_searchString != value )
{
m_searchString = value;
searchInputField.text = m_searchString;
RefreshFiles( false );
}
}
}
private bool m_acceptNonExistingFilename = false;
private bool AcceptNonExistingFilename
{
get { return m_acceptNonExistingFilename; }
set { m_acceptNonExistingFilename = value; }
}
private bool m_folderSelectMode = false;
private bool FolderSelectMode
{
get
{
return m_folderSelectMode;
}
set
{
if( m_folderSelectMode != value )
{
m_folderSelectMode = value;
if( m_folderSelectMode )
{
filtersDropdown.options[0].text = FOLDERS_FILTER_TEXT;
filtersDropdown.value = 0;
filtersDropdown.RefreshShownValue();
filtersDropdown.interactable = false;
}
else
{
filtersDropdown.options[0].text = filters[0].ToString();
filtersDropdown.interactable = true;
}
Text placeholder = filenameInputField.placeholder as Text;
if( placeholder )
placeholder.gameObject.SetActive( !m_folderSelectMode );
}
}
}
private bool m_allowMultiSelection;
internal bool AllowMultiSelection
{
get { return m_allowMultiSelection; }
private set { m_allowMultiSelection = value; }
}
private bool m_multiSelectionToggleSelectionMode;
internal bool MultiSelectionToggleSelectionMode
{
get { return m_multiSelectionToggleSelectionMode; }
set
{
if( m_multiSelectionToggleSelectionMode != value )
{
m_multiSelectionToggleSelectionMode = value;
for( int i = 0; i < allItems.Count; i++ )
{
if( allItems[i].gameObject.activeSelf )
allItems[i].SetSelected( selectedFileEntries.Contains( allItems[i].Position ) );
}
}
}
}
private string Title
{
get { return titleText.text; }
set { titleText.text = value; }
}
private string SubmitButtonText
{
get { return submitButtonText.text; }
set { submitButtonText.text = value; }
}
#endregion
#region Delegates
public delegate void OnSuccess( string[] paths );
public delegate void OnCancel();
#if !UNITY_EDITOR && UNITY_ANDROID
public delegate void DirectoryPickCallback( string rawUri, string name );
#endif
private OnSuccess onSuccess;
private OnCancel onCancel;
#endregion
#region Messages
private void Awake()
{
m_instance = this;
rectTransform = (RectTransform) transform;
windowTR = (RectTransform) window.transform;
canvas = GetComponent<Canvas>();
middleViewOriginalPosition = middleView.anchoredPosition;
middleViewOriginalSize = middleView.sizeDelta;
middleViewQuickLinksOriginalSize = middleViewQuickLinks.sizeDelta;
itemHeight = ( (RectTransform) itemPrefab.transform ).sizeDelta.y;
nullPointerEventData = new PointerEventData( null );
#if !UNITY_EDITOR && ( UNITY_ANDROID || UNITY_IOS || UNITY_WSA || UNITY_WSA_10_0 )
DEFAULT_PATH = Application.persistentDataPath;
#else
DEFAULT_PATH = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments );
#endif
#if !UNITY_EDITOR && UNITY_ANDROID
if( FileBrowserHelpers.ShouldUseSAF )
{
// These UI elements have no use in Storage Access Framework mode (Android 10+)
upButton.gameObject.SetActive( false );
pathInputField.gameObject.SetActive( false );
showHiddenFilesToggle.gameObject.SetActive( false );
}
#endif
InitializeFiletypeIcons();
filetypeIcons = null;
SetExcludedExtensions( excludeExtensions );
excludeExtensions = null;
backButton.interactable = false;
forwardButton.interactable = false;
upButton.interactable = false;
filenameInputField.onValidateInput += OnValidateFilenameInput;
filenameInputField.onValueChanged.AddListener( OnFilenameInputChanged );
allFilesFilter = new Filter( ALL_FILES_FILTER_TEXT );
filters.Add( allFilesFilter );
window.Initialize( this );
listView.SetAdapter( this );
if( !showResizeCursor )
Destroy( resizeCursorHandler );
}
private void OnRectTransformDimensionsChange()
{
canvasDimensionsChanged = true;
}
private void LateUpdate()
{
if( canvasDimensionsChanged )
{
canvasDimensionsChanged = false;
Vector2 windowSize = windowTR.sizeDelta;
EnsureWindowIsWithinBounds();
if( windowTR.sizeDelta != windowSize )
OnWindowDimensionsChanged( windowTR.sizeDelta );
deleteConfirmationPanel.OnCanvasDimensionsChanged( rectTransform.sizeDelta );
if( contextMenu.gameObject.activeSelf )
contextMenu.Hide();
}
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WSA || UNITY_WSA_10_0
// Handle keyboard shortcuts
if( !EventSystem.current.currentSelectedGameObject )
{
if( Input.GetKeyDown( KeyCode.Delete ) )
DeleteSelectedFiles();
if( Input.GetKeyDown( KeyCode.F2 ) )
RenameSelectedFile();
if( Input.GetKeyDown( KeyCode.A ) && ( Input.GetKey( KeyCode.LeftControl ) || Input.GetKey( KeyCode.LeftCommand ) ) )
SelectAllFiles();
}
#endif
// 2 Text objects are used in the filename input field:
// filenameInputField.textComponent: visible when editing the text, has Horizontal Overflow set to Wrap (cuts out words, ugly)
// filenameInputFieldOverlayText: visible when not editing the text, has Horizontal Overflow set to Overflow (doesn't cut out words)
if( EventSystem.current.currentSelectedGameObject == filenameInputField.gameObject )
{
if( filenameInputFieldOverlayText.enabled )
{
filenameInputFieldOverlayText.enabled = false;
Color c = filenameInputField.textComponent.color;
c.a = 1f;
filenameInputField.textComponent.color = c;
}
}
else if( !filenameInputFieldOverlayText.enabled )
{
filenameInputFieldOverlayText.enabled = true;
Color c = filenameInputField.textComponent.color;
c.a = 0f;
filenameInputField.textComponent.color = c;
}
}
private void OnApplicationFocus( bool focus )
{
if( !focus )
PersistFileEntrySelection();
else
RefreshFiles( true );
}
#endregion
#region Interface Methods
OnItemClickedHandler IListViewAdapter.OnItemClicked { get { return null; } set { } }
int IListViewAdapter.Count { get { return validFileEntries.Count; } }
float IListViewAdapter.ItemHeight { get { return itemHeight; } }
ListItem IListViewAdapter.CreateItem()
{
FileBrowserItem item = (FileBrowserItem) Instantiate( itemPrefab, filesContainer, false );
item.SetFileBrowser( this );
allItems.Add( item );
return item;
}
void IListViewAdapter.SetItemContent( ListItem item )
{
FileBrowserItem file = (FileBrowserItem) item;
FileSystemEntry fileInfo = validFileEntries[item.Position];
file.SetFile( GetIconForFileEntry( fileInfo ), fileInfo.Name, fileInfo.IsDirectory );
file.SetSelected( selectedFileEntries.Contains( file.Position ) );
file.SetHidden( ( fileInfo.Attributes & FileAttributes.Hidden ) == FileAttributes.Hidden );
}
#endregion
#region Initialization Functions
private void InitializeFiletypeIcons()
{
filetypeToIcon = new Dictionary<string, Sprite>();
for( int i = 0; i < filetypeIcons.Length; i++ )
{
FiletypeIcon thisIcon = filetypeIcons[i];
filetypeToIcon[thisIcon.extension] = thisIcon.icon;
}
}
private void InitializeQuickLinks()
{
Vector2 anchoredPos = new Vector2( 0f, -quickLinksContainer.sizeDelta.y );
#if !UNITY_EDITOR && UNITY_ANDROID
if( !FileBrowserHelpers.ShouldUseSAF )
{
#endif
if( generateQuickLinksForDrives )
{
#if !UNITY_EDITOR && UNITY_ANDROID
string drivesList = FileBrowserHelpers.AJC.CallStatic<string>( "GetExternalDrives" );
if( drivesList != null && drivesList.Length > 0 )
{
bool defaultPathInitialized = false;
int driveIndex = 1;
string[] drives = drivesList.Split( ':' );
for( int i = 0; i < drives.Length; i++ )
{
try
{
//string driveName = new DirectoryInfo( drives[i] ).Name;
//if( driveName.Length <= 1 )
//{
// try
// {
// driveName = Directory.GetParent( drives[i] ).Name + "/" + driveName;
// }
// catch
// {
// driveName = "Drive " + driveIndex++;
// }
//}
string driveName;
if( !defaultPathInitialized )
{
DEFAULT_PATH = drives[i];
defaultPathInitialized = true;
driveName = "Primary Drive";
}
else
{
if( driveIndex == 1 )
driveName = "External Drive";
else
driveName = "External Drive " + driveIndex;
driveIndex++;
}
AddQuickLink( driveIcon, driveName, drives[i], ref anchoredPos );
}
catch { }
}
}
#elif !UNITY_EDITOR && ( UNITY_IOS || UNITY_WSA || UNITY_WSA_10_0 )
AddQuickLink( driveIcon, "Files", Application.persistentDataPath, ref anchoredPos );
#else
string[] drives = Directory.GetLogicalDrives();
for( int i = 0; i < drives.Length; i++ )
{
if( string.IsNullOrEmpty( drives[i] ) )
continue;
#if UNITY_STANDALONE_OSX
// There are a number of useless drives listed on Mac OS, filter them
if( drives[i] == "/" )
AddQuickLink( driveIcon, "Root", drives[i], ref anchoredPos );
else if( drives[i].StartsWith( "/Volumes/" ) && drives[i] != "/Volumes/Recovery" )
AddQuickLink( driveIcon, drives[i].Substring( drives[i].LastIndexOf( '/' ) + 1 ), drives[i], ref anchoredPos );
#else
AddQuickLink( driveIcon, drives[i], drives[i], ref anchoredPos );
#endif
}
#if UNITY_STANDALONE_OSX
// Add a quick link for user directory on Mac OS
string userDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments );
if( !string.IsNullOrEmpty( userDirectory ) )
AddQuickLink( driveIcon, userDirectory.Substring( userDirectory.LastIndexOf( '/' ) + 1 ), userDirectory, ref anchoredPos );
#endif
#endif
}
#if UNITY_EDITOR || ( !UNITY_ANDROID && !UNITY_WSA && !UNITY_WSA_10_0 )
for( int i = 0; i < quickLinks.Length; i++ )
{
QuickLink quickLink = quickLinks[i];
string quickLinkPath = Environment.GetFolderPath( quickLink.target );
#if UNITY_STANDALONE_OSX
// Documents folder must be appended manually on Mac OS
if( quickLink.target == Environment.SpecialFolder.MyDocuments && !string.IsNullOrEmpty( quickLinkPath ) )
quickLinkPath = Path.Combine( quickLinkPath, "Documents" );
#endif
AddQuickLink( quickLink.icon, quickLink.name, quickLinkPath, ref anchoredPos );
}
quickLinks = null;
#endif
#if !UNITY_EDITOR && UNITY_ANDROID
}
else
{
AddQuickLink( driveIcon, SAF_PICK_FOLDER_QUICK_LINK_TEXT, SAF_PICK_FOLDER_QUICK_LINK_PATH, ref anchoredPos );
try
{
FetchPersistedSAFQuickLinks( ref anchoredPos );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
#endif
quickLinksContainer.sizeDelta = new Vector2( 0f, -anchoredPos.y );
}
#endregion
#region Button Events
public void OnBackButtonPressed()
{
if( currentPathIndex > 0 )
CurrentPath = pathsFollowed[--currentPathIndex];
}
public void OnForwardButtonPressed()
{
if( currentPathIndex < pathsFollowed.Count - 1 )
CurrentPath = pathsFollowed[++currentPathIndex];
}
public void OnUpButtonPressed()
{
#if !UNITY_EDITOR && UNITY_ANDROID
if( FileBrowserHelpers.ShouldUseSAF )
return;
#endif
DirectoryInfo parentPath = Directory.GetParent( m_currentPath );
if( parentPath != null )
CurrentPath = parentPath.FullName;
}
public void OnMoreOptionsButtonClicked()
{
ShowContextMenuAt( rectTransform.InverseTransformPoint( moreOptionsContextMenuPosition.position ), true );
}
internal void OnContextMenuTriggered()
{
filesScrollRect.velocity = Vector2.zero;
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle( rectTransform, Input.mousePosition, canvas.worldCamera, out position );
ShowContextMenuAt( position, false );
}
private void ShowContextMenuAt( Vector2 position, bool isMoreOptionsMenu )
{
if( string.IsNullOrEmpty( m_currentPath ) )
return;
bool selectAllButtonVisible = isMoreOptionsMenu && m_allowMultiSelection && validFileEntries.Count > 0;
bool deselectAllButtonVisible = isMoreOptionsMenu && selectedFileEntries.Count > 1;
bool deleteButtonVisible = contextMenuShowDeleteButton && selectedFileEntries.Count > 0;
bool renameButtonVisible = contextMenuShowRenameButton && selectedFileEntries.Count == 1;
contextMenu.Show( selectAllButtonVisible, deselectAllButtonVisible, deleteButtonVisible, renameButtonVisible, position, isMoreOptionsMenu );
}
public void OnSubmitButtonClicked()
{
string filenameInput = filenameInputField.text.Trim();
if( filenameInput.Length == 0 )
{
if( m_folderSelectMode )
OnOperationSuccessful( new string[1] { m_currentPath } );
else
filenameImage.color = wrongFilenameColor;
return;
}
if( m_allowMultiSelection && selectedFileEntries.Count > 1 )
{
// When multiple files are selected via file browser UI, filenameInputField is not interactable and will show
// only the first FILENAME_INPUT_FIELD_MAX_FILE_COUNT entries for performance reasons. We should iterate over
// selectedFileEntries instead of filenameInputField
// Beforehand, check if a folder is selected in file selection mode. If so, open that directory
if( !m_folderSelectMode )
{
for( int i = 0; i < selectedFileEntries.Count; i++ )
{
if( validFileEntries[selectedFileEntries[i]].IsDirectory )
{
CurrentPath = validFileEntries[selectedFileEntries[i]].Path;
return;
}
}
}
string[] result = new string[selectedFileEntries.Count];
for( int i = 0; i < selectedFileEntries.Count; i++ )
result[i] = validFileEntries[selectedFileEntries[i]].Path;
OnOperationSuccessful( result );
}
else
{
// When multiple files aren't selected via file browser UI, we must consider the rare case where user manually enters
// multiple filenames to filenameInputField in format "file1" "file2" and so on. So, we must parse filenameInputField
// In the first iteration, verify that all filenames entered to the input field are valid
// ExtractFilenameFromInput doesn't use Substring, so this iteration is GC-free
int fileCount = 0;
int startIndex = 0, nextStartIndex;
while( startIndex < filenameInput.Length )
{
int filenameLength = ExtractFilenameFromInput( filenameInput, ref startIndex, out nextStartIndex );
if( filenameLength == 0 )
continue;
if( m_acceptNonExistingFilename )
fileCount++;
else
{
int fileEntryIndex = FilenameInputToFileEntryIndex( filenameInput, startIndex, filenameLength );
if( fileEntryIndex < 0 )
{
// File doesn't exist
filenameImage.color = wrongFilenameColor;
return;
}
if( !validFileEntries[fileEntryIndex].IsDirectory )
fileCount++;
else
{
if( m_folderSelectMode )
fileCount++;
else
{
// Selected a directory in file selection mode, open that directory
CurrentPath = validFileEntries[fileEntryIndex].Path;
return;
}
}
}
startIndex = nextStartIndex;
}
if( fileCount == 0 )
{
filenameImage.color = wrongFilenameColor;
return;
}
// In the second iteration, extract filenames from the input field
string[] result = new string[fileCount];
startIndex = 0;
fileCount = 0;
while( startIndex < filenameInput.Length )
{
int filenameLength = ExtractFilenameFromInput( filenameInput, ref startIndex, out nextStartIndex );
if( filenameLength == 0 )
continue;
int fileEntryIndex = FilenameInputToFileEntryIndex( filenameInput, startIndex, filenameLength );
if( fileEntryIndex >= 0 )
{
// This is an existing file
result[fileCount++] = validFileEntries[fileEntryIndex].Path;
}
else
{
// This is a nonexisting file
string filename = filenameInput.Substring( startIndex, filenameLength );
if( !m_folderSelectMode && filters[filtersDropdown.value].defaultExtension != null )
{
// In file selection mode, make sure that nonexisting files' extensions match one of the required extensions
string fileExtension = Path.GetExtension( filename );
if( string.IsNullOrEmpty( fileExtension ) || !filters[filtersDropdown.value].extensions.Contains( fileExtension.ToLowerInvariant() ) )
filename = Path.ChangeExtension( filename, filters[filtersDropdown.value].defaultExtension );
}
#if !UNITY_EDITOR && UNITY_ANDROID
if( FileBrowserHelpers.ShouldUseSAF )
{
if( m_folderSelectMode )
result[fileCount++] = FileBrowserHelpers.CreateFolderInDirectory( m_currentPath, filename );
else
result[fileCount++] = FileBrowserHelpers.CreateFileInDirectory( m_currentPath, filename );
}
else