aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtUtils.java
blob: 93cd2da1e383cf5ef7f769e26b6bf57a0abf26a7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.eclipse.org/org/documents/epl-v10.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ide.eclipse.adt;

import static com.android.SdkConstants.TOOLS_PREFIX;
import static com.android.SdkConstants.TOOLS_URI;
import static org.eclipse.ui.IWorkbenchPage.MATCH_INPUT;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.sdklib.SdkVersionInfo;
import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.IProjectFilter;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.resources.ResourceFolderType;
import com.android.resources.ResourceType;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.repository.PkgProps;
import com.android.utils.XmlUtils;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IURIEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;


/** Utility methods for ADT */
@SuppressWarnings("restriction") // WST API
public class AdtUtils {
    /**
     * Creates a Java class name out of the given string, if possible. For
     * example, "My Project" becomes "MyProject", "hello" becomes "Hello",
     * "Java's" becomes "Java", and so on.
     *
     * @param string the string to be massaged into a Java class
     * @return the string as a Java class, or null if a class name could not be
     *         extracted
     */
    @Nullable
    public static String extractClassName(@NonNull String string) {
        StringBuilder sb = new StringBuilder(string.length());
        int n = string.length();

        int i = 0;
        for (; i < n; i++) {
            char c = Character.toUpperCase(string.charAt(i));
            if (Character.isJavaIdentifierStart(c)) {
                sb.append(c);
                i++;
                break;
            }
        }
        if (sb.length() > 0) {
            for (; i < n; i++) {
                char c = string.charAt(i);
                if (Character.isJavaIdentifierPart(c)) {
                    sb.append(c);
                }
            }

            return sb.toString();
        }

        return null;
    }

