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