Merge branch 'develop' into thumbnailOOM
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20 package com.owncloud.android.ui.preview;
21
22 import android.annotation.SuppressLint;
23 import android.content.BroadcastReceiver;
24 import android.content.ComponentName;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.ServiceConnection;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.IBinder;
33 import android.os.Message;
34 import android.support.v4.view.ViewPager;
35 import android.view.View;
36
37 import com.actionbarsherlock.app.ActionBar;
38 import com.actionbarsherlock.view.MenuItem;
39 import com.actionbarsherlock.view.Window;
40 import com.ortiz.touch.ExtendedViewPager;
41 import com.owncloud.android.R;
42 import com.owncloud.android.authentication.AccountUtils;
43 import com.owncloud.android.datamodel.FileDataStorageManager;
44 import com.owncloud.android.datamodel.OCFile;
45 import com.owncloud.android.files.services.FileDownloader;
46 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
47 import com.owncloud.android.files.services.FileUploader;
48 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
49 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
50 import com.owncloud.android.lib.common.operations.RemoteOperation;
51 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
52 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
53 import com.owncloud.android.lib.common.utils.Log_OC;
54 import com.owncloud.android.operations.CreateShareOperation;
55 import com.owncloud.android.operations.RemoveFileOperation;
56 import com.owncloud.android.operations.UnshareLinkOperation;
57 import com.owncloud.android.ui.activity.FileActivity;
58 import com.owncloud.android.ui.activity.FileDisplayActivity;
59 import com.owncloud.android.ui.fragment.FileFragment;
60 import com.owncloud.android.utils.DisplayUtils;
61
62
63 /**
64 * Holds a swiping galley where image files contained in an ownCloud directory are shown
65 */
66 public class PreviewImageActivity extends FileActivity implements
67 FileFragment.ContainerActivity,
68 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
69
70 public static final int DIALOG_SHORT_WAIT = 0;
71
72 public static final String TAG = PreviewImageActivity.class.getSimpleName();
73
74 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
75 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
76
77 private static final int INITIAL_HIDE_DELAY = 0; // immediate hide
78
79 private ExtendedViewPager mViewPager;
80 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
81 private int mSavedPosition = 0;
82 private boolean mHasSavedPosition = false;
83
84 private boolean mRequestWaitingForBinder;
85
86 private DownloadFinishReceiver mDownloadFinishReceiver;
87
88 private View mFullScreenAnchorView;
89
90
91 @Override
92 protected void onCreate(Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
94
95 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
96 setContentView(R.layout.preview_image_activity);
97
98 ActionBar actionBar = getSupportActionBar();
99 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
100 actionBar.setDisplayHomeAsUpEnabled(true);
101 actionBar.hide();
102
103 // Make sure we're running on Honeycomb or higher to use FullScreen and
104 // Immersive Mode
105 if (isHoneycombOrHigher()) {
106
107 mFullScreenAnchorView = getWindow().getDecorView();
108 // to keep our UI controls visibility in line with system bars
109 // visibility
110 mFullScreenAnchorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
111 @SuppressLint("InlinedApi")
112 @Override
113 public void onSystemUiVisibilityChange(int flags) {
114 boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
115 ActionBar actionBar = getSupportActionBar();
116 if (visible) {
117 actionBar.show();
118 } else {
119 actionBar.hide();
120 }
121 }
122 });
123
124 }
125
126 if (savedInstanceState != null) {
127 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
128 } else {
129 mRequestWaitingForBinder = false;
130 }
131
132 }
133
134 private void initViewPager() {
135 // get parent from path
136 String parentPath = getFile().getRemotePath().substring(0, getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
137 OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
138 if (parentFolder == null) {
139 // should not be necessary
140 parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
141 }
142 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), getStorageManager());
143 mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
144 int position = mHasSavedPosition ? mSavedPosition : mPreviewImagePagerAdapter.getFilePosition(getFile());
145 position = (position >= 0) ? position : 0;
146 mViewPager.setAdapter(mPreviewImagePagerAdapter);
147 mViewPager.setOnPageChangeListener(this);
148 mViewPager.setCurrentItem(position);
149 if (position == 0 && !getFile().isDown()) {
150 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
151 mRequestWaitingForBinder = true;
152 }
153 }
154
155
156 protected void onPostCreate(Bundle savedInstanceState) {
157 super.onPostCreate(savedInstanceState);
158
159 // Trigger the initial hide() shortly after the activity has been
160 // created, to briefly hint to the user that UI controls
161 // are available
162 delayedHide(INITIAL_HIDE_DELAY);
163
164 }
165
166 Handler mHideSystemUiHandler = new Handler() {
167 @Override
168 public void handleMessage(Message msg) {
169 if (isHoneycombOrHigher()) {
170 hideSystemUI(mFullScreenAnchorView);
171 }
172 getSupportActionBar().hide();
173 }
174 };
175
176 private void delayedHide(int delayMillis) {
177 mHideSystemUiHandler.removeMessages(0);
178 mHideSystemUiHandler.sendEmptyMessageDelayed(0, delayMillis);
179 }
180
181
182 /// handle Window Focus changes
183 @Override
184 public void onWindowFocusChanged(boolean hasFocus) {
185 super.onWindowFocusChanged(hasFocus);
186
187 // When the window loses focus (e.g. the action overflow is shown),
188 // cancel any pending hide action.
189 if (!hasFocus) {
190 mHideSystemUiHandler.removeMessages(0);
191 }
192 }
193
194
195
196 @Override
197 public void onStart() {
198 super.onStart();
199 }
200
201 @Override
202 protected void onSaveInstanceState(Bundle outState) {
203 super.onSaveInstanceState(outState);
204 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
205 }
206
207 @Override
208 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
209 super.onRemoteOperationFinish(operation, result);
210
211 if (operation instanceof CreateShareOperation) {
212 onCreateShareOperationFinish((CreateShareOperation) operation, result);
213
214 } else if (operation instanceof UnshareLinkOperation) {
215 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
216
217 } else if (operation instanceof RemoveFileOperation) {
218 finish();
219 }
220 }
221
222
223 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
224 if (result.isSuccess()) {
225 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
226 if (file != null) {
227 setFile(file);
228 }
229 invalidateOptionsMenu();
230 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
231 backToDisplayActivity();
232 }
233
234 }
235
236 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
237 if (result.isSuccess()) {
238 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
239 if (file != null) {
240 setFile(file);
241 }
242 invalidateOptionsMenu();
243 }
244 }
245
246 @Override
247 protected ServiceConnection newTransferenceServiceConnection() {
248 return new PreviewImageServiceConnection();
249 }
250
251 /** Defines callbacks for service binding, passed to bindService() */
252 private class PreviewImageServiceConnection implements ServiceConnection {
253
254 @Override
255 public void onServiceConnected(ComponentName component, IBinder service) {
256
257 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
258 mDownloaderBinder = (FileDownloaderBinder) service;
259 if (mRequestWaitingForBinder) {
260 mRequestWaitingForBinder = false;
261 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
262 onPageSelected(mViewPager.getCurrentItem());
263 }
264
265 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
266 Log_OC.d(TAG, "Upload service connected");
267 mUploaderBinder = (FileUploaderBinder) service;
268 } else {
269 return;
270 }
271
272 }
273
274 @Override
275 public void onServiceDisconnected(ComponentName component) {
276 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
277 Log_OC.d(TAG, "Download service suddenly disconnected");
278 mDownloaderBinder = null;
279 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
280 Log_OC.d(TAG, "Upload service suddenly disconnected");
281 mUploaderBinder = null;
282 }
283 }
284 };
285
286
287 @Override
288 public void onStop() {
289 super.onStop();
290 }
291
292
293 @Override
294 public void onDestroy() {
295 super.onDestroy();
296 }
297
298 @Override
299 public boolean onOptionsItemSelected(MenuItem item) {
300 boolean returnValue = false;
301
302 switch(item.getItemId()){
303 case android.R.id.home:
304 backToDisplayActivity();
305 returnValue = true;
306 break;
307 default:
308 returnValue = super.onOptionsItemSelected(item);
309 }
310
311 return returnValue;
312 }
313
314
315 @Override
316 protected void onResume() {
317 super.onResume();
318
319 mDownloadFinishReceiver = new DownloadFinishReceiver();
320
321 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
322 filter.addAction(FileDownloader.getDownloadAddedMessage());
323 registerReceiver(mDownloadFinishReceiver, filter);
324 }
325
326 @Override
327 protected void onPostResume() {
328 super.onPostResume();
329 }
330
331 @Override
332 public void onPause() {
333 if (mDownloadFinishReceiver != null){
334 unregisterReceiver(mDownloadFinishReceiver);
335 mDownloadFinishReceiver = null;
336 }
337
338 super.onPause();
339 }
340
341
342 private void backToDisplayActivity() {
343 finish();
344 }
345
346 @Override
347 public void showDetails(OCFile file) {
348 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
349 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
350 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
351 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
352 startActivity(showDetailsIntent);
353 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
354 file = mPreviewImagePagerAdapter.getFileAt(pos);
355
356 }
357
358
359 private void requestForDownload(OCFile file) {
360 if (mDownloaderBinder == null) {
361 Log_OC.d(TAG, "requestForDownload called without binder to download service");
362
363 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
364 Intent i = new Intent(this, FileDownloader.class);
365 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
366 i.putExtra(FileDownloader.EXTRA_FILE, file);
367 startService(i);
368 }
369 }
370
371 /**
372 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
373 *
374 * @param Position Position index of the new selected page
375 */
376 @Override
377 public void onPageSelected(int position) {
378 mSavedPosition = position;
379 mHasSavedPosition = true;
380 if (mDownloaderBinder == null) {
381 mRequestWaitingForBinder = true;
382
383 } else {
384 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
385 getSupportActionBar().setTitle(currentFile.getFileName());
386 if (!currentFile.isDown()) {
387 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
388 requestForDownload(currentFile);
389 }
390 }
391
392 // Call to reset image zoom to initial state
393 ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
394 }
395
396 }
397
398 /**
399 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
400 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
401 *
402 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
403 */
404 @Override
405 public void onPageScrollStateChanged(int state) {
406 }
407
408 /**
409 * This method will be invoked when the current page is scrolled, either as part of a programmatically
410 * initiated smooth scroll or a user initiated touch scroll.
411 *
412 * @param position Position index of the first page currently being displayed.
413 * Page position+1 will be visible if positionOffset is nonzero.
414 *
415 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
416 * @param positionOffsetPixels Value in pixels indicating the offset from position.
417 */
418 @Override
419 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
420 }
421
422
423 /**
424 * Class waiting for broadcast events from the {@link FileDownloader} service.
425 *
426 * Updates the UI when a download is started or finished, provided that it is relevant for the
427 * folder displayed in the gallery.
428 */
429 private class DownloadFinishReceiver extends BroadcastReceiver {
430 @Override
431 public void onReceive(Context context, Intent intent) {
432 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
433 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
434 if (getAccount().name.equals(accountName) &&
435 downloadedRemotePath != null) {
436
437 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
438 int position = mPreviewImagePagerAdapter.getFilePosition(file);
439 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
440 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
441
442 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
443 if (downloadWasFine) {
444 mPreviewImagePagerAdapter.updateFile(position, file);
445
446 } else {
447 mPreviewImagePagerAdapter.updateWithDownloadError(position);
448 }
449 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
450
451 } else {
452 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
453 }
454
455 }
456 removeStickyBroadcast(intent);
457 }
458
459 }
460
461 @SuppressLint("InlinedApi")
462 public void toggleFullScreen() {
463
464 if (isHoneycombOrHigher()) {
465
466 boolean visible = (mFullScreenAnchorView.getSystemUiVisibility()
467 & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
468
469 if (visible) {
470 hideSystemUI(mFullScreenAnchorView);
471 // actionBar.hide(); // propagated through
472 // OnSystemUiVisibilityChangeListener()
473 } else {
474 showSystemUI(mFullScreenAnchorView);
475 // actionBar.show(); // propagated through
476 // OnSystemUiVisibilityChangeListener()
477 }
478
479 } else {
480
481 ActionBar actionBar = getSupportActionBar();
482 if (!actionBar.isShowing()) {
483 actionBar.show();
484
485 } else {
486 actionBar.hide();
487
488 }
489
490 }
491 }
492
493 @Override
494 protected void onAccountSet(boolean stateWasRecovered) {
495 super.onAccountSet(stateWasRecovered);
496 if (getAccount() != null) {
497 OCFile file = getFile();
498 /// Validate handled file (first image to preview)
499 if (file == null) {
500 throw new IllegalStateException("Instanced with a NULL OCFile");
501 }
502 if (!file.isImage()) {
503 throw new IllegalArgumentException("Non-image file passed as argument");
504 }
505
506 // Update file according to DB file, if it is possible
507 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
508 file = getStorageManager().getFileById(file.getFileId());
509
510 if (file != null) {
511 /// Refresh the activity according to the Account and OCFile set
512 setFile(file); // reset after getting it fresh from storageManager
513 getSupportActionBar().setTitle(getFile().getFileName());
514 //if (!stateWasRecovered) {
515 initViewPager();
516 //}
517
518 } else {
519 // handled file not in the current Account
520 finish();
521 }
522 }
523 }
524
525 @Override
526 public void onBrowsedDownTo(OCFile folder) {
527 // TODO Auto-generated method stub
528
529 }
530
531 @Override
532 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
533 // TODO Auto-generated method stub
534
535 }
536
537
538 @SuppressLint("InlinedApi")
539 private void hideSystemUI(View anchorView) {
540 anchorView.setSystemUiVisibility(
541 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
542 | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
543 | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
544 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
545 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
546 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
547 );
548 }
549
550 @SuppressLint("InlinedApi")
551 private void showSystemUI(View anchorView) {
552 anchorView.setSystemUiVisibility(
553 View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
554 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
555 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
556 );
557 }
558
559 /**
560 * Checks if OS version is Honeycomb one or higher
561 *
562 * @return boolean
563 */
564 private boolean isHoneycombOrHigher() {
565 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
566 return true;
567 }
568 return false;
569 }
570 }