OSDN Git Service

やっぱり、OPCのSDKを入れてOlympus Airでも使えるようにする。
[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         String specialSuffix = null;
150         if ((item.getItemId() == R.id.action_get_information)||(item.getItemId() == R.id.action_get_information_raw))
151         {
152             getInformation = true;
153         }
154         else if ((item.getItemId() == R.id.action_download_original_size)||(item.getItemId() == R.id.action_download_original_size_raw))
155         {
156                         doDownload = true;
157                 }
158         else if ((item.getItemId() == R.id.action_download_640x480)||(item.getItemId() == R.id.action_download_640x480_raw))
159         {
160             isSmallSize = true;
161             doDownload = true;
162         }
163         else if (item.getItemId() == R.id.action_download_original_movie)
164         {
165             doDownload = true;
166         }
167         else if (item.getItemId() == R.id.action_download_raw)
168         {
169             doDownload = true;
170             specialSuffix = playbackControl.getRawFileSuffix();
171                 }
172
173                 if (getInformation)
174         {
175                 Thread thread = new Thread(new Runnable() {
176                                 @Override
177                                 public void run()
178                 {
179                     showFileInformation((contentList.get(contentIndex)).getFileInfo());
180                 }
181                 });
182                 try
183             {
184                 thread.start();
185             }
186             catch (Exception e)
187             {
188                 e.printStackTrace();
189             }
190         }
191
192                 if (doDownload)
193                 {
194                         try
195                         {
196                 ICameraFileInfo file = (contentList.get(contentIndex)).getFileInfo();
197                                 String path = file.getDirectoryPath() + "/" + file.getFilename();
198                                 String upperCasePath = path.toUpperCase();
199                                 String suffix = (specialSuffix == null) ? upperCasePath.substring(upperCasePath.lastIndexOf(".")) : specialSuffix;
200                                 Calendar calendar = Calendar.getInstance();
201                                 String filename = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(calendar.getTime()) + suffix;
202
203                                 //  ダイアログを表示して保存する
204                                 saveImageWithDialog(filename, isSmallSize);
205                         }
206                         catch (Exception e)
207                         {
208                                 e.printStackTrace();
209                         }
210                 }
211
212                 return (super.onOptionsItemSelected(item));
213         }
214
215     private void showFileInformation(final ICameraFileInfo fileInfo)
216     {
217         if (playbackControl != null)
218         {
219             playbackControl.updateCameraFileInfo(fileInfo);
220         }
221
222         runOnUiThread(new Runnable() {
223             @Override
224             public void run() {
225                 String message = "";
226                 try {
227                     String model = fileInfo.getModel();
228                     String dateTime = "";
229                     Date date = fileInfo.getDatetime();
230                     if (date != null) {
231                         dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(date);
232                     }
233                     String path = fileInfo.getDirectoryPath() + "/" + fileInfo.getFilename();
234                     String shutter = fileInfo.getShutterSpeed();
235                     shutter = shutter.replace(".", "/");
236                     String aperture = fileInfo.getAperature();
237                     String iso = fileInfo.getIsoSensitivity();
238                     String expRev = fileInfo.getExpRev();
239
240                     message = path + "\r\n" + dateTime + "\r\n" + "- - - - - - - - - -\r\n  " + shutter + "  F" + aperture + " (" + expRev + ")" + " ISO" + iso + "\r\n" + "- - - - - - - - - -\r\n" + "  model : " + model + "\r\n";
241                 }
242                 catch (Exception e)
243                 {
244                     e.printStackTrace();
245                 }
246                 presentMessage(getString(R.string.download_control_get_information_title), message);
247                 System.gc();
248             }
249         });
250     }
251
252     @Override
253         public void onResume()
254     {
255                 super.onResume();
256                 AppCompatActivity activity = (AppCompatActivity)getActivity();
257                 if (activity != null)
258                 {
259             ActionBar bar = activity.getSupportActionBar();
260             if (bar != null)
261             {
262                 bar.setDisplayShowHomeEnabled(true);
263                 bar.show();
264             }
265         }
266
267         if (runMode.isRecordingMode())
268         {
269             // Threadで呼んではダメみたいだ...
270             runMode.changeRunMode(false);
271         }
272
273         viewPager.setCurrentItem(contentIndex);
274         }
275
276         @Override
277         public void onPause()
278         {
279                 super.onPause();
280                 AppCompatActivity activity = (AppCompatActivity)getActivity();
281                 if (activity != null)
282                 {
283             ActionBar bar = activity.getSupportActionBar();
284             if (bar != null)
285             {
286                 bar.hide();
287             }
288         }
289
290         if (!runMode.isRecordingMode())
291         {
292             // Threadで呼んではダメみたいだ...
293             runMode.changeRunMode(true);
294         }
295     }
296
297         private class ImagePagerAdapter extends PagerAdapter
298     {
299
300                 @Override
301                 public int getCount()
302         {
303             int count = 0;
304                     try
305             {
306                 count = contentList.size();
307             }
308             catch (Exception e)
309             {
310                 e.printStackTrace();
311             }
312                         return (count);
313                 }
314
315                 @Override
316                 public boolean isViewFromObject(@NonNull View view, @NonNull Object object)
317         {
318                         return (view.equals(object));
319                 }
320                 
321                 @Override
322                 public @NonNull Object instantiateItem(@NonNull ViewGroup container, int position)
323         {
324                         ImageView view = (ImageView)layoutInflater.inflate(R.layout.view_image_page, container, false);
325                         container.addView(view);
326                         downloadImage(position, view);
327                         return (view);
328                 }
329                 
330                 @Override
331                 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object)
332                 {
333                         container.removeView((ImageView)object);
334                 }
335                 
336         }
337
338         private class ImagePageChangeListener implements OnPageChangeListener
339         {
340
341                 @Override
342                 public void onPageScrollStateChanged(int state)
343                 {
344
345                 }
346
347                 @Override
348                 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
349                 {
350
351                 }
352
353                 @Override
354                 public void onPageSelected(int position)
355                 {
356                         contentIndex = position;
357                         try
358                         {
359                 ICameraFileInfo file = (contentList.get(contentIndex)).getFileInfo();
360                 String path = file.getDirectoryPath() + "/" + file.getFilename();
361
362                 AppCompatActivity activity = (AppCompatActivity) getActivity();
363                 if (activity != null)
364                 {
365                     ActionBar bar = activity.getSupportActionBar();
366                     if (bar != null)
367                     {
368                         bar.setTitle(path);
369                     }
370                     activity.getSupportActionBar().setTitle(path);
371                     activity.getFragmentManager().invalidateOptionsMenu();
372                 }
373                         }
374                         catch (Exception e)
375             {
376                 e.printStackTrace();
377             }
378                 }
379         }
380
381     /**
382      *
383      *
384      */
385         private void downloadImage(final int position, final ImageView view)
386         {
387                 Thread thread = new Thread(new Runnable() {
388                         @Override
389                         public void run() {
390                                 downloadImageImpl(position, view);
391                         }
392                 });
393                 try
394                 {
395                         thread.start();
396                 }
397                 catch (Exception e)
398                 {
399                         e.printStackTrace();
400                 }
401         }
402
403     /**
404      *
405      *
406      */
407         private void downloadImageImpl(int position, final ImageView view)
408     {
409         try
410         {
411             ICameraFileInfo file = (contentList.get(position)).getFileInfo();
412             final String path = file.getDirectoryPath() + "/" + file.getFilename();
413
414             // Get the cached image.
415             final Bitmap bitmap = imageCache.get(path);
416             if (bitmap != null)
417             {
418                 if (view != null && viewPager.indexOfChild(view) > -1)
419                 {
420                     runOnUiThread(new Runnable()
421                     {
422                         @Override
423                         public void run()
424                         {
425                             view.setImageBitmap(bitmap);
426                         }
427                     });
428                 }
429                 return;
430             }
431
432             // Download the image.
433             playbackControl.downloadContentScreennail(path, new IDownloadThumbnailImageCallback() {
434                 @Override
435                                 //public void onCompleted(final byte[] data, final Map<String, Object> metadata) {
436                 public void onCompleted(final Bitmap bitmap, final Map<String, Object> metadata) {
437                     // Cache the downloaded image.
438
439                     //final Bitmap bitmap = createRotatedBitmap(data, metadata);
440                     try {
441                         if (bitmap == null)
442                         {
443                             System.gc();
444                             return;
445                         }
446                         if (imageCache != null)
447                                                 {
448                             imageCache.put(path, bitmap);
449                         }
450                     }
451                     catch (Exception e)
452                     {
453                         e.printStackTrace();
454                     }
455                     runOnUiThread(new Runnable() {
456                         @Override
457                         public void run() {
458                             if ((bitmap != null) && (view != null) && (viewPager.indexOfChild(view) > -1))
459                             {
460                                 view.setImageBitmap(bitmap);
461                             }
462                         }
463                     });
464                 }
465
466                 @Override
467                 public void onErrorOccurred(Exception e) {
468                     final String message = e.getMessage();
469                     runOnUiThread(new Runnable() {
470                         @Override
471                         public void run() {
472                             presentMessage("Load failed", message);
473                         }
474                     });
475                 }
476             });
477         }
478         catch (Exception e)
479         {
480             e.printStackTrace();
481         }
482         }
483
484         /**
485          *   デバイスに画像ファイルをダウンロード(保存)する
486          *
487          * @param filename       ファイル名(カメラ内の)
488          * @param isSmallSize    小さいサイズの量にするか
489      */
490         public void saveImageWithDialog(final String filename, final boolean isSmallSize)
491         {
492         Log.v(TAG, "saveImageWithDialog() : " + filename + " (small : " + isSmallSize + ")");
493         try
494         {
495             final Activity activity = getActivity();
496             if (activity != null)
497             {
498                 Thread thread = new Thread(new Runnable() {
499                     @Override
500                     public void run() {
501                         MyContentDownloader contentDownloader = new MyContentDownloader(activity, playbackControl);
502                         ICameraFileInfo fileInfo = (contentList.get(contentIndex)).getFileInfo();
503                         contentDownloader.startDownload(fileInfo,  (filename.endsWith(playbackControl.getRawFileSuffix())) ? playbackControl.getRawFileSuffix() : null, isSmallSize);
504                     }
505                 });
506                 thread.start();
507             }
508         }
509         catch (Exception e)
510         {
511             e.printStackTrace();
512         }
513         }
514
515         // -------------------------------------------------------------------------
516         // Helpers
517         // -------------------------------------------------------------------------
518         
519         private void presentMessage(final String title, final String message)
520     {
521         runOnUiThread(new Runnable() {
522                 @Override
523                 public void run() {
524                     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
525                     builder.setTitle(title).setMessage(message);
526                     builder.show();
527                 }
528         });
529         }
530         
531         private void runOnUiThread(Runnable action)
532     {
533                 if (getActivity() == null)
534         {
535                         return;
536                 }
537                 getActivity().runOnUiThread(action);
538         }
539
540 /*
541         private Bitmap createRotatedBitmap(byte[] data, Map<String, Object> metadata)
542         {
543                 Bitmap bitmap;
544                 try
545                 {
546                         bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
547                 }
548                 catch (OutOfMemoryError e)
549                 {
550                         e.printStackTrace();
551                         bitmap = null;
552                         System.gc();
553                 }
554                 if (bitmap == null)
555                 {
556                         return (null);
557                 }
558
559                 // ビットマップの回転を行う
560                 int degrees = getRotationDegrees(data, metadata);
561                 if (degrees != 0)
562                 {
563                         Matrix m = new Matrix();
564                         m.postRotate(degrees);
565                         try
566                         {
567                                 bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
568                         }
569                         catch (OutOfMemoryError e)
570                         {
571                                 e.printStackTrace();
572                                 bitmap = null;
573                                 System.gc();
574                         }
575                 }
576                 return (bitmap);
577         }
578         
579         private int getRotationDegrees(byte[] data, Map<String, Object> metadata)
580         {
581                 int degrees = 0;
582                 int orientation = ExifInterface.ORIENTATION_UNDEFINED;
583                 
584                 if (metadata != null && metadata.containsKey("Orientation")) {
585                         orientation = Integer.parseInt((String)metadata.get("Orientation"));
586                 }
587                 else
588                 {
589                         // Gets image orientation to display a picture.
590                         try
591             {
592                                 File tempFile = File.createTempFile("temp", null);
593                                 {
594                                         FileOutputStream outStream = new FileOutputStream(tempFile.getAbsolutePath());
595                                         outStream.write(data);
596                                         outStream.close();
597                                 }
598                                 ExifInterface exifInterface = new ExifInterface(tempFile.getAbsolutePath());
599                                 orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
600                                 if (!tempFile.delete())
601                 {
602                     Log.v(TAG, "temp file delete failure.");
603                 }
604                         }
605             catch (IOException e)
606             {
607                 e.printStackTrace();
608                         }
609                 }
610
611                 switch (orientation)
612                 {
613             case ExifInterface.ORIENTATION_NORMAL:
614                 degrees = 0;
615                 break;
616             case ExifInterface.ORIENTATION_ROTATE_90:
617                 degrees = 90;
618                 break;
619             case ExifInterface.ORIENTATION_ROTATE_180:
620                 degrees = 180;
621                 break;
622             case ExifInterface.ORIENTATION_ROTATE_270:
623                 degrees = 270;
624                 break;
625             default:
626                 break;
627                 }
628                 return degrees;
629         }
630 */
631 }