aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/filemanager/ui/policy/PrintActionPolicy.java
blob: 6f7087c8ccfc541a535689cd79bf7e0ad55b57e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
/*
 * Copyright (C) 2012 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cyanogenmod.filemanager.ui.policy;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.pdf.PdfDocument.Page;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.PrintManager;
import android.print.PrintAttributes.Margins;
import android.print.PrintAttributes.MediaSize;
import android.print.pdf.PrintedPdfDocument;
import android.util.Log;
import android.widget.Toast;

import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.commands.AsyncResultListener;
import com.cyanogenmod.filemanager.commands.ReadExecutable;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper.MimeTypeCategory;
import com.cyanogenmod.filemanager.util.StringHelper;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * A class with the convenience methods to print documents
 */
public final class PrintActionPolicy extends ActionsPolicy {

    private static final String TAG = "PrintActionPolicy"; //$NON-NLS-1$

    private static final String PDF_FILE_EXT = "pdf";

    /**
     * Method that returns if the {@code FileSystemObject} can be printed
     *
     * @param ctx The current context
     * @param fso The fso to check
     * @return boolean If the fso can be printed
     */
    public static boolean isPrintedAllowed(Context ctx, FileSystemObject fso) {
        MimeTypeCategory category = MimeTypeHelper.getCategory(ctx, fso);
        String extension = FileHelper.getExtension(fso);
        return category.compareTo(MimeTypeCategory.TEXT) == 0
                || category.compareTo(MimeTypeCategory.IMAGE) == 0
                || (extension != null && extension.toLowerCase().equals(PDF_FILE_EXT));
    }

    /**
     * Method that prints the passed document
     *
     * @param ctx The current context
     * @param fso The document to print
     */
    public static void printDocument(final Context ctx, FileSystemObject fso) {
        MimeTypeCategory category = MimeTypeHelper.getCategory(ctx, fso);
        if (category.equals(MimeTypeCategory.TEXT)) {
            printTextDocument(ctx, fso);
            return;
        }
        if (category.equals(MimeTypeCategory.IMAGE)) {
            printImage(ctx, fso);
            return;
        }
        String ext = FileHelper.getExtension(fso);
        if (ext != null && ext.toLowerCase().equals(PDF_FILE_EXT)) {
            printPdfDocument(ctx, fso);
            return;
        }
        DialogHelper.showToast(ctx, R.string.print_unsupported_document, Toast.LENGTH_SHORT);
    }

    public static abstract class DocumentAdapterReader {
        /**
         * Read the document to an string array
         *
         * @param lines The array where to put the document
         * @param adjustedLines The array where to put the document
         */
        public abstract void read(List<String> lines, List<String> adjustedLines);

        /**
         * Read the document mode [0-Invalid; 1-Text; 2-Binary]
         *
         * @return int The document mode
         */
        public abstract int getDocumentMode();
    }

    /**
     * A document adapter
     */
    private static class DocumentAdapter extends PrintDocumentAdapter {
        private PrintAttributes mAttributes;
        private Paint mPaint;
        private RectF mTextBounds;
        private List<String> mLines;
        private List<String> mAdjustedLines;

        private static final int MILS_PER_INCH = 1000;
        private static final int POINTS_IN_INCH = 72;

        private final Context mCtx;
        private final FileSystemObject mDocument;
        private final int mPrintPageMargin;
        private final DocumentAdapterReader mReader;

        public DocumentAdapter(Context ctx, FileSystemObject document,
                DocumentAdapterReader reader) {
            super();
            mCtx = ctx;
            mDocument = document;
            mPrintPageMargin = ctx.getResources().getDimensionPixelSize(
                    R.dimen.print_page_margins);
            mReader = reader;
        }

