OSDN Git Service

9a7031bf93789b63f0e9150cd0c4a583d38b4d5f
[gokigen/Gr2Control.git] / app / src / main / java / net / osdn / gokigen / gr2control / playback / detail / ImagePagerViewFragment.java
1 package net.osdn.gokigen.gr2control.playback.detail;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Calendar;
5 import java.util.Date;
6 import java.util.List;
7 import java.util.Locale;
8 import java.util.Map;
9
10 import android.app.Activity;
11 import android.app.AlertDialog;
12 import android.graphics.Bitmap;
13 import android.support.annotation.NonNull;
14 import android.os.Bundle;
15 import android.support.v4.app.Fragment;
16 import android.support.v4.view.PagerAdapter;
17 import android.support.v4.view.ViewPager;
18 import android.support.v4.view.ViewPager.OnPageChangeListener;
19 import android.support.v7.app.ActionBar;
20 import android.support.v7.app.AppCompatActivity;
21 import android.util.Log;
22 import android.util.LruCache;
23 import android.view.LayoutInflater;
24 import android.view.Menu;
25 import android.view.MenuInflater;
26 import android.view.MenuItem;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.widget.ImageView;
30
31 import net.osdn.gokigen.gr2control.R;
32 import net.osdn.gokigen.gr2control.camera.ICameraFileInfo;
33 import net.osdn.gokigen.gr2control.camera.ICameraRunMode;
34 import net.osdn.gokigen.gr2control.camera.playback.IDownloadThumbnailImageCallback;
35 import net.osdn.gokigen.gr2control.camera.playback.IPlaybackControl;
36
37 public class ImagePagerViewFragment extends Fragment
38 {
39     private final String TAG = this.toString();
40     private static final String JPEG_SUFFIX = ".JPG";
41
42     private IPlaybackControl playbackControl;
43     private ICameraRunMode runMode;
44
45         private List<ImageContentInfoEx> contentList = null;
46         private int contentIndex = 0;
47
48         private LayoutInflater layoutInflater = null;
49         private ViewPager viewPager = null;
50         private LruCache<String, Bitmap> imageCache =null;
51
52
53     public static ImagePagerViewFragment newInstance(@NonNull IPlaybackControl playbackControl, @NonNull ICameraRunMode runMode, @NonNull List<ImageContentInfoEx> contentList, int contentIndex)
54         {
55                 ImagePagerViewFragment fragment = new ImagePagerViewFragment();
56                 fragment.setInterface(playbackControl, runMode);
57                 fragment.setContentList(contentList, contentIndex);
58                 return (fragment);
59         }
60
61
62         private void setInterface(@NonNull IPlaybackControl playbackControl, @NonNull ICameraRunMode runMode)
63     {
64         this.playbackControl = playbackControl;
65         this.runMode = runMode;
66     }
67
68
69         private void setContentList(@NonNull List<ImageContentInfoEx> contentList, int contentIndex)
70         {
71                 this.contentList = contentList;
72                 this.contentIndex = contentIndex;
73         }
74
75         @Override
76         public void onCreate(Bundle savedInstanceState)
77         {
78                 super.onCreate(savedInstanceState);
79                 imageCache = new LruCache<>(5);
80                 setHasOptionsMenu(true);
81         }
82
83         @Override
84         public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
85         {
86                 layoutInflater = inflater;
87                 View view = layoutInflater.inflate(R.layout.fragment_image_pager_view, container, false);
88                 viewPager = view.findViewById(R.id.viewPager1);
89                 viewPager.setAdapter(new ImagePagerAdapter());
90                 viewPager.addOnPageChangeListener(new ImagePageChangeListener());
91                 
92                 return (view);
93         }
94
95         @Override
96         public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
97         {
98                 try
99                 {
100                         ImageContentInfoEx info  = contentList.get(contentIndex);
101             ICameraFileInfo file = info.getFileInfo();
102                         String path = file.getDirectoryPath() + "/" + file.getFilename();
103
104                         AppCompatActivity activity = (AppCompatActivity) getActivity();
105                         if (activity != null)
106                         {
107                 ActionBar bar = activity.getSupportActionBar();
108                 if (bar != null)
109                 {
110                     bar.show();
111                     bar.setTitle(path);
112                 }
113             }
114                         String lowerCasePath = path.toUpperCase();
115                         if (lowerCasePath.endsWith(JPEG_SUFFIX))
116             {
117                 if (info.hasRaw())
118                 {
119                     inflater.inflate(R.menu.image_view_with_raw, menu);
120                     MenuItem downloadMenuItem = menu.findItem(R.id.action_download_with_raw);
121                     downloadMenuItem.setEnabled(true);
122                 }
123                 else
124                 {
125                     inflater.inflate(R.menu.image_view, menu);
126                     MenuItem downloadMenuItem = menu.findItem(R.id.action_download);
127                     downloadMenuItem.setEnabled(true);
128                 }
129                         }
130             else
131             {
132                                 inflater.inflate(R.menu.movie_view, menu);
133                                 MenuItem downloadMenuItem = menu.findItem(R.id.action_download_movie);
134                                 downloadMenuItem.setEnabled(true);
135                         }
136                 }
137                 catch (Exception e)
138                 {
139                         e.printStackTrace();
140                 }
141         }
142
143         @Override
144         public boolean onOptionsItemSelected(MenuItem item)
145         {
146                 boolean doDownload = false;
147         boolean getInformation = false;
148                 boolean isSmallSize = false;
149                 boolean isRaw = false;
150         String specialSuffix = null;
151         if ((item.getItemId() == R.id.action_get_information)||(item.getItemId() == R.id.action_get_information_raw))
152         {
153             getInformation = true;
154         }
155         else if ((item.getItemId() == R.id.action_download_original_size)||(item.getItemId() == R.id.action_download_original_size_raw))
156         {
157                         doDownload = true;
158                 }
159         else if ((item.getItemId() == R.id.action_download_640x480)||(item.getItemId() == R.id.action_download_640x480_raw))
160         {
161             isSmallSize = true;
162             doDownload = true;
163         }
164         else if (item.getItemId() == R.id.action_download_original_movie)
165         {
166             doDownload = true;
167         }
168         else if (item.getItemId() == R.id.action_download_raw)
169         {
170             doDownload = true;
171             isRaw = true;
172                 }
173
174                 if (getInformation)
175         {
176                 Thread thread = new Thread(new Runnable() {
177                                 @Override
178                                 public void run()
179                 {
180                     showFileInformation((contentList.get(contentIndex)).getFileInfo());
181                 }
182                 });
183                 try
184             {
185                 thread.start();
186             }
187             catch (Exception e)
188             {
189                 e.printStackTrace();
190             }
191         }
192
193                 if (doDownload)
194                 {
195                         try
196                         {
197                                 //  ダイアログを表示して保存する
198                                 saveImageWithDialog(isRaw, isSmallSize);
199                         }
200                         catch (Exception e)
201                         {
202                                 e.printStackTrace();
203                         }
204                 }
205                 return (super.onOptionsItemSelected(item));
206         }
207
208     private void showFileInformation(final ICameraFileInfo fileInfo)
209     {
210         if (playbackControl != null)
211         {
212             playbackControl.updateCameraFileInfo(fileInfo);
213         }
214
215         runOnUiThread(new Runnable() {
216             @Override
217             public void run() {
218                 String message = "";
219                 try {
220                     String model = fileInfo.getModel();
221                     String dateTime = "";
222                     Date date = fileInfo.getDatetime();
223                     if (date != null) {
224                         dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(date);
225                     }
226                     String path = fileInfo.getDirectoryPath() + "/" + fileInfo.getFilename();
227                     String shutter = fileInfo.getShutterSpeed();
228                     shutter = shutter.replace(".", "/");
229                     String aperture = fileInfo.getAperature();
230                     String iso = fileInfo.getIsoSensitivity();
231                     String expRev = fileInfo.getExpRev();
232
233                     message = path + "\r\n" + dateTime + "\r\n" + "- - - - - - - - - -\r\n  " + shutter + "  F" + aperture + " (" + expRev + ")" + " ISO" + iso + "\r\n" + "- - - - - - - - - -\r\n" + "  model : " + model + "\r\n";
234                 }
235                 catch (Exception e)
236                 {
237                     e.printStackTrace();
238                 }
239                 presentMessage(getString(R.string.download_control_get_information_title), message);
240                 System.gc();
241             }
242         });
243     }
244
245     @Override
246         public void onResume()
247     {
248                 super.onResume();
249                 AppCompatActivity activity = (AppCompatActivity)getActivity();
250                 if (activity != null)
251                 {
252             ActionBar bar = activity.getSupportActionBar();
253             if (bar != null)
254             {
255                 bar.setDisplayShowHomeEnabled(true);
256                 bar.show();
257             }
258         }
259
260         if (runMode.isRecordingMode())
261         {
262             // Threadで呼んではダメみたいだ...
263             runMode.changeRunMode(false);
264         }
265
266         viewPager.setCurrentItem(contentIndex);
267         }
268
269         @Override
270         public void onPause()
271         {
272                 super.onPause();
273                 AppCompatActivity activity = (AppCompatActivity)getActivity();
274                 if (activity != null)
275                 {
276             ActionBar bar = activity.getSupportActionBar();
277             if (bar != null)
278             {
279                 bar.hide();
280             }
281         }
282
283         if (!runMode.isRecordingMode())
284         {
285             // Threadで呼んではダメみたいだ...
286             runMode.changeRunMode(true);
287         }
288     }
289
290         private class ImagePagerAdapter extends PagerAdapter
291     {
292
293                 @Override
294                 public int getCount()
295         {
296             int count = 0;
297                     try
298             {
299                 count = contentList.size();
300             }
301             catch (Exception e)
302             {
303                 e.printStackTrace();
304             }
305                         return (count);
306                 }
307
308                 @Override
309                 public boolean isViewFromObject(@NonNull View view, @NonNull Object object)
310         {
311                         return (view.equals(object));
312                 }
313                 
314                 @Override
315                 public @NonNull Object instantiateItem(@NonNull ViewGroup container, int position)
316         {
317                         ImageView view = (ImageView)layoutInflater.inflate(R.layout.view_image_page, container, false);
318                         container.addView(view);
319                         downloadImage(position, view);
320                         return (view);
321                 }
322                 
323                 @Override
324                 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object)
325                 {
326                         container.removeView((ImageView)object);
327                 }
328                 
329         }
330
331         private class ImagePageChangeListener implements OnPageChangeListener
332         {
333
334                 @Override
335                 public void onPageScrollStateChanged(int state)
336                 {
337
338                 }
339
340                 @Override
341                 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
342                 {
343
344                 }
345
346                 @Override
347                 public void onPageSelected(int position)
348                 {
349                         contentIndex = position;
350                         try
351                         {
352                 ICameraFileInfo file = (contentList.get(contentIndex)).getFileInfo();
353                 String path = file.getDirectoryPath() + "/" + file.getFilename();
354
355                 AppCompatActivity activity = (AppCompatActivity) getActivity();
356                 if (activity != null)
357                 {
358                     ActionBar bar = activity.getSupportActionBar();
359                     if (bar != null)
360                     {
361                         bar.setTitle(path);
362                     }
363                     activity.getSupportActionBar().setTitle(path);
364                     activity.getFragmentManager().invalidateOptionsMenu();
365                 }
366                         }
367                         catch (Exception e)
368             {
369                 e.printStackTrace();
370             }
371                 }
372         }
373
374     /**
375      *
376      *
377      */
378         private void downloadImage(final int position, final ImageView view)
379         {
380                 Thread thread = new Thread(new Runnable() {
381                         @Override
382                         public void run() {
383                                 downloadImageImpl(position, view);
384                         }
385                 });
386                 try
387                 {
388                         thread.start();
389                 }
390                 catch (Exception e)
391                 {
392                         e.printStackTrace();
393                 }
394         }
395
396     /**
397      *
398      *
399      */
400         private void downloadImageImpl(int position, final ImageView view)
401     {
402         try
403         {
404             ICameraFileInfo file = (contentList.get(position)).getFileInfo();
405             final String path = file.getDirectoryPath() + "/" + file.getFilename();
406
407             // Get the cached image.
408             final Bitmap bitmap = imageCache.get(path);
409             if (bitmap != null)
410             {
411                 if (view != null && viewPager.indexOfChild(view) > -1)
412                 {
413                     runOnUiThread(new Runnable()
414                     {
415                         @Override
416                         public void run()
417                         {
418                             view.setImageBitmap(bitmap);
419                         }
420                     });
421                 }
422                 return;
423             }
424
425             // Download the image.
426             playbackControl.downloadContentScreennail(path, new IDownloadThumbnailImageCallback() {
427                 @Override
428                                 //public void onCompleted(final byte[] data, final Map<String, Object> metadata) {
429                 public void onCompleted(final Bitmap bitmap, final Map<String, Object> metadata) {
430                     // Cache the downloaded image.
431
432                     //final Bitmap bitmap = createRotatedBitmap(data, metadata);
433                     try {
434                         if (bitmap == null)
435                         {
436                             System.gc();
437                             return;
438                         }
439                         if (imageCache != null)
440                                                 {
441                             imageCache.put(path, bitmap);
442                         }
443                     }
444                     catch (Exception e)
445                     {
446                         e.printStackTrace();
447                     }
448                     runOnUiThread(new Runnable() {
449                         @Override
450                         public void run() {
451                             if ((bitmap != null) && (view != null) && (viewPager.indexOfChild(view) > -1))
452                             {
453                                 view.setImageBitmap(bitmap);
454                             }
455                         }
456                     });
457                 }
458
459                 @Override
460                 public void onErrorOccurred(Exception e) {
461                     final String message = e.getMessage();
462                     runOnUiThread(new Runnable() {
463                         @Override
464                         public void run() {
465                             presentMessage("Load failed", message);
466                         }
467                     });
468                 }
469             });
470         }
471         catch (Exception e)
472         {
473             e.printStackTrace();
474         }
475         }
476
477         /**
478          *   デバイスに画像ファイルをダウンロード(保存)する
479          *
480          * @param isRaw           RAWファイルをダウンロードするか
481          * @param isSmallSize    小さいサイズの量にするか
482      */
483         public void saveImageWithDialog(final boolean isRaw, final boolean isSmallSize)
484         {
485         Log.v(TAG, "saveImageWithDialog() : raw : " + isRaw + " (small : " + isSmallSize + ")");
486         try
487         {
488             final Activity activity = getActivity();
489             if (activity != null)
490             {
491                 Thread thread = new Thread(new Runnable() {
492                     @Override
493                     public void run() {
494                         MyContentDownloader contentDownloader = new MyContentDownloader(activity, playbackControl);
495                         ImageContentInfoEx infoEx = contentList.get(contentIndex);
496                         if (infoEx != null)
497                         {
498                             ICameraFileInfo fileInfo = infoEx.getFileInfo();
499                             contentDownloader.startDownload(fileInfo, (isRaw) ? infoEx.getRawSuffix() : null, isSmallSize);
500                         }
501                     }
502                 });
503                 thread.start();
504             }
505         }
506         catch (Exception e)
507         {
508             e.printStackTrace();
509         }
510         }
511
512         // -------------------------------------------------------------------------
513         // Helpers
514         // -------------------------------------------------------------------------
515         
516         private void presentMessage(final String title, final String message)
517     {
518         runOnUiThread(new Runnable() {
519                 @Override
520                 public void run() {
521                     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
522                     builder.setTitle(title).setMessage(message);
523                     builder.show();
524                 }
525         });
526         }
527         
528         private void runOnUiThread(Runnable action)
529     {
530                 if (getActivity() == null)
531         {
532                         return;
533                 }
534                 getActivity().runOnUiThread(action);
535         }
536
537 /*
538         private Bitmap createRotatedBitmap(byte[] data, Map<String, Object> metadata)
539         {
540                 Bitmap bitmap;
541                 try
542                 {
543                         bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
544                 }
545                 catch (OutOfMemoryError e)
546                 {
547                         e.printStackTrace();
548                         bitmap = null;
549                         System.gc();
550                 }
551                 if (bitmap == null)
552                 {
553                         return (null);
554                 }
555
556                 // ビットマップの回転を行う
557                 int degrees = getRotationDegrees(data, metadata);
558                 if (degrees != 0)
559                 {
560                         Matrix m = new Matrix();
561                         m.postRotate(degrees);
562                         try
563                         {
564                                 bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
565                         }
566                         catch (OutOfMemoryError e)
567                         {
568                                 e.printStackTrace();
569                                 bitmap = null;
570                                 System.gc();
571                         }
572                 }
573                 return (bitmap);
574         }
575         
576         private int getRotationDegrees(byte[] data, Map<String, Object> metadata)
577         {
578                 int degrees = 0;
579                 int orientation = ExifInterface.ORIENTATION_UNDEFINED;
580                 
581                 if (metadata != null && metadata.containsKey("Orientation")) {
582                         orientation = Integer.parseInt((String)metadata.get("Orientation"));
583                 }
584                 else
585                 {
586                         // Gets image orientation to display a picture.
587                         try
588             {
589                                 File tempFile = File.createTempFile("temp", null);
590                                 {
591                                         FileOutputStream outStream = new FileOutputStream(tempFile.getAbsolutePath());
592                                         outStream.write(data);
593                                         outStream.close();
594                                 }
595                                 ExifInterface exifInterface = new ExifInterface(tempFile.getAbsolutePath());
596                                 orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
597                                 if (!tempFile.delete())
598                 {
599                     Log.v(TAG, "temp file delete failure.");
600                 }
601                         }
602             catch (IOException e)
603             {
604                 e.printStackTrace();
605                         }
606                 }
607
608                 switch (orientation)
609                 {
610             case ExifInterface.ORIENTATION_NORMAL:
611                 degrees = 0;
612                 break;
613             case ExifInterface.ORIENTATION_ROTATE_90:
614                 degrees = 90;
615                 break;
616             case ExifInterface.ORIENTATION_ROTATE_180:
617                 degrees = 180;
618                 break;
619             case ExifInterface.ORIENTATION_ROTATE_270:
620                 degrees = 270;
621                 break;
622             default:
623                 break;
624                 }
625                 return degrees;
626         }
627 */
628 }