    /**
     * Strips off the last file extension from the given filename, e.g.
     * "foo.backup.diff" will be turned into "foo.backup".
     * <p>
     * Note that dot files (e.g. ".profile") will be left alone.
     *
     * @param filename the filename to be stripped
     * @return the filename without the last file extension.
     */
    public static String stripLastExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex > 0) { // > 0 instead of != -1: Treat dot files (e.g. .profile) differently
            return filename.substring(0, dotIndex);
        } else {
            return filename;
        }
    }

    /**
     * Strips off all extensions from the given filename, e.g. "foo.9.png" will
     * be turned into "foo".
     * <p>
     * Note that dot files (e.g. ".profile") will be left alone.
     *
     * @param filename the filename to be stripped
     * @return the filename without any file extensions
     */
    public static String stripAllExtensions(String filename) {
        int dotIndex = filename.indexOf('.');
        if (dotIndex > 0) { // > 0 instead of != -1: Treat dot files (e.g. .profile) differently
            return filename.substring(0, dotIndex);
        } else {
            return filename;
        }
    }

    /**
     * Strips the given suffix from the given string, provided that the string ends with
     * the suffix.
     *
     * @param string the full string to strip from
     * @param suffix the suffix to strip out
     * @return the string without the suffix at the end
     */
    public static String stripSuffix(@NonNull String string, @NonNull String suffix) {
        if (string.endsWith(suffix)) {
            return string.substring(0, string.length() - suffix.length());
        }

        return string;
    }

    /**
     * Capitalizes the string, i.e. transforms the initial [a-z] into [A-Z].
     * Returns the string unmodified if the first character is not [a-z].
     *
     * @param str The string to capitalize.
     * @return The capitalized string
     */
    public static String capitalize(String str) {
        if (str == null || str.length() < 1 || Character.isUpperCase(str.charAt(0))) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(Character.toUpperCase(str.charAt(0)));
        sb.append(str.substring(1));
        return sb.toString();
    }

    /**
     * Converts a CamelCase word into an underlined_word
     *
     * @param string the CamelCase version of the word
     * @return the underlined version of the word
     */
    public static String camelCaseToUnderlines(String string) {
        if (string.isEmpty()) {
            return string;
        }

        StringBuilder sb = new StringBuilder(2 * string.length());
        int n = string.length();
        boolean lastWasUpperCase = Character.isUpperCase(string.charAt(0));
        for (int i = 0; i < n; i++) {
            char c = string.charAt(i);
            boolean isUpperCase = Character.isUpperCase(c);
            if (isUpperCase && !lastWasUpperCase) {
                sb.append('_');
            }
            lastWasUpperCase = isUpperCase;
            c = Character.toLowerCase(c);
            sb.append(c);
        }

        return sb.toString();
    }

    /**
     * Converts an underlined_word into a CamelCase word
     *
     * @param string the underlined word to convert
     * @return the CamelCase version of the word
     */
    public static String underlinesToCamelCase(String string) {
        StringBuilder sb = new StringBuilder(string.length());
        int n = string.length();

        int i = 0;
        boolean upcaseNext = true;
        for (; i < n; i++) {
            char c = string.charAt(i);
            if (c == '_') {
                upcaseNext = true;
            } else {
                if (upcaseNext) {
                    c = Character.toUpperCase(c);
                }
                upcaseNext = false;
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
     * Returns the current editor (the currently visible and active editor), or null if
     * not found
     *
     * @return the current editor, or null
     */
    public static IEditorPart getActiveEditor() {
        IWorkbenchWindow window = getActiveWorkbenchWindow();
        if (window != null) {
            IWorkbenchPage page = window.getActivePage();
            if (page != null) {
                return page.getActiveEditor();
            }
        }

        return null;
    }

    /**
     * Returns the current active workbench, or null if not found
     *
     * @return the current window, or null
     */
    @Nullable
    public static IWorkbenchWindow getActiveWorkbenchWindow() {
        IWorkbench workbench = PlatformUI.getWorkbench();
        IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
        if (window == null) {
            IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
            if (windows.length > 0) {
                window = windows[0];
            }
        }

        return window;
    }

    /**
     * Returns the current active workbench page, or null if not found
     *
     * @return the current page, or null
     */
    @Nullable
    public static IWorkbenchPage getActiveWorkbenchPage() {
        IWorkbenchWindow window = getActiveWorkbenchWindow();
        if (window != null) {
            IWorkbenchPage page = window.getActivePage();
            if (page == null) {
                IWorkbenchPage[] pages = window.getPages();
                if (pages.length > 0) {
                    page = pages[0];
                }
            }

            return page;
        }

        return null;
    }

    /**
     * Returns the current active workbench part, or null if not found
     *
     * @return the current active workbench part, or null
     */
    @Nullable
    public static IWorkbenchPart getActivePart() {
        IWorkbenchWindow window = getActiveWorkbenchWindow();
        if (window != null) {
            IWorkbenchPage activePage = window.getActivePage();
            if (activePage != null) {
                return activePage.getActivePart();
            }
        }
        return null;
    }

    /**
     * Returns the current text editor (the currently visible and active editor), or null
     * if not found.
     *
     * @return the current text editor, or null
     */
    public static ITextEditor getActiveTextEditor() {
        IEditorPart editor = getActiveEditor();
        if (editor != null) {
            if (editor instanceof ITextEditor) {
                return (ITextEditor) editor;
            } else {
                return (ITextEditor) editor.getAdapter(ITextEditor.class);
            }
        }

        return null;
    }

    /**
     * Looks through the open editors and returns the editors that have the
     * given file as input.
     *
     * @param file the file to search for
     * @param restore whether editors should be restored (if they have an open
     *            tab, but the editor hasn't been restored since the most recent
     *            IDE start yet
     * @return a collection of editors
     */
    @NonNull
    public static Collection<IEditorPart> findEditorsFor(@NonNull IFile file, boolean restore) {
        FileEditorInput input = new FileEditorInput(file);
        List<IEditorPart> result = null;
        IWorkbench workbench = PlatformUI.getWorkbench();
        IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
        for (IWorkbenchWindow window : windows) {
            IWorkbenchPage[] pages = window.getPages();
            for (IWorkbenchPage page : pages) {
                IEditorReference[] editors = page.findEditors(input, null,  MATCH_INPUT);
                if (editors != null) {
                    for (IEditorReference reference : editors) {
                        IEditorPart editor = reference.getEditor(restore);
                        if (editor != null) {
                            if (result == null) {
                                result = new ArrayList<IEditorPart>();
                            }
                            result.add(editor);
                        }
                    }
                }
            }
        }

        if (result == null) {
            return Collections.emptyList();
        }

        return result;
    }

    /**
     * Attempts to convert the given {@link URL} into a {@link File}.
     *
     * @param url the {@link URL} to be converted
     * @return the corresponding {@link File}, which may not exist
     */
    @NonNull
    public static File getFile(@NonNull URL url) {
        try {
            // First try URL.toURI(): this will work for URLs that contain %20 for spaces etc.
            // Unfortunately, it *doesn't* work for "broken" URLs where the URL contains
            // spaces, which is often the case.
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            // ...so as a fallback, go to the old url.getPath() method, which handles space paths.
            return new File(url.getPath());
        }
    }

    /**
     * Returns the file for the current editor, if any.
     *
     * @return the file for the current editor, or null if none
     */
    public static IFile getActiveFile() {
        IEditorPart editor = getActiveEditor();
        if (editor != null) {
            IEditorInput input = editor.getEditorInput();
            if (input instanceof IFileEditorInput) {
                IFileEditorInput fileInput = (IFileEditorInput) input;
                return fileInput.getFile();
            }
        }

        return null;
    }

    /**
     * Returns an absolute path to the given resource
     *
     * @param resource the resource to look up a path for
     * @return an absolute file system path to the resource
     */
    @NonNull
    public static IPath getAbsolutePath(@NonNull IResource resource) {
        IPath location = resource.getRawLocation();
        if (location != null) {
            return location.makeAbsolute();
        } else {
            IWorkspace workspace = ResourcesPlugin.getWorkspace();
            IWorkspaceRoot root = workspace.getRoot();
            IPath workspacePath = root.getLocation();
            return workspacePath.append(resource.getFullPath());
        }
    }

    /**
     * Converts a workspace-relative path to an absolute file path
     *
     * @param path the workspace-relative path to convert
     * @return the corresponding absolute file in the file system
     */
    @NonNull
    public static File workspacePathToFile(@NonNull IPath path) {
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IResource res = root.findMember(path);
        if (res != null) {
            IPath location = res.getLocation();
            if (location != null) {
                return location.toFile();
            }
            return root.getLocation().append(path).toFile();
        }

        return path.toFile();
    }

    /**
     * Converts a {@link File} to an {@link IFile}, if possible.
     *
     * @param file a file to be converted
     * @return the corresponding {@link IFile}, or null
     */
    public static IFile fileToIFile(File file) {
        if (!file.isAbsolute()) {
            file = file.getAbsoluteFile();
        }

        IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
        IFile[] files = workspace.findFilesForLocationURI(file.toURI());
        if (files.length > 0) {
            return files[0];
        }

        IPath filePath = new Path(file.getPath());
        return pathToIFile(filePath);
    }

    /**
     * Converts a {@link File} to an {@link IResource}, if possible.
     *
     * @param file a file to be converted
     * @return the corresponding {@link IResource}, or null
     */
    public static IResource fileToResource(File file) {
        if (!file.isAbsolute()) {
            file = file.getAbsoluteFile();
        }

        IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
        IFile[] files = workspace.findFilesForLocationURI(file.toURI());
        if (files.length > 0) {
            return files[0];
        }

        IPath filePath = new Path(file.getPath());
        return pathToResource(filePath);
    }

    /**
     * Converts a {@link IPath} to an {@link IFile}, if possible.
     *
     * @param path a path to be converted
     * @return the corresponding {@link IFile}, or null
     */
    public static IFile pathToIFile(IPath path) {
        IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();

        IFile[] files = workspace.findFilesForLocationURI(URIUtil.toURI(path.makeAbsolute()));
        if (files.length > 0) {
            return files[0];
        }

        IPath workspacePath = workspace.getLocation();
        if (workspacePath.isPrefixOf(path)) {
            IPath relativePath = path.makeRelativeTo(workspacePath);
            IResource member = workspace.findMember(relativePath);
            if (member instanceof IFile) {
                return (IFile) member;
            }
        } else if (path.isAbsolute()) {
            return workspace.getFileForLocation(path);
        }

        return null;
    }

    /**
     * Converts a {@link IPath} to an {@link IResource}, if possible.
     *
     * @param path a path to be converted
     * @return the corresponding {@link IResource}, or null
     */
    public static IResource pathToResource(IPath path) {
        IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();

        IFile[] files = workspace.findFilesForLocationURI(URIUtil.toURI(path.makeAbsolute()));
        if (files.length > 0) {
            return files[0];
        }

        IPath workspacePath = workspace.getLocation();
        if (workspacePath.isPrefixOf(path)) {
            IPath relativePath = path.makeRelativeTo(workspacePath);
            return workspace.findMember(relativePath);
        } else if (path.isAbsolute()) {
            return workspace.getFileForLocation(path);
        }

        return null;
    }

    /**
     * Returns all markers in a file/document that fit on the same line as the given offset
     *
     * @param markerType the marker type
     * @param file the file containing the markers
     * @param document the document showing the markers
     * @param offset the offset to be checked
     * @return a list (possibly empty but never null) of matching markers
     */
    @NonNull
    public static List<IMarker> findMarkersOnLine(
            @NonNull String markerType,
            @NonNull IResource file,
            @NonNull IDocument document,
            int offset) {
        List<IMarker> matchingMarkers = new ArrayList<IMarker>(2);
        try {
            IMarker[] markers = file.findMarkers(markerType, true, IResource.DEPTH_ZERO);

            // Look for a match on the same line as the caret.
            IRegion lineInfo = document.getLineInformationOfOffset(offset);
            int lineStart = lineInfo.getOffset();
            int lineEnd = lineStart + lineInfo.getLength();
            int offsetLine = document.getLineOfOffset(offset);


            for (IMarker marker : markers) {
                int start = marker.getAttribute(IMarker.CHAR_START, -1);
                int end = marker.getAttribute(IMarker.CHAR_END, -1);
                if (start >= lineStart && start <= lineEnd && end > start) {
                    matchingMarkers.add(marker);
                } else if (start == -1 && end == -1) {
                    // Some markers don't set character range, they only set the line
                    int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
                    if (line == offsetLine + 1) {
                        matchingMarkers.add(marker);
                    }
                }
            }
        } catch (CoreException e) {
            AdtPlugin.log(e, null);
        } catch (BadLocationException e) {
            AdtPlugin.log(e, null);
        }

        return matchingMarkers;
    }

    /**
     * Returns the available and open Android projects
     *
     * @return the available and open Android projects, never null
     */
    @NonNull
    public static IJavaProject[] getOpenAndroidProjects() {
        return BaseProjectHelper.getAndroidProjects(new IProjectFilter() {
            @Override
            public boolean accept(IProject project) {
                return project.isAccessible();
            }
        });
    }

    /**
     * Returns a unique project name, based on the given {@code base} file name
     * possibly with a {@code conjunction} and a new number behind it to ensure
     * that the project name is unique. For example,
     * {@code getUniqueProjectName("project", "_")} will return
     * {@code "project"} if that name does not already exist, and if it does, it
     * will return {@code "project_2"}.
     *
     * @param base the base name to use, such as "foo"
     * @param conjunction a string to insert between the base name and the
     *            number.
     * @return a unique project name based on the given base and conjunction
     */
    public static String getUniqueProjectName(String base, String conjunction) {
        // We're using all workspace projects here rather than just open Android project
        // via getOpenAndroidProjects because the name cannot conflict with non-Android
        // or closed projects either
        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
        IProject[] projects = workspaceRoot.getProjects();

        for (int i = 1; i < 1000; i++) {
            String name = i == 1 ? base : base + conjunction + Integer.toString(i);
            boolean found = false;
            for (IProject project : projects) {
                // Need to make case insensitive comparison, since otherwise we can hit
                // org.eclipse.core.internal.resources.ResourceException:
                // A resource exists with a different case: '/test'.
                if (project.getName().equalsIgnoreCase(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return name;
            }
        }

        return base;
    }

    /**
     * Returns the name of the parent folder for the given editor input
     *
     * @param editorInput the editor input to check
     * @return the parent folder, which is never null but may be ""
     */
    @NonNull
    public static String getParentFolderName(@Nullable IEditorInput editorInput) {
        if (editorInput instanceof IFileEditorInput) {
             IFile file = ((IFileEditorInput) editorInput).getFile();
             return file.getParent().getName();
        }

        if (editorInput instanceof IURIEditorInput) {
            IURIEditorInput urlEditorInput = (IURIEditorInput) editorInput;
            String path = urlEditorInput.getURI().toString();
            int lastIndex = path.lastIndexOf('/');
            if (lastIndex != -1) {
                int lastLastIndex = path.lastIndexOf('/', lastIndex - 1);
                if (lastLastIndex != -1) {
                    return path.substring(lastLastIndex + 1, lastIndex);
                }
            }
        }

        return "";
    }

    /**
     * Returns the XML editor for the given editor part
     *
     * @param part the editor part to look up the editor for
     * @return the editor or null if this part is not an XML editor
     */
    @Nullable
    public static AndroidXmlEditor getXmlEditor(@NonNull IEditorPart part) {
        if (part instanceof AndroidXmlEditor) {
            return (AndroidXmlEditor) part;
        } else if (part instanceof GraphicalEditorPart) {
            ((GraphicalEditorPart) part).getEditorDelegate().getEditor();
        }

        return null;
    }

    /**
     * Sets the given tools: attribute in the given XML editor document, adding
     * the tools name space declaration if necessary, formatting the affected
     * document region, and optionally comma-appending to an existing value and
     * optionally opening and revealing the attribute.
     *
     * @param editor the associated editor
     * @param element the associated element
     * @param description the description of the attribute (shown in the undo
     *            event)
     * @param name the name of the attribute
     * @param value the attribute value
     * @param reveal if true, open the editor and select the given attribute
     *            node
     * @param appendValue if true, add this value as a comma separated value to
     *            the existing attribute value, if any
     */
    public static void setToolsAttribute(
            @NonNull final AndroidXmlEditor editor,
            @NonNull final Element element,
            @NonNull final String description,
            @NonNull final String name,
            @Nullable final String value,
            final boolean reveal,
            final boolean appendValue) {
        editor.wrapUndoEditXmlModel(description, new Runnable() {
            @Override
            public void run() {
                String prefix = XmlUtils.lookupNamespacePrefix(element, TOOLS_URI, null, true);
                if (prefix == null) {
                    // Add in new prefix...
                    prefix = XmlUtils.lookupNamespacePrefix(element,
                            TOOLS_URI, TOOLS_PREFIX, true /*create*/);
                    if (value != null) {
                        // ...and ensure that the header is formatted such that
                        // the XML namespace declaration is placed in the right
                        // position and wrapping is applied etc.
                        editor.scheduleNodeReformat(editor.getUiRootNode(),
                                true /*attributesOnly*/);
                    }
                }

                String v = value;
                if (appendValue && v != null) {
                    String prev = element.getAttributeNS(TOOLS_URI, name);
                    if (prev.length() > 0) {
                        v = prev + ',' + value;
                    }
                }

                // Use the non-namespace form of set attribute since we can't
                // reference the namespace until the model has been reloaded
                if (v != null) {
                    element.setAttribute(prefix + ':' + name, v);
                } else {
                    element.removeAttribute(prefix + ':' + name);
                }

                UiElementNode rootUiNode = editor.getUiRootNode();
                if (rootUiNode != null && v != null) {
                    final UiElementNode uiNode = rootUiNode.findXmlNode(element);
                    if (uiNode != null) {
                        editor.scheduleNodeReformat(uiNode, true /*attributesOnly*/);

                        if (reveal) {
                            // Update editor selection after format
                            Display display = AdtPlugin.getDisplay();
                            if (display != null) {
                                display.asyncExec(new Runnable() {
                                    @Override
                                    public void run() {
                                        Node xmlNode = uiNode.getXmlNode();
                                        Attr attribute = ((Element) xmlNode).getAttributeNodeNS(
                                                TOOLS_URI, name);
                                        if (attribute instanceof IndexedRegion) {
                                            IndexedRegion region = (IndexedRegion) attribute;
                                            editor.getStructuredTextEditor().selectAndReveal(
                                                    region.getStartOffset(), region.getLength());
                                        }
                                    }
                                });
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * Returns a string label for the given target, of the form
     * "API 16: Android 4.1 (Jelly Bean)".
     *
     * @param target the target to generate a string from
     * @return a suitable display string
     */
    @NonNull
    public static String getTargetLabel(@NonNull IAndroidTarget target) {
        if (target.isPlatform()) {
            AndroidVersion version = target.getVersion();
            String codename = target.getProperty(PkgProps.PLATFORM_CODENAME);
            String release = target.getProperty("ro.build.version.release"); //$NON-NLS-1$
            if (codename != null) {
                return String.format("API %1$d: Android %2$s (%3$s)",
                        version.getApiLevel(),
                        release,
                        codename);
            }
            return String.format("API %1$d: Android %2$s", version.getApiLevel(),
                    release);
        }

        return String.format("%1$s (API %2$s)", target.getFullName(),
                target.getVersion().getApiString());
    }

    /**
     * Sets the given tools: attribute in the given XML editor document, adding
     * the tools name space declaration if necessary, and optionally
     * comma-appending to an existing value.
     *
     * @param file the file associated with the element
     * @param element the associated element
     * @param description the description of the attribute (shown in the undo
     *            event)
     * @param name the name of the attribute
     * @param value the attribute value
     * @param appendValue if true, add this value as a comma separated value to
     *            the existing attribute value, if any
     */
    public static void setToolsAttribute(
            @NonNull final IFile file,
            @NonNull final Element element,
            @NonNull final String description,
            @NonNull final String name,
            @Nullable final String value,
            final boolean appendValue) {
        IModelManager modelManager = StructuredModelManager.getModelManager();
        if (modelManager == null) {
            return;
        }

        try {
            IStructuredModel model = null;
            if (model == null) {
                model = modelManager.getModelForEdit(file);
            }
            if (model != null) {
                try {
                    model.aboutToChangeModel();
                    if (model instanceof IDOMModel) {
                        IDOMModel domModel = (IDOMModel) model;
                        Document doc = domModel.getDocument();
                        if (doc != null && element.getOwnerDocument() == doc) {
                            String prefix = XmlUtils.lookupNamespacePrefix(element, TOOLS_URI,
                                    null, true);
                            if (prefix == null) {
                                // Add in new prefix...
                                prefix = XmlUtils.lookupNamespacePrefix(element,
                                        TOOLS_URI, TOOLS_PREFIX, true);
                            }

                            String v = value;
                            if (appendValue && v != null) {
                                String prev = element.getAttributeNS(TOOLS_URI, name);
                                if (prev.length() > 0) {
                                    v = prev + ',' + value;
                                }
                            }

                            // Use the non-namespace form of set attribute since we can't
                            // reference the namespace until the model has been reloaded
                            if (v != null) {
                                element.setAttribute(prefix + ':' + name, v);
                            } else {
                                element.removeAttribute(prefix + ':' + name);
                            }
                        }
                    }
                } finally {
                    model.changedModel();
                    String updated = model.getStructuredDocument().get();
                    model.releaseFromEdit();
                    model.save(file);

                    // Must also force a save on disk since the above model.save(file) often
                    // (always?) has no effect.
                    ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
                    NullProgressMonitor monitor = new NullProgressMonitor();
                    IPath path = file.getFullPath();
                    manager.connect(path, LocationKind.IFILE, monitor);
                    try {
                        ITextFileBuffer buffer = manager.getTextFileBuffer(path,
                                LocationKind.IFILE);
                        IDocument currentDocument = buffer.getDocument();
                        currentDocument.set(updated);
                        buffer.commit(monitor, true);
                    } finally {
                        manager.disconnect(path, LocationKind.IFILE,  monitor);
                    }
                }
            }
        } catch (Exception e) {
            AdtPlugin.log(e, null);
        }
    }

    /**
     * Returns the Android version and code name of the given API level
     *
     * @param api the api level
     * @return a suitable version display name
     */
    public static String getAndroidName(int api) {
        if (api <= SdkVersionInfo.HIGHEST_KNOWN_API) {
            return SdkVersionInfo.getAndroidName(api);
        }

        // Consult SDK manager to see if we know any more (later) names,
        // installed by user
        Sdk sdk = Sdk.getCurrent();
        if (sdk != null) {
            for (IAndroidTarget target : sdk.getTargets()) {
                if (target.isPlatform()) {
                    AndroidVersion version = target.getVersion();
                    if (version.getApiLevel() == api) {
                        return getTargetLabel(target);
                    }
                }
            }
        }

        return "API " + api;
    }

    /**
     * Returns the highest known API level to this version of ADT. The
     * {@link #getAndroidName(int)} method will return real names up to and
     * including this number.
     *
     * @return the highest known API number
     */
    public static int getHighestKnownApiLevel() {
        return SdkVersionInfo.HIGHEST_KNOWN_API;
    }

    /**
     * Returns a list of known API names
     *
     * @return a list of string API names, starting from 1 and up through the
     *         maximum known versions (with no gaps)
     */
    public static String[] getKnownVersions() {
        int max = getHighestKnownApiLevel();
        Sdk sdk = Sdk.getCurrent();
        if (sdk != null) {
            for (IAndroidTarget target : sdk.getTargets()) {
                if (target.isPlatform()) {
                    AndroidVersion version = target.getVersion();
                    if (!version.isPreview()) {
                        max = Math.max(max, version.getApiLevel());
                    }
                }
            }
        }

        String[] versions = new String[max];
        for (int api = 1; api <= max; api++) {
            versions[api-1] = getAndroidName(api);
        }

        return versions;
    }

    /**
     * Returns the Android project(s) that are selected or active, if any. This
     * considers the selection, the active editor, etc.
     *
     * @param selection the current selection
     * @return a list of projects, possibly empty (but never null)
     */
    @NonNull
    public static List<IProject> getSelectedProjects(@Nullable ISelection selection) {
        List<IProject> projects = new ArrayList<IProject>();

        if (selection instanceof IStructuredSelection) {
            IStructuredSelection structuredSelection = (IStructuredSelection) selection;
            // get the unique selected item.
            Iterator<?> iterator = structuredSelection.iterator();
            while (iterator.hasNext()) {
                Object element = iterator.next();

                // First look up the resource (since some adaptables
                // provide an IResource but not an IProject, and we can
                // always go from IResource to IProject)
                IResource resource = null;
                if (element instanceof IResource) { // may include IProject
                   resource = (IResource) element;
                } else if (element instanceof IAdaptable) {
                    IAdaptable adaptable = (IAdaptable)element;
                    Object adapter = adaptable.getAdapter(IResource.class);
                    resource = (IResource) adapter;
                }

                // get the project object from it.
                IProject project = null;
                if (resource != null) {
                    project = resource.getProject();
                } else if (element instanceof IAdaptable) {
                    project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
                }

                if (project != null && !projects.contains(project)) {
                    projects.add(project);
                }
            }
        }

        if (projects.isEmpty()) {
            // Try to look at the active editor instead
            IFile file = AdtUtils.getActiveFile();
            if (file != null) {
                projects.add(file.getProject());
            }
        }

        if (projects.isEmpty()) {
            // If we didn't find a default project based on the selection, check how many
            // open Android projects we can find in the current workspace. If there's only
            // one, we'll just select it by default.
            IJavaProject[] open = AdtUtils.getOpenAndroidProjects();
            for (IJavaProject project : open) {
                projects.add(project.getProject());
            }
            return projects;
        } else {
            // Make sure all the projects are Android projects
            List<IProject> androidProjects = new ArrayList<IProject>(projects.size());
            for (IProject project : projects) {
                if (BaseProjectHelper.isAndroidProject(project)) {
                    androidProjects.add(project);
                }
            }
            return androidProjects;
        }
    }

    private static Boolean sEclipse4;

    /**
     * Returns true if the running Eclipse is version 4.x or later
     *
     * @return true if the current Eclipse version is 4.x or later, false
     *         otherwise
     */
    public static boolean isEclipse4() {
        if (sEclipse4 == null) {
            sEclipse4 = Platform.getBundle("org.eclipse.e4.ui.model.workbench") != null; //$NON-NLS-1$
        }

        return sEclipse4;
    }

    /**
     * Reads the contents of an {@link IFile} and return it as a byte array
     *
     * @param file the file to be read
     * @return the String read from the file, or null if there was an error
     */
    @SuppressWarnings("resource") // Eclipse doesn't understand Closeables.closeQuietly yet
    @Nullable
    public static byte[] readData(@NonNull IFile file) {
        InputStream contents = null;
        try {
            contents = file.getContents();
            return ByteStreams.toByteArray(contents);
        } catch (Exception e) {
            // Pass -- just return null
        } finally {
            Closeables.closeQuietly(contents);
        }

        return null;
    }

    /**
     * Ensure that a given folder (and all its parents) are created. This implements
     * the equivalent of {@link File#mkdirs()} for {@link IContainer} folders.
     *
     * @param container the container to ensure exists
     * @throws CoreException if an error occurs
     */
    public static void ensureExists(@Nullable IContainer container) throws CoreException {
        if (container == null || container.exists()) {
            return;
        }
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IFolder folder = root.getFolder(container.getFullPath());
        ensureExists(folder);
    }

    private static void ensureExists(IFolder folder) throws CoreException {
        if (folder != null && !folder.exists()) {
            IContainer parent = folder.getParent();
            if (parent instanceof IFolder) {
                ensureExists((IFolder) parent);
            }
            folder.create(false, false, null);
        }
    }

    /**
     * Format the given floating value into an XML string, omitting decimals if
     * 0
     *
     * @param value the value to be formatted
     * @return the corresponding XML string for the value
     */
    public static String formatFloatAttribute(float value) {
        if (value != (int) value) {
            // Run String.format without a locale, because we don't want locale-specific
            // conversions here like separating the decimal part with a comma instead of a dot!
            return String.format((Locale) null, "%.2f", value); //$NON-NLS-1$
        } else {
            return Integer.toString((int) value);
        }
    }

    /**
     * Creates all the directories required for the given path.
     *
     * @param wsPath the path to create all the parent directories for
     * @return true if all the parent directories were created
     */
    public static boolean createWsParentDirectory(IContainer wsPath) {
        if (wsPath.getType() == IResource.FOLDER) {
            if (wsPath.exists()) {
                return true;
            }

            IFolder folder = (IFolder) wsPath;
            try {
                if (createWsParentDirectory(wsPath.getParent())) {
                    folder.create(true /* force */, true /* local */, null /* monitor */);
                    return true;
                }
            } catch (CoreException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    /**
     * Lists the files of the given directory and returns them as an array which
     * is never null. This simplifies processing file listings from for each
     * loops since {@link File#listFiles} can return null. This method simply
     * wraps it and makes sure it returns an empty array instead if necessary.
     *
     * @param dir the directory to list
     * @return the children, or empty if it has no children, is not a directory,
     *         etc.
     */
    @NonNull
    public static File[] listFiles(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            return files;
        } else {
            return new File[0];
        }
    }

    /**
     * Closes all open editors that are showing a file for the given project. This method
     * should be called when a project is closed or deleted.
     * <p>
     * This method can be called from any thread, but if it is not called on the GUI thread
     * the editor will be closed asynchronously.
     *
     * @param project the project to close all editors for
     * @param save whether unsaved editors should be saved first
     */
    public static void closeEditors(@NonNull final IProject project, final boolean save) {
        final Display display = AdtPlugin.getDisplay();
        if (display == null || display.isDisposed()) {
            return;
        }
        if (display.getThread() != Thread.currentThread()) {
            display.asyncExec(new Runnable() {
                @Override
                public void run() {
                    closeEditors(project, save);
                }
            });
            return;
        }

        // Close editors for removed files
        IWorkbench workbench = PlatformUI.getWorkbench();
        for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
            for (IWorkbenchPage page : window.getPages()) {
                List<IEditorReference> matching = null;
                for (IEditorReference ref : page.getEditorReferences()) {
                    boolean close = false;
                    try {
                        IEditorInput input = ref.getEditorInput();
                        if (input instanceof IFileEditorInput) {
                            IFileEditorInput fileInput = (IFileEditorInput) input;
                            if (project.equals(fileInput.getFile().getProject())) {
                                close = true;
                            }
                        }
                    } catch (PartInitException ex) {
                        close = true;
                    }
                    if (close) {
                        if (matching == null) {
                            matching = new ArrayList<IEditorReference>(2);
                        }
                        matching.add(ref);
                    }
                }
                if (matching != null) {
                    IEditorReference[] refs = new IEditorReference[matching.size()];
                    page.closeEditors(matching.toArray(refs), save);
                }
            }
        }
    }

    /**
     * Closes all open editors for the given file. Note that a file can be open in
     * more than one editor, for example by using Open With on the file to choose different
     * editors.
     * <p>
     * This method can be called from any thread, but if it is not called on the GUI thread
     * the editor will be closed asynchronously.
     *
     * @param file the file whose editors should be closed.
     * @param save whether unsaved editors should be saved first
     */
    public static void closeEditors(@NonNull final IFile file, final boolean save) {
        final Display display = AdtPlugin.getDisplay();
        if (display == null || display.isDisposed()) {
            return;
        }
        if (display.getThread() != Thread.currentThread()) {
            display.asyncExec(new Runnable() {
                @Override
                public void run() {
                    closeEditors(file, save);
                }
            });
            return;
        }

        // Close editors for removed files
        IWorkbench workbench = PlatformUI.getWorkbench();
        for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
            for (IWorkbenchPage page : window.getPages()) {
                List<IEditorReference> matching = null;
                for (IEditorReference ref : page.getEditorReferences()) {
                    boolean close = false;
                    try {
                        IEditorInput input = ref.getEditorInput();
                        if (input instanceof IFileEditorInput) {
                            IFileEditorInput fileInput = (IFileEditorInput) input;
                            if (file.equals(fileInput.getFile())) {
                                close = true;
                            }
                        }
                    } catch (PartInitException ex) {
                        close = true;
                    }
                    if (close) {
                        // Found
                        if (matching == null) {
                            matching = new ArrayList<IEditorReference>(2);
                        }
                        matching.add(ref);
                        // We don't break here in case the file is
                        // opened multiple times with different editors.
                    }
                }
                if (matching != null) {
                    IEditorReference[] refs = new IEditorReference[matching.size()];
                    page.closeEditors(matching.toArray(refs), save);
                }
            }
        }
    }

    /**
     * Returns the offset region of the given 0-based line number in the given
     * file
     *
     * @param file the file to look up the line number in
     * @param line the line number (0-based, meaning that the first line is line
     *            0)
     * @return the corresponding offset range, or null
     */
    @Nullable
    public static IRegion getRegionOfLine(@NonNull IFile file, int line) {
        IDocumentProvider provider = new TextFileDocumentProvider();
        try {
            provider.connect(file);
            IDocument document = provider.getDocument(file);
            if (document != null) {
                return document.getLineInformation(line);
            }
        } catch (Exception e) {
            AdtPlugin.log(e, "Can't find range information for %1$s", file.getName());
        } finally {
            provider.disconnect(file);
        }

        return null;
    }

    /**
     * Returns all resource variations for the given file
     *
     * @param file resource file, which should be an XML file in one of the
     *            various resource folders, e.g. res/layout, res/values-xlarge, etc.
     * @param includeSelf if true, include the file itself in the list,
     *            otherwise exclude it
     * @return a list of all the resource variations
     */
    public static List<IFile> getResourceVariations(@Nullable IFile file, boolean includeSelf) {
        if (file == null) {
            return Collections.emptyList();
        }

        // Compute the set of layout files defining this layout resource
        List<IFile> variations = new ArrayList<IFile>();
        String name = file.getName();
        IContainer parent = file.getParent();
        if (parent != null) {
            IContainer resFolder = parent.getParent();
            if (resFolder != null) {
                String parentName = parent.getName();
                String prefix = parentName;
                int qualifiers = prefix.indexOf('-');

                if (qualifiers != -1) {
                    parentName = prefix.substring(0, qualifiers);
                    prefix = prefix.substring(0, qualifiers + 1);
                } else {
                    prefix = prefix + '-';
                }
                try {
                    for (IResource resource : resFolder.members()) {
                        String n = resource.getName();
                        if ((n.startsWith(prefix) || n.equals(parentName))
                                && resource instanceof IContainer) {
                            IContainer layoutFolder = (IContainer) resource;
                            IResource r = layoutFolder.findMember(name);
                            if (r instanceof IFile) {
                                IFile variation = (IFile) r;
                                if (!includeSelf && file.equals(variation)) {
                                    continue;
                                }
                                variations.add(variation);
                            }
                        }
                    }
                } catch (CoreException e) {
                    AdtPlugin.log(e, null);
                }
            }
        }

        return variations;
    }

    /**
     * Returns whether the current thread is the UI thread
     *
     * @return true if the current thread is the UI thread
     */
    public static boolean isUiThread() {
        return AdtPlugin.getDisplay() != null
                && AdtPlugin.getDisplay().getThread() == Thread.currentThread();
    }

    /**
     * Replaces any {@code \\uNNNN} references in the given string with the corresponding
     * unicode characters.
     *
     * @param s the string to perform replacements in
     * @return the string with unicode escapes replaced with actual characters
     */
    @NonNull
    public static String replaceUnicodeEscapes(@NonNull String s) {
        // Handle unicode escapes
        if (s.indexOf("\\u") != -1) { //$NON-NLS-1$
            StringBuilder sb = new StringBuilder(s.length());
            for (int i = 0, n = s.length(); i < n; i++) {
                char c = s.charAt(i);
                if (c == '\\' && i < n - 1) {
                    char next = s.charAt(i + 1);
                    if (next == 'u' && i < n - 5) { // case sensitive
                        String hex = s.substring(i + 2, i + 6);
                        try {
                            int unicodeValue = Integer.parseInt(hex, 16);
                            sb.append((char) unicodeValue);
                            i += 5;
                            continue;
                        } catch (NumberFormatException nufe) {
                            // Invalid escape: Just proceed to literally transcribe it
                            sb.append(c);
                        }
                    } else {
                        sb.append(c);
                        sb.append(next);
                        i++;
                        continue;
                    }
                } else {
                    sb.append(c);
                }
            }
            s = sb.toString();
        }

        return s;
    }

    /**
     * Looks up the {@link ResourceFolderType} corresponding to a given
     * {@link ResourceType}: the folder where those resources can be found.
     * <p>
     * Note that {@link ResourceType#ID} is a special case: it can not just
     * be defined in {@link ResourceFolderType#VALUES}, but it can also be
     * defined inline via {@code @+id} in {@link ResourceFolderType#LAYOUT} and
     * {@link ResourceFolderType#MENU} folders.
     *
     * @param type the resource type
     * @return the corresponding resource folder type
     */
    @NonNull
    public static ResourceFolderType getFolderTypeFor(@NonNull ResourceType type) {
        switch (type) {
            case ANIM:
                return ResourceFolderType.ANIM;
            case ANIMATOR:
                return ResourceFolderType.ANIMATOR;
            case ARRAY:
                return ResourceFolderType.VALUES;
            case COLOR:
                return ResourceFolderType.COLOR;
            case DRAWABLE:
                return ResourceFolderType.DRAWABLE;
            case INTERPOLATOR:
                return ResourceFolderType.INTERPOLATOR;
            case LAYOUT:
                return ResourceFolderType.LAYOUT;
            case MENU:
                return ResourceFolderType.MENU;
            case MIPMAP:
                return ResourceFolderType.MIPMAP;
            case RAW:
                return ResourceFolderType.RAW;
            case XML:
                return ResourceFolderType.XML;
            case ATTR:
            case BOOL:
            case DECLARE_STYLEABLE:
            case DIMEN:
            case FRACTION:
            case ID:
            case INTEGER:
            case PLURALS:
            case PUBLIC:
            case STRING:
            case STYLE:
            case STYLEABLE:
                return ResourceFolderType.VALUES;
            default:
                assert false : type;
            return ResourceFolderType.VALUES;

        }
    }

    /**
     * Looks up the {@link ResourceType} defined in a given {@link ResourceFolderType}.
     * <p>
     * Note that for {@link ResourceFolderType#VALUES} there are many, many
     * different types of resources that can be defined, so this method returns
     * {@code null} for that scenario.
     * <p>
     * Note also that {@link ResourceType#ID} is a special case: it can not just
     * be defined in {@link ResourceFolderType#VALUES}, but it can also be
     * defined inline via {@code @+id} in {@link ResourceFolderType#LAYOUT} and
     * {@link ResourceFolderType#MENU} folders.
     *
     * @param folderType the resource folder type
     * @return the corresponding resource type, or null if {@code folderType} is
     *         {@link ResourceFolderType#VALUES}
     */
    @Nullable
    public static ResourceType getResourceTypeFor(@NonNull ResourceFolderType folderType) {
        switch (folderType) {
            case ANIM:
                return ResourceType.ANIM;
            case ANIMATOR:
                return ResourceType.ANIMATOR;
            case COLOR:
                return ResourceType.COLOR;
            case DRAWABLE:
                return ResourceType.DRAWABLE;
            case INTERPOLATOR:
                return ResourceType.INTERPOLATOR;
            case LAYOUT:
                return ResourceType.LAYOUT;
            case MENU:
                return ResourceType.MENU;
            case MIPMAP:
                return ResourceType.MIPMAP;
            case RAW:
                return ResourceType.RAW;
            case XML:
                return ResourceType.XML;
            case VALUES:
                return null;
            default:
                assert false : folderType;
                return null;
        }
    }
}