        @Override
        public void onStart() {
            super.onStart();

            // Create the paint used for draw text
            Typeface courier = Typeface.createFromAsset(mCtx.getAssets(),
                    "fonts/Courier-Prime.ttf");
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setTypeface(courier);
            mPaint.setTextSize(mCtx.getResources().getDimensionPixelSize(
                    R.dimen.print_text_size));
            mPaint.setColor(Color.BLACK);

            // Get the text width and height
            mTextBounds = new RectF();
            mTextBounds.right = mPaint.measureText(new char[]{'A'}, 0, 1);
            mTextBounds.bottom = mPaint.getFontMetrics().descent
                    - mPaint.getFontMetrics().ascent + mPaint.getFontMetrics().leading;

            mLines = new ArrayList<String>();
            mAdjustedLines = new ArrayList<String>();
            mReader.read(mLines, mAdjustedLines);
        }

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination,
                CancellationSignal cancellationSignal, WriteResultCallback callback) {
            PrintedPdfDocument pdfDocument = new PrintedPdfDocument(mCtx,
                    mAttributes);
            try {
                Rect pageContentRect = getContentRect(mAttributes);
                int charsPerRow = (int) (pageContentRect.width() / mTextBounds.width());
                int rowsPerPage = rowsPerPage(pageContentRect);

                int currentPage = 0;
                int currentLine = 0;
                Page page = null;
                if (mAdjustedLines.size() > 0) {
                    page = pdfDocument.startPage(currentPage++);
                    printHeader(mCtx, page, pageContentRect, charsPerRow);
                }
                // Top (with margin) + header
                float top = pageContentRect.top + (mTextBounds.height() * 2);
                for (String line : mAdjustedLines) {
                    currentLine++;
                    page.getCanvas().drawText(line, pageContentRect.left,
                            top + (currentLine * mTextBounds.height()), mPaint);

                    if (currentLine >= rowsPerPage) {
                        if (page != null) {
                            printFooter(mCtx, page, pageContentRect, currentPage);
                            pdfDocument.finishPage(page);
                        }
                        currentLine = 0;
                        page = pdfDocument.startPage(currentPage++);
                        printHeader(mCtx, page, pageContentRect, charsPerRow);
                    }
                }

                // Finish the last page
                if (page != null) {
                    printFooter(mCtx, page, pageContentRect, currentPage);
                    pdfDocument.finishPage(page);
                } else {
                    page = pdfDocument.startPage(1);
                    printHeader(mCtx, page, pageContentRect, charsPerRow);
                    printFooter(mCtx, page, pageContentRect, currentPage);
                    pdfDocument.finishPage(page);
                }

                try {
                    // Write the document
                    pdfDocument.writeTo(new FileOutputStream(destination.getFileDescriptor()));

                    // Done
                    callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
                } catch (IOException ioe) {
                    // Failed.
                    ExceptionUtil.translateException(mCtx, ioe);
                    callback.onWriteFailed("Failed to print image");
                }
            } finally {
                if (destination != null) {
                    try {
                        destination.close();
                    } catch (IOException ioe) {
                        /* ignore */
                    }
                }
            }
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,
                CancellationSignal cancellationSignal, LayoutResultCallback callback,
                Bundle extras) {

            // Check if document is valid
            if (mReader.getDocumentMode() == 0) {
                callback.onLayoutFailed("Failed to read document");
                return;
            }

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }
            mAttributes = newAttributes;
            Rect pageContentRect = getContentRect(newAttributes);
            int charsPerRow = (int) (pageContentRect.width() / mTextBounds.width());
            int rowsPerPage = rowsPerPage(pageContentRect);
            adjustLines(pageContentRect, charsPerRow);

