1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package com
.owncloud
.android
.ui
.preview
;
19 import android
.annotation
.SuppressLint
;
20 import android
.content
.BroadcastReceiver
;
21 import android
.content
.ComponentName
;
22 import android
.content
.Context
;
23 import android
.content
.Intent
;
24 import android
.content
.IntentFilter
;
25 import android
.content
.ServiceConnection
;
26 import android
.media
.MediaScannerConnection
;
27 import android
.media
.MediaScannerConnection
.OnScanCompletedListener
;
28 import android
.net
.Uri
;
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
;
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
;
67 * Holds a swiping galley where image files contained in an ownCloud directory are shown
69 * @author David A. Velasco
71 public class PreviewImageActivity
extends FileActivity
implements
72 FileFragment
.ContainerActivity
,
73 ViewPager
.OnPageChangeListener
, OnRemoteOperationListener
{
75 public static final int DIALOG_SHORT_WAIT
= 0;
77 public static final String TAG
= PreviewImageActivity
.class.getSimpleName();
79 public static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
80 private static final String KEY_WAITING_FOR_BINDER
= "WAITING_FOR_BINDER";
82 private static final int INITIAL_HIDE_DELAY
= 0; // immediate hide
84 private ExtendedViewPager mViewPager
;
85 private PreviewImagePagerAdapter mPreviewImagePagerAdapter
;
87 private boolean mRequestWaitingForBinder
;
89 private DownloadFinishReceiver mDownloadFinishReceiver
;
91 private View mFullScreenAnchorView
;
95 protected void onCreate(Bundle savedInstanceState
) {
96 super.onCreate(savedInstanceState
);
98 requestWindowFeature(Window
.FEATURE_ACTION_BAR_OVERLAY
);
99 setContentView(R
.layout
.preview_image_activity
);
101 ActionBar actionBar
= getSupportActionBar();
102 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
103 actionBar
.setDisplayHomeAsUpEnabled(true
);
107 if (getIntent().getExtras() != null
&& savedInstanceState
== null
&& fromNotification()) {
111 // Make sure we're running on Honeycomb or higher to use FullScreen and
113 if (isHoneycombOrHigher()) {
115 mFullScreenAnchorView
= getWindow().getDecorView();
116 // to keep our UI controls visibility in line with system bars
118 mFullScreenAnchorView
.setOnSystemUiVisibilityChangeListener(new View
.OnSystemUiVisibilityChangeListener() {
119 @SuppressLint("InlinedApi")
121 public void onSystemUiVisibilityChange(int flags
) {
122 boolean visible
= (flags
& View
.SYSTEM_UI_FLAG_HIDE_NAVIGATION
) == 0;
123 ActionBar actionBar
= getSupportActionBar();
134 if (savedInstanceState
!= null
) {
135 mRequestWaitingForBinder
= savedInstanceState
.getBoolean(KEY_WAITING_FOR_BINDER
);
137 mRequestWaitingForBinder
= false
;
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
);
150 mPreviewImagePagerAdapter
= new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder
, getAccount(), getStorageManager());
151 mViewPager
= (ExtendedViewPager
) findViewById(R
.id
.fragmentPager
);
152 int position
= 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
;
164 protected void onPostCreate(Bundle savedInstanceState
) {
165 super.onPostCreate(savedInstanceState
);
167 // Trigger the initial hide() shortly after the activity has been
168 // created, to briefly hint to the user that UI controls
170 delayedHide(INITIAL_HIDE_DELAY
);
174 Handler mHideSystemUiHandler
= new Handler() {
176 public void handleMessage(Message msg
) {
177 if (isHoneycombOrHigher()) {
178 hideSystemUI(mFullScreenAnchorView
);
180 getSupportActionBar().hide();
184 private void delayedHide(int delayMillis
) {
185 mHideSystemUiHandler
.removeMessages(0);
186 mHideSystemUiHandler
.sendEmptyMessageDelayed(0, delayMillis
);
190 /// handle Window Focus changes
192 public void onWindowFocusChanged(boolean hasFocus
) {
193 super.onWindowFocusChanged(hasFocus
);
195 // When the window loses focus (e.g. the action overflow is shown),
196 // cancel any pending hide action.
198 mHideSystemUiHandler
.removeMessages(0);
205 public void onStart() {
210 protected void onSaveInstanceState(Bundle outState
) {
211 super.onSaveInstanceState(outState
);
212 outState
.putBoolean(KEY_WAITING_FOR_BINDER
, mRequestWaitingForBinder
);
216 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
217 super.onRemoteOperationFinish(operation
, result
);
219 if (operation
instanceof CreateShareOperation
) {
220 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
222 } else if (operation
instanceof UnshareLinkOperation
) {
223 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
225 } else if (operation
instanceof RemoveFileOperation
) {
231 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
232 if (result
.isSuccess()) {
233 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
237 invalidateOptionsMenu();
238 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
239 backToDisplayActivity();
244 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
245 if (result
.isSuccess()) {
246 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
250 invalidateOptionsMenu();
255 protected ServiceConnection
newTransferenceServiceConnection() {
256 return new PreviewImageServiceConnection();
259 /** Defines callbacks for service binding, passed to bindService() */
260 private class PreviewImageServiceConnection
implements ServiceConnection
{
263 public void onServiceConnected(ComponentName component
, IBinder service
) {
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());
273 } else if (component
.equals(new ComponentName(PreviewImageActivity
.this, FileUploader
.class))) {
274 Log_OC
.d(TAG
, "Upload service connected");
275 mUploaderBinder
= (FileUploaderBinder
) service
;
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
;
296 public void onStop() {
302 public void onDestroy() {
307 public boolean onOptionsItemSelected(MenuItem item
) {
308 boolean returnValue
= false
;
310 switch(item
.getItemId()){
311 case android
.R
.id
.home
:
312 backToDisplayActivity();
316 returnValue
= super.onOptionsItemSelected(item
);
324 protected void onResume() {
326 //Log_OC.e(TAG, "ACTIVITY, ONRESUME");
327 mDownloadFinishReceiver
= new DownloadFinishReceiver();
329 IntentFilter filter
= new IntentFilter(FileDownloader
.getDownloadFinishMessage());
330 filter
.addAction(FileDownloader
.getDownloadAddedMessage());
331 registerReceiver(mDownloadFinishReceiver
, filter
);
335 protected void onPostResume() {
336 //Log_OC.e(TAG, "ACTIVITY, ONPOSTRESUME");
337 super.onPostResume();
341 public void onPause() {
342 unregisterReceiver(mDownloadFinishReceiver
);
343 mDownloadFinishReceiver
= null
;
348 private void backToDisplayActivity() {
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
);
365 private void requestForDownload(OCFile file
) {
366 if (mDownloaderBinder
== null
) {
367 Log_OC
.d(TAG
, "requestForDownload called without binder to download service");
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
);
378 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
380 * @param Position Position index of the new selected page
383 public void onPageSelected(int position
) {
384 if (mDownloaderBinder
== null
) {
385 mRequestWaitingForBinder
= true
;
388 OCFile currentFile
= mPreviewImagePagerAdapter
.getFileAt(position
);
389 getSupportActionBar().setTitle(currentFile
.getFileName());
390 if (!currentFile
.isDown()) {
391 if (!mPreviewImagePagerAdapter
.pendingErrorAt(position
)) {
392 requestForDownload(currentFile
);
396 // Call to reset image zoom to initial state
397 ((PreviewImagePagerAdapter
) mViewPager
.getAdapter()).resetZoom();
403 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
404 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
406 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
409 public void onPageScrollStateChanged(int state
) {
413 * This method will be invoked when the current page is scrolled, either as part of a programmatically
414 * initiated smooth scroll or a user initiated touch scroll.
416 * @param position Position index of the first page currently being displayed.
417 * Page position+1 will be visible if positionOffset is nonzero.
419 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
420 * @param positionOffsetPixels Value in pixels indicating the offset from position.
423 public void onPageScrolled(int position
, float positionOffset
, int positionOffsetPixels
) {
428 * Class waiting for broadcast events from the {@link FielDownloader} service.
430 * Updates the UI when a download is started or finished, provided that it is relevant for the
431 * folder displayed in the gallery.
433 private class DownloadFinishReceiver
extends BroadcastReceiver
{
435 public void onReceive(Context context
, Intent intent
) {
436 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
437 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
441 if (getAccount().name
.equals(accountName
) &&
442 downloadedRemotePath
!= null
) {
444 OCFile file
= getStorageManager().getFileByPath(downloadedRemotePath
);
445 int position
= mPreviewImagePagerAdapter
.getFilePosition(file
);
446 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
447 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
449 if (downloadWasFine
){
451 MediaScannerConnection
.scanFile(
453 new String
[]{file
.getStoragePath()},
457 if (position
>= 0 && intent
.getAction().equals(FileDownloader
.getDownloadFinishMessage())) {
458 if (downloadWasFine
) {
459 mPreviewImagePagerAdapter
.updateFile(position
, file
);
462 mPreviewImagePagerAdapter
.updateWithDownloadError(position
);
464 mPreviewImagePagerAdapter
.notifyDataSetChanged(); // will trigger the creation of new fragments
467 Log_OC
.d(TAG
, "Download finished, but the fragment is offscreen");
471 removeStickyBroadcast(intent
);
476 @SuppressLint("InlinedApi")
477 public void toggleFullScreen() {
479 if (isHoneycombOrHigher()) {
481 boolean visible
= (mFullScreenAnchorView
.getSystemUiVisibility()
482 & View
.SYSTEM_UI_FLAG_HIDE_NAVIGATION
) == 0;
485 hideSystemUI(mFullScreenAnchorView
);
486 // actionBar.hide(); // propagated through
487 // OnSystemUiVisibilityChangeListener()
489 showSystemUI(mFullScreenAnchorView
);
490 // actionBar.show(); // propagated through
491 // OnSystemUiVisibilityChangeListener()
496 ActionBar actionBar
= getSupportActionBar();
497 if (!actionBar
.isShowing()) {
509 protected void onAccountSet(boolean stateWasRecovered
) {
510 super.onAccountSet(stateWasRecovered
);
511 if (getAccount() != null
) {
512 OCFile file
= getFile();
513 /// Validate handled file (first image to preview)
515 throw new IllegalStateException("Instanced with a NULL OCFile");
517 if (!file
.isImage()) {
518 throw new IllegalArgumentException("Non-image file passed as argument");
521 // Update file according to DB file, if it is possible
522 if (file
.getFileId() > FileDataStorageManager
.ROOT_PARENT_ID
)
523 file
= getStorageManager().getFileById(file
.getFileId());
526 /// Refresh the activity according to the Account and OCFile set
527 setFile(file
); // reset after getting it fresh from storageManager
528 getSupportActionBar().setTitle(getFile().getFileName());
529 //if (!stateWasRecovered) {
534 // handled file not in the current Account
542 * Launch an intent to request the PIN code to the user before letting him use the app
544 private void requestPinCode() {
545 boolean pinStart
= false
;
546 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
547 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
549 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
550 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "PreviewImageActivity");
556 public void onBrowsedDownTo(OCFile folder
) {
557 // TODO Auto-generated method stub
562 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
563 // TODO Auto-generated method stub
568 @SuppressLint("InlinedApi")
569 private void hideSystemUI(View anchorView
) {
570 anchorView
.setSystemUiVisibility(
571 View
.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// hides NAVIGATION BAR; Android >= 4.0
572 | View
.SYSTEM_UI_FLAG_FULLSCREEN
// hides STATUS BAR; Android >= 4.1
573 | View
.SYSTEM_UI_FLAG_IMMERSIVE
// stays interactive; Android >= 4.4
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
580 @SuppressLint("InlinedApi")
581 private void showSystemUI(View anchorView
) {
582 anchorView
.setSystemUiVisibility(
583 View
.SYSTEM_UI_FLAG_LAYOUT_STABLE
// draw full window; Android >= 4.1
584 | View
.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// draw full window; Android >= 4.1
585 | View
.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// draw full window; Android >= 4.1
590 * Checks if OS version is Honeycomb one or higher
594 private boolean isHoneycombOrHigher() {
595 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.HONEYCOMB
) {