trigger Media Scan on:
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import android.content.BroadcastReceiver;
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.ServiceConnection;
25 import android.media.MediaScannerConnection;
26 import android.media.MediaScannerConnection.OnScanCompletedListener;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.IBinder;
30 import android.support.v4.app.Fragment;
31 import android.support.v4.app.FragmentManager;
32 import android.support.v4.app.FragmentTransaction;
33 import android.support.v4.view.ViewPager;
34 import android.view.MotionEvent;
35 import android.view.View;
36 import android.view.View.OnTouchListener;
37
38 import com.actionbarsherlock.app.ActionBar;
39 import com.actionbarsherlock.view.MenuItem;
40 import com.actionbarsherlock.view.Window;
41 import com.owncloud.android.Log_OC;
42 import com.owncloud.android.R;
43 import com.owncloud.android.authentication.AccountUtils;
44 import com.owncloud.android.datamodel.FileDataStorageManager;
45 import com.owncloud.android.datamodel.OCFile;
46 import com.owncloud.android.files.services.FileDownloader;
47 import com.owncloud.android.files.services.FileUploader;
48 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
49 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
50 import com.owncloud.android.ui.activity.FileActivity;
51 import com.owncloud.android.ui.activity.FileDisplayActivity;
52 import com.owncloud.android.ui.dialog.LoadingDialog;
53 import com.owncloud.android.ui.fragment.FileFragment;
54
55
56 /**
57 * Holds a swiping galley where image files contained in an ownCloud directory are shown
58 *
59 * @author David A. Velasco
60 */
61 public class PreviewImageActivity extends FileActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
62
63 public static final int DIALOG_SHORT_WAIT = 0;
64
65 public static final String TAG = PreviewImageActivity.class.getSimpleName();
66
67 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
68 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
69
70 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
71
72 private FileDataStorageManager mStorageManager;
73
74 private ViewPager mViewPager;
75 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
76
77 private FileDownloaderBinder mDownloaderBinder = null;
78 private ServiceConnection mDownloadConnection, mUploadConnection = null;
79 private FileUploaderBinder mUploaderBinder = null;
80
81 private boolean mRequestWaitingForBinder;
82
83 private DownloadFinishReceiver mDownloadFinishReceiver;
84
85 private boolean mFullScreen;
86
87
88 @Override
89 protected void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
91
92 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
93 setContentView(R.layout.preview_image_activity);
94
95 ActionBar actionBar = getSupportActionBar();
96 actionBar.setDisplayHomeAsUpEnabled(true);
97 actionBar.hide();
98
99 mFullScreen = true;
100 if (savedInstanceState != null) {
101 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
102 } else {
103 mRequestWaitingForBinder = false;
104 }
105
106 }
107
108 private void initViewPager() {
109 // get parent from path
110 String parentPath = getFile().getRemotePath().substring(0, getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
111 OCFile parentFolder = mStorageManager.getFileByPath(parentPath);
112 //OCFile parentFolder = mStorageManager.getFileById(getFile().getParentId());
113 if (parentFolder == null) {
114 // should not be necessary
115 parentFolder = mStorageManager.getFileByPath(OCFile.ROOT_PATH);
116 }
117 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), mStorageManager);
118 mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
119 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
120 position = (position >= 0) ? position : 0;
121 mViewPager.setAdapter(mPreviewImagePagerAdapter);
122 mViewPager.setOnPageChangeListener(this);
123 mViewPager.setCurrentItem(position);
124 if (position == 0 && !getFile().isDown()) {
125 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
126 mRequestWaitingForBinder = true;
127 }
128 }
129
130
131 @Override
132 public void onStart() {
133 super.onStart();
134 mDownloadConnection = new PreviewImageServiceConnection();
135 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
136 mUploadConnection = new PreviewImageServiceConnection();
137 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
138 }
139
140 @Override
141 protected void onSaveInstanceState(Bundle outState) {
142 super.onSaveInstanceState(outState);
143 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
144 }
145
146
147 /** Defines callbacks for service binding, passed to bindService() */
148 private class PreviewImageServiceConnection implements ServiceConnection {
149
150 @Override
151 public void onServiceConnected(ComponentName component, IBinder service) {
152
153 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
154 mDownloaderBinder = (FileDownloaderBinder) service;
155 if (mRequestWaitingForBinder) {
156 mRequestWaitingForBinder = false;
157 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
158 onPageSelected(mViewPager.getCurrentItem());
159 }
160
161 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
162 Log_OC.d(TAG, "Upload service connected");
163 mUploaderBinder = (FileUploaderBinder) service;
164 } else {
165 return;
166 }
167
168 }
169
170 @Override
171 public void onServiceDisconnected(ComponentName component) {
172 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
173 Log_OC.d(TAG, "Download service suddenly disconnected");
174 mDownloaderBinder = null;
175 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
176 Log_OC.d(TAG, "Upload service suddenly disconnected");
177 mUploaderBinder = null;
178 }
179 }
180 };
181
182
183 @Override
184 public void onStop() {
185 super.onStop();
186 if (mDownloadConnection != null) {
187 unbindService(mDownloadConnection);
188 mDownloadConnection = null;
189 }
190 if (mUploadConnection != null) {
191 unbindService(mUploadConnection);
192 mUploadConnection = null;
193 }
194 }
195
196
197 @Override
198 public void onDestroy() {
199 super.onDestroy();
200 }
201
202
203 @Override
204 public boolean onOptionsItemSelected(MenuItem item) {
205 boolean returnValue = false;
206
207 switch(item.getItemId()){
208 case android.R.id.home:
209 backToDisplayActivity();
210 returnValue = true;
211 break;
212 default:
213 returnValue = super.onOptionsItemSelected(item);
214 }
215
216 return returnValue;
217 }
218
219
220 @Override
221 protected void onResume() {
222 super.onResume();
223 //Log.e(TAG, "ACTIVITY, ONRESUME");
224 mDownloadFinishReceiver = new DownloadFinishReceiver();
225
226 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
227 filter.addAction(FileDownloader.getDownloadAddedMessage());
228 registerReceiver(mDownloadFinishReceiver, filter);
229 }
230
231 @Override
232 protected void onPostResume() {
233 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
234 super.onPostResume();
235 }
236
237 @Override
238 public void onPause() {
239 super.onPause();
240 unregisterReceiver(mDownloadFinishReceiver);
241 mDownloadFinishReceiver = null;
242 }
243
244
245 private void backToDisplayActivity() {
246 finish();
247 }
248
249 /**
250 * Show loading dialog
251 */
252 public void showLoadingDialog() {
253 // Construct dialog
254 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
255 FragmentManager fm = getSupportFragmentManager();
256 FragmentTransaction ft = fm.beginTransaction();
257 loading.show(ft, DIALOG_WAIT_TAG);
258
259 }
260
261 /**
262 * Dismiss loading dialog
263 */
264 public void dismissLoadingDialog(){
265 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
266 if (frag != null) {
267 LoadingDialog loading = (LoadingDialog) frag;
268 loading.dismiss();
269 }
270 }
271
272 /**
273 * {@inheritDoc}
274 */
275 @Override
276 public void onFileStateChanged() {
277 // nothing to do here!
278 }
279
280
281 /**
282 * {@inheritDoc}
283 */
284 @Override
285 public FileDownloaderBinder getFileDownloaderBinder() {
286 return mDownloaderBinder;
287 }
288
289
290 @Override
291 public FileUploaderBinder getFileUploaderBinder() {
292 return mUploaderBinder;
293 }
294
295
296 @Override
297 public void showDetails(OCFile file) {
298 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
299 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
300 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
301 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
302 startActivity(showDetailsIntent);
303 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
304 file = mPreviewImagePagerAdapter.getFileAt(pos);
305
306 }
307
308
309 private void requestForDownload(OCFile file) {
310 if (mDownloaderBinder == null) {
311 Log_OC.d(TAG, "requestForDownload called without binder to download service");
312
313 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
314 Intent i = new Intent(this, FileDownloader.class);
315 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
316 i.putExtra(FileDownloader.EXTRA_FILE, file);
317 startService(i);
318 }
319 }
320
321 /**
322 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
323 *
324 * @param Position Position index of the new selected page
325 */
326 @Override
327 public void onPageSelected(int position) {
328 if (mDownloaderBinder == null) {
329 mRequestWaitingForBinder = true;
330
331 } else {
332 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
333 getSupportActionBar().setTitle(currentFile.getFileName());
334 if (!currentFile.isDown()) {
335 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
336 requestForDownload(currentFile);
337 }
338 }
339 }
340 }
341
342 /**
343 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
344 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
345 *
346 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
347 */
348 @Override
349 public void onPageScrollStateChanged(int state) {
350 }
351
352 /**
353 * This method will be invoked when the current page is scrolled, either as part of a programmatically
354 * initiated smooth scroll or a user initiated touch scroll.
355 *
356 * @param position Position index of the first page currently being displayed.
357 * Page position+1 will be visible if positionOffset is nonzero.
358 *
359 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
360 * @param positionOffsetPixels Value in pixels indicating the offset from position.
361 */
362 @Override
363 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
364 }
365
366
367 /**
368 * Class waiting for broadcast events from the {@link FielDownloader} service.
369 *
370 * Updates the UI when a download is started or finished, provided that it is relevant for the
371 * folder displayed in the gallery.
372 */
373 private class DownloadFinishReceiver extends BroadcastReceiver {
374 @Override
375 public void onReceive(Context context, Intent intent) {
376 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
377 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
378
379
380
381 if (getAccount().name.equals(accountName) &&
382 downloadedRemotePath != null) {
383
384 final OCFile file = mStorageManager.getFileByPath(downloadedRemotePath);
385 int position = mPreviewImagePagerAdapter.getFilePosition(file);
386 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
387 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
388
389 if (downloadWasFine){
390 // Trigger Mediascan
391 MediaScannerConnection.scanFile(
392 context,
393 new String[]{file.getStoragePath()},
394 null,null);
395 }
396
397 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
398 if (downloadWasFine) {
399 mPreviewImagePagerAdapter.updateFile(position, file);
400
401 } else {
402 mPreviewImagePagerAdapter.updateWithDownloadError(position);
403 }
404 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
405
406 } else {
407 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
408 }
409
410 }
411 removeStickyBroadcast(intent);
412 }
413
414 }
415
416
417 @Override
418 public boolean onTouch(View v, MotionEvent event) {
419 if (event.getAction() == MotionEvent.ACTION_UP) {
420 toggleFullScreen();
421 }
422 return true;
423 }
424
425
426 private void toggleFullScreen() {
427 ActionBar actionBar = getSupportActionBar();
428 if (mFullScreen) {
429 actionBar.show();
430
431 } else {
432 actionBar.hide();
433
434 }
435 mFullScreen = !mFullScreen;
436 }
437
438 @Override
439 protected void onAccountSet(boolean stateWasRecovered) {
440 if (getAccount() != null) {
441 OCFile file = getFile();
442 /// Validate handled file (first image to preview)
443 if (file == null) {
444 throw new IllegalStateException("Instanced with a NULL OCFile");
445 }
446 if (!file.isImage()) {
447 throw new IllegalArgumentException("Non-image file passed as argument");
448 }
449 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
450
451 // Update file according to DB file, if it is possible
452 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
453 file = mStorageManager.getFileById(file.getFileId());
454
455 if (file != null) {
456 /// Refresh the activity according to the Account and OCFile set
457 setFile(file); // reset after getting it fresh from mStorageManager
458 getSupportActionBar().setTitle(getFile().getFileName());
459 //if (!stateWasRecovered) {
460 initViewPager();
461 //}
462
463 } else {
464 // handled file not in the current Account
465 finish();
466 }
467
468 } else {
469 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
470 }
471 }
472
473
474 }