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