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