            PrintDocumentInfo info = new PrintDocumentInfo.Builder(mDocument.getName())
                .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                .setPageCount(calculatePageCount(rowsPerPage))
                .build();
            info.setDataSize(mDocument.getSize());
            boolean changed = !newAttributes.equals(oldAttributes);
            callback.onLayoutFinished(info, changed);
        }

        private Rect getContentRect(PrintAttributes attributes) {
            MediaSize mediaSize = attributes.getMediaSize();

            // Compute the size of the target canvas from the attributes.
            int pageWidth = (int) (((float) mediaSize.getWidthMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);
            int pageHeight = (int) (((float) mediaSize.getHeightMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);

            // Compute the content size from the attributes.
            Margins minMargins = attributes.getMinMargins();
            final int marginLeft = (int) (((float) minMargins.getLeftMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);
            final int marginTop = (int) (((float) minMargins.getTopMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);
            final int marginRight = (int) (((float) minMargins.getRightMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);
            final int marginBottom = (int) (((float) minMargins.getBottomMils() / MILS_PER_INCH)
                    * POINTS_IN_INCH);
            return new Rect(
                    Math.max(marginLeft, mPrintPageMargin),
                    Math.max(marginTop, mPrintPageMargin),
                    pageWidth - Math.max(marginRight, mPrintPageMargin),
                    pageHeight - Math.max(marginBottom, mPrintPageMargin));
        }

        private void printHeader(Context ctx, Page page, Rect pageContentRect,
                int charsPerRow) {
            String header = ctx.getString(R.string.print_document_header, mDocument.getName());
            if (header.length() >= charsPerRow) {
                header = header.substring(header.length() - 3) + "...";
            }
            page.getCanvas().drawText(header,
                    (int) (pageContentRect.width() / 2) - (mPaint.measureText(header) / 2),
                    pageContentRect.top + mTextBounds.height(), mPaint);
        }

        private void printFooter(Context ctx, Page page, Rect pageContentRect, int pageNumber) {
            String footer = ctx.getString(R.string.print_document_footer, pageNumber);
            page.getCanvas().drawText(footer,
                    (int) (pageContentRect.width() / 2) - (mPaint.measureText(footer) / 2),
                    pageContentRect.bottom - mTextBounds.height(), mPaint);
        }

        private void adjustLines(Rect pageRect, int charsPerRow) {
            if (mReader.getDocumentMode() == 2) {
                return;
            }
            mAdjustedLines = new ArrayList<String>(mLines);
            for (int i = 0; i < mAdjustedLines.size(); i++) {
                String line = mAdjustedLines.get(i);
                if (line.length() > charsPerRow) {
                    int prevSpace = line.lastIndexOf(" ", charsPerRow);
                    if (prevSpace != -1) {
                        // Split in the previous word
                        String currentLine = line.substring(0, prevSpace + 1);
                        String nextLine = line.substring(prevSpace + 1);
                        mAdjustedLines.set(i, currentLine);
                        mAdjustedLines.add(i + 1, nextLine);
                    } else {
                        // Just split at margin
                        String currentLine = line.substring(0, charsPerRow);
                        String nextLine = line.substring(charsPerRow);
                        mAdjustedLines.set(i, currentLine);
                        mAdjustedLines.add(i + 1, nextLine);
                    }
                }
            }
        }

        private int calculatePageCount(int rowsPerPage) {
            int pages = mAdjustedLines.size() / rowsPerPage;
            return pages <= 0 ? PrintDocumentInfo.PAGE_COUNT_UNKNOWN : pages;
        }

        private int rowsPerPage(Rect pageContentRect) {
            // Text height - header - footer
            return (int) ((pageContentRect.height() / mTextBounds.height()) - 4);
        }
    }

    /**
     * Method that prints the document from a string buffer
     *
     * @param ctx The current context
     * @param fso The document to print
     * @param sb The buffer to print
     * @param adjustLines If document must be adjusted
     */
    public static void printStringDocument(final Context ctx, final FileSystemObject document,
            final StringBuilder sb) {
        PrintManager printManager = (PrintManager) ctx.getSystemService(Context.PRINT_SERVICE);
        PrintAttributes attr = new PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT)
                .setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME)
                .build();
        final DocumentAdapterReader reader = new DocumentAdapterReader() {
            @Override
            public void read(List<String> lines, List<String> adjustedLines) {
                BufferedReader br = null;
                try {
                    int bufferSize = ctx.getResources().getInteger(R.integer.buffer_size);
                    br = new BufferedReader(new StringReader(sb.toString()), bufferSize);
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        lines.add(line);
                    }

                } catch (IOException ex) {
                    Log.e(TAG, "Failed to read file " + document.getFullPath(), ex);
                    lines.clear();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException ex) {
                            // Ignore
                        }
                    }
                }
            }

            @Override
            public int getDocumentMode() {
                // Always is text
                return 1;
            }
        };
        printManager.print(document.getName(), new DocumentAdapter(ctx, document, reader), attr);
    }

    /**
     * Method that prints the document as a text document
     *
     * @param ctx The current context
     * @param fso The document to print
     */
    private static void printTextDocument(final Context ctx, final FileSystemObject document) {
        PrintManager printManager = (PrintManager) ctx.getSystemService(Context.PRINT_SERVICE);
        PrintAttributes attr = new PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT)
                .setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME)
                .build();
        final DocumentAdapterReader reader = new DocumentAdapterReader() {
            private int mDocumentMode = -1;

            @Override
            public void read(List<String> lines, List<String> adjustedLines) {
                mDocumentMode = getDocumentMode();
                if (mDocumentMode <= 0) {
                    lines.clear();
                } else if (mDocumentMode == 2) {
                    adjustedLines.addAll(readHexDumpDocumentFile(ctx, document, lines));
                } else {
                    readDocumentFile(ctx, document, lines);
                }
            }

            @Override
            public int getDocumentMode() {
                if (mDocumentMode == -1) {
                    String mimeType = MimeTypeHelper.getMimeType(ctx, document);
                    if (mimeType == null) {
                        mDocumentMode = 0; // Invalid
                    } else {
                        mDocumentMode = isBinaryDocument(ctx, document) ? 2 : 1; // binary / text
                    }
                }
                return mDocumentMode;
            }
        };
        printManager.print(document.getName(), new DocumentAdapter(ctx, document, reader), attr);
    }

    /**
     * Method that prints the document as a Pdf
     *
     * @param ctx The current context
     * @param fso The pdf to print
     */
    private static void printPdfDocument(final Context ctx, final FileSystemObject document) {
        PrintManager printManager = (PrintManager) ctx.getSystemService(Context.PRINT_SERVICE);
        PrintAttributes.MediaSize mediaSize = PrintAttributes.MediaSize.UNKNOWN_PORTRAIT;
        PrintAttributes attr = new PrintAttributes.Builder()
                .setMediaSize(mediaSize)
                .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                .build();
        printManager.print(document.getName(), new PrintDocumentAdapter() {
            @Override
            public void onWrite(PageRange[] pages, ParcelFileDescriptor destination,
                    CancellationSignal cancellationSignal, WriteResultCallback callback) {
                FileInputStream fis = null;
                FileOutputStream fos = null;
                AsyncDocumentReader reader = null;

                try {
                    // Try first with java.io before using pipes

                    File file = new File(document.getFullPath());
                    if (file.isFile() && file.canRead()) {
                        fis = new FileInputStream(file);
                    } else {
                        reader = new AsyncDocumentReader(ctx);
                        CommandHelper.read(ctx, document.getFullPath(), reader, null);
                        fis = reader.mIn;
                    }
                    fos = new FileOutputStream(destination.getFileDescriptor());

                    // Write the document
                    int bufferSize = ctx.getResources().getInteger(R.integer.buffer_size);
                    byte[] data = new byte[bufferSize];
                    int read = 0;
                    while ((read = fis.read(data)) > 0) {
                        fos.write(data, 0, read);
                    }

                    // All was ok
                    callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});

                } catch (Exception ex) {
                    // Failed.
                    ExceptionUtil.translateException(ctx, ex);
                    callback.onWriteFailed("Failed to print image");

                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        // Ignore
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        // Ignore
                    }
                    if (reader != null && reader.mIn != null) {
                        try {
                            reader.mIn.close();
                        } catch (IOException ex) {
                            //Ignore
                        }
                    }
                }
            }

            @Override
            public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,
                    CancellationSignal cancellationSignal, LayoutResultCallback callback,
                    Bundle extras) {

                if (cancellationSignal.isCanceled()) {
                    callback.onLayoutCancelled();
                    return;
                }

                PrintDocumentInfo info = new PrintDocumentInfo.Builder(document.getName())
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                    .build();
                boolean changed = !newAttributes.equals(oldAttributes);
                callback.onLayoutFinished(info, changed);
            }
        }, attr);
    }

    /**
     * Method that prints the document as an image
     *
     * @param ctx The current context
     * @param fso The image to print
     */
    private static void printImage(final Context ctx, final FileSystemObject image) {
        // Check that the image is supported by Android
        if (isValidImageDocument(image.getFullPath())) {
            DialogHelper.showToast(ctx, R.string.print_unsupported_image, Toast.LENGTH_SHORT);
            return;
        }

        Bitmap bitmap = null;
        AsyncDocumentReader reader = null;
        try {
            // Try first with java.io before using pipes
            File file = new File(image.getFullPath());
            if (file.isFile() && file.canRead()) {
                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bitmap = BitmapFactory.decodeFile(image.getFullPath(), options);
            } else {
                reader = new AsyncDocumentReader(ctx);
                CommandHelper.read(ctx, image.getFullPath(), reader, null);

                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bitmap = BitmapFactory.decodeStream(reader.mIn);
            }
            if (bitmap == null) {
                throw new IOException("Failed to load image");
            }

        } catch (Exception ex) {
            ExceptionUtil.translateException(ctx, ex);
            return;

        } finally {
            if (reader != null && reader.mIn != null) {
                try {
                    reader.mIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mFdIn != null) {
                try {
                    reader.mFdIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
        }

        final Bitmap fBitmap = bitmap;
        PrintManager printManager = (PrintManager) ctx.getSystemService(Context.PRINT_SERVICE);
        PrintAttributes.MediaSize mediaSize = PrintAttributes.MediaSize.UNKNOWN_PORTRAIT;
        if (fBitmap.getWidth() > fBitmap.getHeight()) {
            mediaSize = PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE;
        }
        PrintAttributes attr = new PrintAttributes.Builder()
                .setMediaSize(mediaSize)
                .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                .build();
        printManager.print(image.getName(), new PrintDocumentAdapter() {
            private PrintAttributes mAttributes;

            @Override
            public void onWrite(PageRange[] pages, ParcelFileDescriptor destination,
                    CancellationSignal cancellationSignal, WriteResultCallback callback) {
                PrintedPdfDocument pdfDocument = new PrintedPdfDocument(ctx,
                        mAttributes);
                try {
                    Page page = pdfDocument.startPage(1);
                    RectF content = new RectF(page.getInfo().getContentRect());
                    Matrix matrix = getMatrix(fBitmap.getWidth(), fBitmap.getHeight(), content);

                    // Draw the bitmap.
                    page.getCanvas().drawBitmap(fBitmap, matrix, null);

                    // Finish the page.
                    pdfDocument.finishPage(page);

                    try {
                        // Write the document
                        pdfDocument.writeTo(new FileOutputStream(destination.getFileDescriptor()));

                        // Done
                        callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
                    } catch (IOException ioe) {
                        // Failed.
                        ExceptionUtil.translateException(ctx, ioe);
                        callback.onWriteFailed("Failed to print image");
                    }
                } finally {
                    if (pdfDocument != null) {
                        pdfDocument.close();
                    }
                    if (destination != null) {
                        try {
                            destination.close();
                        } catch (IOException ioe) {
                            /* ignore */
                        }
                    }
                }
            }

            @Override
            public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,
                    CancellationSignal cancellationSignal, LayoutResultCallback callback,
                    Bundle extras) {

                if (cancellationSignal.isCanceled()) {
                    callback.onLayoutCancelled();
                    return;
                }
                mAttributes = newAttributes;

                PrintDocumentInfo info = new PrintDocumentInfo.Builder(image.getName())
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO)
                    .setPageCount(1)
                    .build();
                boolean changed = !newAttributes.equals(oldAttributes);
                callback.onLayoutFinished(info, changed);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (fBitmap != null) {
                    fBitmap.recycle();
                }
            }

            private Matrix getMatrix(int imageWidth, int imageHeight, RectF content) {
                Matrix matrix = new Matrix();

                // Compute and apply scale to fill the page.
                float widthRatio = content.width() / imageWidth;
                float heightRatio = content.height() / imageHeight;
                float scale = Math.max(widthRatio, heightRatio);
                matrix.postScale(scale, scale);

                // Center the content.
                final float translateX = (content.width()
                        - imageWidth * scale) / 2;
                final float translateY = (content.height()
                        - imageHeight * scale) / 2;
                matrix.postTranslate(translateX, translateY);
                return matrix;
            }
        }, attr);
    }

    /**
     * Check if the file is a valid image document allowed by android to be printed
     *
     * @param file The image to check
     * @return boolean If the image is a valid document
     */
    private static boolean isValidImageDocument(String file) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeFile(file, options);
        if (bitmap != null) {
            bitmap.recycle();
        }
        return bitmap != null;
    }

    /**
     * Method that checks if the file has a binary format
     *
     * @param ctx The current context
     * @param document The document to read
     * @return boolean If the document has a binary format
     */
    private static boolean isBinaryDocument(Context ctx, FileSystemObject document) {
        BufferedReader br = null;
        boolean binary = false;
        AsyncDocumentReader reader = null;
        try {
            reader = new AsyncDocumentReader(ctx);
            ReadExecutable command = CommandHelper.read(ctx, document.getFullPath(), reader, null);
            br = new BufferedReader(new InputStreamReader(reader.mIn));

            char[] data = new char[50];
            int read = br.read(data);
            for (int i = 0; i < read; i++) {
                if (!StringHelper.isPrintableCharacter(data[i])) {
                    binary = true;
                    break;
                }
            }
            command.cancel();

        } catch (Exception ex) {
            //Ignore
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mIn != null) {
                try {
                    reader.mIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mFdIn != null) {
                try {
                    reader.mFdIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
        }
        return binary;
    }

    /**
     * Read a file as document
     *
     * @param ctx The current context
     * @param document The document to read
     * @param lines The output
     */
    private static void readDocumentFile(Context ctx, FileSystemObject document,
            List<String> lines) {
        BufferedReader br = null;
        AsyncDocumentReader reader = null;
        try {
            // Async read the document while blocking with a buffered reader
            int bufferSize = ctx.getResources().getInteger(R.integer.buffer_size);
            reader = new AsyncDocumentReader(ctx);
            CommandHelper.read(ctx, document.getFullPath(), reader, null);
            br = new BufferedReader(new InputStreamReader(reader.mIn), bufferSize);

            String line = null;
            while((line = br.readLine()) != null) {
                lines.add(line);
            }

            // Got an exception?
            if (reader.mCause != null) {
                lines.clear();
                Log.e(TAG, "Failed to read file " + document.getFullPath(), reader.mCause);
            }

        } catch (Exception ex) {
            lines.clear();
            Log.e(TAG, "Failed to read file " + document.getFullPath(), ex);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mIn != null) {
                try {
                    reader.mIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mFdIn != null) {
                try {
                    reader.mFdIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
        }
    }

    /**
     * Read a file as hex document
     *
     * @param ctx The current context
     * @param document The document to read
     * @param lines The internal output
     * @return output The output
     */
    private static List<String> readHexDumpDocumentFile(Context ctx, FileSystemObject document,
            List<String> lines) {
        InputStream is = null;
        ByteArrayOutputStream baos;
        AsyncDocumentReader reader = null;
        try {
            // Async read the document while blocking with a buffered stream
            reader = new AsyncDocumentReader(ctx);
            CommandHelper.read(ctx, document.getFullPath(), reader, null);

            int bufferSize = ctx.getResources().getInteger(R.integer.buffer_size);
            baos = new ByteArrayOutputStream();
            is = new BufferedInputStream(reader.mIn);

            byte[] data = new byte[bufferSize];
            int read = 0;
            while((read = is.read(data, 0, bufferSize)) != -1) {
                baos.write(data, 0, read);
            }

            // Got an exception?
            if (reader.mCause != null) {
                lines.clear();
                Log.e(TAG, "Failed to read file " + document.getFullPath(), reader.mCause);
            }
        } catch (Exception ex) {
            Log.e(TAG, "Failed to read file " + document.getFullPath(), ex);
            lines.clear();
            return new ArrayList<String>();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mIn != null) {
                try {
                    reader.mIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
            if (reader != null && reader.mFdIn != null) {
                try {
                    reader.mFdIn.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
        }

        // Convert the bytes to a hex printable string and free resources
        String documentBuffer = StringHelper.toHexPrintableString(baos.toByteArray());
        try {
            baos.close();
        } catch (IOException ex) {
            //Ignore
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new StringReader(documentBuffer));
            String line = null;
            while((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException ex) {
            lines.clear();
            Log.e(TAG, "Failed to read file " + document.getFullPath(), ex);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    //Ignore
                }
            }
        }

        // Use the final array and clear the original (we don't use it anymore)
        List<String> output = new ArrayList<String>(lines);
        lines.clear();
        return output;
    }

    /**
     * An implementation of an {@code AsyncResultListener} based on pipes for readers
     */
    private static class AsyncDocumentReader implements AsyncResultListener {

        final FileInputStream mIn;
        private final FileOutputStream mOut;
        final ParcelFileDescriptor mFdIn;
        private final ParcelFileDescriptor mFdOut;
        Exception mCause;

        public AsyncDocumentReader(Context ctx) throws IOException {
            super();

            ParcelFileDescriptor[] fds = ParcelFileDescriptor.createReliablePipe();
            mFdIn = fds[0];
            mFdOut = fds[1];
            mIn = new ParcelFileDescriptor.AutoCloseInputStream(mFdIn);
            mOut = new ParcelFileDescriptor.AutoCloseOutputStream(mFdOut);
            mCause = null;
        }

        @Override
        public void onAsyncStart() {
            // Ignore
        }

        @Override
        public void onAsyncEnd(boolean cancelled) {
            // Ignore
        }

        @Override
        public void onAsyncExitCode(int exitCode) {
            close();
        }

        @Override
        public void onPartialResult(Object result) {
            try {
                if (result == null) return;
                byte[] partial = (byte[])result;
                mOut.write(partial);
                mOut.flush();
            } catch (Exception ex) {
                Log.w(TAG, "Failed to parse partial result data", ex);
                closeWithError("Failed to parse partial result data: " + ex.getMessage());
                mCause = ex;
            }
        }

        @Override
        public void onException(Exception cause) {
            Log.w(TAG, "Got exception while reading data", cause);
            closeWithError("Got exception while reading data: " + cause.getMessage());
            mCause = cause;
        }

        private void close() {
            try {
                mOut.close();
            } catch (IOException ex) {
                // Ignore
            }
            try {
                mFdOut.close();
            } catch (IOException ex) {
                // Ignore
            }
        }

        private void closeWithError(String msg) {
            try {
                mOut.close();
            } catch (IOException ex) {
                // Ignore
            }
            try {
                mIn.close();
            } catch (IOException ex) {
                // Ignore
            }
            try {
                mFdOut.closeWithError(msg);
            } catch (IOException ex) {
                // Ignore
            }
            try {
                mFdIn.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
}