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