aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/explorer/activities/BookmarksActivity.java
blob: d005fe80e607b8dddbd46581463e335bf49622a0 (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
/*
 * Copyright (C) 2012 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.cyanogenmod.explorer.activities;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.util.XmlUtils;
import com.cyanogenmod.explorer.R;
import com.cyanogenmod.explorer.adapters.BookmarksAdapter;
import com.cyanogenmod.explorer.model.Bookmark;
import com.cyanogenmod.explorer.model.Bookmark.BOOKMARK_TYPE;
import com.cyanogenmod.explorer.preferences.Bookmarks;
import com.cyanogenmod.explorer.preferences.ExplorerSettings;
import com.cyanogenmod.explorer.preferences.Preferences;
import com.cyanogenmod.explorer.ui.dialogs.InitialDirectoryDialog;
import com.cyanogenmod.explorer.util.DialogHelper;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * An activity for show bookmarks and links.
 */
public class BookmarksActivity extends Activity implements OnItemClickListener, OnClickListener {

    private static final String TAG = "BookmarksActivity"; //$NON-NLS-1$

    private static boolean DEBUG = false;

    // Bookmark list XML tags
    private static final String TAG_BOOKMARKS = "Bookmarks"; //$NON-NLS-1$
    private static final String TAG_BOOKMARK = "bookmark"; //$NON-NLS-1$

    private ListView mBookmarksListView;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onCreate(Bundle state) {
        if (DEBUG) {
            Log.d(TAG, "NavigationActivity.onCreate"); //$NON-NLS-1$
        }

        //Request features
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //Set in transition
        overridePendingTransition(R.anim.translate_to_right_in, R.anim.hold_out);

        //Set the main layout of the activity
        setContentView(R.layout.bookmarks);

        //Initialize action bars and data
        initTitleActionBar();
        initBookmarks();

        //Save state
        super.onCreate(state);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
        //Set out transition
        overridePendingTransition(R.anim.hold_in, R.anim.translate_to_left_out);
        super.onPause();
    }

    /**
     * Method that initializes the titlebar of the activity.
     */
    private void initTitleActionBar() {
        //Configure the action bar options
        getActionBar().setBackgroundDrawable(
                getResources().getDrawable(R.drawable.bg_holo_titlebar));
        getActionBar().setDisplayOptions(
                ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        View customTitle = getLayoutInflater().inflate(R.layout.simple_customtitle, null, false);
        TextView title = (TextView)customTitle.findViewById(R.id.customtitle_title);
        title.setText(R.string.bookmarks);
        title.setContentDescription(getString(R.string.bookmarks));
        getActionBar().setCustomView(customTitle);

    }

    /**
     * Method that initializes the titlebar of the activity.
     */
    private void initBookmarks() {
        this.mBookmarksListView = (ListView)findViewById(R.id.bookmarks_listview);
        BookmarksAdapter adapter = new BookmarksAdapter(this, loadBookmarks(), this);
        this.mBookmarksListView.setAdapter(adapter);
        this.mBookmarksListView.setOnItemClickListener(this);
    }

    /**
     * Method that makes the refresh of the data.
     */
    void refresh() {
        BookmarksAdapter adapter = (BookmarksAdapter)this.mBookmarksListView.getAdapter();
        adapter.clear();
        adapter.addAll(loadBookmarks());
        adapter.notifyDataSetChanged();
        this.mBookmarksListView.setSelection(0);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                back(true, null);
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
          case android.R.id.home:
              back(true, null);
              return true;
          default:
             return super.onOptionsItemSelected(item);
       }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bookmark bookmark = ((BookmarksAdapter)parent.getAdapter()).getItem(position);
        back(false, bookmark.mDirectory);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClick(View v) {
      //Retrieve the position
      int position = ((Integer)v.getTag()).intValue();
      BookmarksAdapter adapter = (BookmarksAdapter)this.mBookmarksListView.getAdapter();
      Bookmark bookmark = adapter.getItem(position);

      //Configure home
      if (bookmark.mType.compareTo(BOOKMARK_TYPE.HOME) == 0) {
          //Show a dialog for configure initial directory
          InitialDirectoryDialog dialog = new InitialDirectoryDialog(this);
          dialog.setOnValueChangedListener(new InitialDirectoryDialog.OnValueChangedListener() {
              @Override
              public void onValueChanged(String newInitialDir) {
                  refresh();
              }
          });
          dialog.show();
          return;
      }

      //Remove bookmark
      if (bookmark.mType.compareTo(BOOKMARK_TYPE.USER_DEFINED) == 0) {
          boolean result = Bookmarks.removeBookmark(this, bookmark);
          if (!result) {
              //Show warning
              DialogHelper.showToast(this, R.string.msgs_operation_failure, Toast.LENGTH_SHORT);
              return;
          }
          refresh();
          return;
      }
    }

    /**
     * Method that returns to previous activity and.
     *
     * @param canceled Indicates if the activity was canceled
     * @param directory The directory of the selected bookmark
     */
    private void back(final boolean canceled, final String directory) {
        Intent intent =  new Intent();
        if (canceled) {
            setResult(RESULT_CANCELED, intent);
        } else {
            intent.putExtra(NavigationActivity.EXTRA_BOOKMARK_SELECTION, directory);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    /**
     * Method that loads all kind of bookmarks and join in
     * an array to be used in the listview adapter.
     *
     * @return List<Bookmark>
     */
    private List<Bookmark> loadBookmarks() {
        //Bookmarks = HOME + FILESYSTEM + SD STORAGES + USER DEFINED
        List<Bookmark> bookmarks = new ArrayList<Bookmark>();
        bookmarks.add(loadHomeBookmarks());
        bookmarks.addAll(loadFilesystemBookmarks());
        bookmarks.addAll(loadSdStorageBookmarks());
        bookmarks.addAll(loadUserBookmarks());
        return bookmarks;
    }

    /**
     * Method that loads the home bookmark from the user preference.
     *
     * @return Bookmark The bookmark loaded
     */
    private Bookmark loadHomeBookmarks() {
        String initialDir = Preferences.getSharedPreferences().getString(
                                ExplorerSettings.SETTINGS_INITIAL_DIR.getId(),
                                (String)ExplorerSettings.SETTINGS_INITIAL_DIR.getDefaultValue());
        return new Bookmark(BOOKMARK_TYPE.HOME, getString(R.string.bookmarks_home), initialDir);
    }

    /**
     * Method that loads the filesystem bookmarks from the internal xml file.
     * (defined by this application)
     *
     * @return List<Bookmark> The bookmarks loaded
     */
    private List<Bookmark> loadFilesystemBookmarks() {
        try {
            //Initialize the bookmarks
            List<Bookmark> bookmarks = new ArrayList<Bookmark>();

            //Read the command list xml file
            XmlResourceParser parser = getResources().getXml(R.xml.filesystem_bookmarks);

            try {
                //Find the root element
                XmlUtils.beginDocument(parser, TAG_BOOKMARKS);
                while (true) {
                    XmlUtils.nextElement(parser);
                    String element = parser.getName();
                    if (element == null) {
                        break;
                    }

                    if (TAG_BOOKMARK.equals(element)) {
                        CharSequence name = null;
                        CharSequence directory = null;

                        try {
                            name =
                                    getString(parser.getAttributeResourceValue(
                                            R.styleable.Bookmark_name, 0));
                        } catch (Exception e) {/**NON BLOCK**/}
                        try {
                            directory =
                                    getString(parser.getAttributeResourceValue(
                                            R.styleable.Bookmark_directory, 0));
                        } catch (Exception e) {/**NON BLOCK**/}
                        if (directory == null) {
                            directory =
                                    parser.getAttributeValue(R.styleable.Bookmark_directory);
                        }
                        if (name != null && directory != null) {
                            bookmarks.add(
                                    new Bookmark(
                                            BOOKMARK_TYPE.FILESYSTEM,
                                            name.toString(),
                                            directory.toString()));
                        }
                    }
                }

                //Return the bookmarks
                return bookmarks;

            } finally {
                parser.close();
            }
        } catch (Throwable ex) {
            Log.e(TAG, "Load filesystem bookmarks failed", ex); //$NON-NLS-1$
        }

        //No data
        return new ArrayList<Bookmark>();
    }

    /**
     * Method that loads the secure digital card storage bookmarks from the system.
     *
     * @return List<Bookmark> The bookmarks loaded
     */
    private List<Bookmark> loadSdStorageBookmarks() {
        //Initialize the bookmarks
        List<Bookmark> bookmarks = new ArrayList<Bookmark>();

        try {
            //Recovery sdcards from storage manager
            //IMP!! Android SDK doesn't have a "getVolumeList" but is supported by CM10.
            //Use reflect to get this value (if possible)
            StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
            Method method = sm.getClass().getMethod("getVolumeList"); //$NON-NLS-1$
            StorageVolume[] volumes = (StorageVolume[])method.invoke(sm);
            int cc = volumes.length;
            for (int i = 0; i < cc ; i++) {
                if (volumes[i].getPath().toLowerCase().indexOf("usb") != -1) { //$NON-NLS-1$
                    bookmarks.add(
                            new Bookmark(
                                    BOOKMARK_TYPE.USB,
                                    getStorageVolumeDescription(volumes[i]),
                                    volumes[i].getPath()));
                } else {
                    bookmarks.add(
                            new Bookmark(
                                    BOOKMARK_TYPE.SDCARD,
                                    getStorageVolumeDescription(volumes[i]),
                                    volumes[i].getPath()));
                }
            }

            //Return the bookmarks
            return bookmarks;

        } catch (NoSuchMethodException nsmex) {
            //Ignore. Android SDK StorageManager class doesn't have this method
            //Use default android information from environment
            try {
                File externalStorage = Environment.getExternalStorageDirectory();
                if (externalStorage != null) {
                    String path = externalStorage.getCanonicalPath();
                    if (path.toLowerCase().indexOf("usb") != -1) { //$NON-NLS-1$
                        bookmarks.add(
                                new Bookmark(
                                        BOOKMARK_TYPE.USB,
                                        getString(R.string.bookmarks_external_storage),
                                        path));
                    } else {
                        bookmarks.add(
                                new Bookmark(
                                        BOOKMARK_TYPE.SDCARD,
                                        getString(R.string.bookmarks_external_storage),
                                        path));
                    }
                }
                //Return the bookmarks
                return bookmarks;
            } catch (Throwable ex) {
                /**NON BLOCK**/
            }


        } catch (Throwable ex) {
            Log.e(TAG, "Load filesystem bookmarks failed", ex); //$NON-NLS-1$
        }

        //No data
        return new ArrayList<Bookmark>();
    }

    /**
     * Method that returns the storage volume description. This method uses
     * reflection to retrieve the description because CM10 has a {@link Context}
     * as first parameter, that AOSP hasn't.
     *
     * @param volume The storage volume
     * @return String The description of the storage volume
     */
    private String getStorageVolumeDescription(StorageVolume volume) {
        try {
            Method method = volume.getClass().getMethod(
                                            "getDescription", //$NON-NLS-1$
                                            new Class[]{Context.class});
            if (method == null) {
                // AOSP
                method = volume.getClass().getMethod("getDescription"); //$NON-NLS-1$
                return (String)method.invoke(volume);
            }

            // CM10
            return (String)method.invoke(volume, (Context)getApplication());

        } catch (Throwable _throw) {
            // Returns the volume storage path
            return volume.getPath();
        }
    }

    /**
     * Method that loads the user bookmarks (added by the user).
     *
     * @return List<Bookmark> The bookmarks loaded
     */
    private List<Bookmark> loadUserBookmarks() {
        List<Bookmark> bookmarks = new ArrayList<Bookmark>();
        Cursor cursor = Bookmarks.getAllBookmarks(this.getContentResolver());
        if (cursor != null && cursor.moveToFirst()) {
            do {
                bookmarks.add(new Bookmark(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }
        return bookmarks;
    }
}