Debian Codegraph @

sdk-common/src/main/java/com/android/ide/common/resources/ResourceRepository.java

raw
1 /*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.ide.common.resources;
18
19 import static com.android.SdkConstants.ATTR_REF_PREFIX;
20 import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
21 import static com.android.SdkConstants.PREFIX_THEME_REF;
22 import static com.android.SdkConstants.RESOURCE_CLZ_ATTR;
23
24 import com.android.SdkConstants;
25 import com.android.annotations.NonNull;
26 import com.android.annotations.Nullable;
27 import com.android.ide.common.rendering.api.ResourceValue;
28 import com.android.ide.common.resources.configuration.Configurable;
29 import com.android.ide.common.resources.configuration.FolderConfiguration;
30 import com.android.ide.common.resources.configuration.LocaleQualifier;
31 import com.android.io.IAbstractFile;
32 import com.android.io.IAbstractFolder;
33 import com.android.io.IAbstractResource;
34 import com.android.resources.FolderTypeRelationship;
35 import com.android.resources.ResourceFolderType;
36 import com.android.resources.ResourceType;
37
38 import java.io.File;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.EnumMap;
43 import java.util.HashMap;
44 import java.util.IdentityHashMap;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
51
52 /**
53 * Base class for resource repository.
54 *
55 * A repository is both a file representation of a resource folder and a representation
56 * of the generated resources, organized by type.
57 *
58 * {@link #getResourceFolder(IAbstractFolder)} and {@link #getSourceFiles(ResourceType, String, FolderConfiguration)}
59 * give access to the folders and files of the resource folder.
60 *
61 * {@link #getResourceItemsOfType(ResourceType)} gives access to the resources directly.
62 *
63 */
64 public abstract class ResourceRepository {
65
66 private final IAbstractFolder mResourceFolder;
67
68 protected Map<ResourceFolderType, List<ResourceFolder>> mFolderMap =
69 new EnumMap<ResourceFolderType, List<ResourceFolder>>(ResourceFolderType.class);
70
71 protected Map<ResourceType, Map<String, ResourceItem>> mResourceMap =
72 new EnumMap<ResourceType, Map<String, ResourceItem>>(
73 ResourceType.class);
74
75 private Map<Map<String, ResourceItem>, Collection<ResourceItem>> mReadOnlyListMap =
76 new IdentityHashMap<Map<String, ResourceItem>, Collection<ResourceItem>>();
77
78 private final boolean mFrameworkRepository;
79 private boolean mCleared = true;
80 private boolean mInitializing = false;
81
82 /**
83 * Makes a resource repository
84 * @param resFolder the resource folder of the repository.
85 * @param isFrameworkRepository whether the repository is for framework resources.
86 */
87 protected ResourceRepository(@NonNull IAbstractFolder resFolder,
88 boolean isFrameworkRepository) {
89 mResourceFolder = resFolder;
90 mFrameworkRepository = isFrameworkRepository;
91 }
92
93 public IAbstractFolder getResFolder() {
94 return mResourceFolder;
95 }
96
97 public boolean isFrameworkRepository() {
98 return mFrameworkRepository;
99 }
100
101 public synchronized void clear() {
102 mCleared = true;
103 mFolderMap = new EnumMap<ResourceFolderType, List<ResourceFolder>>(
104 ResourceFolderType.class);
105 mResourceMap = new EnumMap<ResourceType, Map<String, ResourceItem>>(
106 ResourceType.class);
107
108 mReadOnlyListMap =
109 new IdentityHashMap<Map<String, ResourceItem>, Collection<ResourceItem>>();
110 }
111
112 /**
113 * Ensures that the repository has been initialized again after a call to
114 * {@link ResourceRepository#clear()}
115 *
116 * @return true if the repository was just re-initialized.
117 */
118 public synchronized boolean ensureInitialized() {
119 if (mCleared && !mInitializing) {
120 ScanningContext context = new ScanningContext(this);
121 mInitializing = true;
122
123 IAbstractResource[] resources = mResourceFolder.listMembers();
124
125 for (IAbstractResource res : resources) {
126 if (res instanceof IAbstractFolder) {
127 IAbstractFolder folder = (IAbstractFolder)res;
128 ResourceFolder resFolder = processFolder(folder);
129
130 if (resFolder != null) {
131 // now we process the content of the folder
132 IAbstractResource[] files = folder.listMembers();
133
134 for (IAbstractResource fileRes : files) {
135 if (fileRes instanceof IAbstractFile) {
136 IAbstractFile file = (IAbstractFile)fileRes;
137
138 resFolder.processFile(file, ResourceDeltaKind.ADDED, context);
139 }
140 }
141 }
142 }
143 }
144
145 mInitializing = false;
146 mCleared = false;
147 return true;
148 }
149
150 return false;
151 }
152
153 /**
154 * Adds a Folder Configuration to the project.
155 * @param type The resource type.
156 * @param config The resource configuration.
157 * @param folder The workspace folder object.
158 * @return the {@link ResourceFolder} object associated to this folder.
159 */
160 private ResourceFolder add(
161 @NonNull ResourceFolderType type,
162 @NonNull FolderConfiguration config,
163 @NonNull IAbstractFolder folder) {
164 // get the list for the resource type
165 List<ResourceFolder> list = mFolderMap.get(type);
166
167 if (list == null) {
168 list = new ArrayList<ResourceFolder>();
169
170 ResourceFolder cf = new ResourceFolder(type, config, folder, this);
171 list.add(cf);
172
173 mFolderMap.put(type, list);
174
175 return cf;
176 }
177
178 // look for an already existing folder configuration.
179 for (ResourceFolder cFolder : list) {
180 if (cFolder.mConfiguration.equals(config)) {
181 // config already exist. Nothing to be done really, besides making sure
182 // the IAbstractFolder object is up to date.
183 cFolder.mFolder = folder;
184 return cFolder;
185 }
186 }
187
188 // If we arrive here, this means we didn't find a matching configuration.
189 // So we add one.
190 ResourceFolder cf = new ResourceFolder(type, config, folder, this);
191 list.add(cf);
192
193 return cf;
194 }
195
196 /**
197 * Removes a {@link ResourceFolder} associated with the specified {@link IAbstractFolder}.
198 * @param type The type of the folder
199 * @param removedFolder the IAbstractFolder object.
200 * @param context the scanning context
201 * @return the {@link ResourceFolder} that was removed, or null if no matches were found.
202 */
203 @Nullable
204 public ResourceFolder removeFolder(
205 @NonNull ResourceFolderType type,
206 @NonNull IAbstractFolder removedFolder,
207 @Nullable ScanningContext context) {
208 ensureInitialized();
209
210 // get the list of folders for the resource type.
211 List<ResourceFolder> list = mFolderMap.get(type);
212
213 if (list != null) {
214 int count = list.size();
215 for (int i = 0 ; i < count ; i++) {
216 ResourceFolder resFolder = list.get(i);
217 IAbstractFolder folder = resFolder.getFolder();
218 if (removedFolder.equals(folder)) {
219 // we found the matching ResourceFolder. we need to remove it.
220 list.remove(i);
221
222 // remove its content
223 resFolder.dispose(context);
224
225 return resFolder;
226 }
227 }
228 }
229
230 return null;
231 }
232
233 /**
234 * Returns true if this resource repository contains a resource of the given
235 * name.
236 *
237 * @param url the resource URL
238 * @return true if the resource is known
239 */
240 public boolean hasResourceItem(@NonNull String url) {
241 // Handle theme references
242 if (url.startsWith(PREFIX_THEME_REF)) {
243 String remainder = url.substring(PREFIX_THEME_REF.length());
244 if (url.startsWith(ATTR_REF_PREFIX)) {
245 url = PREFIX_RESOURCE_REF + url.substring(PREFIX_THEME_REF.length());
246 return hasResourceItem(url);
247 }
248 int colon = url.indexOf(':');
249 if (colon != -1) {
250 // Convert from ?android:progressBarStyleBig to ?android:attr/progressBarStyleBig
251 if (remainder.indexOf('/', colon) == -1) {
252 remainder = remainder.substring(0, colon) + RESOURCE_CLZ_ATTR + '/'
253 + remainder.substring(colon);
254 }
255 url = PREFIX_RESOURCE_REF + remainder;
256 return hasResourceItem(url);
257 } else {
258 int slash = url.indexOf('/');
259 if (slash == -1) {
260 url = PREFIX_RESOURCE_REF + RESOURCE_CLZ_ATTR + '/' + remainder;
261 return hasResourceItem(url);
262 }
263 }
264 }
265
266 if (!url.startsWith(PREFIX_RESOURCE_REF)) {
267 return false;
268 }
269
270 assert url.startsWith("@") || url.startsWith("?") : url;
271
272 ensureInitialized();
273
274 int typeEnd = url.indexOf('/', 1);
275 if (typeEnd != -1) {
276 int nameBegin = typeEnd + 1;
277
278 // Skip @ and @+
279 int typeBegin = url.startsWith("@+") ? 2 : 1; //$NON-NLS-1$
280
281 int colon = url.lastIndexOf(':', typeEnd);
282 if (colon != -1) {
283 typeBegin = colon + 1;
284 }
285 String typeName = url.substring(typeBegin, typeEnd);
286 ResourceType type = ResourceType.getEnum(typeName);
287 if (type != null) {
288 String name = url.substring(nameBegin);
289 return hasResourceItem(type, name);
290 }
291 }
292
293 return false;
294 }
295
296 /**
297 * Returns true if this resource repository contains a resource of the given
298 * name.
299 *
300 * @param type the type of resource to look up
301 * @param name the name of the resource
302 * @return true if the resource is known
303 */
304 public boolean hasResourceItem(@NonNull ResourceType type, @NonNull String name) {
305 ensureInitialized();
306
307 Map<String, ResourceItem> map = mResourceMap.get(type);
308
309 if (map != null) {
310
311 ResourceItem resourceItem = map.get(name);
312 if (resourceItem != null) {
313 return true;
314 }
315 }
316
317 return false;
318 }
319
320 /**
321 * Returns a {@link ResourceItem} matching the given {@link ResourceType} and name. If none
322 * exist, it creates one.
323 *
324 * @param type the resource type
325 * @param name the name of the resource.
326 * @return A resource item matching the type and name.
327 */
328 @NonNull
329 public ResourceItem getResourceItem(@NonNull ResourceType type, @NonNull String name) {
330 ensureInitialized();
331
332 // looking for an existing ResourceItem with this type and name
333 ResourceItem item = findDeclaredResourceItem(type, name);
334
335 // create one if there isn't one already, or if the existing one is inlined, since
336 // clearly we need a non inlined one (the inline one is removed too)
337 if (item == null || item.isDeclaredInline()) {
338 ResourceItem oldItem = item != null && item.isDeclaredInline() ? item : null;
339
340 item = createResourceItem(name);
341
342 Map<String, ResourceItem> map = mResourceMap.get(type);
343
344 if (map == null) {
345 if (isFrameworkRepository()) {
346 // Pick initial size for the maps. Also change the load factor to 1.0
347 // to avoid rehashing the whole table when we (as expected) get near
348 // the known rough size of each resource type map.
349 int size;
350 switch (type) {
351 // Based on counts in API 16. Going back to API 10, the counts
352 // are roughly 25-50% smaller (e.g. compared to the top 5 types below
353 // the fractions are 1107 vs 1734, 831 vs 1508, 895 vs 1255,
354 // 733 vs 1064 and 171 vs 783.
355 case PUBLIC: size = 1734; break;
356 case DRAWABLE: size = 1508; break;
357 case STRING: size = 1255; break;
358 case ATTR: size = 1064; break;
359 case STYLE: size = 783; break;
360 case ID: size = 347; break;
361 case DECLARE_STYLEABLE: size = 210; break;
362 case LAYOUT: size = 187; break;
363 case COLOR: size = 120; break;
364 case ANIM: size = 95; break;
365 case DIMEN: size = 81; break;
366 case BOOL: size = 54; break;
367 case INTEGER: size = 52; break;
368 case ARRAY: size = 51; break;
369 case PLURALS: size = 20; break;
370 case XML: size = 14; break;
371 case INTERPOLATOR : size = 13; break;
372 case ANIMATOR: size = 8; break;
373 case RAW: size = 4; break;
374 case MENU: size = 2; break;
375 case MIPMAP: size = 2; break;
376 case FRACTION: size = 1; break;
377 default:
378 size = 2;
379 }
380 map = new HashMap<String, ResourceItem>(size, 1.0f);
381 } else {
382 map = new HashMap<String, ResourceItem>();
383 }
384 mResourceMap.put(type, map);
385 }
386
387 map.put(item.getName(), item);
388
389 if (oldItem != null) {
390 map.remove(oldItem.getName());
391
392 }
393 }
394
395 return item;
396 }
397
398 /**
399 * Creates a resource item with the given name.
400 * @param name the name of the resource
401 * @return a new ResourceItem (or child class) instance.
402 */
403 @NonNull
404 protected abstract ResourceItem createResourceItem(@NonNull String name);
405
406 /**
407 * Processes a folder and adds it to the list of existing folders.
408 * @param folder the folder to process
409 * @return the ResourceFolder created from this folder, or null if the process failed.
410 */
411 @Nullable
412 public ResourceFolder processFolder(@NonNull IAbstractFolder folder) {
413 ensureInitialized();
414
415 // split the name of the folder in segments.
416 String[] folderSegments = folder.getName().split(SdkConstants.RES_QUALIFIER_SEP);
417
418 // get the enum for the resource type.
419 ResourceFolderType type = ResourceFolderType.getTypeByName(folderSegments[0]);
420
421 if (type != null) {
422 // get the folder configuration.
423 FolderConfiguration config = FolderConfiguration.getConfig(folderSegments);
424
425 if (config != null) {
426 return add(type, config, folder);
427 }
428 }
429
430 return null;
431 }
432
433 /**
434 * Returns a list of {@link ResourceFolder} for a specific {@link ResourceFolderType}.
435 * @param type The {@link ResourceFolderType}
436 */
437 @Nullable
438 public List<ResourceFolder> getFolders(@NonNull ResourceFolderType type) {
439 ensureInitialized();
440
441 return mFolderMap.get(type);
442 }
443
444 @NonNull
445 public List<ResourceType> getAvailableResourceTypes() {
446 ensureInitialized();
447
448 List<ResourceType> list = new ArrayList<ResourceType>();
449
450 // For each key, we check if there's a single ResourceType match.
451 // If not, we look for the actual content to give us the resource type.
452
453 for (ResourceFolderType folderType : mFolderMap.keySet()) {
454 List<ResourceType> types = FolderTypeRelationship.getRelatedResourceTypes(folderType);
455 if (types.size() == 1) {
456 // before we add it we check if it's not already present, since a ResourceType
457 // could be created from multiple folders, even for the folders that only create
458 // one type of resource (drawable for instance, can be created from drawable/ and
459 // values/)
460 if (list.contains(types.get(0)) == false) {
461 list.add(types.get(0));
462 }
463 } else {
464 // there isn't a single resource type out of this folder, so we look for all
465 // content.
466 List<ResourceFolder> folders = mFolderMap.get(folderType);
467 if (folders != null) {
468 for (ResourceFolder folder : folders) {
469 Collection<ResourceType> folderContent = folder.getResourceTypes();
470
471 // then we add them, but only if they aren't already in the list.
472 for (ResourceType folderResType : folderContent) {
473 if (list.contains(folderResType) == false) {
474 list.add(folderResType);
475 }
476 }
477 }
478 }
479 }
480 }
481
482 return list;
483 }
484
485 /**
486 * Returns a list of {@link ResourceItem} matching a given {@link ResourceType}.
487 * @param type the type of the resource items to return
488 * @return a non null collection of resource items
489 */
490 @NonNull
491 public Collection<ResourceItem> getResourceItemsOfType(@NonNull ResourceType type) {
492 ensureInitialized();
493
494 Map<String, ResourceItem> map = mResourceMap.get(type);
495
496 if (map == null) {
497 return Collections.emptyList();
498 }
499
500 Collection<ResourceItem> roList = mReadOnlyListMap.get(map);
501 if (roList == null) {
502 roList = Collections.unmodifiableCollection(map.values());
503 mReadOnlyListMap.put(map, roList);
504 }
505
506 return roList;
507 }
508
509 /**
510 * Returns whether the repository has resources of a given {@link ResourceType}.
511 * @param type the type of resource to check.
512 * @return true if the repository contains resources of the given type, false otherwise.
513 */
514 public boolean hasResourcesOfType(@NonNull ResourceType type) {
515 ensureInitialized();
516
517 Map<String, ResourceItem> items = mResourceMap.get(type);
518 return (items != null && !items.isEmpty());
519 }
520
521 /**
522 * Returns the {@link ResourceFolder} associated with a {@link IAbstractFolder}.
523 * @param folder The {@link IAbstractFolder} object.
524 * @return the {@link ResourceFolder} or null if it was not found.
525 */
526 @Nullable
527 public ResourceFolder getResourceFolder(@NonNull IAbstractFolder folder) {
528 ensureInitialized();
529
530 Collection<List<ResourceFolder>> values = mFolderMap.values();
531
532 for (List<ResourceFolder> list : values) {
533 for (ResourceFolder resFolder : list) {
534 IAbstractFolder wrapper = resFolder.getFolder();
535 if (wrapper.equals(folder)) {
536 return resFolder;
537 }
538 }
539 }
540
541 return null;
542 }
543
544 /**
545 * Returns the {@link ResourceFile} matching the given name,
546 * {@link ResourceFolderType} and configuration.
547 * <p>
548 * This only works with files generating one resource named after the file
549 * (for instance, layouts, bitmap based drawable, xml, anims).
550 *
551 * @param name the resource name or file name
552 * @param type the folder type search for
553 * @param config the folder configuration to match for
554 * @return the matching file or <code>null</code> if no match was found.
555 */
556 @Nullable
557 public ResourceFile getMatchingFile(
558 @NonNull String name,
559 @NonNull ResourceFolderType type,
560 @NonNull FolderConfiguration config) {
561 List<ResourceType> types = FolderTypeRelationship.getRelatedResourceTypes(type);
562 for (ResourceType t : types) {
563 if (t == ResourceType.ID) {
564 continue;
565 }
566 ResourceFile match = getMatchingFile(name, t, config);
567 if (match != null) {
568 return match;
569 }
570 }
571
572 return null;
573 }
574
575 /**
576 * Returns the {@link ResourceFile} matching the given name,
577 * {@link ResourceType} and configuration.
578 * <p>
579 * This only works with files generating one resource named after the file
580 * (for instance, layouts, bitmap based drawable, xml, anims).
581 *
582 * @param name the resource name or file name
583 * @param type the folder type search for
584 * @param config the folder configuration to match for
585 * @return the matching file or <code>null</code> if no match was found.
586 */
587 @Nullable
588 public ResourceFile getMatchingFile(
589 @NonNull String name,
590 @NonNull ResourceType type,
591 @NonNull FolderConfiguration config) {
592 ensureInitialized();
593
594 String resourceName = name;
595 int dot = resourceName.indexOf('.');
596 if (dot != -1) {
597 resourceName = resourceName.substring(0, dot);
598 }
599
600 Map<String, ResourceItem> items = mResourceMap.get(type);
601 if (items != null) {
602 ResourceItem item = items.get(resourceName);
603 if (item != null) {
604 List<ResourceFile> files = item.getSourceFileList();
605 if (files != null) {
606 if (files.size() > 1) {
607 ResourceValue value = item.getResourceValue(type, config,
608 isFrameworkRepository());
609 if (value != null) {
610 String v = value.getValue();
611 if (v != null) {
612 ResourceUrl url = ResourceUrl.parse(v);
613 if (url != null) {
614 return getMatchingFile(url.name, url.type, config);
615 } else {
616 // Looks like the resource value is pointing to a file
617 // It's most likely one of the source files for this
618 // resource item, so check those first
619 for (ResourceFile f : files) {
620 if (v.equals(f.getFile().getOsLocation())) {
621 // Found the file
622 return f;
623 }
624 }
625
626 // No; look up the resource file from the full path
627 File file = new File(v);
628 if (file.exists()) {
629 ResourceFile f = findResourceFile(file);
630 if (f != null) {
631 return f;
632 }
633 }
634 }
635 }
636 }
637 } else if (files.size() == 1) {
638 // Single file: see if it matches
639 ResourceFile matchingFile = files.get(0);
640 if (matchingFile.getFolder().getConfiguration().isMatchFor(config)) {
641 return matchingFile;
642 }
643 }
644 }
645 }
646 }
647
648 return null;
649 }
650
651 /**
652 * Looks up the {@link ResourceFile} for the given {@link File}, if possible
653 *
654 * @param file the file
655 * @return the corresponding {@link ResourceFile}, or null if not a known {@link ResourceFile}
656 */
657 @Nullable
658 protected ResourceFile findResourceFile(@NonNull File file) {
659 // Look up the right resource file for this path
660 String parentName = file.getParentFile().getName();
661 IAbstractFolder folder = getResFolder().getFolder(parentName);
662 if (folder != null) {
663 ResourceFolder resourceFolder = getResourceFolder(folder);
664 if (resourceFolder == null) {
665 FolderConfiguration configForFolder = FolderConfiguration
666 .getConfigForFolder(parentName);
667 if (configForFolder != null) {
668 ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
669 if (folderType != null) {
670 resourceFolder = add(folderType, configForFolder, folder);
671 }
672 }
673 }
674 if (resourceFolder != null) {
675 ResourceFile resourceFile = resourceFolder.getFile(file.getName());
676 if (resourceFile != null) {
677 return resourceFile;
678 }
679 }
680 }
681
682 return null;
683 }
684
685 /**
686 * Returns the list of source files for a given resource.
687 * Optionally, if a {@link FolderConfiguration} is given, then only the best
688 * match for this config is returned.
689 *
690 * @param type the type of the resource.
691 * @param name the name of the resource.
692 * @param referenceConfig an optional config for which only the best match will be returned.
693 *
694 * @return a list of files generating this resource or null if it was not found.
695 */
696 @Nullable
697 public List<ResourceFile> getSourceFiles(@NonNull ResourceType type, @NonNull String name,
698 @Nullable FolderConfiguration referenceConfig) {
699 ensureInitialized();
700
701 Collection<ResourceItem> items = getResourceItemsOfType(type);
702
703 for (ResourceItem item : items) {
704 if (name.equals(item.getName())) {
705 if (referenceConfig != null) {
706 Configurable match = referenceConfig.findMatchingConfigurable(
707 item.getSourceFileList());
708
709 if (match instanceof ResourceFile) {
710 return Collections.singletonList((ResourceFile) match);
711 }
712
713 return null;
714 }
715 return item.getSourceFileList();
716 }
717 }
718
719 return null;
720 }
721
722 /**
723 * Returns the resources values matching a given {@link FolderConfiguration}.
724 *
725 * @param referenceConfig the configuration that each value must match.
726 * @return a map with guaranteed to contain an entry for each {@link ResourceType}
727 */
728 @NonNull
729 public Map<ResourceType, Map<String, ResourceValue>> getConfiguredResources(
730 @NonNull FolderConfiguration referenceConfig) {
731 ensureInitialized();
732
733 return doGetConfiguredResources(referenceConfig);
734 }
735
736 /**
737 * Returns the resources values matching a given {@link FolderConfiguration} for the current
738 * project.
739 *
740 * @param referenceConfig the configuration that each value must match.
741 * @return a map with guaranteed to contain an entry for each {@link ResourceType}
742 */
743 @NonNull
744 protected final Map<ResourceType, Map<String, ResourceValue>> doGetConfiguredResources(
745 @NonNull FolderConfiguration referenceConfig) {
746 ensureInitialized();
747
748 Map<ResourceType, Map<String, ResourceValue>> map =
749 new EnumMap<ResourceType, Map<String, ResourceValue>>(ResourceType.class);
750
751 for (ResourceType key : ResourceType.values()) {
752 // get the local results and put them in the map
753 map.put(key, getConfiguredResource(key, referenceConfig));
754 }
755
756 return map;
757 }
758
759 /**
760 * Returns the sorted list of languages used in the resources.
761 */
762 @NonNull
763 public SortedSet<String> getLanguages() {
764 ensureInitialized();
765
766 SortedSet<String> set = new TreeSet<String>();
767
768 Collection<List<ResourceFolder>> folderList = mFolderMap.values();
769 for (List<ResourceFolder> folderSubList : folderList) {
770 for (ResourceFolder folder : folderSubList) {
771 FolderConfiguration config = folder.getConfiguration();
772 LocaleQualifier locale = config.getLocaleQualifier();
773 if (locale != null) {
774 set.add(locale.getLanguage());
775 }
776 }
777 }
778
779 return set;
780 }
781
782 /**
783 * Returns the sorted list of regions used in the resources with the given language.
784 * @param currentLanguage the current language the region must be associated with.
785 */
786 @NonNull
787 public SortedSet<String> getRegions(@NonNull String currentLanguage) {
788 ensureInitialized();
789
790 SortedSet<String> set = new TreeSet<String>();
791
792 Collection<List<ResourceFolder>> folderList = mFolderMap.values();
793 for (List<ResourceFolder> folderSubList : folderList) {
794 for (ResourceFolder folder : folderSubList) {
795 FolderConfiguration config = folder.getConfiguration();
796
797 // get the language
798 LocaleQualifier locale = config.getLocaleQualifier();
799 if (locale != null && currentLanguage.equals(locale.getLanguage())
800 && locale.getRegion() != null) {
801 set.add(locale.getRegion());
802 }
803 }
804 }
805
806 return set;
807 }
808
809 /**
810 * Loads the resources.
811 */
812 public void loadResources() {
813 clear();
814 ensureInitialized();
815 }
816
817 protected void removeFile(@NonNull Collection<ResourceType> types,
818 @NonNull ResourceFile file) {
819 ensureInitialized();
820
821 for (ResourceType type : types) {
822 removeFile(type, file);
823 }
824 }
825
826 protected void removeFile(@NonNull ResourceType type, @NonNull ResourceFile file) {
827 Map<String, ResourceItem> map = mResourceMap.get(type);
828 if (map != null) {
829 Collection<ResourceItem> values = map.values();
830 List<ResourceItem> toDelete = null;
831 for (ResourceItem item : values) {
832 item.removeFile(file);
833 if (item.hasNoSourceFile()) {
834 if (toDelete == null) {
835 toDelete = new ArrayList<ResourceItem>(values.size());
836 }
837 toDelete.add(item);
838 }
839 }
840 if (toDelete != null) {
841 for (ResourceItem item : toDelete) {
842 map.remove(item.getName());
843 }
844 }
845 }
846 }
847
848 /**
849 * Returns a map of (resource name, resource value) for the given {@link ResourceType}.
850 * <p>The values returned are taken from the resource files best matching a given
851 * {@link FolderConfiguration}.
852 * @param type the type of the resources.
853 * @param referenceConfig the configuration to best match.
854 */
855 @NonNull
856 private Map<String, ResourceValue> getConfiguredResource(@NonNull ResourceType type,
857 @NonNull FolderConfiguration referenceConfig) {
858
859 // get the resource item for the given type
860 Map<String, ResourceItem> items = mResourceMap.get(type);
861 if (items == null) {
862 return new HashMap<String, ResourceValue>();
863 }
864
865 // create the map
866 HashMap<String, ResourceValue> map = new HashMap<String, ResourceValue>(items.size());
867
868 for (ResourceItem item : items.values()) {
869 ResourceValue value = item.getResourceValue(type, referenceConfig,
870 isFrameworkRepository());
871 if (value != null) {
872 map.put(item.getName(), value);
873 }
874 }
875
876 return map;
877 }
878
879 /**
880 * Cleans up the repository of resource items that have no source file anymore.
881 */
882 public void postUpdateCleanUp() {
883 // Since removed files/folders remove source files from existing ResourceItem, loop through
884 // all resource items and remove the ones that have no source files.
885
886 Collection<Map<String, ResourceItem>> maps = mResourceMap.values();
887 for (Map<String, ResourceItem> map : maps) {
888 Set<String> keySet = map.keySet();
889 Iterator<String> iterator = keySet.iterator();
890 while (iterator.hasNext()) {
891 String name = iterator.next();
892 ResourceItem resourceItem = map.get(name);
893 if (resourceItem.hasNoSourceFile()) {
894 iterator.remove();
895 }
896 }
897 }
898 }
899
900 /**
901 * Looks up an existing {@link ResourceItem} by {@link ResourceType} and name. This
902 * ignores inline resources.
903 * @param type the Resource Type.
904 * @param name the Resource name.
905 * @return the existing ResourceItem or null if no match was found.
906 */
907 @Nullable
908 private ResourceItem findDeclaredResourceItem(@NonNull ResourceType type,
909 @NonNull String name) {
910 Map<String, ResourceItem> map = mResourceMap.get(type);
911
912 if (map != null) {
913 ResourceItem resourceItem = map.get(name);
914 if (resourceItem != null && !resourceItem.isDeclaredInline()) {
915 return resourceItem;
916 }
917 }
918
919 return null;
920 }
921 }
922