1ab92842b7732c92e636ee1f33ba9fd7c2fa1868
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
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 as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package eu.alefzero.owncloud.ui.fragment;
19
20 import java.util.List;
21
22 import android.accounts.Account;
23 import android.accounts.AccountManager;
24 import android.app.ActionBar.LayoutParams;
25 import android.content.ActivityNotFoundException;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.pm.PackageManager;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.graphics.BitmapFactory.Options;
34 import android.graphics.Path.FillType;
35 import android.net.Uri;
36 import android.os.Bundle;
37 import android.util.Log;
38 import android.view.LayoutInflater;
39 import android.view.View;
40 import android.view.View.OnClickListener;
41 import android.view.ViewGroup;
42 import android.webkit.MimeTypeMap;
43 import android.widget.Button;
44 import android.widget.ImageView;
45 import android.widget.TextView;
46 import android.widget.Toast;
47
48 import com.actionbarsherlock.app.SherlockFragment;
49
50 import eu.alefzero.owncloud.DisplayUtils;
51 import eu.alefzero.owncloud.R;
52 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
53 import eu.alefzero.owncloud.datamodel.OCFile;
54 import eu.alefzero.owncloud.files.services.FileDownloader;
55 import eu.alefzero.owncloud.utils.OwnCloudVersion;
56
57 /**
58 * This Fragment is used to display the details about a file.
59 *
60 * @author Bartek Przybylski
61 *
62 */
63 public class FileDetailFragment extends SherlockFragment implements
64 OnClickListener {
65
66 public static final String EXTRA_FILE = "FILE";
67
68 private DownloadFinishReceiver mDownloadFinishReceiver;
69 private Intent mIntent;
70 private int mLayout;
71 private View mView;
72 private OCFile mFile;
73 private static final String TAG = "FileDetailFragment";
74
75 /**
76 * Default constructor - contains real layout
77 */
78 public FileDetailFragment(){
79 mLayout = R.layout.file_details_fragment;
80 }
81
82 /**
83 * Creates a dummy layout. For use if the user never has
84 * tapped on a file before
85 *
86 * @param useEmptyView If true, use empty layout
87 */
88 public FileDetailFragment(boolean useEmptyView){
89 if(useEmptyView){
90 mLayout = R.layout.file_details_empty;
91 } else {
92 mLayout = R.layout.file_details_fragment;
93 }
94 }
95
96 /**
97 * Use this when creating the fragment and display
98 * a file at the same time
99 *
100 * @param showDetailsIntent The Intent with the required parameters
101 * @see FileDetailFragment#updateFileDetails(Intent)
102 */
103 public FileDetailFragment(Intent showDetailsIntent) {
104 mIntent = showDetailsIntent;
105 mLayout = R.layout.file_details_fragment;
106 }
107
108 @Override
109 public void onResume() {
110 super.onResume();
111 mDownloadFinishReceiver = new DownloadFinishReceiver();
112 IntentFilter filter = new IntentFilter(
113 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
114 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
115 }
116
117 @Override
118 public void onPause() {
119 super.onPause();
120 getActivity().unregisterReceiver(mDownloadFinishReceiver);
121 mDownloadFinishReceiver = null;
122 }
123
124 @Override
125 public View onCreateView(LayoutInflater inflater, ViewGroup container,
126 Bundle savedInstanceState) {
127 View view = null;
128 view = inflater.inflate(mLayout, container, false);
129 mView = view;
130 if(mLayout == R.layout.file_details_fragment){
131 // Phones will launch an activity with this intent
132 if(mIntent == null){
133 mIntent = getActivity().getIntent();
134 }
135 updateFileDetails();
136 }
137
138 return view;
139 }
140
141 @Override
142 public View getView() {
143 return super.getView() == null ? mView : super.getView();
144 }
145
146 @Override
147 public void onClick(View v) {
148 Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();
149 Intent i = new Intent(getActivity(), FileDownloader.class);
150 i.putExtra(FileDownloader.EXTRA_ACCOUNT,
151 mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT));
152 i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
153 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getURLDecodedRemotePath());
154 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());
155 getActivity().startService(i);
156 }
157
158 /**
159 * Can be used to get the file that is currently being displayed.
160 * @return The file on the screen.
161 */
162 public OCFile getDisplayedFile(){
163 return mFile;
164 }
165
166 /**
167 * Use this method to signal this Activity that it shall update its view.
168 *
169 * @param intent The {@link Intent} that contains extra information about
170 * this file The intent needs to have these extras:
171 * <p>
172 *
173 * {@link FileDetailFragment#EXTRA_FILE}: An {@link OCFile}
174 * {@link FileDownloader#EXTRA_ACCOUNT}: The Account that file
175 * belongs to (required for downloading)
176 */
177 public void updateFileDetails(Intent intent) {
178 mIntent = intent;
179 updateFileDetails();
180 }
181
182 /**
183 * Updates the view with all relevant details about that file.
184 */
185 private void updateFileDetails() {
186 mFile = mIntent.getParcelableExtra(EXTRA_FILE);
187 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
188
189 if (mFile != null) {
190 // set file details
191 setFilename(mFile.getFileName());
192 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
193 .getMimetype()));
194 setFilesize(mFile.getFileLength());
195 if(ocVersionSupportsTimeCreated()){
196 setTimeCreated(mFile.getCreationTimestamp());
197 }
198
199 setTimeModified(mFile.getModificationTimestamp());
200
201 // Update preview
202 if (mFile.getStoragePath() != null) {
203 ImageView preview = (ImageView) getView().findViewById(R.id.fdPreview);
204 try {
205 if (mFile.getMimetype().startsWith("image/")) {
206 BitmapFactory.Options options = new Options();
207 options.inScaled = true;
208 options.inPurgeable = true;
209 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
210 options.inPreferQualityOverSpeed = false;
211 }
212 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
213 options.inMutable = false;
214 }
215
216 Bitmap bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);
217
218 int width = options.outWidth;
219 int height = options.outHeight;
220 int scale = 1;
221 if (width >= 2048 || height >= 2048) {
222 scale = (int) (Math.ceil(Math.max(height, width)/2048.));
223 options.inSampleSize = scale;
224 bmp.recycle();
225
226 bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);
227 }
228 preview.setImageBitmap(bmp);
229 }
230 } catch (OutOfMemoryError e) {
231 preview.setVisibility(View.INVISIBLE);
232 Log.e(TAG, "Out of memory occured for file with size " + mFile.getFileLength());
233
234 } catch (NoSuchFieldError e) {
235 preview.setVisibility(View.INVISIBLE);
236 Log.e(TAG, "Error from access to unexisting field despite protection " + mFile.getFileLength());
237
238 } catch (Throwable t) {
239 preview.setVisibility(View.INVISIBLE);
240 Log.e(TAG, "Unexpected error while creating image preview " + mFile.getFileLength(), t);
241 }
242 downloadButton.setText(R.string.filedetails_open);
243 downloadButton.setOnClickListener(new OnClickListener() {
244 @Override
245 public void onClick(View v) {
246 String storagePath = mFile.getStoragePath();
247 try {
248 Intent i = new Intent(Intent.ACTION_VIEW);
249 i.setDataAndType(Uri.parse("file://"+ storagePath), mFile.getMimetype());
250 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
251 startActivity(i);
252
253 } catch (Throwable t) {
254 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
255 boolean toastIt = true;
256 String mimeType = "";
257 try {
258 Intent i = new Intent(Intent.ACTION_VIEW);
259 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
260 if (mimeType != mFile.getMimetype()) {
261 i.setDataAndType(Uri.parse("file://"+mFile.getStoragePath()), mimeType);
262 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
263 startActivity(i);
264 toastIt = false;
265 }
266
267 } catch (IndexOutOfBoundsException e) {
268 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
269
270 } catch (ActivityNotFoundException e) {
271 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
272
273 } catch (Throwable th) {
274 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
275
276 } finally {
277 if (toastIt) {
278 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
279 }
280 }
281
282 }
283 }
284 });
285 } else {
286 // Make download button effective
287 downloadButton.setOnClickListener(this);
288 }
289 }
290 }
291
292 /**
293 * Updates the filename in view
294 * @param filename to set
295 */
296 private void setFilename(String filename) {
297 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
298 if (tv != null)
299 tv.setText(filename);
300 }
301
302 /**
303 * Updates the MIME type in view
304 * @param mimetype to set
305 */
306 private void setFiletype(String mimetype) {
307 TextView tv = (TextView) getView().findViewById(R.id.fdType);
308 if (tv != null)
309 tv.setText(mimetype);
310 }
311
312 /**
313 * Updates the file size in view
314 * @param filesize in bytes to set
315 */
316 private void setFilesize(long filesize) {
317 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
318 if (tv != null)
319 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
320 }
321
322 /**
323 * Updates the time that the file was created in view
324 * @param milliseconds Unix time to set
325 */
326 private void setTimeCreated(long milliseconds){
327 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
328 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
329 if(tv != null){
330 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
331 tv.setVisibility(View.VISIBLE);
332 tvLabel.setVisibility(View.VISIBLE);
333 }
334 }
335
336 /**
337 * Updates the time that the file was last modified
338 * @param milliseconds Unix time to set
339 */
340 private void setTimeModified(long milliseconds){
341 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
342 if(tv != null){
343 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
344 }
345 }
346
347 /**
348 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
349 * the time that the file was created. There is a chance that this will
350 * be fixed in future versions. Use this method to check if this version of
351 * ownCloud has this fix.
352 * @return True, if ownCloud the ownCloud version is supporting creationg time
353 */
354 private boolean ocVersionSupportsTimeCreated(){
355 if(mIntent != null){
356 Account ocAccount = mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT);
357 if(ocAccount != null){
358 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
359 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
360 .getUserData(ocAccount, AccountAuthenticator.KEY_OC_VERSION));
361 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
362 return true;
363 }
364 }
365 }
366 return false;
367 }
368
369 /**
370 * Once the file download has finished -> update view
371 * @author Bartek Przybylski
372 */
373 private class DownloadFinishReceiver extends BroadcastReceiver {
374 @Override
375 public void onReceive(Context context, Intent intent) {
376 if (intent.getAction().equals(FileDownloader.BAD_DOWNLOAD_MESSAGE)) {
377 Toast.makeText(context, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
378
379 } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
380 ((OCFile)mIntent.getParcelableExtra(EXTRA_FILE)).setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
381 updateFileDetails(mIntent);
382 }
383 }
384
385 }
386
387 }