aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/filemanager/ui/policy/CompressActionPolicy.java
blob: b5021b88c1a96f83325d11ef064917b37e001060 (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
/*
 * 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.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.text.Spanned;
import android.widget.Toast;

import com.cyanogenmod.filemanager.FileManagerApplication;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.commands.AsyncResultListener;
import com.cyanogenmod.filemanager.commands.CompressExecutable;
import com.cyanogenmod.filemanager.commands.UncompressExecutable;
import com.cyanogenmod.filemanager.console.ConsoleBuilder;
import com.cyanogenmod.filemanager.console.ExecutionException;
import com.cyanogenmod.filemanager.console.RelaunchableException;
import com.cyanogenmod.filemanager.listeners.OnRequestRefreshListener;
import com.cyanogenmod.filemanager.listeners.OnSelectionListener;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.preferences.CompressionMode;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.ExceptionUtil.OnRelaunchCommandResult;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.FixedQueue;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A class with the convenience methods for resolve compress/uncompress related actions
 */
public final class CompressActionPolicy extends ActionsPolicy {

    /**
     * A class that holds a listener for compression/uncompression operations
     */
    private static class CompressListener implements AsyncResultListener {

        final FixedQueue<String> mQueue;
        boolean mEnd;
        Throwable mCause;

        /**
         * Constructor of <code>CompressListener</code>
         */
        public CompressListener() {
            super();
            this.mEnd = false;
            this.mQueue = new FixedQueue<String>(2); //Holds only one item
            this.mCause = null;
        }

        @Override
        public void onPartialResult(Object result) {
            this.mQueue.insert((String)result);
        }

        @Override
        public void onException(Exception cause) {
            this.mCause = cause;
        }

        @Override
        public void onAsyncStart() {/**NON BLOCK**/}

        @Override
        public void onAsyncEnd(boolean cancelled) {/**NON BLOCK**/}

        @Override
        public void onAsyncExitCode(int exitCode) {
            this.mEnd = true;
        }
    }

    /**
     * Method that compresses the list of files of the selection.
     *
     * @param ctx The current context
     * @param onSelectionListener The listener for obtain selection information (required)
     * @param onRequestRefreshListener The listener for request a refresh (optional)
     * @hide
     */
    public static void compress(
            final Context ctx,
            final OnSelectionListener onSelectionListener,
            final OnRequestRefreshListener onRequestRefreshListener) {

        // Retrieve the current selection
        final List<FileSystemObject> selection = onSelectionListener.onRequestSelectedFiles();
        if (selection != null && selection.size() > 0) {
            // Show a dialog to allow the user make the compression mode choice
            final String[] labels = getSupportedCompressionModesLabels(ctx, selection);
            AlertDialog dialog = DialogHelper.createSingleChoiceDialog(
                    ctx, R.string.compression_mode_title,
                    labels,
                    CompressionMode.AC_GZIP.ordinal(),
                    new DialogHelper.OnSelectChoiceListener() {
                        @Override
                        public void onSelectChoice(int choice) {
                            // Do the compression
                            compress(
                                    ctx,
                                    getCompressionModeFromUserChoice(ctx, labels, choice),
                                    selection,
                                    onSelectionListener,
                                    onRequestRefreshListener);
                        }

                        @Override
                        public void onNoSelectChoice() {/**NON BLOCK**/}
                    });
            DialogHelper.delegateDialogShow(ctx, dialog);
        }
    }

    /**
     * Method that compresses an uncompressed file.
     *
     * @param ctx The current context
     * @param fso The compressed file
     * @param onSelectionListener The listener for obtain selection information (required)
     * @param onRequestRefreshListener The listener for request a refresh (optional)
     * @hide
     */
    public static void compress(
            final Context ctx, final FileSystemObject fso,
            final OnSelectionListener onSelectionListener,
            final OnRequestRefreshListener onRequestRefreshListener) {

        // Create a list with the item
        final List<FileSystemObject> items = new ArrayList<FileSystemObject>();
        items.add(fso);

        // Show a dialog to allow the user make the compression mode choice
        final String[] labels = getSupportedCompressionModesLabels(ctx, items);
        AlertDialog dialog = DialogHelper.createSingleChoiceDialog(
                ctx, R.string.compression_mode_title,
                getSupportedCompressionModesLabels(ctx, items),
                CompressionMode.AC_GZIP.ordinal(),
                new DialogHelper.OnSelectChoiceListener() {
                    @Override
                    public void onSelectChoice(int choice) {
                        // Do the compression
                        compress(
                                ctx,
                                getCompressionModeFromUserChoice(ctx, labels, choice),
                                items,
                                onSelectionListener,
                                onRequestRefreshListener);
                    }

                    @Override
                    public void onNoSelectChoice() {/**NON BLOCK**/}
                });
        DialogHelper.delegateDialogShow(ctx, dialog);
    }


    /**
     * Method that compresses some uncompressed files or folders
     *
     * @param ctx The current context
     * @param mode The compression mode
     * @param fsos The list of files to compress
     * @param onSelectionListener The listener for obtain selection information (required)
     * @param onRequestRefreshListener The listener for request a refresh (optional)
     * @hide
     */
    static void compress(
            final Context ctx, final CompressionMode mode, final List<FileSystemObject> fsos,
            final OnSelectionListener onSelectionListener,
            final OnRequestRefreshListener onRequestRefreshListener) {

        // The callable interface
        final BackgroundCallable callable = new BackgroundCallable() {
            // The current items
            final Context mCtx = ctx;
            final CompressionMode mMode = mode;
            final List<FileSystemObject> mFsos = fsos;
            final OnRequestRefreshListener mOnRequestRefreshListener = onRequestRefreshListener;

            final Object mSync = new Object();
            Throwable mCause;
            CompressExecutable cmd = null;

            final CompressListener mListener =
                                new CompressListener();
            private String mMsg;
            private boolean mStarted = false;

            @Override
            public int getDialogTitle() {
                return R.string.waiting_dialog_compressing_title;
            }
            @Override
            public int getDialogIcon() {
                return 0;
            }
            @Override
            public boolean isDialogCancellable() {
                return true;
            }

            @Override
            public Spanned requestProgress() {
                // Initializing the dialog
                if (!this.mStarted) {
                    String progress =
                            this.mCtx.getResources().
                                getString(
                                    R.string.waiting_dialog_analizing_msg);
                    return Html.fromHtml(progress);
                }

                // Return the current operation
                String msg = (this.mMsg == null) ? "" : this.mMsg; //$NON-NLS-1$
                String progress =
                      this.mCtx.getResources().
                          getString(
                              R.string.waiting_dialog_compressing_msg,
                              msg);
                return Html.fromHtml(progress);
            }

            @Override
            public void onSuccess() {
                try {
                    if (this.cmd != null && this.cmd.isCancellable() && !this.cmd.isCancelled()) {
                        this.cmd.cancel();
                    }
                } catch (Exception e) {/**NON BLOCK**/}

                //Operation complete. Refresh
                if (this.mOnRequestRefreshListener != null) {
                  // The reference is not the same, so refresh the complete navigation view
                  this.mOnRequestRefreshListener.onRequestRefresh(null, true);
                }
                if (this.cmd != null) {
                    showOperationSuccessMsg(
                            ctx,
                            R.string.msgs_compressing_success,
                            this.cmd.getOutCompressedFile());
                } else {
                    ActionsPolicy.showOperationSuccessMsg(ctx);
                }
            }

            @Override
            public void onCancel() {
                // nop
            }

            @Override
            public void doInBackground(Object... params) throws Throwable {
                this.mCause = null;
                this.mStarted = true;

                // This method expect to receive
                // 1.- BackgroundAsyncTask
                BackgroundAsyncTask task = (BackgroundAsyncTask)params[0];
                String out = null;
                try {
                    // Archive or Archive-Compression
                    if (this.mMode.mArchive) {
                        // Convert the list to an array of full paths
                        String[] src = new String[this.mFsos.size()];
                        int cc = this.mFsos.size();
                        for (int i = 0; i < cc; i++) {
                            src[i] = this.mFsos.get(i).getFullPath();
                        }

                        // Use the current directory name for create the compressed file
                        String curDirName =
                                new File(onSelectionListener.onRequestCurrentDir()).getName();
                        if (src.length == 1) {
                            // But only one file is passed, then used the name of unique file
                            curDirName = FileHelper.getName(this.mFsos.get(0).getName());
                        }
                        String name =
                                String.format(
                                        "%s.%s", curDirName, this.mMode.mExtension); //$NON-NLS-1$
                        String newName =
                                FileHelper.createNonExistingName(
                                        ctx,
                                        onSelectionListener.onRequestCurrentItems(),
                                        name,
                                        R.string.create_new_compress_file_regexp);
                        String newNameAbs =
                                new File(
                                        onSelectionListener.onRequestCurrentDir(),
                                        newName).getAbsolutePath();

                        // Do the compression
                        this.cmd =
                           CommandHelper.compress(
                                ctx,
                                this.mMode,
                                newNameAbs,
                                src,
                                this.mListener, null);

                    // Compression
                    } else {
                        // Only the first item from the list is valid. If there are more in the
                        // list, then discard them
                        String src = this.mFsos.get(0).getFullPath();

                        // Do the compression
                        this.cmd =
                           CommandHelper.compress(
                                ctx,
                                this.mMode,
                                src,
                                this.mListener, null);
                    }
                    out = this.cmd.getOutCompressedFile();

                    // Request paint the
                    this.mListener.mQueue.insert(out);
                    task.onRequestProgress();

                    // Don't use an active blocking because this suppose that all message
                    // will be processed by the UI. Instead, refresh with a delay and
                    // display the active file
                    while (!this.mListener.mEnd) {
                        // Sleep to don't saturate the UI thread
                        Thread.sleep(50L);

                        List<String> msgs = this.mListener.mQueue.peekAll();
                        if (msgs.size() > 0) {
                            this.mMsg = msgs.get(msgs.size()-1);
                            task.onRequestProgress();
                        }
                    }

                    // Dialog is ended. Force the last redraw
                    List<String> msgs = this.mListener.mQueue.peekAll();
                    if (msgs.size() > 0) {
                        this.mMsg = msgs.get(msgs.size()-1);
                        task.onRequestProgress();
                    }

                } catch (Exception e) {
                    // Need to be relaunched?
                    if (e instanceof RelaunchableException) {
                        OnRelaunchCommandResult rl = new OnRelaunchCommandResult() {
                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onSuccess() {
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }

                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onFailed(Throwable cause) {
                                mCause = cause;
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }
                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onCancelled() {
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }
                        };

                        // Translate the exception (and wait for the result)
                        ExceptionUtil.translateException(ctx, e, false, true, rl);
                        synchronized (this.mSync) {
                            this.mSync.wait();
                        }

                        // Persist the exception?
                        if (this.mCause != null) {
                            // The exception must be elevated
                            throw this.mCause;
                        }

                    } else {
                        // The exception must be elevated
                        throw e;
                    }
                }


                // Any exception?
                Thread.sleep(100L);
                if (this.mListener.mCause != null) {
                    throw this.mListener.mCause;
                }

                // Check that the operation was completed retrieving the compressed file or folder
                boolean failed = false;
                try {
                    FileSystemObject fso = CommandHelper.getFileInfo(ctx, out, false, null);
                    if (fso == null) {
                        // Failed. The file or folder not exists
                        failed = true;
                    }

                    // Operation complete successfully

                } catch (Throwable e) {
                    // Failed. The file or folder not exists
                    failed = true;
                }
                if (failed) {
                    throw new ExecutionException(
                            String.format(
                                    "Failed to compress file(s) to: %s", out)); //$NON-NLS-1$
                }
            }
        };
        final BackgroundAsyncTask task = new BackgroundAsyncTask(ctx, callable);

        // Check if the output exists. When the mode is archive, this method generate a new
        // name based in the current directory. When the mode is compressed then the name
        // is the name of the file to compress without extension. In this case the name should
        // be validate prior to compress
        boolean askUser = false;
        try {
            if (!mode.mArchive) {
                // Only the first item from the list is valid. If there are more in the
                // list, then discard them
                String src = fsos.get(0).getFullPath();
                CompressExecutable ucmd =
                        FileManagerApplication.getBackgroundConsole().
                            getExecutableFactory().newCreator().
                                createCompressExecutable(mode, src, null);
                String dst = ucmd.getOutCompressedFile();
                FileSystemObject info = CommandHelper.getFileInfo(ctx, dst, null);
                if (info != null) {
                    askUser = true;
                }
            }
        } catch (Exception e) {/**NON BLOCK**/}

        // Ask the user because the destination file or folder exists
        if (askUser) {
            //Show a dialog asking the user for overwrite the files
            AlertDialog dialog =
                    DialogHelper.createTwoButtonsQuestionDialog(
                            ctx,
                            android.R.string.cancel,
                            R.string.overwrite,
                            R.string.confirm_overwrite,
                            ctx.getString(R.string.msgs_overwrite_files),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface alertDialog, int which) {
                                    // NEGATIVE (overwrite)  POSITIVE (cancel)
                                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                                        // Execute background task
                                        task.execute(task);
                                    }
                                }
                           });
            DialogHelper.delegateDialogShow(ctx, dialog);
        } else {
            // Execute background task
            task.execute(task);
        }
    }

    /**
     * Method that uncompress a compressed file.
     *
     * @param ctx The current context
     * @param fso The compressed file
     * @param onRequestRefreshListener The listener for request a refresh (optional)
     * @hide
     */
    public static void uncompress(
            final Context ctx, final FileSystemObject fso,
            final OnRequestRefreshListener onRequestRefreshListener) {

        // The callable interface
        final BackgroundCallable callable = new BackgroundCallable() {
            // The current items
            final Context mCtx = ctx;
            final FileSystemObject mFso = fso;
            final OnRequestRefreshListener mOnRequestRefreshListener = onRequestRefreshListener;

            final Object mSync = new Object();
            Throwable mCause;
            UncompressExecutable cmd;

            final CompressListener mListener =
                                new CompressListener();
            private String mMsg;
            private boolean mStarted = false;

            @Override
            public int getDialogTitle() {
                return R.string.waiting_dialog_extracting_title;
            }
            @Override
            public int getDialogIcon() {
                return 0;
            }
            @Override
            public boolean isDialogCancellable() {
                return true;
            }

            @Override
            public Spanned requestProgress() {
                // Initializing the dialog
                if (!this.mStarted) {
                    String progress =
                            this.mCtx.getResources().
                                getString(
                                    R.string.waiting_dialog_analizing_msg);
                    return Html.fromHtml(progress);
                }

                // Return the current operation
                String msg = (this.mMsg == null) ? "" : this.mMsg; //$NON-NLS-1$
                String progress =
                      this.mCtx.getResources().
                          getString(
                              R.string.waiting_dialog_extracting_msg,
                              msg);
                return Html.fromHtml(progress);
            }

            @Override
            public void onSuccess() {
                try {
                    if (this.cmd != null && this.cmd.isCancellable() && !this.cmd.isCancelled()) {
                        this.cmd.cancel();
                    }
                } catch (Exception e) {/**NON BLOCK**/}

                //Operation complete. Refresh
                if (this.mOnRequestRefreshListener != null) {
                  // The reference is not the same, so refresh the complete navigation view
                  this.mOnRequestRefreshListener.onRequestRefresh(null, true);
                }
                if (this.cmd != null) {
                    showOperationSuccessMsg(
                            ctx,
                            R.string.msgs_extracting_success,
                            this.cmd.getOutUncompressedFile());
                } else {
                    ActionsPolicy.showOperationSuccessMsg(ctx);
                }
            }

            @Override
            public void onCancel() {
                // nop
            }

            @Override
            public void doInBackground(Object... params) throws Throwable {
                this.mCause = null;
                this.mStarted = true;

                // This method expect to receive
                // 1.- BackgroundAsyncTask
                BackgroundAsyncTask task = (BackgroundAsyncTask)params[0];
                String out = null;
                try {
                    this.cmd =
                        CommandHelper.uncompress(
                                ctx,
                                this.mFso.getFullPath(),
                                null,
                                this.mListener, null);
                    out = this.cmd.getOutUncompressedFile();

                    // Request paint the
                    this.mListener.mQueue.insert(out);
                    task.onRequestProgress();

                    // Don't use an active blocking because this suppose that all message
                    // will be processed by the UI. Instead, refresh with a delay and
                    // display the active file
                    while (!this.mListener.mEnd) {
                        // Sleep to don't saturate the UI thread
                        Thread.sleep(50L);

                        List<String> msgs = this.mListener.mQueue.peekAll();
                        if (msgs.size() > 0) {
                            this.mMsg = msgs.get(msgs.size()-1);
                            task.onRequestProgress();
                        }
                    }

                    // Dialog is ended. Force the last redraw
                    List<String> msgs = this.mListener.mQueue.peekAll();
                    if (msgs.size() > 0) {
                        this.mMsg = msgs.get(msgs.size()-1);
                        task.onRequestProgress();
                    }

                } catch (Exception e) {
                    // Need to be relaunched?
                    if (e instanceof RelaunchableException) {
                        OnRelaunchCommandResult rl = new OnRelaunchCommandResult() {
                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onSuccess() {
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }

                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onFailed(Throwable cause) {
                                mCause = cause;
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }
                            @Override
                            @SuppressWarnings("unqualified-field-access")
                            public void onCancelled() {
                                synchronized (mSync) {
                                    mSync.notify();
                                }
                            }
                        };

                        // Translate the exception (and wait for the result)
                        ExceptionUtil.translateException(ctx, e, false, true, rl);
                        synchronized (this.mSync) {
                            this.mSync.wait();
                        }

                        // Persist the exception?
                        if (this.mCause != null) {
                            // The exception must be elevated
                            throw this.mCause;
                        }

                    } else {
                        // The exception must be elevated
                        throw e;
                    }
                }


                // Any exception?
                Thread.sleep(100L);
                if (this.mListener.mCause != null) {
                    throw this.mListener.mCause;
                }

                // Check that the operation was completed retrieving the uncompressed
                // file or folder
                boolean failed = false;
                try {
                    FileSystemObject fso2 = CommandHelper.getFileInfo(ctx, out, false, null);
                    if (fso2 == null) {
                        // Failed. The file or folder not exists
                        failed = true;
                    }

                    // Operation complete successfully

                } catch (Throwable e) {
                    // Failed. The file or folder not exists
                    failed = true;
                }
                if (failed) {
                    throw new ExecutionException(
                            String.format(
                                    "Failed to extract file: %s", //$NON-NLS-1$
                                    this.mFso.getFullPath()));
                }
            }
        };
        final BackgroundAsyncTask task = new BackgroundAsyncTask(ctx, callable);

        // Check if the output exists
        boolean askUser = false;
        try {
            UncompressExecutable ucmd =
                    FileManagerApplication.getBackgroundConsole().
                        getExecutableFactory().newCreator().
                            createUncompressExecutable(fso.getFullPath(), null, null);
            String dst = ucmd.getOutUncompressedFile();
            FileSystemObject info = CommandHelper.getFileInfo(ctx, dst, null);
            if (info != null) {
                askUser = true;
            }
        } catch (Exception e) {/**NON BLOCK**/}

        // Ask the user because the destination file or folder exists
        if (askUser) {
            //Show a dialog asking the user for overwrite the files
            AlertDialog dialog =
                    DialogHelper.createTwoButtonsQuestionDialog(
                            ctx,
                            android.R.string.cancel,
                            R.string.overwrite,
                            R.string.confirm_overwrite,
                            ctx.getString(R.string.msgs_overwrite_files),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface alertDialog, int which) {
                                    // NEGATIVE (overwrite)  POSITIVE (cancel)
                                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                                        // Check if the necessary to display a warning because
                                        // security issues
                                        checkZipSecurityWarning(ctx, task, fso);
                                    }
                                }
                           });
            DialogHelper.delegateDialogShow(ctx, dialog);
        } else {
            // Execute background task
            task.execute(task);
        }
    }

    /**
     * Method that checks if it is necessary to display a warning dialog because
     * the privileged extraction of a zip file.
     *
     * @param ctx The current context
     * @param task The task
     * @param fso The zip file
     * @hide
     */
    static void checkZipSecurityWarning(
            final Context ctx, final BackgroundAsyncTask task, FileSystemObject fso) {
        // WARNING! Extracting a ZIP file with relatives or absolutes path could break
        // the system and is need a security alert that the user can confirm prior to
        // make the extraction
        String ext = FileHelper.getExtension(fso);
        if (ConsoleBuilder.isPrivileged() && ext.compareToIgnoreCase("zip") == 0) { //$NON-NLS-1$
            AlertDialog dialog = DialogHelper.createYesNoDialog(
                ctx,
                R.string.confirm_overwrite,
                R.string.security_warning_extract,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface alertDialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            // Execute background task
                            task.execute(task);
                        }
                    }
               });
            dialog.show();
        } else {
            // Execute background task
            task.execute(task);
        }
    }

    /**
     * Method that returns the supported compression modes
     *
     * @param ctx The current context
     * @param fsos The list of file system objects to compress
     * @return String[] An array with the compression mode labels
     */
    private static String[] getSupportedCompressionModesLabels(
                                Context ctx, List<FileSystemObject> fsos) {
        String[] labels = ctx.getResources().getStringArray(R.array.compression_modes_labels);
        // If more than a file are requested, compression is not available
        // The same applies if the unique item is a folder
        if (fsos.size() > 1 || (fsos.size() == 1 && FileHelper.isDirectory(fsos.get(0)))) {
            ArrayList<String> validLabels = new ArrayList<String>();
            CompressionMode[] values = CompressionMode.values();
            int cc = values.length;
            for (int i = 0; i < cc; i++) {
                if (values[i].mArchive) {
                    if (values[i].mCommandId == null ||
                        FileManagerApplication.hasOptionalCommand(values[i].mCommandId)) {
                        validLabels.add(labels[i]);
                    }
                }
            }
            labels = validLabels.toArray(new String[]{});
        } else {
            // Remove optional commands
            ArrayList<String> validLabels = new ArrayList<String>();
            CompressionMode[] values = CompressionMode.values();
            int cc = values.length;
            for (int i = 0; i < cc; i++) {
                if (values[i].mCommandId == null ||
                    FileManagerApplication.hasOptionalCommand(values[i].mCommandId)) {
                    validLabels.add(labels[i]);
                }
            }
            labels = validLabels.toArray(new String[]{});
        }
        return labels;
    }

    /**
     * Method that returns the compression mode from the user choice
     *
     * @param ctx The current context
     * @param labels The dialog labels
     * @param choice The choice of the user
     * @return CompressionMode The compression mode
     */
    static CompressionMode getCompressionModeFromUserChoice(
            Context ctx, String[] labels, int choice) {
        String label = labels[choice];
        String[] allLabels = ctx.getResources().getStringArray(R.array.compression_modes_labels);
        CompressionMode[] values = CompressionMode.values();
        int cc = allLabels.length;
        for (int i = 0; i < cc; i++) {
            if (allLabels[i].compareTo(label) == 0) {
                return values[i];
            }
        }
        return null;
    }

    /**
     * Method that shows a message when the operation is complete successfully
     *
     * @param ctx The current context
     * @param res The resource identifier
     * @param dst The destination output
     * @hide
     */
    protected static void showOperationSuccessMsg(Context ctx, int res, String dst) {
        DialogHelper.showToast(ctx, ctx.getString(res, dst), Toast.LENGTH_SHORT);
    }
}