Home | History | Annotate | Download | only in data
      1 /*
      2  * Copyright (C) 2010 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.gallery3d.data;
     18 
     19 import com.android.gallery3d.app.GalleryApp;
     20 import com.android.gallery3d.common.Utils;
     21 import com.android.gallery3d.data.MediaSet.ItemConsumer;
     22 import com.android.gallery3d.data.MediaSource.PathId;
     23 import com.android.gallery3d.picasasource.PicasaSource;
     24 
     25 import android.database.ContentObserver;
     26 import android.net.Uri;
     27 import android.os.Handler;
     28 
     29 import java.util.ArrayList;
     30 import java.util.Comparator;
     31 import java.util.HashMap;
     32 import java.util.LinkedHashMap;
     33 import java.util.Map.Entry;
     34 import java.util.WeakHashMap;
     35 
     36 // DataManager manages all media sets and media items in the system.
     37 //
     38 // Each MediaSet and MediaItem has a unique 64 bits id. The most significant
     39 // 32 bits represents its parent, and the least significant 32 bits represents
     40 // the self id. For MediaSet the self id is is globally unique, but for
     41 // MediaItem it's unique only relative to its parent.
     42 //
     43 // To make sure the id is the same when the MediaSet is re-created, a child key
     44 // is provided to obtainSetId() to make sure the same self id will be used as
     45 // when the parent and key are the same. A sequence of child keys is called a
     46 // path. And it's used to identify a specific media set even if the process is
     47 // killed and re-created, so child keys should be stable identifiers.
     48 
     49 public class DataManager {
     50     public static final int INCLUDE_IMAGE = 1;
     51     public static final int INCLUDE_VIDEO = 2;
     52     public static final int INCLUDE_ALL = INCLUDE_IMAGE | INCLUDE_VIDEO;
     53     public static final int INCLUDE_LOCAL_ONLY = 4;
     54     public static final int INCLUDE_LOCAL_IMAGE_ONLY =
     55             INCLUDE_LOCAL_ONLY | INCLUDE_IMAGE;
     56     public static final int INCLUDE_LOCAL_VIDEO_ONLY =
     57             INCLUDE_LOCAL_ONLY | INCLUDE_VIDEO;
     58     public static final int INCLUDE_LOCAL_ALL_ONLY =
     59             INCLUDE_LOCAL_ONLY | INCLUDE_IMAGE | INCLUDE_VIDEO;
     60 
     61     // Any one who would like to access data should require this lock
     62     // to prevent concurrency issue.
     63     public static final Object LOCK = new Object();
     64 
     65     private static final String TAG = "DataManager";
     66 
     67     // This is the path for the media set seen by the user at top level.
     68     private static final String TOP_SET_PATH =
     69             "/combo/{/mtp,/local/all,/picasa/all}";
     70     private static final String TOP_IMAGE_SET_PATH =
     71             "/combo/{/mtp,/local/image,/picasa/image}";
     72     private static final String TOP_VIDEO_SET_PATH =
     73             "/combo/{/local/video,/picasa/video}";
     74     private static final String TOP_LOCAL_SET_PATH =
     75             "/local/all";
     76     private static final String TOP_LOCAL_IMAGE_SET_PATH =
     77             "/local/image";
     78     private static final String TOP_LOCAL_VIDEO_SET_PATH =
     79             "/local/video";
     80 
     81     public static final Comparator<MediaItem> sDateTakenComparator =
     82             new DateTakenComparator();
     83 
     84     private static class DateTakenComparator implements Comparator<MediaItem> {
     85         public int compare(MediaItem item1, MediaItem item2) {
     86             return -Utils.compare(item1.getDateInMs(), item2.getDateInMs());
     87         }
     88     }
     89 
     90     private final Handler mDefaultMainHandler;
     91 
     92     private GalleryApp mApplication;
     93     private int mActiveCount = 0;
     94 
     95     private HashMap<Uri, NotifyBroker> mNotifierMap =
     96             new HashMap<Uri, NotifyBroker>();
     97 
     98 
     99     private HashMap<String, MediaSource> mSourceMap =
    100             new LinkedHashMap<String, MediaSource>();
    101 
    102     public DataManager(GalleryApp application) {
    103         mApplication = application;
    104         mDefaultMainHandler = new Handler(application.getMainLooper());
    105     }
    106 
    107     public synchronized void initializeSourceMap() {
    108         if (!mSourceMap.isEmpty()) return;
    109 
    110         // the order matters, the UriSource must come last
    111         addSource(new LocalSource(mApplication));
    112         addSource(new PicasaSource(mApplication));
    113         addSource(new MtpSource(mApplication));
    114         addSource(new ComboSource(mApplication));
    115         addSource(new ClusterSource(mApplication));
    116         addSource(new FilterSource(mApplication));
    117         addSource(new UriSource(mApplication));
    118 
    119         if (mActiveCount > 0) {
    120             for (MediaSource source : mSourceMap.values()) {
    121                 source.resume();
    122             }
    123         }
    124     }
    125 
    126     public String getTopSetPath(int typeBits) {
    127 
    128         switch (typeBits) {
    129             case INCLUDE_IMAGE: return TOP_IMAGE_SET_PATH;
    130             case INCLUDE_VIDEO: return TOP_VIDEO_SET_PATH;
    131             case INCLUDE_ALL: return TOP_SET_PATH;
    132             case INCLUDE_LOCAL_IMAGE_ONLY: return TOP_LOCAL_IMAGE_SET_PATH;
    133             case INCLUDE_LOCAL_VIDEO_ONLY: return TOP_LOCAL_VIDEO_SET_PATH;
    134             case INCLUDE_LOCAL_ALL_ONLY: return TOP_LOCAL_SET_PATH;
    135             default: throw new IllegalArgumentException();
    136         }
    137     }
    138 
    139     // open for debug
    140     void addSource(MediaSource source) {
    141         mSourceMap.put(source.getPrefix(), source);
    142     }
    143 
    144     public MediaObject peekMediaObject(Path path) {
    145         return path.getObject();
    146     }
    147 
    148     public MediaSet peekMediaSet(Path path) {
    149         return (MediaSet) path.getObject();
    150     }
    151 
    152     public MediaObject getMediaObject(Path path) {
    153         MediaObject obj = path.getObject();
    154         if (obj != null) return obj;
    155 
    156         MediaSource source = mSourceMap.get(path.getPrefix());
    157         if (source == null) {
    158             Log.w(TAG, "cannot find media source for path: " + path);
    159             return null;
    160         }
    161 
    162         MediaObject object = source.createMediaObject(path);
    163         if (object == null) {
    164             Log.w(TAG, "cannot create media object: " + path);
    165         }
    166         return object;
    167     }
    168 
    169     public MediaObject getMediaObject(String s) {
    170         return getMediaObject(Path.fromString(s));
    171     }
    172 
    173     public MediaSet getMediaSet(Path path) {
    174         return (MediaSet) getMediaObject(path);
    175     }
    176 
    177     public MediaSet getMediaSet(String s) {
    178         return (MediaSet) getMediaObject(s);
    179     }
    180 
    181     public MediaSet[] getMediaSetsFromString(String segment) {
    182         String[] seq = Path.splitSequence(segment);
    183         int n = seq.length;
    184         MediaSet[] sets = new MediaSet[n];
    185         for (int i = 0; i < n; i++) {
    186             sets[i] = getMediaSet(seq[i]);
    187         }
    188         return sets;
    189     }
    190 
    191     // Maps a list of Paths to MediaItems, and invoke consumer.consume()
    192     // for each MediaItem (may not be in the same order as the input list).
    193     // An index number is also passed to consumer.consume() to identify
    194     // the original position in the input list of the corresponding Path (plus
    195     // startIndex).
    196     public void mapMediaItems(ArrayList<Path> list, ItemConsumer consumer,
    197             int startIndex) {
    198         HashMap<String, ArrayList<PathId>> map =
    199                 new HashMap<String, ArrayList<PathId>>();
    200 
    201         // Group the path by the prefix.
    202         int n = list.size();
    203         for (int i = 0; i < n; i++) {
    204             Path path = list.get(i);
    205             String prefix = path.getPrefix();
    206             ArrayList<PathId> group = map.get(prefix);
    207             if (group == null) {
    208                 group = new ArrayList<PathId>();
    209                 map.put(prefix, group);
    210             }
    211             group.add(new PathId(path, i + startIndex));
    212         }
    213 
    214         // For each group, ask the corresponding media source to map it.
    215         for (Entry<String, ArrayList<PathId>> entry : map.entrySet()) {
    216             String prefix = entry.getKey();
    217             MediaSource source = mSourceMap.get(prefix);
    218             source.mapMediaItems(entry.getValue(), consumer);
    219         }
    220     }
    221 
    222     // The following methods forward the request to the proper object.
    223     public int getSupportedOperations(Path path) {
    224         return getMediaObject(path).getSupportedOperations();
    225     }
    226 
    227     public void delete(Path path) {
    228         getMediaObject(path).delete();
    229     }
    230 
    231     public void rotate(Path path, int degrees) {
    232         getMediaObject(path).rotate(degrees);
    233     }
    234 
    235     public Uri getContentUri(Path path) {
    236         return getMediaObject(path).getContentUri();
    237     }
    238 
    239     public int getMediaType(Path path) {
    240         return getMediaObject(path).getMediaType();
    241     }
    242 
    243     public MediaDetails getDetails(Path path) {
    244         return getMediaObject(path).getDetails();
    245     }
    246 
    247     public void cache(Path path, int flag) {
    248         getMediaObject(path).cache(flag);
    249     }
    250 
    251     public Path findPathByUri(Uri uri) {
    252         if (uri == null) return null;
    253         for (MediaSource source : mSourceMap.values()) {
    254             Path path = source.findPathByUri(uri);
    255             if (path != null) return path;
    256         }
    257         return null;
    258     }
    259 
    260     public Path getDefaultSetOf(Path item) {
    261         MediaSource source = mSourceMap.get(item.getPrefix());
    262         return source == null ? null : source.getDefaultSetOf(item);
    263     }
    264 
    265     // Returns number of bytes used by cached pictures currently downloaded.
    266     public long getTotalUsedCacheSize() {
    267         long sum = 0;
    268         for (MediaSource source : mSourceMap.values()) {
    269             sum += source.getTotalUsedCacheSize();
    270         }
    271         return sum;
    272     }
    273 
    274     // Returns number of bytes used by cached pictures if all pending
    275     // downloads and removals are completed.
    276     public long getTotalTargetCacheSize() {
    277         long sum = 0;
    278         for (MediaSource source : mSourceMap.values()) {
    279             sum += source.getTotalTargetCacheSize();
    280         }
    281         return sum;
    282     }
    283 
    284     public void registerChangeNotifier(Uri uri, ChangeNotifier notifier) {
    285         NotifyBroker broker = null;
    286         synchronized (mNotifierMap) {
    287             broker = mNotifierMap.get(uri);
    288             if (broker == null) {
    289                 broker = new NotifyBroker(mDefaultMainHandler);
    290                 mApplication.getContentResolver()
    291                         .registerContentObserver(uri, true, broker);
    292                 mNotifierMap.put(uri, broker);
    293             }
    294         }
    295         broker.registerNotifier(notifier);
    296     }
    297 
    298     public void resume() {
    299         if (++mActiveCount == 1) {
    300             for (MediaSource source : mSourceMap.values()) {
    301                 source.resume();
    302             }
    303         }
    304     }
    305 
    306     public void pause() {
    307         if (--mActiveCount == 0) {
    308             for (MediaSource source : mSourceMap.values()) {
    309                 source.pause();
    310             }
    311         }
    312     }
    313 
    314     private static class NotifyBroker extends ContentObserver {
    315         private WeakHashMap<ChangeNotifier, Object> mNotifiers =
    316                 new WeakHashMap<ChangeNotifier, Object>();
    317 
    318         public NotifyBroker(Handler handler) {
    319             super(handler);
    320         }
    321 
    322         public synchronized void registerNotifier(ChangeNotifier notifier) {
    323             mNotifiers.put(notifier, null);
    324         }
    325 
    326         @Override
    327         public synchronized void onChange(boolean selfChange) {
    328             for(ChangeNotifier notifier : mNotifiers.keySet()) {
    329                 notifier.onChange(selfChange);
    330             }
    331         }
    332     }
    333 }
    334