summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/activity/DirectoryChooserActivity.java
blob: 54c4f05891d85397daec42c1e4d8b7ad91098e89 (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
package de.danoeh.antennapod.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.preferences.UserPreferences;

/**
 * Let's the user choose a directory on the storage device. The selected folder
 * will be sent back to the starting activity as an activity result.
 */
public class DirectoryChooserActivity extends SherlockActivity {
	private static final String TAG = "DirectoryChooserActivity";

	private static final String CREATE_DIRECTORY_NAME = "AntennaPod";

	public static final String RESULT_SELECTED_DIR = "selected_dir";
	public static final int RESULT_CODE_DIR_SELECTED = 1;

	private Button butConfirm;
	private Button butCancel;
	private ImageButton butNavUp;
	private TextView txtvSelectedFolder;
	private ListView listDirectories;

	private ArrayAdapter<String> listDirectoriesAdapter;
	private ArrayList<String> filenames;
	/** The directory that is currently being shown. */
	private File selectedDir;
	private File[] filesInDir;

	private FileObserver fileObserver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(UserPreferences.getTheme());
		super.onCreate(savedInstanceState);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		setContentView(R.layout.directory_chooser);
		butConfirm = (Button) findViewById(R.id.butConfirm);
		butCancel = (Button) findViewById(R.id.butCancel);
		butNavUp = (ImageButton) findViewById(R.id.butNavUp);
		txtvSelectedFolder = (TextView) findViewById(R.id.txtvSelectedFolder);
		listDirectories = (ListView) findViewById(R.id.directory_list);

		butConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isValidFile(selectedDir)) {
					if (selectedDir.list().length == 0) {
						returnSelectedFolder();
					} else {
						showNonEmptyDirectoryWarning();
					}
				}
			}

			private void showNonEmptyDirectoryWarning() {
				AlertDialog.Builder adb = new AlertDialog.Builder(
						DirectoryChooserActivity.this);
				adb.setTitle(R.string.folder_not_empty_dialog_title);
				adb.setMessage(R.string.folder_not_empty_dialog_msg);
				adb.setNegativeButton(R.string.cancel_label,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				adb.setPositiveButton(R.string.confirm_label,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								returnSelectedFolder();
							}
						});
				adb.create().show();
			}
		});

		butCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(Activity.RESULT_CANCELED);
				finish();
			}
		});

		listDirectories.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view,
					int position, long id) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Selected index: " + position);
				if (filesInDir != null && position >= 0
						&& position < filesInDir.length) {
					changeDirectory(filesInDir[position]);
				}
			}
		});

		butNavUp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				File parent = null;
				if (selectedDir != null
						&& (parent = selectedDir.getParentFile()) != null) {
					changeDirectory(parent);
				}
			}
		});

		filenames = new ArrayList<String>();
		listDirectoriesAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, filenames);
		listDirectories.setAdapter(listDirectoriesAdapter);
		changeDirectory(Environment.getExternalStorageDirectory());
	}

	/**
	 * Finishes the activity and returns the selected folder as a result. The
	 * selected folder can also be null.
	 */
	private void returnSelectedFolder() {
		if (selectedDir != null && AppConfig.DEBUG)
			Log.d(TAG, "Returning " + selectedDir.getAbsolutePath()
					+ " as result");
		Intent resultData = new Intent();
		if (selectedDir != null) {
			resultData.putExtra(RESULT_SELECTED_DIR,
					selectedDir.getAbsolutePath());
		}
		setResult(RESULT_CODE_DIR_SELECTED, resultData);
		finish();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (fileObserver != null) {
			fileObserver.stopWatching();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (fileObserver != null) {
			fileObserver.startWatching();
		}
	}

	/**
	 * Change the directory that is currently being displayed.
	 * 
	 * @param dir
	 *            The file the activity should switch to. This File must be
	 *            non-null and a directory, otherwise the displayed directory
	 *            will not be changed
	 */
	private void changeDirectory(File dir) {
		if (dir != null && dir.isDirectory()) {
			File[] contents = dir.listFiles();
			if (contents != null) {
				int numDirectories = 0;
				for (File f : contents) {
					if (f.isDirectory()) {
						numDirectories++;
					}
				}
				filesInDir = new File[numDirectories];
				filenames.clear();
				for (int i = 0, counter = 0; i < numDirectories; counter++) {
					if (contents[counter].isDirectory()) {
						filesInDir[i] = contents[counter];
						filenames.add(contents[counter].getName());
						i++;
					}
				}
				Arrays.sort(filesInDir);
				Collections.sort(filenames);
				selectedDir = dir;
				txtvSelectedFolder.setText(dir.getAbsolutePath());
				listDirectoriesAdapter.notifyDataSetChanged();
				fileObserver = createFileObserver(dir.getAbsolutePath());
				fileObserver.startWatching();
				if (AppConfig.DEBUG)
					Log.d(TAG, "Changed directory to " + dir.getAbsolutePath());
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG,
							"Could not change folder: contents of dir were null");
			}
		} else {
			if (dir == null) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Could not change folder: dir was null");
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Could not change folder: dir is no directory");
			}
		}
		refreshButtonState();
	}

	/**
	 * Changes the state of the buttons depending on the currently selected file
	 * or folder.
	 */
	private void refreshButtonState() {
		if (selectedDir != null) {
			butConfirm.setEnabled(isValidFile(selectedDir));
			supportInvalidateOptionsMenu();
		}
	}

	/** Refresh the contents of the directory that is currently shown. */
	private void refreshDirectory() {
		if (selectedDir != null) {
			changeDirectory(selectedDir);
		}
	}

	/** Sets up a FileObserver to watch the current directory. */
	private FileObserver createFileObserver(String path) {
		return new FileObserver(path, FileObserver.CREATE | FileObserver.DELETE
				| FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

			@Override
			public void onEvent(int event, String path) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "FileObserver received event " + event);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						refreshDirectory();
					}
				});
			}
		};
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(R.id.new_folder_item)
				.setVisible(isValidFile(selectedDir));
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.directory_chooser, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.new_folder_item:
			openNewFolderDialog();
			return true;
		case R.id.set_to_default_folder_item:
			selectedDir = null;
			returnSelectedFolder();
			return true;
		default:
			return false;
		}
	}

	/**
	 * Shows a confirmation dialog that asks the user if he wants to create a
	 * new folder.
	 */
	private void openNewFolderDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.create_folder_label);
		builder.setMessage(String.format(getString(R.string.create_folder_msg),
				CREATE_DIRECTORY_NAME));
		builder.setNegativeButton(R.string.cancel_label,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.setPositiveButton(R.string.confirm_label,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						int msg = createFolder();
						Toast t = Toast.makeText(DirectoryChooserActivity.this,
								msg, Toast.LENGTH_SHORT);
						t.show();
					}
				});
		builder.create().show();
	}

	/**
	 * Creates a new folder in the current directory with the name
	 * CREATE_DIRECTORY_NAME.
	 */
	private int createFolder() {
		if (selectedDir != null && selectedDir.canWrite()) {
			File newDir = new File(selectedDir, CREATE_DIRECTORY_NAME);
			if (!newDir.exists()) {
				boolean result = newDir.mkdir();
				if (result) {
					return R.string.create_folder_success;
				} else {
					return R.string.create_folder_error;
				}
			} else {
				return R.string.create_folder_error_already_exists;
			}
		} else if (selectedDir.canWrite() == false) {
			return R.string.create_folder_error_no_write_access;
		} else {
			return R.string.create_folder_error;
		}
	}

	/** Returns true if the selected file or directory would be valid selection. */
	private boolean isValidFile(File file) {
		return (file != null && file.isDirectory() && file.canRead() && file
				.canWrite());
	}
}