Add gestion for errors when moving files
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
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.
7 *
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.
12 *
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/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import android.content.BroadcastReceiver;
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.ServiceConnection;
25 import android.content.SharedPreferences;
26 import android.os.Bundle;
27 import android.os.IBinder;
28 import android.preference.PreferenceManager;
29 import android.support.v4.view.ViewPager;
30
31 import com.actionbarsherlock.app.ActionBar;
32 import com.actionbarsherlock.view.MenuItem;
33 import com.actionbarsherlock.view.Window;
34 import com.ortiz.touch.ExtendedViewPager;
35 import com.owncloud.android.R;
36 import com.owncloud.android.authentication.AccountUtils;
37 import com.owncloud.android.datamodel.FileDataStorageManager;
38 import com.owncloud.android.datamodel.OCFile;
39 import com.owncloud.android.files.services.FileDownloader;
40 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
41 import com.owncloud.android.files.services.FileUploader;
42 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
43 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
44 import com.owncloud.android.lib.common.operations.RemoteOperation;
45 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
46 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
47 import com.owncloud.android.operations.CreateShareOperation;
48 import com.owncloud.android.operations.RemoveFileOperation;
49 import com.owncloud.android.operations.UnshareLinkOperation;
50 import com.owncloud.android.ui.activity.FileActivity;
51 import com.owncloud.android.ui.activity.FileDisplayActivity;
52 import com.owncloud.android.ui.activity.PinCodeActivity;
53 import com.owncloud.android.ui.fragment.FileFragment;
54 import com.owncloud.android.utils.DisplayUtils;
55 import com.owncloud.android.utils.Log_OC;
56
57
58 /**
59 * Holds a swiping galley where image files contained in an ownCloud directory are shown
60 *
61 * @author David A. Velasco
62 */
63 public class PreviewImageActivity extends FileActivity implements
64 FileFragment.ContainerActivity,
65 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
66
67 public static final int DIALOG_SHORT_WAIT = 0;
68
69 public static final String TAG = PreviewImageActivity.class.getSimpleName();
70
71 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
72 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
73
74 private ExtendedViewPager mViewPager;
75 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
76
77 private boolean mRequestWaitingForBinder;
78
79 private DownloadFinishReceiver mDownloadFinishReceiver;
80
81 private boolean mFullScreen;
82
83
84 @Override
85 protected void onCreate(Bundle savedInstanceState) {
86 super.onCreate(savedInstanceState);
87
88 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
89 setContentView(R.layout.preview_image_activity);
90
91 ActionBar actionBar = getSupportActionBar();
92 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
93 actionBar.setDisplayHomeAsUpEnabled(true);
94 actionBar.hide();
95
96 // PIN CODE request
97 if (getIntent().getExtras() != null && savedInstanceState == null && fromNotification()) {
98 requestPinCode();
99 }
100
101 mFullScreen = true;
102 if (savedInstanceState != null) {
103 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
104 } else {
105 mRequestWaitingForBinder = false;
106 }
107
108 }
109
110 private void initViewPager() {
111 // get parent from path
112 String parentPath = getFile().getRemotePath().substring(0, getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
113 OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
114 if (parentFolder == null) {
115 // should not be necessary
116 parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
117 }
118 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), getStorageManager());
119 mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
120 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
121 position = (position >= 0) ? position : 0;
122 mViewPager.setAdapter(mPreviewImagePagerAdapter);
123 mViewPager.setOnPageChangeListener(this);
124 mViewPager.setCurrentItem(position);
125 if (position == 0 && !getFile().isDown()) {
126 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
127 mRequestWaitingForBinder = true;
128 }
129 }
130
131
132 @Override
133 public void onStart() {
134 super.onStart();
135 }
136
137 @Override
138 protected void onSaveInstanceState(Bundle outState) {
139 super.onSaveInstanceState(outState);
140 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
141 }
142
143 @Override
144 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
145 super.onRemoteOperationFinish(operation, result);
146
147 if (operation instanceof CreateShareOperation) {
148 onCreateShareOperationFinish((CreateShareOperation) operation, result);
149
150 } else if (operation instanceof UnshareLinkOperation) {
151 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
152
153 } else if (operation instanceof RemoveFileOperation) {
154 finish();
155 }
156 }
157
158
159 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
160 if (result.isSuccess()) {
161 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
162 if (file != null) {
163 setFile(file);
164 }
165 invalidateOptionsMenu();
166 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
167 backToDisplayActivity();
168 }
169
170 }
171
172 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
173 if (result.isSuccess()) {
174 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
175 if (file != null) {
176 setFile(file);
177 }
178 invalidateOptionsMenu();
179 }
180 }
181
182 @Override
183 protected ServiceConnection newTransferenceServiceConnection() {
184 return new PreviewImageServiceConnection();
185 }
186
187 /** Defines callbacks for service binding, passed to bindService() */
188 private class PreviewImageServiceConnection implements ServiceConnection {
189
190 @Override
191 public void onServiceConnected(ComponentName component, IBinder service) {
192
193 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
194 mDownloaderBinder = (FileDownloaderBinder) service;
195 if (mRequestWaitingForBinder) {
196 mRequestWaitingForBinder = false;
197 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
198 onPageSelected(mViewPager.getCurrentItem());
199 }
200
201 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
202 Log_OC.d(TAG, "Upload service connected");
203 mUploaderBinder = (FileUploaderBinder) service;
204 } else {
205 return;
206 }
207
208 }
209
210 @Override
211 public void onServiceDisconnected(ComponentName component) {
212 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
213 Log_OC.d(TAG, "Download service suddenly disconnected");
214 mDownloaderBinder = null;
215 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
216 Log_OC.d(TAG, "Upload service suddenly disconnected");
217 mUploaderBinder = null;
218 }
219 }
220 };
221
222
223 @Override
224 public void onStop() {
225 super.onStop();
226 }
227
228
229 @Override
230 public void onDestroy() {
231 super.onDestroy();
232 }
233
234 @Override
235 public boolean onOptionsItemSelected(MenuItem item) {
236 boolean returnValue = false;
237
238 switch(item.getItemId()){
239 case android.R.id.home:
240 backToDisplayActivity();
241 returnValue = true;
242 break;
243 default:
244 returnValue = super.onOptionsItemSelected(item);
245 }
246
247 return returnValue;
248 }
249
250
251 @Override
252 protected void onResume() {
253 super.onResume();
254 //Log.e(TAG, "ACTIVITY, ONRESUME");
255 mDownloadFinishReceiver = new DownloadFinishReceiver();
256
257 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
258 filter.addAction(FileDownloader.getDownloadAddedMessage());
259 registerReceiver(mDownloadFinishReceiver, filter);
260 }
261
262 @Override
263 protected void onPostResume() {
264 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
265 super.onPostResume();
266 }
267
268 @Override
269 public void onPause() {
270 unregisterReceiver(mDownloadFinishReceiver);
271 mDownloadFinishReceiver = null;
272 super.onPause();
273 }
274
275
276 private void backToDisplayActivity() {
277 finish();
278 }
279
280 @Override
281 public void showDetails(OCFile file) {
282 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
283 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
284 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
285 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
286 startActivity(showDetailsIntent);
287 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
288 file = mPreviewImagePagerAdapter.getFileAt(pos);
289
290 }
291
292
293 private void requestForDownload(OCFile file) {
294 if (mDownloaderBinder == null) {
295 Log_OC.d(TAG, "requestForDownload called without binder to download service");
296
297 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
298 Intent i = new Intent(this, FileDownloader.class);
299 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
300 i.putExtra(FileDownloader.EXTRA_FILE, file);
301 startService(i);
302 }
303 }
304
305 /**
306 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
307 *
308 * @param Position Position index of the new selected page
309 */
310 @Override
311 public void onPageSelected(int position) {
312 if (mDownloaderBinder == null) {
313 mRequestWaitingForBinder = true;
314
315 } else {
316 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
317 getSupportActionBar().setTitle(currentFile.getFileName());
318 if (!currentFile.isDown()) {
319 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
320 requestForDownload(currentFile);
321 }
322 }
323
324 // Call to reset image zoom to initial state
325 ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
326 }
327
328 }
329
330 /**
331 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
332 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
333 *
334 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
335 */
336 @Override
337 public void onPageScrollStateChanged(int state) {
338 }
339
340 /**
341 * This method will be invoked when the current page is scrolled, either as part of a programmatically
342 * initiated smooth scroll or a user initiated touch scroll.
343 *
344 * @param position Position index of the first page currently being displayed.
345 * Page position+1 will be visible if positionOffset is nonzero.
346 *
347 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
348 * @param positionOffsetPixels Value in pixels indicating the offset from position.
349 */
350 @Override
351 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
352 }
353
354
355 /**
356 * Class waiting for broadcast events from the {@link FielDownloader} service.
357 *
358 * Updates the UI when a download is started or finished, provided that it is relevant for the
359 * folder displayed in the gallery.
360 */
361 private class DownloadFinishReceiver extends BroadcastReceiver {
362 @Override
363 public void onReceive(Context context, Intent intent) {
364 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
365 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
366 if (getAccount().name.equals(accountName) &&
367 downloadedRemotePath != null) {
368
369 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
370 int position = mPreviewImagePagerAdapter.getFilePosition(file);
371 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
372 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
373
374 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
375 if (downloadWasFine) {
376 mPreviewImagePagerAdapter.updateFile(position, file);
377
378 } else {
379 mPreviewImagePagerAdapter.updateWithDownloadError(position);
380 }
381 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
382
383 } else {
384 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
385 }
386
387 }
388 removeStickyBroadcast(intent);
389 }
390
391 }
392
393 public void toggleFullScreen() {
394 ActionBar actionBar = getSupportActionBar();
395 if (mFullScreen) {
396 actionBar.show();
397
398 } else {
399 actionBar.hide();
400
401 }
402 mFullScreen = !mFullScreen;
403 }
404
405 @Override
406 protected void onAccountSet(boolean stateWasRecovered) {
407 super.onAccountSet(stateWasRecovered);
408 if (getAccount() != null) {
409 OCFile file = getFile();
410 /// Validate handled file (first image to preview)
411 if (file == null) {
412 throw new IllegalStateException("Instanced with a NULL OCFile");
413 }
414 if (!file.isImage()) {
415 throw new IllegalArgumentException("Non-image file passed as argument");
416 }
417
418 // Update file according to DB file, if it is possible
419 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
420 file = getStorageManager().getFileById(file.getFileId());
421
422 if (file != null) {
423 /// Refresh the activity according to the Account and OCFile set
424 setFile(file); // reset after getting it fresh from storageManager
425 getSupportActionBar().setTitle(getFile().getFileName());
426 //if (!stateWasRecovered) {
427 initViewPager();
428 //}
429
430 } else {
431 // handled file not in the current Account
432 finish();
433 }
434 }
435 }
436
437
438 /**
439 * Launch an intent to request the PIN code to the user before letting him use the app
440 */
441 private void requestPinCode() {
442 boolean pinStart = false;
443 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
444 pinStart = appPrefs.getBoolean("set_pincode", false);
445 if (pinStart) {
446 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
447 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "PreviewImageActivity");
448 startActivity(i);
449 }
450 }
451
452 @Override
453 public void onBrowsedDownTo(OCFile folder) {
454 // TODO Auto-generated method stub
455
456 }
457
458 @Override
459 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
460 // TODO Auto-generated method stub
461
462 }
463
464 }