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